Cleaned up the iPhone code so that it compiles with the 3.1.2 SDK. Also tightened up warnings and cleaned up the C++ code that violated the warnings.

Fixed up some memory issues.



git-svn-id: https://zxing.googlecode.com/svn/trunk@1334 59b500cc-1b3d-0410-9834-0bbf25fbcc57
This commit is contained in:
dmaclach 2010-05-04 21:44:53 +00:00
parent 4c91a1279a
commit 505af10197
118 changed files with 1242 additions and 1078 deletions

View file

@ -9,6 +9,7 @@ Androida.hu / http://www.androida.hu/
Brian Brown (Google) Brian Brown (Google)
Christian Brunschen (Google) Christian Brunschen (Google)
Daniel Switkin (Google) Daniel Switkin (Google)
Dave MacLachlan (Google)
David Albert (Bug Labs) David Albert (Bug Labs)
Diego Pierotto Diego Pierotto
Eric Kobrin (Velocitude) Eric Kobrin (Velocitude)

View file

@ -23,7 +23,7 @@
namespace zxing { namespace zxing {
Binarizer::Binarizer(Ref<LuminanceSource> source) : source_(source) { Binarizer::Binarizer(Ref<LuminanceSource> source) : source_(source), array_(NULL), matrix_(NULL) {
} }
Binarizer::~Binarizer() { Binarizer::~Binarizer() {

View file

@ -23,7 +23,7 @@
namespace zxing { namespace zxing {
BinaryBitmap::BinaryBitmap(Ref<Binarizer> binarizer) : bits_(NULL), binarizer_(binarizer) { BinaryBitmap::BinaryBitmap(Ref<Binarizer> binarizer) : bits_(NULL), array_bits_(NULL), binarizer_(binarizer) {
} }

View file

@ -16,7 +16,7 @@ Exception::Exception(const char *msg) :
} }
const char* Exception::what() const throw() { const char* Exception::what() const throw() {
return message; return message.c_str();
} }
Exception::~Exception() throw() { Exception::~Exception() throw() {

View file

@ -28,7 +28,7 @@ namespace zxing {
class Exception : public std::exception { class Exception : public std::exception {
private: private:
const char * message; std::string message;
public: public:
Exception(const char *msg); Exception(const char *msg);

View file

@ -28,7 +28,7 @@ LuminanceSource::LuminanceSource() {
LuminanceSource::~LuminanceSource() { LuminanceSource::~LuminanceSource() {
} }
unsigned char* LuminanceSource::copyMatrix() { unsigned char* LuminanceSource::copyMatrix() const {
int width = getWidth(); int width = getWidth();
int height = getHeight(); int height = getHeight();
unsigned char* matrix = new unsigned char[width*height]; unsigned char* matrix = new unsigned char[width*height];

View file

@ -30,11 +30,11 @@ public:
LuminanceSource(); LuminanceSource();
virtual ~LuminanceSource(); virtual ~LuminanceSource();
virtual int getWidth() = 0; virtual int getWidth() const = 0;
virtual int getHeight() = 0; virtual int getHeight() const = 0;
virtual unsigned char getPixel(int x, int y) = 0; virtual unsigned char getPixel(int x, int y) const = 0;
virtual unsigned char* copyMatrix(); virtual unsigned char* copyMatrix() const;
}; };
} }

View file

@ -27,19 +27,17 @@
#include <zxing/ReaderException.h> #include <zxing/ReaderException.h>
namespace zxing { namespace zxing {
MultiFormatReader::MultiFormatReader(){ MultiFormatReader::MultiFormatReader() : readers() {
readers = new std::vector<Reader*>(); readers.push_back(Ref<Reader>(new zxing::qrcode::QRCodeReader()));
readers.push_back(Ref<Reader>(new zxing::datamatrix::DataMatrixReader()));
readers->push_back(new zxing::qrcode::QRCodeReader()); readers.push_back(Ref<Reader>(new zxing::oned::MultiFormatUPCEANReader()));
readers->push_back(new zxing::datamatrix::DataMatrixReader()); readers.push_back(Ref<Reader>(new zxing::oned::MultiFormatOneDReader()));
readers->push_back(new zxing::oned::MultiFormatUPCEANReader());
readers->push_back(new zxing::oned::MultiFormatOneDReader());
} }
Ref<Result> MultiFormatReader::decode(Ref<BinaryBitmap> image){ Ref<Result> MultiFormatReader::decode(Ref<BinaryBitmap> image){
int size = readers->size(); int size = readers.size();
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
Reader* reader = (*readers)[i]; Ref<Reader> reader = readers[i];
try { try {
return reader->decode(image); return reader->decode(image);
} catch (ReaderException re) { } catch (ReaderException re) {
@ -48,11 +46,4 @@ namespace zxing {
} }
throw ReaderException("No code detected"); throw ReaderException("No code detected");
} }
MultiFormatReader::~MultiFormatReader(){
int size = readers->size();
for (int i = 0; i < size; i++) {
delete (*readers)[i];
}
delete readers;
}
} }

View file

@ -27,12 +27,11 @@ namespace zxing {
class MultiFormatReader : public Reader { class MultiFormatReader : public Reader {
private: private:
std::vector<Reader*>* readers; std::vector<Ref<Reader> >readers;
public: public:
MultiFormatReader(); MultiFormatReader();
Ref<Result> decode(Ref<BinaryBitmap> image); Ref<Result> decode(Ref<BinaryBitmap> image);
~MultiFormatReader();
}; };
} }

View file

@ -26,7 +26,9 @@
namespace zxing { namespace zxing {
class Reader { class Reader : public Counted {
protected:
Reader() {}
public: public:
virtual Ref<Result> decode(Ref<BinaryBitmap> image) = 0; virtual Ref<Result> decode(Ref<BinaryBitmap> image) = 0;
virtual ~Reader(); virtual ~Reader();

View file

@ -39,11 +39,11 @@ ArrayRef<unsigned char> Result::getRawBytes() {
return rawBytes_; return rawBytes_;
} }
std::vector<Ref<ResultPoint> > Result::getResultPoints() { const std::vector<Ref<ResultPoint> >& Result::getResultPoints() const {
return resultPoints_; return resultPoints_;
} }
BarcodeFormat Result::getBarcodeFormat() { BarcodeFormat Result::getBarcodeFormat() const {
return format_; return format_;
} }

View file

@ -44,8 +44,8 @@ public:
~Result(); ~Result();
Ref<String> getText(); Ref<String> getText();
ArrayRef<unsigned char> getRawBytes(); ArrayRef<unsigned char> getRawBytes();
std::vector<Ref<ResultPoint> > getResultPoints(); const std::vector<Ref<ResultPoint> >& getResultPoints() const;
BarcodeFormat getBarcodeFormat(); BarcodeFormat getBarcodeFormat() const;
friend std::ostream& operator<<(std::ostream &out, Result& result); friend std::ostream& operator<<(std::ostream &out, Result& result);
}; };

View file

@ -26,9 +26,11 @@
namespace zxing { namespace zxing {
class ResultPoint : public Counted { class ResultPoint : public Counted {
protected:
ResultPoint() {}
public: public:
virtual float getX() = 0; virtual float getX() const = 0;
virtual float getY() = 0; virtual float getY() const = 0;
}; };
} }

View file

@ -44,9 +44,6 @@ size_t BitArray::wordsForBits(size_t bits) {
} }
return arraySize; return arraySize;
} }
BitArray::BitArray() {
cout << "hey! don't use this BitArrayConstructor!\n";
}
BitArray::BitArray(size_t size) : BitArray::BitArray(size_t size) :
size_(size), bits_(wordsForBits(size), (const unsigned int)0) { size_(size), bits_(wordsForBits(size), (const unsigned int)0) {

View file

@ -53,7 +53,7 @@ static size_t wordsForSize(size_t width, size_t height) {
} }
BitMatrix::BitMatrix(size_t dimension) : BitMatrix::BitMatrix(size_t dimension) :
width_(dimension), height_(dimension), bits_(NULL) { width_(dimension), height_(dimension), words_(0), bits_(NULL) {
words_ = wordsForSize(width_, height_); words_ = wordsForSize(width_, height_);
bits_ = new unsigned int[words_]; bits_ = new unsigned int[words_];
@ -61,7 +61,7 @@ BitMatrix::BitMatrix(size_t dimension) :
} }
BitMatrix::BitMatrix(size_t width, size_t height) : BitMatrix::BitMatrix(size_t width, size_t height) :
width_(width), height_(height), bits_(NULL) { width_(width), height_(height), words_(0), bits_(NULL) {
words_ = wordsForSize(width_, height_); words_ = wordsForSize(width_, height_);
bits_ = new unsigned int[words_]; bits_ = new unsigned int[words_];
@ -125,11 +125,11 @@ size_t BitMatrix::getDimension() const {
return width_; return width_;
} }
unsigned int* BitMatrix::getBits() { unsigned int* BitMatrix::getBits() const {
return bits_; return bits_;
} }
ostream& operator<<(ostream &out, BitMatrix &bm) { ostream& operator<<(ostream &out, const BitMatrix &bm) {
for (size_t y = 0; y < bm.height_; y++) { for (size_t y = 0; y < bm.height_; y++) {
for (size_t x = 0; x < bm.width_; x++) { for (size_t x = 0; x < bm.width_; x++) {
out << (bm.get(x, y) ? "X " : " "); out << (bm.get(x, y) ? "X " : " ");

View file

@ -49,10 +49,14 @@ public:
size_t getWidth() const; size_t getWidth() const;
size_t getHeight() const; size_t getHeight() const;
unsigned int* getBits(); unsigned int* getBits() const;
friend std::ostream& operator<<(std::ostream &out, BitMatrix &bm); friend std::ostream& operator<<(std::ostream &out, const BitMatrix &bm);
const char *description(); const char *description();
private:
BitMatrix(const BitMatrix&);
BitMatrix& operator =(const BitMatrix&);
}; };
} }

View file

@ -172,10 +172,10 @@ public:
T& operator*() { T& operator*() {
return *object_; return *object_;
} }
T* operator->() { T* operator->() const {
return object_; return object_;
} }
operator T*() { operator T*() const {
return object_; return object_;
} }

View file

@ -23,18 +23,13 @@
namespace zxing { namespace zxing {
using namespace std; using namespace std;
PerspectiveTransform::PerspectiveTransform(float a11, float a21, float a31, float a12, float a22, float a32, float a13, PerspectiveTransform::PerspectiveTransform(float inA11, float inA21,
float a23, float a33) { float inA31, float inA12,
this->a11 = a11; float inA22, float inA32,
this->a12 = a12; float inA13, float inA23,
this->a13 = a13; float inA33) :
this->a21 = a21; a11(inA11), a21(inA21), a31(inA31), a12(inA12), a22(inA22), a32(inA32),
this->a22 = a22; a13(inA13), a23(inA23), a33(inA33) {}
this->a23 = a23;
this->a31 = a31;
this->a32 = a32;
this->a33 = a33;
}
Ref<PerspectiveTransform> PerspectiveTransform::quadrilateralToQuadrilateral(float x0, float y0, float x1, float y1, Ref<PerspectiveTransform> PerspectiveTransform::quadrilateralToQuadrilateral(float x0, float y0, float x1, float y1,
float x2, float y2, float x3, float y3, float x0p, float y0p, float x1p, float y1p, float x2p, float y2p, float x2, float y2, float x3, float y3, float x0p, float y0p, float x1p, float y1p, float x2p, float y2p,
@ -93,15 +88,6 @@ Ref<PerspectiveTransform> PerspectiveTransform::times(Ref<PerspectiveTransform>
void PerspectiveTransform::transformPoints(vector<float> &points) { void PerspectiveTransform::transformPoints(vector<float> &points) {
int max = points.size(); int max = points.size();
float a11 = this->a11;
float a12 = this->a12;
float a13 = this->a13;
float a21 = this->a21;
float a22 = this->a22;
float a23 = this->a23;
float a31 = this->a31;
float a32 = this->a32;
float a33 = this->a33;
for (int i = 0; i < max; i += 2) { for (int i = 0; i < max; i += 2) {
float x = points[i]; float x = points[i];
float y = points[i + 1]; float y = points[i + 1];
@ -111,7 +97,7 @@ void PerspectiveTransform::transformPoints(vector<float> &points) {
} }
} }
ostream& operator<<(ostream& out, PerspectiveTransform &pt) { ostream& operator<<(ostream& out, const PerspectiveTransform &pt) {
out << pt.a11 << ", " << pt.a12 << ", " << pt.a13 << ", \n"; out << pt.a11 << ", " << pt.a12 << ", " << pt.a13 << ", \n";
out << pt.a21 << ", " << pt.a22 << ", " << pt.a23 << ", \n"; out << pt.a21 << ", " << pt.a22 << ", " << pt.a23 << ", \n";
out << pt.a31 << ", " << pt.a32 << ", " << pt.a33 << "\n"; out << pt.a31 << ", " << pt.a32 << ", " << pt.a33 << "\n";

View file

@ -43,7 +43,7 @@ public:
Ref<PerspectiveTransform> times(Ref<PerspectiveTransform> other); Ref<PerspectiveTransform> times(Ref<PerspectiveTransform> other);
void transformPoints(std::vector<float> &points); void transformPoints(std::vector<float> &points);
friend std::ostream& operator<<(std::ostream& out, PerspectiveTransform &pt); friend std::ostream& operator<<(std::ostream& out, const PerspectiveTransform &pt);
}; };
} }

View file

@ -26,7 +26,7 @@ using namespace std;
String::String(const std::string &text) : String::String(const std::string &text) :
text_(text) { text_(text) {
} }
std::string& String::getText() { const std::string& String::getText() const {
return text_; return text_;
} }

View file

@ -32,7 +32,7 @@ private:
std::string text_; std::string text_;
public: public:
String(const std::string &text); String(const std::string &text);
std::string &getText(); const std::string &getText() const;
friend std::ostream &operator<<(std::ostream &out, const String &s); friend std::ostream &operator<<(std::ostream &out, const String &s);
}; };

View file

@ -53,8 +53,8 @@ Ref<Result> DataMatrixReader::decode(Ref<BinaryBitmap> image) {
#ifdef DEBUG #ifdef DEBUG
cout << "(3) extracted points " << &points << "\n" << flush; cout << "(3) extracted points " << &points << "\n" << flush;
cout << "found " << points->size() << " points:\n"; cout << "found " << points.size() << " points:\n";
for (size_t i = 0; i < points->size(); i++) { for (size_t i = 0; i < points.size(); i++) {
cout << " " << points[i]->getX() << "," << points[i]->getY() << "\n"; cout << " " << points[i]->getX() << "," << points[i]->getY() << "\n";
} }
cout << "bits:\n"; cout << "bits:\n";

View file

@ -39,13 +39,11 @@ int ECB::getDataCodewords() {
} }
ECBlocks::ECBlocks(int ecCodewords, ECB *ecBlocks) : ECBlocks::ECBlocks(int ecCodewords, ECB *ecBlocks) :
ecCodewords_(ecCodewords) { ecCodewords_(ecCodewords), ecBlocks_(1, ecBlocks) {
ecBlocks_.push_back(ecBlocks);
} }
ECBlocks::ECBlocks(int ecCodewords, ECB *ecBlocks1, ECB *ecBlocks2) : ECBlocks::ECBlocks(int ecCodewords, ECB *ecBlocks1, ECB *ecBlocks2) :
ecCodewords_(ecCodewords) { ecCodewords_(ecCodewords), ecBlocks_(1, ecBlocks1) {
ecBlocks_.push_back(ecBlocks1);
ecBlocks_.push_back(ecBlocks2); ecBlocks_.push_back(ecBlocks2);
} }
@ -70,7 +68,7 @@ Version::Version(int versionNumber, int symbolSizeRows, int symbolSizeColumns, i
int dataRegionSizeColumns, ECBlocks* ecBlocks) : versionNumber_(versionNumber), int dataRegionSizeColumns, ECBlocks* ecBlocks) : versionNumber_(versionNumber),
symbolSizeRows_(symbolSizeRows), symbolSizeColumns_(symbolSizeColumns), symbolSizeRows_(symbolSizeRows), symbolSizeColumns_(symbolSizeColumns),
dataRegionSizeRows_(dataRegionSizeRows), dataRegionSizeColumns_(dataRegionSizeColumns), dataRegionSizeRows_(dataRegionSizeRows), dataRegionSizeColumns_(dataRegionSizeColumns),
ecBlocks_(ecBlocks) { ecBlocks_(ecBlocks), totalCodewords_(0) {
// Calculate the total number of codewords // Calculate the total number of codewords
int total = 0; int total = 0;
int ecCodewords = ecBlocks_->getECCodewords(); int ecCodewords = ecBlocks_->getECCodewords();
@ -114,7 +112,7 @@ ECBlocks* Version::getECBlocks() {
return ecBlocks_; return ecBlocks_;
} }
Version* Version::getVersionForDimensions(int numRows, int numColumns) { Ref<Version> Version::getVersionForDimensions(int numRows, int numColumns) {
if ((numRows & 0x01) != 0 || (numColumns & 0x01) != 0) { if ((numRows & 0x01) != 0 || (numColumns & 0x01) != 0) {
throw ReaderException("Number of rows and columns must be even"); throw ReaderException("Number of rows and columns must be even");
} }
@ -123,7 +121,7 @@ Version* Version::getVersionForDimensions(int numRows, int numColumns) {
// If we interleave the rectangular versions with the square versions we could // If we interleave the rectangular versions with the square versions we could
// do a binary search. // do a binary search.
for (int i = 0; i < N_VERSIONS; ++i){ for (int i = 0; i < N_VERSIONS; ++i){
Version* version = VERSIONS[i]; Ref<Version> version(VERSIONS[i]);
if (version->getSymbolSizeRows() == numRows && version->getSymbolSizeColumns() == numColumns) { if (version->getSymbolSizeRows() == numRows && version->getSymbolSizeColumns() == numColumns) {
return version; return version;
} }

View file

@ -28,7 +28,6 @@
namespace zxing { namespace zxing {
namespace datamatrix { namespace datamatrix {
using namespace std;
class ECB { class ECB {
private: private:
@ -76,7 +75,11 @@ public:
int getTotalCodewords(); int getTotalCodewords();
ECBlocks* getECBlocks(); ECBlocks* getECBlocks();
static int buildVersions(); static int buildVersions();
Version* getVersionForDimensions(int numRows, int numColumns); Ref<Version> getVersionForDimensions(int numRows, int numColumns);
private:
Version(const Version&);
Version & operator=(const Version&);
}; };
} }
} }

View file

@ -28,7 +28,9 @@ int BitMatrixParser::copyBit(size_t x, size_t y, int versionBits) {
return bitMatrix_->get(x, y) ? (versionBits << 1) | 0x1 : versionBits << 1; return bitMatrix_->get(x, y) ? (versionBits << 1) | 0x1 : versionBits << 1;
} }
BitMatrixParser::BitMatrixParser(Ref<BitMatrix> bitMatrix) : parsedVersion_(0) { BitMatrixParser::BitMatrixParser(Ref<BitMatrix> bitMatrix) : parsedVersion_(NULL),
bitMatrix_(NULL),
readBitMatrix_(NULL) {
size_t dimension = bitMatrix->getDimension(); size_t dimension = bitMatrix->getDimension();
if (dimension < 10 || dimension > 144 || (dimension & 0x01) != 0) if (dimension < 10 || dimension > 144 || (dimension & 0x01) != 0)
throw ReaderException("Dimension must be even, > 10 < 144"); throw ReaderException("Dimension must be even, > 10 < 144");
@ -39,7 +41,7 @@ BitMatrixParser::BitMatrixParser(Ref<BitMatrix> bitMatrix) : parsedVersion_(0) {
readBitMatrix_ = new BitMatrix(bitMatrix_->getDimension()); readBitMatrix_ = new BitMatrix(bitMatrix_->getDimension());
} }
Version *BitMatrixParser::readVersion(Ref<BitMatrix> bitMatrix) { Ref<Version> BitMatrixParser::readVersion(Ref<BitMatrix> bitMatrix) {
if (parsedVersion_ != 0) { if (parsedVersion_ != 0) {
return parsedVersion_; return parsedVersion_;
} }
@ -48,7 +50,7 @@ Version *BitMatrixParser::readVersion(Ref<BitMatrix> bitMatrix) {
int numRows = bitMatrix->getDimension(); int numRows = bitMatrix->getDimension();
int numColumns = numRows; int numColumns = numRows;
Version* version = parsedVersion_->getVersionForDimensions(numRows, numColumns); Ref<Version> version = parsedVersion_->getVersionForDimensions(numRows, numColumns);
if (version != 0) { if (version != 0) {
return version; return version;
} }

View file

@ -34,13 +34,13 @@ class BitMatrixParser : public Counted {
private: private:
Ref<BitMatrix> bitMatrix_; Ref<BitMatrix> bitMatrix_;
Ref<BitMatrix> readBitMatrix_; Ref<BitMatrix> readBitMatrix_;
Version *parsedVersion_; Ref<Version> parsedVersion_;
int copyBit(size_t x, size_t y, int versionBits); int copyBit(size_t x, size_t y, int versionBits);
public: public:
BitMatrixParser(Ref<BitMatrix> bitMatrix); BitMatrixParser(Ref<BitMatrix> bitMatrix);
Version *readVersion(Ref<BitMatrix> bitMatrix); Ref<Version> readVersion(Ref<BitMatrix> bitMatrix);
ArrayRef<unsigned char> readCodewords(); ArrayRef<unsigned char> readCodewords();
bool readModule(int row, int column, int numRows, int numColumns); bool readModule(int row, int column, int numRows, int numColumns);

View file

@ -27,18 +27,18 @@ namespace zxing {
using namespace std; using namespace std;
CornerPoint::CornerPoint(float posX, float posY) : CornerPoint::CornerPoint(float posX, float posY) :
posX_(posX), posY_(posY) { posX_(posX), posY_(posY), counter_(0) {
} }
float CornerPoint::getX() { float CornerPoint::getX() const {
return posX_; return posX_;
} }
float CornerPoint::getY() { float CornerPoint::getY() const {
return posY_; return posY_;
} }
int CornerPoint::getCount() { int CornerPoint::getCount() const {
return counter_; return counter_;
} }
@ -46,7 +46,7 @@ namespace zxing {
counter_++; counter_++;
} }
bool CornerPoint::equals(Ref<CornerPoint> other) { bool CornerPoint::equals(Ref<CornerPoint> other) const {
return posX_ == other->getX() && posY_ == other->getY(); return posX_ == other->getX() && posY_ == other->getY();
} }

View file

@ -35,11 +35,11 @@ namespace zxing {
public: public:
CornerPoint(float posX, float posY); CornerPoint(float posX, float posY);
float getX(); float getX() const;
float getY(); float getY() const;
int getCount(); int getCount() const;
void incrementCount(); void incrementCount();
bool equals(Ref<CornerPoint> other); bool equals(Ref<CornerPoint> other) const;
}; };
} }
} }

View file

@ -29,17 +29,14 @@ namespace datamatrix {
using namespace std; using namespace std;
ResultPointsAndTransitions::ResultPointsAndTransitions() { ResultPointsAndTransitions::ResultPointsAndTransitions() : from_(), to_(), transitions_(0) {
Ref<CornerPoint> ref(new CornerPoint(0,0)); Ref<CornerPoint> ref(new CornerPoint(0,0));
from_ = ref; from_ = ref;
to_ = ref; to_ = ref;
transitions_ = 0;
} }
ResultPointsAndTransitions::ResultPointsAndTransitions(Ref<CornerPoint> from, Ref<CornerPoint> to, int transitions) { ResultPointsAndTransitions::ResultPointsAndTransitions(Ref<CornerPoint> from, Ref<CornerPoint> to, int transitions) :
from_ = from; from_(from), to_(to), transitions_(transitions) {
to_ = to;
transitions_ = transitions;
} }
Ref<CornerPoint> ResultPointsAndTransitions::getFrom() { Ref<CornerPoint> ResultPointsAndTransitions::getFrom() {

View file

@ -46,17 +46,16 @@ namespace zxing {
}; };
static int ASTERISK_ENCODING = 0x094; static int ASTERISK_ENCODING = 0x094;
static const char* ALPHABET_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%";
/** /**
* Creates a reader that assumes all encoded data is data, and does not treat the final * Creates a reader that assumes all encoded data is data, and does not treat the final
* character as a check digit. It will not decoded "extended Code 39" sequences. * character as a check digit. It will not decoded "extended Code 39" sequences.
*/ */
Code39Reader::Code39Reader(){ Code39Reader::Code39Reader() : alphabet_string(ALPHABET_STRING),
ALPHABET_STRING = new std::string("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%"); usingCheckDigit(false),
usingCheckDigit = false; extendedMode(false) {
extendedMode = false;
} }
/** /**
@ -66,10 +65,9 @@ namespace zxing {
* @param usingCheckDigit if true, treat the last data character as a check digit, not * @param usingCheckDigit if true, treat the last data character as a check digit, not
* data, and verify that the checksum passes. * data, and verify that the checksum passes.
*/ */
Code39Reader::Code39Reader(bool usingCheckDigit_){ Code39Reader::Code39Reader(bool usingCheckDigit_) : alphabet_string(ALPHABET_STRING),
ALPHABET_STRING = new std::string("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%"); usingCheckDigit(usingCheckDigit_),
usingCheckDigit = usingCheckDigit_; extendedMode(false) {
extendedMode = false;
} }
@ -138,9 +136,9 @@ namespace zxing {
int max = tmpResultString.length() - 1; int max = tmpResultString.length() - 1;
int total = 0; int total = 0;
for (int i = 0; i < max; i++) { for (int i = 0; i < max; i++) {
total += ALPHABET_STRING->find_first_of(tmpResultString[i], 0); total += alphabet_string.find_first_of(tmpResultString[i], 0);
} }
if (total % 43 != ALPHABET_STRING->find_first_of(tmpResultString[max], 0)) { if (total % 43 != alphabet_string.find_first_of(tmpResultString[max], 0)) {
throw ReaderException(""); throw ReaderException("");
} }
tmpResultString.erase(max, 1); tmpResultString.erase(max, 1);
@ -344,11 +342,5 @@ namespace zxing {
Ref<String> decoded(new String(tmpDecoded)); Ref<String> decoded(new String(tmpDecoded));
return decoded; return decoded;
} }
Code39Reader::~Code39Reader(){
delete ALPHABET_STRING;
}
} }
} }

View file

@ -33,7 +33,7 @@ namespace zxing {
class Code39Reader : public OneDReader { class Code39Reader : public OneDReader {
private: private:
std::string* ALPHABET_STRING; std::string alphabet_string;
bool usingCheckDigit; bool usingCheckDigit;
bool extendedMode; bool extendedMode;
@ -49,8 +49,6 @@ namespace zxing {
Code39Reader(bool usingCheckDigit_); Code39Reader(bool usingCheckDigit_);
Ref<Result> decodeRow(int rowNumber, Ref<BitArray> row); Ref<Result> decodeRow(int rowNumber, Ref<BitArray> row);
~Code39Reader();
}; };
} }
} }

View file

@ -27,20 +27,11 @@ namespace zxing {
static const int FIRST_DIGIT_ENCODINGS[10] = {0x00, 0x0B, 0x0D, 0xE, 0x13, 0x19, 0x1C, 0x15, 0x16, 0x1A}; static const int FIRST_DIGIT_ENCODINGS[10] = {0x00, 0x0B, 0x0D, 0xE, 0x13, 0x19, 0x1C, 0x15, 0x16, 0x1A};
EAN13Reader::EAN13Reader(){ EAN13Reader::EAN13Reader() { }
decodeMiddleCounters = new int[4];
for (int i=0; i<4; i++) {
decodeMiddleCounters[i] = 0;
}
}
int EAN13Reader::decodeMiddle(Ref<BitArray> row, int startRange[], int startRangeLen, std::string& resultString){ int EAN13Reader::decodeMiddle(Ref<BitArray> row, int startRange[], int startRangeLen, std::string& resultString){
int countersLen = 4; const int countersLen = 4;
int* counters = decodeMiddleCounters; int counters[countersLen] = { 0, 0, 0, 0 };
counters[0] = 0;
counters[1] = 0;
counters[2] = 0;
counters[3] = 0;
int end = row->getSize(); int end = row->getSize();
@ -88,8 +79,5 @@ namespace zxing {
BarcodeFormat EAN13Reader::getBarcodeFormat(){ BarcodeFormat EAN13Reader::getBarcodeFormat(){
return BarcodeFormat_EAN_13; return BarcodeFormat_EAN_13;
} }
EAN13Reader::~EAN13Reader(){
delete [] decodeMiddleCounters;
}
} }
} }

View file

@ -26,7 +26,6 @@ namespace zxing {
class EAN13Reader : public UPCEANReader { class EAN13Reader : public UPCEANReader {
private: private:
int* decodeMiddleCounters;
static void determineFirstDigit(std::string& resultString, int lgPatternFound); //throws ReaderException static void determineFirstDigit(std::string& resultString, int lgPatternFound); //throws ReaderException
public: public:
@ -35,7 +34,6 @@ namespace zxing {
int decodeMiddle(Ref<BitArray> row, int startRange[], int startRangeLen, std::string& resultString); //throws ReaderException int decodeMiddle(Ref<BitArray> row, int startRange[], int startRangeLen, std::string& resultString); //throws ReaderException
BarcodeFormat getBarcodeFormat(); BarcodeFormat getBarcodeFormat();
~EAN13Reader();
}; };
} }
} }

View file

@ -24,21 +24,11 @@
namespace zxing { namespace zxing {
namespace oned { namespace oned {
EAN8Reader::EAN8Reader(){ EAN8Reader::EAN8Reader(){ }
decodeMiddleCounters = new int[4];
for (int i=0; i<4; i++) {
decodeMiddleCounters[i] = 0;
}
}
int EAN8Reader::decodeMiddle(Ref<BitArray> row, int startRange[], int startRangeLen, std::string& resultString){ int EAN8Reader::decodeMiddle(Ref<BitArray> row, int startRange[], int startRangeLen, std::string& resultString){
int countersLen = 4; const int countersLen = 4;
int* counters = decodeMiddleCounters; int counters[countersLen] = { 0, 0, 0, 0 };
counters[0] = 0;
counters[1] = 0;
counters[2] = 0;
counters[3] = 0;
int end = row->getSize(); int end = row->getSize();
int rowOffset = startRange[1]; int rowOffset = startRange[1];
@ -68,8 +58,5 @@ namespace zxing {
BarcodeFormat EAN8Reader::getBarcodeFormat(){ BarcodeFormat EAN8Reader::getBarcodeFormat(){
return BarcodeFormat_EAN_8; return BarcodeFormat_EAN_8;
} }
EAN8Reader::~EAN8Reader(){
delete [] decodeMiddleCounters;
}
} }
} }

View file

@ -25,16 +25,12 @@ namespace zxing {
namespace oned { namespace oned {
class EAN8Reader : public UPCEANReader { class EAN8Reader : public UPCEANReader {
private:
int* decodeMiddleCounters;
public: public:
EAN8Reader(); EAN8Reader();
int decodeMiddle(Ref<BitArray> row, int startRange[], int startRangeLen, std::string& resultString); //throws ReaderException int decodeMiddle(Ref<BitArray> row, int startRange[], int startRangeLen, std::string& resultString); //throws ReaderException
BarcodeFormat getBarcodeFormat(); BarcodeFormat getBarcodeFormat();
~EAN8Reader();
}; };
} }
} }

View file

@ -62,8 +62,7 @@ namespace zxing {
}; };
ITFReader::ITFReader(){ ITFReader::ITFReader() : narrowLineWidth(-1) {
narrowLineWidth = -1;
} }

View file

@ -28,18 +28,17 @@
namespace zxing { namespace zxing {
namespace oned { namespace oned {
MultiFormatOneDReader::MultiFormatOneDReader(){ MultiFormatOneDReader::MultiFormatOneDReader() : readers() {
readers = new std::vector<OneDReader*>(); readers.push_back(Ref<OneDReader>(new MultiFormatUPCEANReader()));
readers->push_back(new MultiFormatUPCEANReader()); readers.push_back(Ref<OneDReader>(new Code39Reader()));
readers->push_back(new Code39Reader()); readers.push_back(Ref<OneDReader>(new Code128Reader()));
readers->push_back(new Code128Reader()); readers.push_back(Ref<OneDReader>(new ITFReader()));
readers->push_back(new ITFReader());
} }
Ref<Result> MultiFormatOneDReader::decodeRow(int rowNumber, Ref<BitArray> row){ Ref<Result> MultiFormatOneDReader::decodeRow(int rowNumber, Ref<BitArray> row){
int size = readers->size(); int size = readers.size();
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
OneDReader* reader = (*readers)[i]; OneDReader* reader = readers[i];
try { try {
return reader->decodeRow(rowNumber, row); return reader->decodeRow(rowNumber, row);
} catch (ReaderException re) { } catch (ReaderException re) {
@ -48,12 +47,5 @@ namespace zxing {
} }
throw ReaderException("No code detected"); throw ReaderException("No code detected");
} }
MultiFormatOneDReader::~MultiFormatOneDReader(){
int size = readers->size();
for (int i = 0; i < size; i++) {
delete (*readers)[i];
}
delete readers;
}
} }
} }

View file

@ -27,13 +27,11 @@ namespace zxing {
class MultiFormatOneDReader : public OneDReader { class MultiFormatOneDReader : public OneDReader {
private: private:
std::vector<OneDReader*>* readers; std::vector<Ref<OneDReader> > readers;
public: public:
MultiFormatOneDReader(); MultiFormatOneDReader();
Ref<Result> decodeRow(int rowNumber, Ref<BitArray> row); Ref<Result> decodeRow(int rowNumber, Ref<BitArray> row);
~MultiFormatOneDReader();
}; };
} }
} }

View file

@ -30,19 +30,18 @@
namespace zxing { namespace zxing {
namespace oned { namespace oned {
MultiFormatUPCEANReader::MultiFormatUPCEANReader(){ MultiFormatUPCEANReader::MultiFormatUPCEANReader() : readers() {
readers = new std::vector<OneDReader*>(); readers.push_back(Ref<OneDReader>(new EAN13Reader()));
readers->push_back(new EAN13Reader());
// UPC-A is covered by EAN-13 // UPC-A is covered by EAN-13
readers->push_back(new EAN8Reader()); readers.push_back(Ref<OneDReader>(new EAN8Reader()));
readers->push_back(new UPCEReader()); readers.push_back(Ref<OneDReader>(new UPCEReader()));
} }
Ref<Result> MultiFormatUPCEANReader::decodeRow(int rowNumber, Ref<BitArray> row){ Ref<Result> MultiFormatUPCEANReader::decodeRow(int rowNumber, Ref<BitArray> row){
// Compute this location once and reuse it on multiple implementations // Compute this location once and reuse it on multiple implementations
int size = readers->size(); int size = readers.size();
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
OneDReader* reader = (*readers)[i]; Ref<OneDReader> reader = readers[i];
Ref<Result> result; Ref<Result> result;
try { try {
result = reader->decodeRow(rowNumber, row);//decodeRow(rowNumber, row, startGuardPattern); result = reader->decodeRow(rowNumber, row);//decodeRow(rowNumber, row, startGuardPattern);
@ -60,7 +59,7 @@ namespace zxing {
// UPC-A. So we special case it here, and convert an EAN-13 result to a UPC-A // UPC-A. So we special case it here, and convert an EAN-13 result to a UPC-A
// result if appropriate. // result if appropriate.
if (result->getBarcodeFormat() == BarcodeFormat_EAN_13) { if (result->getBarcodeFormat() == BarcodeFormat_EAN_13) {
std::string& text = (result->getText())->getText(); const std::string& text = (result->getText())->getText();
if (text[0] == '0') { if (text[0] == '0') {
Ref<String> resultString(new String(text.substr(1))); Ref<String> resultString(new String(text.substr(1)));
Ref<Result> res(new Result(resultString, result->getRawBytes(), result->getResultPoints(), BarcodeFormat_UPC_A)); Ref<Result> res(new Result(resultString, result->getRawBytes(), result->getResultPoints(), BarcodeFormat_UPC_A));
@ -71,13 +70,5 @@ namespace zxing {
} }
throw ReaderException("No EAN code detected"); throw ReaderException("No EAN code detected");
} }
MultiFormatUPCEANReader::~MultiFormatUPCEANReader(){
int size = readers->size();
for (int i = 0; i < size; i++) {
delete (*readers)[i];
}
delete readers;
}
} }
} }

View file

@ -29,13 +29,11 @@ namespace zxing {
class MultiFormatUPCEANReader : public OneDReader { class MultiFormatUPCEANReader : public OneDReader {
private: private:
std::vector<OneDReader*>* readers; std::vector<Ref<OneDReader> > readers;
public: public:
MultiFormatUPCEANReader(); MultiFormatUPCEANReader();
Ref<Result> decodeRow(int rowNumber, Ref<BitArray> row); Ref<Result> decodeRow(int rowNumber, Ref<BitArray> row);
~MultiFormatUPCEANReader();
}; };
} }
} }

View file

@ -23,16 +23,14 @@
namespace zxing { namespace zxing {
namespace oned { namespace oned {
using namespace std;
OneDResultPoint::OneDResultPoint(float posX, float posY) : posX_(posX), posY_(posY){ OneDResultPoint::OneDResultPoint(float posX, float posY) : posX_(posX), posY_(posY){
} }
float OneDResultPoint::getX() { float OneDResultPoint::getX() const {
return posX_; return posX_;
} }
float OneDResultPoint::getY() { float OneDResultPoint::getY() const {
return posY_; return posY_;
} }
} }

View file

@ -30,8 +30,8 @@ namespace zxing {
public: public:
OneDResultPoint(float posX, float posY); OneDResultPoint(float posX, float posY);
float getX(); float getX() const;
float getY(); float getY() const;
}; };
} }
} }

View file

@ -19,31 +19,29 @@
*/ */
#include "UPCAReader.h" #include "UPCAReader.h"
#include <zxing/oned/EAN13Reader.h>
#include <zxing/ReaderException.h> #include <zxing/ReaderException.h>
namespace zxing { namespace zxing {
namespace oned { namespace oned {
UPCAReader::UPCAReader(){ UPCAReader::UPCAReader() : ean13Reader() {
ean13Reader = new EAN13Reader();
} }
Ref<Result> UPCAReader::decodeRow(int rowNumber, Ref<BitArray> row){ Ref<Result> UPCAReader::decodeRow(int rowNumber, Ref<BitArray> row){
return maybeReturnResult(ean13Reader->decodeRow(rowNumber, row)); return maybeReturnResult(ean13Reader.decodeRow(rowNumber, row));
} }
Ref<Result> UPCAReader::decodeRow(int rowNumber, Ref<BitArray> row, int startGuardRange[]){ Ref<Result> UPCAReader::decodeRow(int rowNumber, Ref<BitArray> row, int startGuardRange[]){
return maybeReturnResult(ean13Reader->decodeRow(rowNumber, row, startGuardRange)); return maybeReturnResult(ean13Reader.decodeRow(rowNumber, row, startGuardRange));
} }
Ref<Result> UPCAReader::decode(Ref<BinaryBitmap> image){ Ref<Result> UPCAReader::decode(Ref<BinaryBitmap> image){
return maybeReturnResult(ean13Reader->decode(image)); return maybeReturnResult(ean13Reader.decode(image));
} }
int UPCAReader::decodeMiddle(Ref<BitArray> row, int startRange[], int startRangeLen, std::string& resultString){ int UPCAReader::decodeMiddle(Ref<BitArray> row, int startRange[], int startRangeLen, std::string& resultString){
return ean13Reader->decodeMiddle(row, startRange, startRangeLen, resultString); return ean13Reader.decodeMiddle(row, startRange, startRangeLen, resultString);
} }
Ref<Result> UPCAReader::maybeReturnResult(Ref<Result> result){ Ref<Result> UPCAReader::maybeReturnResult(Ref<Result> result){
std::string& text = (result->getText())->getText(); const std::string& text = (result->getText())->getText();
if (text[0] == '0') { if (text[0] == '0') {
Ref<String> resultString(new String(text.substr(1))); Ref<String> resultString(new String(text.substr(1)));
Ref<Result> res(new Result(resultString, result->getRawBytes(), result->getResultPoints(), BarcodeFormat_UPC_A)); Ref<Result> res(new Result(resultString, result->getRawBytes(), result->getResultPoints(), BarcodeFormat_UPC_A));
@ -57,8 +55,5 @@ namespace zxing {
BarcodeFormat UPCAReader::getBarcodeFormat(){ BarcodeFormat UPCAReader::getBarcodeFormat(){
return BarcodeFormat_UPC_A; return BarcodeFormat_UPC_A;
} }
UPCAReader::~UPCAReader(){
delete ean13Reader;
}
} }
} }

View file

@ -18,15 +18,14 @@
* limitations under the License. * limitations under the License.
*/ */
#include <zxing/oned/UPCEANReader.h> #include <zxing/oned/EAN13Reader.h>
#include <zxing/Result.h>
namespace zxing { namespace zxing {
namespace oned { namespace oned {
class UPCAReader : public UPCEANReader { class UPCAReader : public UPCEANReader {
private: private:
UPCEANReader* ean13Reader; EAN13Reader ean13Reader;
static Ref<Result> maybeReturnResult(Ref<Result> result); //throws ReaderException static Ref<Result> maybeReturnResult(Ref<Result> result); //throws ReaderException
public: public:
@ -39,7 +38,6 @@ namespace zxing {
Ref<Result> decode(Ref<BinaryBitmap> image); Ref<Result> decode(Ref<BinaryBitmap> image);
BarcodeFormat getBarcodeFormat(); BarcodeFormat getBarcodeFormat();
~UPCAReader();
}; };
} }
} }

View file

@ -63,3 +63,4 @@ namespace zxing {
}; };
} }
} }

View file

@ -40,21 +40,11 @@ namespace zxing {
{0x07, 0x0B, 0x0D, 0x0E, 0x13, 0x19, 0x1C, 0x15, 0x16, 0x1A} {0x07, 0x0B, 0x0D, 0x0E, 0x13, 0x19, 0x1C, 0x15, 0x16, 0x1A}
}; };
UPCEReader::UPCEReader(){ UPCEReader::UPCEReader(){}
decodeMiddleCounters = new int[4];
for (int i=0; i<4; i++) {
decodeMiddleCounters[i] = 0;
}
}
int UPCEReader::decodeMiddle(Ref<BitArray> row, int startRange[], int startRangeLen, std::string& resultString){ int UPCEReader::decodeMiddle(Ref<BitArray> row, int startRange[], int startRangeLen, std::string& resultString){
int countersLen = 4; const int countersLen = 4;
int* counters = decodeMiddleCounters; int counters[countersLen] = { 0, 0, 0, 0 };
counters[0] = 0;
counters[1] = 0;
counters[2] = 0;
counters[3] = 0;
int end = row->getSize(); int end = row->getSize();
int rowOffset = startRange[1]; int rowOffset = startRange[1];
@ -143,8 +133,5 @@ namespace zxing {
BarcodeFormat UPCEReader::getBarcodeFormat(){ BarcodeFormat UPCEReader::getBarcodeFormat(){
return BarcodeFormat_UPC_E; return BarcodeFormat_UPC_E;
} }
UPCEReader::~UPCEReader(){
delete [] decodeMiddleCounters;
}
} }
} }

View file

@ -26,7 +26,6 @@ namespace zxing {
class UPCEReader : public UPCEANReader { class UPCEReader : public UPCEANReader {
private: private:
int* decodeMiddleCounters;
static void determineFirstDigit(std::string& resultString, int lgPatternFound); //throws ReaderException static void determineFirstDigit(std::string& resultString, int lgPatternFound); //throws ReaderException
static void determineNumSysAndCheckDigit(std::string& resultString, int lgPatternFound); //throws ReaderException static void determineNumSysAndCheckDigit(std::string& resultString, int lgPatternFound); //throws ReaderException
protected: protected:
@ -39,7 +38,6 @@ namespace zxing {
static std::string& convertUPCEtoUPCA(std::string upce); static std::string& convertUPCEtoUPCA(std::string upce);
BarcodeFormat getBarcodeFormat(); BarcodeFormat getBarcodeFormat();
~UPCEReader();
}; };
} }
} }

View file

@ -23,8 +23,8 @@
namespace zxing { namespace zxing {
namespace qrcode { namespace qrcode {
ErrorCorrectionLevel::ErrorCorrectionLevel(int ordinal) : ErrorCorrectionLevel::ErrorCorrectionLevel(int inOrdinal) :
ordinal_(ordinal) { ordinal_(inOrdinal) {
} }
int ErrorCorrectionLevel::ordinal() { int ErrorCorrectionLevel::ordinal() {

View file

@ -29,7 +29,7 @@ namespace qrcode {
class ErrorCorrectionLevel { class ErrorCorrectionLevel {
private: private:
int ordinal_; int ordinal_;
ErrorCorrectionLevel(int ordinal); ErrorCorrectionLevel(int inOrdinal);
static ErrorCorrectionLevel *FOR_BITS[]; static ErrorCorrectionLevel *FOR_BITS[];
static int N_LEVELS; static int N_LEVELS;
public: public:

View file

@ -41,13 +41,11 @@ int ECB::getDataCodewords() {
} }
ECBlocks::ECBlocks(int ecCodewords, ECB *ecBlocks) : ECBlocks::ECBlocks(int ecCodewords, ECB *ecBlocks) :
ecCodewords_(ecCodewords) { ecCodewords_(ecCodewords), ecBlocks_(1, ecBlocks) {
ecBlocks_.push_back(ecBlocks);
} }
ECBlocks::ECBlocks(int ecCodewords, ECB *ecBlocks1, ECB *ecBlocks2) : ECBlocks::ECBlocks(int ecCodewords, ECB *ecBlocks1, ECB *ecBlocks2) :
ecCodewords_(ecCodewords) { ecCodewords_(ecCodewords), ecBlocks_(1, ecBlocks1) {
ecBlocks_.push_back(ecBlocks1);
ecBlocks_.push_back(ecBlocks2); ecBlocks_.push_back(ecBlocks2);
} }
@ -102,7 +100,7 @@ Version *Version::getProvisionalVersionForDimension(int dimension) {
} }
Version *Version::getVersionForNumber(int versionNumber) { Version *Version::getVersionForNumber(int versionNumber) {
if (versionNumber < 1 || versionNumber > 40) { if (versionNumber < 1 || versionNumber > N_VERSIONS) {
throw ReaderException("versionNumber must be between 1 and 40"); throw ReaderException("versionNumber must be between 1 and 40");
} }
@ -111,7 +109,7 @@ Version *Version::getVersionForNumber(int versionNumber) {
Version::Version(int versionNumber, vector<int> *alignmentPatternCenters, ECBlocks *ecBlocks1, ECBlocks *ecBlocks2, Version::Version(int versionNumber, vector<int> *alignmentPatternCenters, ECBlocks *ecBlocks1, ECBlocks *ecBlocks2,
ECBlocks *ecBlocks3, ECBlocks *ecBlocks4) : ECBlocks *ecBlocks3, ECBlocks *ecBlocks4) :
versionNumber_(versionNumber), alignmentPatternCenters_(*alignmentPatternCenters), ecBlocks_(4) { versionNumber_(versionNumber), alignmentPatternCenters_(*alignmentPatternCenters), ecBlocks_(4), totalCodewords_(0) {
ecBlocks_[0] = ecBlocks1; ecBlocks_[0] = ecBlocks1;
ecBlocks_[1] = ecBlocks2; ecBlocks_[1] = ecBlocks2;
ecBlocks_[2] = ecBlocks3; ecBlocks_[2] = ecBlocks3;

View file

@ -158,8 +158,8 @@ ArrayRef<unsigned char> BitMatrixParser::readCodewords() {
x--; x--;
} }
// Read alternatingly from bottom to top then top to bottom // Read alternatingly from bottom to top then top to bottom
for (int count = 0; count < dimension; count++) { for (int counter = 0; counter < dimension; counter++) {
int y = readingUp ? dimension - 1 - count : count; int y = readingUp ? dimension - 1 - counter : counter;
for (int col = 0; col < 2; col++) { for (int col = 0; col < 2; col++) {
// Ignore bits covered by the function pattern // Ignore bits covered by the function pattern
if (!functionPattern->get(x - col, y)) { if (!functionPattern->get(x - col, y)) {

View file

@ -44,6 +44,11 @@ public:
Ref<FormatInformation> readFormatInformation(); Ref<FormatInformation> readFormatInformation();
Version *readVersion(); Version *readVersion();
ArrayRef<unsigned char> readCodewords(); ArrayRef<unsigned char> readCodewords();
private:
BitMatrixParser(const BitMatrixParser&);
BitMatrixParser& operator =(const BitMatrixParser&);
}; };
} }

View file

@ -29,15 +29,15 @@ AlignmentPattern::AlignmentPattern(float posX, float posY, float estimatedModule
posX_(posX), posY_(posY), estimatedModuleSize_(estimatedModuleSize) { posX_(posX), posY_(posY), estimatedModuleSize_(estimatedModuleSize) {
} }
float AlignmentPattern::getX() { float AlignmentPattern::getX() const {
return posX_; return posX_;
} }
float AlignmentPattern::getY() { float AlignmentPattern::getY() const {
return posY_; return posY_;
} }
bool AlignmentPattern::aboutEquals(float moduleSize, float i, float j) { bool AlignmentPattern::aboutEquals(float moduleSize, float i, float j) const {
return abs(i - posY_) <= moduleSize && abs(j - posX_) <= moduleSize && (abs(moduleSize - estimatedModuleSize_) return abs(i - posY_) <= moduleSize && abs(j - posX_) <= moduleSize && (abs(moduleSize - estimatedModuleSize_)
<= 1.0f || abs(moduleSize - estimatedModuleSize_) / estimatedModuleSize_ <= 0.1f); <= 1.0f || abs(moduleSize - estimatedModuleSize_) / estimatedModuleSize_ <= 0.1f);
} }

View file

@ -35,9 +35,9 @@ namespace zxing {
public: public:
AlignmentPattern(float posX, float posY, float estimatedModuleSize); AlignmentPattern(float posX, float posY, float estimatedModuleSize);
float getX(); float getX() const;
float getY(); float getY() const;
bool aboutEquals(float moduleSize, float i, float j); bool aboutEquals(float moduleSize, float i, float j) const;
}; };
} }

View file

@ -55,6 +55,11 @@ public:
float moduleSize); float moduleSize);
~AlignmentPatternFinder(); ~AlignmentPatternFinder();
Ref<AlignmentPattern> find(); Ref<AlignmentPattern> find();
private:
AlignmentPatternFinder(const AlignmentPatternFinder&);
AlignmentPatternFinder& operator =(const AlignmentPatternFinder&);
}; };
} }
} }

View file

@ -29,19 +29,19 @@ namespace zxing {
posX_(posX), posY_(posY), estimatedModuleSize_(estimatedModuleSize), counter_(1) { posX_(posX), posY_(posY), estimatedModuleSize_(estimatedModuleSize), counter_(1) {
} }
float FinderPattern::getX() { float FinderPattern::getX() const {
return posX_; return posX_;
} }
float FinderPattern::getY() { float FinderPattern::getY() const {
return posY_; return posY_;
} }
int FinderPattern::getCount() { int FinderPattern::getCount() const {
return counter_; return counter_;
} }
float FinderPattern::getEstimatedModuleSize() { float FinderPattern::getEstimatedModuleSize() const {
return estimatedModuleSize_; return estimatedModuleSize_;
} }
@ -49,7 +49,7 @@ namespace zxing {
counter_++; counter_++;
} }
bool FinderPattern::aboutEquals(float moduleSize, float i, float j) { bool FinderPattern::aboutEquals(float moduleSize, float i, float j) const {
return abs(i - posY_) <= moduleSize && abs(j - posX_) <= moduleSize && (abs(moduleSize - estimatedModuleSize_) return abs(i - posY_) <= moduleSize && abs(j - posX_) <= moduleSize && (abs(moduleSize - estimatedModuleSize_)
<= 1.0f || abs(moduleSize - estimatedModuleSize_) / estimatedModuleSize_ <= 0.1f); <= 1.0f || abs(moduleSize - estimatedModuleSize_) / estimatedModuleSize_ <= 0.1f);
} }

View file

@ -36,12 +36,12 @@ namespace zxing {
public: public:
FinderPattern(float posX, float posY, float estimatedModuleSize); FinderPattern(float posX, float posY, float estimatedModuleSize);
float getX(); float getX() const;
float getY(); float getY() const;
int getCount(); int getCount() const;
float getEstimatedModuleSize(); float getEstimatedModuleSize() const;
void incrementCount(); void incrementCount();
bool aboutEquals(float moduleSize, float i, float j); bool aboutEquals(float moduleSize, float i, float j) const;
}; };
} }
} }

View file

@ -41,7 +41,7 @@
@property (nonatomic, copy) NSString *urlString; @property (nonatomic, copy) NSString *urlString;
@property (nonatomic, copy) NSString *address; @property (nonatomic, copy) NSString *address;
+ actionWithName:(NSString *)n + (id)actionWithName:(NSString *)n
phoneNumbers:(NSArray *)nums phoneNumbers:(NSArray *)nums
email:(NSString *)em email:(NSString *)em
url:(NSString *)us url:(NSString *)us

View file

@ -32,7 +32,7 @@
@synthesize urlString; @synthesize urlString;
@synthesize address; @synthesize address;
+ actionWithName:(NSString *)n + (id)actionWithName:(NSString *)n
phoneNumbers:(NSArray *)nums phoneNumbers:(NSArray *)nums
email:(NSString *)em email:(NSString *)em
url:(NSString *)us url:(NSString *)us

View file

@ -36,6 +36,6 @@
@property (nonatomic, retain) NSDateFormatter *dateFormatter; @property (nonatomic, retain) NSDateFormatter *dateFormatter;
- (NSInteger)scanIndexForRow:(NSInteger)row; - (NSInteger)scanIndexForRow:(NSInteger)row;
- initWithDecoderViewController:(DecoderViewController *)dc; - (id)initWithDecoderViewController:(DecoderViewController *)dc;
@end @end

View file

@ -35,8 +35,8 @@
@synthesize decoderViewController; @synthesize decoderViewController;
@synthesize dateFormatter; @synthesize dateFormatter;
- initWithDecoderViewController:(DecoderViewController *)dc { - (id)initWithDecoderViewController:(DecoderViewController *)dc {
if (self = [super initWithStyle:UITableViewStylePlain]) { if ((self = [super initWithStyle:UITableViewStylePlain])) {
decoderViewController = [dc retain]; decoderViewController = [dc retain];
scans = [[NSMutableArray alloc] init]; scans = [[NSMutableArray alloc] init];
results = [[NSMutableArray alloc] init]; results = [[NSMutableArray alloc] init];
@ -66,17 +66,17 @@
} }
// Configure the cell // Configure the cell
int index = [self scanIndexForRow:indexPath.row]; int idx = [self scanIndexForRow:indexPath.row];
Scan *scan = [scans objectAtIndex:index]; Scan *scan = [scans objectAtIndex:idx];
[cell setScan:scan]; [cell setScan:scan];
return cell; return cell;
} }
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//[decoderViewController showScan:[scans objectAtIndex:[self scanIndexForRow:indexPath.row]]]; //[decoderViewController showScan:[scans objectAtIndex:[self scanIndexForRow:indexPath.row]]];
int index = [self scanIndexForRow:indexPath.row]; int idx = [self scanIndexForRow:indexPath.row];
Scan *scan = [scans objectAtIndex:index]; Scan *scan = [scans objectAtIndex:idx];
ParsedResult *result = [results objectAtIndex:index]; ParsedResult *result = [results objectAtIndex:idx];
ScanViewController *scanViewController = [[ScanViewController alloc] initWithResult:result forScan:scan]; ScanViewController *scanViewController = [[ScanViewController alloc] initWithResult:result forScan:scan];
[self.navigationController pushViewController:scanViewController animated:YES]; [self.navigationController pushViewController:scanViewController animated:YES];
[scanViewController release]; [scanViewController release];
@ -84,14 +84,14 @@
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) { if (editingStyle == UITableViewCellEditingStyleDelete) {
int index = [self scanIndexForRow:indexPath.row]; int idx = [self scanIndexForRow:indexPath.row];
Scan *scan = [self.scans objectAtIndex:index]; Scan *scan = [self.scans objectAtIndex:idx];
// delete the scan from the database ... // delete the scan from the database ...
[[Database sharedDatabase] deleteScan:scan]; [[Database sharedDatabase] deleteScan:scan];
// ... delete the scan from our in-memory cache of the database ... // ... delete the scan from our in-memory cache of the database ...
[scans removeObjectAtIndex:index]; [scans removeObjectAtIndex:idx];
// ... delete the corresponding result from our in-memory cache ... // ... delete the corresponding result from our in-memory cache ...
[results removeObjectAtIndex:index]; [results removeObjectAtIndex:idx];
// ... and remove the row from the table view. // ... and remove the row from the table view.
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
// [tableView reloadData]; // [tableView reloadData];

View file

@ -24,6 +24,10 @@
@implementation BookmarkDoCoMoResultParser @implementation BookmarkDoCoMoResultParser
+ (void)load {
[ResultParser registerResultParserClass:self];
}
+ (ParsedResult *)parsedResultForString:(NSString *)s { + (ParsedResult *)parsedResultForString:(NSString *)s {
NSRange foundRange = [s rangeOfString:@"MEBKM:"]; NSRange foundRange = [s rangeOfString:@"MEBKM:"];
if (foundRange.location == NSNotFound) { if (foundRange.location == NSNotFound) {

View file

@ -30,7 +30,7 @@
+ (NSURL *)urlForNumber:(NSString *)number; + (NSURL *)urlForNumber:(NSString *)number;
- initWithNumber:(NSString *)number; - (id)initWithNumber:(NSString *)number;
+ actionWithNumber:(NSString *)number; + (id)actionWithNumber:(NSString *)number;
@end @end

View file

@ -31,14 +31,14 @@
return [NSURL URLWithString:urlString]; return [NSURL URLWithString:urlString];
} }
- initWithNumber:(NSString *)n { - (id)initWithNumber:(NSString *)n {
if ((self = [super initWithURL:[[self class] urlForNumber:n]]) != nil) { if ((self = [super initWithURL:[[self class] urlForNumber:n]]) != nil) {
self.number = n; self.number = n;
} }
return self; return self;
} }
+ actionWithNumber:(NSString *)number { + (id)actionWithNumber:(NSString *)number {
return [[[self alloc] initWithNumber:number] autorelease]; return [[[self alloc] initWithNumber:number] autorelease];
} }

View file

@ -32,7 +32,7 @@
@property sqlite3 *connection; @property sqlite3 *connection;
@property int nextScanIdent; @property int nextScanIdent;
+ sharedDatabase; + (id)sharedDatabase;
- (void)addScanWithText:(NSString *)text; - (void)addScanWithText:(NSString *)text;
- (NSArray *)scans; - (NSArray *)scans;

View file

@ -34,7 +34,7 @@ static sqlite3_stmt *deleteStatement;
static Database *sharedDatabase = nil; static Database *sharedDatabase = nil;
+ sharedDatabase { + (id)sharedDatabase {
if (!sharedDatabase) { if (!sharedDatabase) {
sharedDatabase = [[self alloc] init]; sharedDatabase = [[self alloc] init];
@ -58,17 +58,17 @@ static Database *sharedDatabase = nil;
sqlite3_open([writableDBPath UTF8String], &connection); sqlite3_open([writableDBPath UTF8String], &connection);
sharedDatabase.connection = connection; sharedDatabase.connection = connection;
static char *maxIdSql = "SELECT MAX(id) FROM SCAN"; static const char *maxIdSql = "SELECT MAX(id) FROM SCAN";
sqlite3_prepare_v2(connection, maxIdSql, -1, &maxIdStatement, NULL); sqlite3_prepare_v2(connection, maxIdSql, -1, &maxIdStatement, NULL);
static char *selectAllSql = "SELECT id, text, stamp FROM SCAN ORDER BY id"; static const char *selectAllSql = "SELECT id, text, stamp FROM SCAN ORDER BY id";
sqlite3_prepare_v2(connection, selectAllSql, -1, &selectAllStatement, NULL); sqlite3_prepare_v2(connection, selectAllSql, -1, &selectAllStatement, NULL);
static char *insertSql = static const char *insertSql =
"INSERT INTO SCAN (id, text, stamp) VALUES (?, ?, ?)"; "INSERT INTO SCAN (id, text, stamp) VALUES (?, ?, ?)";
sqlite3_prepare_v2(connection, insertSql, -1, &insertStatement, NULL); sqlite3_prepare_v2(connection, insertSql, -1, &insertStatement, NULL);
static char *deleteSql = "DELETE FROM SCAN WHERE id = ?"; static const char *deleteSql = "DELETE FROM SCAN WHERE id = ?";
sqlite3_prepare_v2(connection, deleteSql, -1, &deleteStatement, NULL); sqlite3_prepare_v2(connection, deleteSql, -1, &deleteStatement, NULL);
if (SQLITE_ROW == sqlite3_step(maxIdStatement)) { if (SQLITE_ROW == sqlite3_step(maxIdStatement)) {

View file

@ -1,265 +0,0 @@
//
// Decoder.m
// ZXing
//
// Created by Christian Brunschen on 31/03/2008.
//
/*
* Copyright 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import "Decoder.h"
#import "TwoDDecoderResult.h"
#include <zxing/qrcode/QRCodeReader.h>
#include <zxing/MultiFormatReader.h>
#include <zxing/BinaryBitmap.h>
#include <zxing/ReaderException.h>
#include <zxing/common/IllegalArgumentException.h>
#include <zxing/common/GlobalHistogramBinarizer.h>
#include "GrayBytesMonochromeBitmapSource.h"
using namespace zxing;
@implementation Decoder
@synthesize image;
@synthesize cropRect;
@synthesize subsetImage;
@synthesize subsetData;
@synthesize subsetWidth;
@synthesize subsetHeight;
@synthesize subsetBytesPerRow;
@synthesize delegate;
- (void)willDecodeImage {
[self.delegate decoder:self willDecodeImage:self.image usingSubset:self.subsetImage];
}
- (void)progressDecodingImage:(NSString *)progress {
[self.delegate decoder:self
decodingImage:self.image
usingSubset:self.subsetImage
progress:progress];
}
- (void)didDecodeImage:(TwoDDecoderResult *)result {
[self.delegate decoder:self didDecodeImage:self.image usingSubset:self.subsetImage withResult:result];
}
- (void)failedToDecodeImage:(NSString *)reason {
[self.delegate decoder:self failedToDecodeImage:self.image usingSubset:self.subsetImage reason:reason];
}
#define SUBSET_SIZE 320.0
- (void) prepareSubset {
CGSize size = [image size];
#ifdef DEBUG
NSLog(@"decoding: image is (%.1f x %.1f), cropRect is (%.1f,%.1f)x(%.1f,%.1f)", size.width, size.height,
cropRect.origin.x, cropRect.origin.y, cropRect.size.width, cropRect.size.height);
#endif
float scale = fminf(1.0f, fmaxf(SUBSET_SIZE / cropRect.size.width, SUBSET_SIZE / cropRect.size.height));
CGPoint offset = CGPointMake(-cropRect.origin.x, -cropRect.origin.y);
#ifdef DEBUG
NSLog(@" offset = (%.1f, %.1f), scale = %.3f", offset.x, offset.y, scale);
#endif
subsetWidth = cropRect.size.width * scale;
subsetHeight = cropRect.size.height * scale;
subsetBytesPerRow = ((subsetWidth + 0xf) >> 4) << 4;
#ifdef DEBUG
NSLog(@"decoding: image to decode is (%d x %d) (%d bytes/row)", subsetWidth, subsetHeight, subsetBytesPerRow);
#endif
subsetData = (unsigned char *)malloc(subsetBytesPerRow * subsetHeight);
#ifdef DEBUG
NSLog(@"allocated %d bytes of memory", subsetBytesPerRow * subsetHeight);
#endif
CGColorSpaceRef grayColorSpace = CGColorSpaceCreateDeviceGray();
CGContextRef ctx =
CGBitmapContextCreate(subsetData, subsetWidth, subsetHeight,
8, subsetBytesPerRow, grayColorSpace,
kCGImageAlphaNone);
CGColorSpaceRelease(grayColorSpace);
CGContextSetInterpolationQuality(ctx, kCGInterpolationNone);
CGContextSetAllowsAntialiasing(ctx, false);
// adjust the coordinate system
CGContextTranslateCTM(ctx, 0.0, subsetHeight);
CGContextScaleCTM(ctx, 1.0, -1.0);
#ifdef DEBUG
NSLog(@"created %dx%d bitmap context", subsetWidth, subsetHeight);
#endif
UIGraphicsPushContext(ctx);
CGRect rect = CGRectMake(offset.x * scale, offset.y * scale, scale * size.width, scale * size.height);
#ifdef DEBUG
NSLog(@"rect for image = (%.1f,%.1f)x(%.1f,%.1f)", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
#endif
[image drawInRect:rect];
UIGraphicsPopContext();
#ifdef DEBUG
NSLog(@"drew image into %d(%d)x%d bitmap context", subsetWidth, subsetBytesPerRow, subsetHeight);
#endif
CGContextFlush(ctx);
#ifdef DEBUG
NSLog(@"flushed context");
#endif
CGImageRef subsetImageRef = CGBitmapContextCreateImage(ctx);
#ifdef DEBUG
NSLog(@"created CGImage from context");
#endif
self.subsetImage = [UIImage imageWithCGImage:subsetImageRef];
CGImageRelease(subsetImageRef);
CGContextRelease(ctx);
#ifdef DEBUG
NSLog(@"released context");
#endif
}
- (void)decode:(id)arg {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
{
MultiFormatReader reader;
#ifdef DEBUG
NSLog(@"created MultiFormatReader");
#endif
Ref<LuminanceSource> source (new GrayBytesMonochromeBitmapSource(subsetData, subsetWidth, subsetHeight, subsetBytesPerRow));
Ref<Binarizer> binarizer (new GlobalHistogramBinarizer(source));
Ref<BinaryBitmap> grayImage (new BinaryBitmap(binarizer));
#ifdef DEBUG
NSLog(@"created GrayBytesMonochromeBitmapSource", subsetWidth, subsetHeight);
NSLog(@"grayImage count = %d", grayImage->count());
#endif
TwoDDecoderResult *decoderResult = nil;
#ifdef TRY_ROTATIONS
for (int i = 0; !decoderResult && i < 4; i++) {
#endif
try {
#ifdef DEBUG
NSLog(@"decoding gray image");
#endif
Ref<Result> result(reader.decode(grayImage));
#ifdef DEBUG
NSLog(@"gray image decoded");
#endif
Ref<String> resultText(result->getText());
const char *cString = resultText->getText().c_str();
std::vector<Ref<ResultPoint> > resultPoints = result->getResultPoints();
NSMutableArray *points =
[NSMutableArray arrayWithCapacity:resultPoints.size()];
for (size_t i = 0; i < resultPoints.size(); i++) {
Ref<ResultPoint> rp(resultPoints[i]);
CGPoint p = CGPointMake(rp->getX(), rp->getY());
[points addObject:[NSValue valueWithCGPoint:p]];
}
NSString *resultString = [NSString stringWithCString:cString
encoding:NSUTF8StringEncoding];
decoderResult = [TwoDDecoderResult resultWithText:resultString
points:points];
} catch (ReaderException rex) {
NSLog(@"failed to decode, caught ReaderException '%s'",
rex.what());
} catch (IllegalArgumentException iex) {
NSLog(@"failed to decode, caught IllegalArgumentException '%s'",
iex.what());
} catch (...) {
NSLog(@"Caught unknown exception!");
}
#ifdef TRY_ROTATIONS
if (!decoderResult) {
#ifdef DEBUG
NSLog(@"rotating gray image");
#endif
grayImage = grayImage->rotateCounterClockwise();
#ifdef DEBUG
NSLog(@"gray image rotated");
#endif
}
}
#endif
if (decoderResult) {
[self performSelectorOnMainThread:@selector(didDecodeImage:)
withObject:decoderResult
waitUntilDone:NO];
} else {
[self performSelectorOnMainThread:@selector(failedToDecodeImage:)
withObject:NSLocalizedString(@"Decoder BarcodeDetectionFailure", @"No barcode detected.")
waitUntilDone:NO];
}
free(subsetData);
self.subsetData = NULL;
}
[pool release];
#ifdef DEBUG
NSLog(@"finished decoding.");
#endif
// if this is not the main thread, then we end it
if (![NSThread isMainThread]) {
[NSThread exit];
}
}
- (void) decodeImage:(UIImage *)i {
[self decodeImage:i cropRect:CGRectMake(0.0f, 0.0f, image.size.width, image.size.height)];
}
- (void) decodeImage:(UIImage *)i cropRect:(CGRect)cr {
self.image = i;
self.cropRect = cr;
[self prepareSubset];
[self.delegate decoder:self willDecodeImage:i usingSubset:self.subsetImage];
[self performSelectorOnMainThread:@selector(progressDecodingImage:)
withObject:NSLocalizedString(@"Decoder MessageWhileDecoding", @"Decoding ...")
waitUntilDone:NO];
[NSThread detachNewThreadSelector:@selector(decode:)
toTarget:self
withObject:nil];
}
- (void) dealloc {
[image release];
[subsetImage release];
if (subsetData) free(subsetData);
[super dealloc];
}
@end

264
iphone/Classes/Decoder.mm Normal file
View file

@ -0,0 +1,264 @@
//
// Decoder.m
// ZXing
//
// Created by Christian Brunschen on 31/03/2008.
//
/*
* Copyright 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import "Decoder.h"
#import "TwoDDecoderResult.h"
#import "FormatReader.h"
#include <zxing/BinaryBitmap.h>
#include <zxing/ReaderException.h>
#include <zxing/common/IllegalArgumentException.h>
#include <zxing/common/GlobalHistogramBinarizer.h>
#include "GrayBytesMonochromeBitmapSource.h"
using namespace zxing;
@implementation Decoder
@synthesize image;
@synthesize cropRect;
@synthesize subsetImage;
@synthesize subsetData;
@synthesize subsetWidth;
@synthesize subsetHeight;
@synthesize subsetBytesPerRow;
@synthesize delegate;
- (void)willDecodeImage {
if ([self.delegate respondsToSelector:@selector(decoder:willDecodeImage:usingSubset:)]) {
[self.delegate decoder:self willDecodeImage:self.image usingSubset:self.subsetImage];
}
}
- (void)progressDecodingImage:(NSString *)progress {
if ([self.delegate respondsToSelector:@selector(decoder:decodingImage:usingSubset:progress:)]) {
[self.delegate decoder:self decodingImage:self.image usingSubset:self.subsetImage progress:progress];
}
}
- (void)didDecodeImage:(TwoDDecoderResult *)result {
if ([self.delegate respondsToSelector:@selector(decoder:didDecodeImage:usingSubset:withResult:)]) {
[self.delegate decoder:self didDecodeImage:self.image usingSubset:self.subsetImage withResult:result];
}
}
- (void)failedToDecodeImage:(NSString *)reason {
if ([self.delegate respondsToSelector:@selector(decoder:failedToDecodeImage:usingSubset:reason:)]) {
[self.delegate decoder:self failedToDecodeImage:self.image usingSubset:self.subsetImage reason:reason];
}
}
#define SUBSET_SIZE 320.0
- (void) prepareSubset {
CGSize size = [image size];
#ifdef DEBUG
NSLog(@"decoding: image is (%.1f x %.1f), cropRect is (%.1f,%.1f)x(%.1f,%.1f)", size.width, size.height,
cropRect.origin.x, cropRect.origin.y, cropRect.size.width, cropRect.size.height);
#endif
float scale = fminf(1.0f, fmaxf(SUBSET_SIZE / cropRect.size.width, SUBSET_SIZE / cropRect.size.height));
CGPoint offset = CGPointMake(-cropRect.origin.x, -cropRect.origin.y);
#ifdef DEBUG
NSLog(@" offset = (%.1f, %.1f), scale = %.3f", offset.x, offset.y, scale);
#endif
subsetWidth = cropRect.size.width * scale;
subsetHeight = cropRect.size.height * scale;
subsetBytesPerRow = ((subsetWidth + 0xf) >> 4) << 4;
#ifdef DEBUG
NSLog(@"decoding: image to decode is (%d x %d) (%d bytes/row)", subsetWidth, subsetHeight, subsetBytesPerRow);
#endif
subsetData = (unsigned char *)malloc(subsetBytesPerRow * subsetHeight);
#ifdef DEBUG
NSLog(@"allocated %d bytes of memory", subsetBytesPerRow * subsetHeight);
#endif
CGColorSpaceRef grayColorSpace = CGColorSpaceCreateDeviceGray();
CGContextRef ctx =
CGBitmapContextCreate(subsetData, subsetWidth, subsetHeight,
8, subsetBytesPerRow, grayColorSpace,
kCGImageAlphaNone);
CGColorSpaceRelease(grayColorSpace);
CGContextSetInterpolationQuality(ctx, kCGInterpolationNone);
CGContextSetAllowsAntialiasing(ctx, false);
// adjust the coordinate system
CGContextTranslateCTM(ctx, 0.0, subsetHeight);
CGContextScaleCTM(ctx, 1.0, -1.0);
#ifdef DEBUG
NSLog(@"created %dx%d bitmap context", subsetWidth, subsetHeight);
#endif
UIGraphicsPushContext(ctx);
CGRect rect = CGRectMake(offset.x * scale, offset.y * scale, scale * size.width, scale * size.height);
#ifdef DEBUG
NSLog(@"rect for image = (%.1f,%.1f)x(%.1f,%.1f)", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
#endif
[image drawInRect:rect];
UIGraphicsPopContext();
#ifdef DEBUG
NSLog(@"drew image into %d(%d)x%d bitmap context", subsetWidth, subsetBytesPerRow, subsetHeight);
#endif
CGContextFlush(ctx);
#ifdef DEBUG
NSLog(@"flushed context");
#endif
CGImageRef subsetImageRef = CGBitmapContextCreateImage(ctx);
#ifdef DEBUG
NSLog(@"created CGImage from context");
#endif
self.subsetImage = [UIImage imageWithCGImage:subsetImageRef];
CGImageRelease(subsetImageRef);
CGContextRelease(ctx);
#ifdef DEBUG
NSLog(@"released context");
#endif
}
- (void)decode:(id)arg {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
{
NSSet *formatReaders = [FormatReader formatReaders];
Ref<LuminanceSource> source (new GrayBytesMonochromeBitmapSource(subsetData, subsetWidth, subsetHeight, subsetBytesPerRow));
Ref<Binarizer> binarizer (new GlobalHistogramBinarizer(source));
Ref<BinaryBitmap> grayImage (new BinaryBitmap(binarizer));
#ifdef DEBUG
NSLog(@"created GrayBytesMonochromeBitmapSource", subsetWidth, subsetHeight);
NSLog(@"grayImage count = %d", grayImage->count());
#endif
TwoDDecoderResult *decoderResult = nil;
#ifdef TRY_ROTATIONS
for (int i = 0; !decoderResult && i < 4; i++) {
#endif
for (FormatReader *reader in formatReaders) {
try {
#ifdef DEBUG
NSLog(@"decoding gray image");
#endif
Ref<Result> result([reader decode:grayImage]);
#ifdef DEBUG
NSLog(@"gray image decoded");
#endif
Ref<String> resultText(result->getText());
const char *cString = resultText->getText().c_str();
const std::vector<Ref<ResultPoint> > &resultPoints = result->getResultPoints();
NSMutableArray *points =
[NSMutableArray arrayWithCapacity:resultPoints.size()];
for (size_t i = 0; i < resultPoints.size(); i++) {
const Ref<ResultPoint> &rp = resultPoints[i];
CGPoint p = CGPointMake(rp->getX(), rp->getY());
[points addObject:[NSValue valueWithCGPoint:p]];
}
NSString *resultString = [NSString stringWithCString:cString
encoding:NSUTF8StringEncoding];
decoderResult = [TwoDDecoderResult resultWithText:resultString
points:points];
} catch (ReaderException &rex) {
NSLog(@"failed to decode, caught ReaderException '%s'",
rex.what());
} catch (IllegalArgumentException &iex) {
NSLog(@"failed to decode, caught IllegalArgumentException '%s'",
iex.what());
} catch (...) {
NSLog(@"Caught unknown exception!");
}
}
#ifdef TRY_ROTATIONS
if (!decoderResult) {
#ifdef DEBUG
NSLog(@"rotating gray image");
#endif
grayImage = grayImage->rotateCounterClockwise();
#ifdef DEBUG
NSLog(@"gray image rotated");
#endif
}
}
#endif
if (decoderResult) {
[self performSelectorOnMainThread:@selector(didDecodeImage:)
withObject:decoderResult
waitUntilDone:NO];
} else {
[self performSelectorOnMainThread:@selector(failedToDecodeImage:)
withObject:NSLocalizedString(@"Decoder BarcodeDetectionFailure", @"No barcode detected.")
waitUntilDone:NO];
}
free(subsetData);
self.subsetData = NULL;
}
[pool drain];
#ifdef DEBUG
NSLog(@"finished decoding.");
#endif
// if this is not the main thread, then we end it
if (![NSThread isMainThread]) {
[NSThread exit];
}
}
- (void) decodeImage:(UIImage *)i {
[self decodeImage:i cropRect:CGRectMake(0.0f, 0.0f, image.size.width, image.size.height)];
}
- (void) decodeImage:(UIImage *)i cropRect:(CGRect)cr {
self.image = i;
self.cropRect = cr;
[self prepareSubset];
[self willDecodeImage];
[self performSelectorOnMainThread:@selector(progressDecodingImage:)
withObject:NSLocalizedString(@"Decoder MessageWhileDecoding", @"Decoding ...")
waitUntilDone:NO];
[NSThread detachNewThreadSelector:@selector(decode:)
toTarget:self
withObject:nil];
}
- (void) dealloc {
[image release];
[subsetImage release];
if (subsetData) free(subsetData);
[super dealloc];
}
@end

View file

@ -24,8 +24,8 @@
@class Decoder; @class Decoder;
@class TwoDDecoderResult; @class TwoDDecoderResult;
@protocol DecoderDelegate @protocol DecoderDelegate<NSObject>
@optional
- (void)decoder:(Decoder *)decoder willDecodeImage:(UIImage *)image usingSubset:(UIImage *)subset; - (void)decoder:(Decoder *)decoder willDecodeImage:(UIImage *)image usingSubset:(UIImage *)subset;
- (void)decoder:(Decoder *)decoder decodingImage:(UIImage *)image usingSubset:(UIImage *)subset progress:(NSString *)message; - (void)decoder:(Decoder *)decoder decodingImage:(UIImage *)image usingSubset:(UIImage *)subset progress:(NSString *)message;
- (void)decoder:(Decoder *)decoder didDecodeImage:(UIImage *)image usingSubset:(UIImage *)subset withResult:(TwoDDecoderResult *)result; - (void)decoder:(Decoder *)decoder didDecodeImage:(UIImage *)image usingSubset:(UIImage *)subset withResult:(TwoDDecoderResult *)result;

View file

@ -53,7 +53,7 @@
@synthesize resultPointViews; @synthesize resultPointViews;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) { if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
// Initialization code // Initialization code
self.title = NSLocalizedString(@"DecoderViewController AppTitle", @"Barcode Scanner"); self.title = NSLocalizedString(@"DecoderViewController AppTitle", @"Barcode Scanner");
@ -87,7 +87,7 @@
onSuccess:@selector(messageReady:) onSuccess:@selector(messageReady:)
onFailure:@selector(messageFailed:)]; onFailure:@selector(messageFailed:)];
hintsController.title = NSLocalizedString(@"DecoderViewController Hints MessageViewController title", @"Hints"); hintsController.title = NSLocalizedString(@"DecoderViewController Hints MessageViewController title", @"Hints");
hintsController.view; [hintsController view];
} }
- (void) showAbout:(id)sender { - (void) showAbout:(id)sender {
@ -99,7 +99,7 @@
onSuccess:@selector(messageReady:) onSuccess:@selector(messageReady:)
onFailure:@selector(messageFailed:)]; onFailure:@selector(messageFailed:)];
aboutController.title = NSLocalizedString(@"DecoderViewController About MessageViewController title", @"About"); aboutController.title = NSLocalizedString(@"DecoderViewController About MessageViewController title", @"About");
aboutController.view; [aboutController view];
} }
@ -257,11 +257,11 @@
NSLog(@"Showing message '%@' %@ help Button", message, showHelpButton ? @"with" : @"without"); NSLog(@"Showing message '%@' %@ help Button", message, showHelpButton ? @"with" : @"without");
#endif #endif
CGSize maxSize = imageView.bounds.size; CGSize imageMaxSize = imageView.bounds.size;
if (showHelpButton) { if (showHelpButton) {
maxSize.width -= messageHelpButton.frame.size.width; imageMaxSize.width -= messageHelpButton.frame.size.width;
} }
CGSize size = [message sizeWithFont:messageTextView.font constrainedToSize:maxSize lineBreakMode:UILineBreakModeWordWrap]; CGSize size = [message sizeWithFont:messageTextView.font constrainedToSize:imageMaxSize lineBreakMode:UILineBreakModeWordWrap];
float height = 20.0 + fmin(100.0, size.height); float height = 20.0 + fmin(100.0, size.height);
if (showHelpButton) { if (showHelpButton) {
height = fmax(HELP_BUTTON_HEIGHT, height); height = fmax(HELP_BUTTON_HEIGHT, height);

View file

@ -28,7 +28,7 @@
@property (nonatomic, copy) NSString *recipient; @property (nonatomic, copy) NSString *recipient;
- initWithRecipient:(NSString *)recipient subject:(NSString *)subject body:(NSString *)body; - (id)initWithRecipient:(NSString *)recipient subject:(NSString *)subject body:(NSString *)body;
+ actionWithRecipient:(NSString *)recipient subject:(NSString *)subject body:(NSString *)body; + (id)actionWithRecipient:(NSString *)recipient subject:(NSString *)subject body:(NSString *)body;
@end @end

View file

@ -37,14 +37,14 @@ static NSURL *MailtoURL(NSString *to, NSString *sub, NSString *body) {
return [NSURL URLWithString:result]; return [NSURL URLWithString:result];
} }
- initWithRecipient:(NSString *)rec subject:(NSString *)subject body:(NSString *)body { - (id)initWithRecipient:(NSString *)rec subject:(NSString *)subject body:(NSString *)body {
if ((self = [super initWithURL:MailtoURL(rec, subject, body)]) != nil) { if ((self = [super initWithURL:MailtoURL(rec, subject, body)]) != nil) {
self.recipient = rec; self.recipient = rec;
} }
return self; return self;
} }
+ actionWithRecipient:(NSString *)recipient subject:(NSString *)subject body:(NSString *)body { + (id)actionWithRecipient:(NSString *)recipient subject:(NSString *)subject body:(NSString *)body {
return [[[self alloc] initWithRecipient:recipient subject:subject body:body] autorelease]; return [[[self alloc] initWithRecipient:recipient subject:subject body:body] autorelease];
} }

View file

@ -24,6 +24,10 @@
@implementation EmailDoCoMoResultParser @implementation EmailDoCoMoResultParser
+ (void)load {
[ResultParser registerResultParserClass:self];
}
+ (ParsedResult *)parsedResultForString:(NSString *)s { + (ParsedResult *)parsedResultForString:(NSString *)s {
NSRange foundRange = [s rangeOfString:@"MATMSG:"]; NSRange foundRange = [s rangeOfString:@"MATMSG:"];
if (foundRange.location == NSNotFound) { if (foundRange.location == NSNotFound) {

View file

@ -0,0 +1,37 @@
//
// FormatReader.h
//
// Created by Dave MacLachlan on 2010-05-03.
/*
* Copyright 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import <Foundation/Foundation.h>
#import <zxing/common/Counted.h>
#import <zxing/Result.h>
#import <zxing/BinaryBitmap.h>
#import <zxing/Reader.h>
@interface FormatReader : NSObject {
zxing::Reader *reader_;
}
+ (void)registerFormatReader:(FormatReader *)formatReader;
+ (NSSet *)formatReaders;
- (id)initWithReader:(zxing::Reader *)reader;
- (zxing::Ref<zxing::Result>)decode:(zxing::Ref<zxing::BinaryBitmap>)grayImage;
@end

View file

@ -0,0 +1,62 @@
//
// FormatReader.mm
//
// Created by Dave MacLachlan on 2010-05-03.
/*
* Copyright 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import "FormatReader.h"
@implementation FormatReader
static NSMutableSet *sFormatReaders = nil;
+ (void)registerFormatReader:(FormatReader*)formatReader {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
@synchronized(self) {
if (!sFormatReaders) {
sFormatReaders = [[NSMutableSet alloc] init];
}
[sFormatReaders addObject:formatReader];
}
[pool drain];
}
+ (NSSet *)formatReaders {
NSSet *formatReaders = nil;
@synchronized(self) {
formatReaders = [[sFormatReaders copy] autorelease];
}
return formatReaders;
}
- (id)initWithReader:(zxing::Reader *)reader {
if ((self = [super init])) {
reader_ = reader;
}
return self;
}
- (void)dealloc {
delete reader_;
[super dealloc];
}
- (zxing::Ref<zxing::Result>)decode:(zxing::Ref<zxing::BinaryBitmap>)grayImage {
return reader_->decode(grayImage);
}
@end

View file

@ -28,7 +28,7 @@
@property (nonatomic, copy) NSString *location; @property (nonatomic, copy) NSString *location;
- initWithLocation:(NSString *)location; - (id)initWithLocation:(NSString *)location;
@end @end

View file

@ -26,7 +26,7 @@
@synthesize location; @synthesize location;
- initWithLocation:(NSString *)l { - (id)initWithLocation:(NSString *)l {
if ((self = [super init]) != nil) { if ((self = [super init]) != nil) {
self.location = l; self.location = l;
} }

View file

@ -26,6 +26,10 @@
@implementation GeoResultParser @implementation GeoResultParser
+ (void)load {
[ResultParser registerResultParserClass:self];
}
+ (ParsedResult *)parsedResultForString:(NSString *)s { + (ParsedResult *)parsedResultForString:(NSString *)s {
NSRange prefixRange = [s rangeOfString:PREFIX options:NSCaseInsensitiveSearch]; NSRange prefixRange = [s rangeOfString:PREFIX options:NSCaseInsensitiveSearch];
if (prefixRange.location == 0) { if (prefixRange.location == 0) {

View file

@ -33,15 +33,15 @@ GrayBytesMonochromeBitmapSource::GrayBytesMonochromeBitmapSource(const unsigned
bytesPerRow_(bytesPerRow) { } bytesPerRow_(bytesPerRow) { }
int GrayBytesMonochromeBitmapSource::getWidth() { int GrayBytesMonochromeBitmapSource::getWidth() const{
return width_; return width_;
} }
int GrayBytesMonochromeBitmapSource::getHeight() { int GrayBytesMonochromeBitmapSource::getHeight() const {
return height_; return height_;
} }
unsigned char GrayBytesMonochromeBitmapSource::getPixel(int x, int y) { unsigned char GrayBytesMonochromeBitmapSource::getPixel(int x, int y) const {
/* if (x >= width_ || y >= height_) { /* if (x >= width_ || y >= height_) {
throw new ReaderException("bitmap coordinate out of bounds"); throw new ReaderException("bitmap coordinate out of bounds");
}*/ }*/

View file

@ -38,11 +38,14 @@ public:
int bytesPerRow); int bytesPerRow);
virtual ~GrayBytesMonochromeBitmapSource() { } virtual ~GrayBytesMonochromeBitmapSource() { }
virtual unsigned char getPixel(int x, int y); virtual unsigned char getPixel(int x, int y) const;
virtual int getWidth(); virtual int getWidth() const;
virtual int getHeight(); virtual int getHeight() const;
private:
GrayBytesMonochromeBitmapSource(const GrayBytesMonochromeBitmapSource&);
GrayBytesMonochromeBitmapSource& operator=(const GrayBytesMonochromeBitmapSource&);
}; };
#endif // __GRAY_BYTES_MONOCHROM_BITMAP_SOURCE_H__ #endif // __GRAY_BYTES_MONOCHROM_BITMAP_SOURCE_H__

View file

@ -24,6 +24,10 @@
@implementation MeCardParser @implementation MeCardParser
+ (void)load {
[ResultParser registerResultParserClass:self];
}
+ (ParsedResult *)parsedResultForString:(NSString *)s { + (ParsedResult *)parsedResultForString:(NSString *)s {
NSRange foundRange = [s rangeOfString:@"MECARD:"]; NSRange foundRange = [s rangeOfString:@"MECARD:"];
if (foundRange.location == NSNotFound) { if (foundRange.location == NSNotFound) {

View file

@ -37,7 +37,7 @@
target:(id)cbt target:(id)cbt
onSuccess:(SEL)ss onSuccess:(SEL)ss
onFailure:(SEL)fs { onFailure:(SEL)fs {
if (self = [super initWithNibName:@"Message" bundle:nil]) { if ((self = [super initWithNibName:@"Message" bundle:nil])) {
self.callbackTarget = cbt; self.callbackTarget = cbt;
self.callbackSelectorSuccess = ss; self.callbackSelectorSuccess = ss;
self.callbackSelectorFailure = fs; self.callbackSelectorFailure = fs;

View file

@ -0,0 +1,40 @@
//
// MultiFormatReader.mm
//
// Created by Dave MacLachlan on 2010-05-03.
/*
* Copyright 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import "FormatReader.h"
#import <zxing/MultiFormatReader.h>
@interface MultiFormatReader : FormatReader
@end
@implementation MultiFormatReader
+ (void)load {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[FormatReader registerFormatReader:[[[self alloc] init] autorelease]];
[pool drain];
}
- (id)init {
zxing::MultiFormatReader *reader = new zxing::MultiFormatReader();
return [super initWithReader:reader];
}
@end

View file

@ -28,8 +28,8 @@
@property(nonatomic, retain) NSURL *URL; @property(nonatomic, retain) NSURL *URL;
- initWithURL:(NSURL *)URL; - (id)initWithURL:(NSURL *)URL;
+ actionWithURL:(NSURL *)URL; + (id)actionWithURL:(NSURL *)URL;
- (void)openURL; - (void)openURL;
- (NSString *)alertTitle; - (NSString *)alertTitle;

View file

@ -26,14 +26,14 @@
@synthesize URL; @synthesize URL;
- initWithURL:(NSURL *)url { - (id)initWithURL:(NSURL *)url {
if ((self = [super init]) != nil) { if ((self = [super init]) != nil) {
self.URL = url; self.URL = url;
} }
return self; return self;
} }
+ actionWithURL:(NSURL *)URL { + (id)actionWithURL:(NSURL *)URL {
return [[[self alloc] initWithURL:URL] autorelease]; return [[[self alloc] initWithURL:URL] autorelease];
} }

View file

@ -24,6 +24,10 @@
@implementation PlainEmailResultParser @implementation PlainEmailResultParser
+ (void)load {
[ResultParser registerResultParserClass:self];
}
+ (ParsedResult *)parsedResultForString:(NSString *)s { + (ParsedResult *)parsedResultForString:(NSString *)s {
if ([EmailParsedResult looksLikeAnEmailAddress:s]) { if ([EmailParsedResult looksLikeAnEmailAddress:s]) {
EmailParsedResult *result = [[[EmailParsedResult alloc] init] autorelease]; EmailParsedResult *result = [[[EmailParsedResult alloc] init] autorelease];

View file

@ -0,0 +1,42 @@
//
// QRCodeFormatReader.mm
// OTPAuth
//
// Created by Dave MacLachlan on 2010-05-03.
/*
* Copyright 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import "FormatReader.h"
#import <zxing/qrcode/QRCodeReader.h>
@interface QRCodeFormatReader : FormatReader
@end
@implementation QRCodeFormatReader
+ (void)load {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[FormatReader registerFormatReader:[[[self alloc] init] autorelease]];
[pool drain];
}
- (id)init {
zxing::qrcode::QRCodeReader *reader = new zxing::qrcode::QRCodeReader();
return [super initWithReader:reader];
}
@end

View file

@ -25,7 +25,7 @@
@interface ResultParser : NSObject { @interface ResultParser : NSObject {
} }
+ (void)registerResultParserClass:(Class)resultParser;
+ (ParsedResult *)parsedResultForString:(NSString *)s; + (ParsedResult *)parsedResultForString:(NSString *)s;
@end @end

View file

@ -21,37 +21,25 @@
#import "ResultParser.h" #import "ResultParser.h"
#import "MeCardParser.h"
#import "EmailDoCoMoResultParser.h"
#import "BookmarkDoCoMoResultParser.h"
#import "TelResultParser.h"
#import "GeoResultParser.h"
#import "URLTOResultParser.h"
#import "URLResultParser.h"
#import "TextResultParser.h"
#import "SMSResultParser.h"
#import "SMSTOResultParser.h"
#import "PlainEmailResultParser.h"
@implementation ResultParser @implementation ResultParser
static NSArray *resultParsers = nil; static NSMutableSet *sResultParsers = nil;
+ (NSArray *)resultParsers {
if (resultParsers == nil) { + (void)registerResultParserClass:(Class)resultParser {
resultParsers = NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[[NSArray alloc] initWithObjects: @synchronized(self) {
[MeCardParser class], if (!sResultParsers) {
[EmailDoCoMoResultParser class], sResultParsers = [[NSMutableSet alloc] init];
[BookmarkDoCoMoResultParser class], }
[TelResultParser class], [sResultParsers addObject:resultParser];
[GeoResultParser class], }
[SMSTOResultParser class], [pool drain];
[SMSResultParser class], }
[URLTOResultParser class],
[URLResultParser class], + (NSSet *)resultParsers {
[PlainEmailResultParser class], NSSet *resultParsers = nil;
[TextResultParser class], @synchronized(self) {
nil]; resultParsers = [[sResultParsers copy] autorelease];
} }
return resultParsers; return resultParsers;
} }

View file

@ -31,6 +31,6 @@
@property (nonatomic, copy) NSString *number; @property (nonatomic, copy) NSString *number;
@property (nonatomic, copy) NSString *body; @property (nonatomic, copy) NSString *body;
- initWithNumber:(NSString *)n body:(NSString *)b; - (id)initWithNumber:(NSString *)n body:(NSString *)b;
@end @end

View file

@ -27,7 +27,7 @@
@synthesize number; @synthesize number;
@synthesize body; @synthesize body;
- initWithNumber:(NSString *)n body:(NSString *)b { - (id)initWithNumber:(NSString *)n body:(NSString *)b {
if ((self = [super init]) != nil) { if ((self = [super init]) != nil) {
self.number = n; self.number = n;
self.body = b; self.body = b;

View file

@ -26,6 +26,10 @@
@implementation SMSResultParser @implementation SMSResultParser
+ (void)load {
[ResultParser registerResultParserClass:self];
}
+ (ParsedResult *)parsedResultForString:(NSString *)s { + (ParsedResult *)parsedResultForString:(NSString *)s {
NSRange prefixRange = [s rangeOfString:PREFIX options:NSCaseInsensitiveSearch]; NSRange prefixRange = [s rangeOfString:PREFIX options:NSCaseInsensitiveSearch];
if (prefixRange.location == 0) { if (prefixRange.location == 0) {

View file

@ -26,6 +26,10 @@
@implementation SMSTOResultParser @implementation SMSTOResultParser
+ (void)load {
[ResultParser registerResultParserClass:self];
}
+ (ParsedResult *)parsedResultForString:(NSString *)s { + (ParsedResult *)parsedResultForString:(NSString *)s {
NSRange prefixRange = [s rangeOfString:PREFIX options:NSCaseInsensitiveSearch]; NSRange prefixRange = [s rangeOfString:PREFIX options:NSCaseInsensitiveSearch];
if (prefixRange.location == 0) { if (prefixRange.location == 0) {

View file

@ -32,6 +32,6 @@
@property (nonatomic, copy) NSString *text; @property (nonatomic, copy) NSString *text;
@property (nonatomic, retain) NSDate *stamp; @property (nonatomic, retain) NSDate *stamp;
- initWithIdent:(int)i text:(NSString *)t stamp:(NSDate *)s; - (id)initWithIdent:(int)i text:(NSString *)t stamp:(NSDate *)s;
@end @end

View file

@ -28,7 +28,7 @@
@synthesize text; @synthesize text;
@synthesize stamp; @synthesize stamp;
- initWithIdent:(int)i text:(NSString *)t stamp:(NSDate *)s { - (id)initWithIdent:(int)i text:(NSString *)t stamp:(NSDate *)s {
if ((self = [super init]) != nil) { if ((self = [super init]) != nil) {
self.ident = i; self.ident = i;
self.text = t; self.text = t;

View file

@ -66,7 +66,7 @@ static NSString *_timeString(NSDate *date) {
- (id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier { - (id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) { if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier])) {
imageView = [[UIImageView alloc] initWithFrame:CGRectZero]; imageView = [[UIImageView alloc] initWithFrame:CGRectZero];
imageView.contentMode = UIViewContentModeCenter; imageView.contentMode = UIViewContentModeCenter;
[self.contentView addSubview:imageView]; [self.contentView addSubview:imageView];

View file

@ -39,7 +39,7 @@
#define FONT_SIZE 16 #define FONT_SIZE 16
- (id)initWithResult:(ParsedResult *)r forScan:(Scan *)s { - (id)initWithResult:(ParsedResult *)r forScan:(Scan *)s {
if (self = [super initWithStyle:UITableViewStyleGrouped]) { if ((self = [super initWithStyle:UITableViewStyleGrouped])) {
self.result = r; self.result = r;
self.scan = s; self.scan = s;
self.title = NSLocalizedString(@"ScanViewController title", @"Scan"); self.title = NSLocalizedString(@"ScanViewController title", @"Scan");
@ -86,9 +86,10 @@
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:DatetimeIdentifier]; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:DatetimeIdentifier];
if (cell == nil) { if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectMake(0, 0, 320, 34) reuseIdentifier:DatetimeIdentifier] autorelease]; cell = [[[UITableViewCell alloc] initWithFrame:CGRectMake(0, 0, 320, 34) reuseIdentifier:DatetimeIdentifier] autorelease];
cell.font = [UIFont systemFontOfSize:[UIFont systemFontSize] * 2.0 / 3.0]; UILabel *label = [cell textLabel];
cell.textColor = [UIColor grayColor]; label.font = [UIFont systemFontOfSize:[UIFont systemFontSize] * 2.0 / 3.0];
cell.textAlignment = UITextAlignmentCenter; label.textColor = [UIColor grayColor];
label.textAlignment = UITextAlignmentCenter;
} }
return cell; return cell;
} }
@ -152,15 +153,18 @@
if (indexPath.section == 0) { if (indexPath.section == 0) {
if (indexPath.row == 0) { if (indexPath.row == 0) {
cell = [self titleCellInTableView:tableView]; cell = [self titleCellInTableView:tableView];
cell.image = [result icon]; UIImageView *imageView = cell.imageView;
cell.text = [[result class] typeName]; imageView.image = [result icon];
UILabel *textLabel = cell.textLabel;
textLabel.text = [[result class] typeName];
} else if (indexPath.row == 1) { } else if (indexPath.row == 1) {
cell = [self bodyCellInTableView:tableView]; cell = [self bodyCellInTableView:tableView];
UITextView *textView = (UITextView *)[cell viewWithTag:TEXT_VIEW_TAG]; UITextView *textView = (UITextView *)[cell viewWithTag:TEXT_VIEW_TAG];
textView.text = [result stringForDisplay]; textView.text = [result stringForDisplay];
} else if (indexPath.row == 2) { } else if (indexPath.row == 2) {
cell = [self datetimeCellInTableView:tableView]; cell = [self datetimeCellInTableView:tableView];
cell.text = [dateFormatter stringFromDate:[scan stamp]]; UILabel *textLabel = cell.textLabel;
textLabel.text = [dateFormatter stringFromDate:[scan stamp]];
} }
} else if (indexPath.section == 1) { } else if (indexPath.section == 1) {
cell = [self buttonCellInTableView:tableView]; cell = [self buttonCellInTableView:tableView];

View file

@ -25,7 +25,7 @@
@implementation ScannedImageView @implementation ScannedImageView
- (id)initWithFrame:(CGRect)frame { - (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) { if ((self = [super initWithFrame:frame])) {
resultPoints = [[NSMutableArray alloc] initWithCapacity:10]; resultPoints = [[NSMutableArray alloc] initWithCapacity:10];
} }
return self; return self;

View file

@ -28,7 +28,7 @@
@property (nonatomic, copy) NSString *location; @property (nonatomic, copy) NSString *location;
- initWithLocation:(NSString *)location; - (id)initWithLocation:(NSString *)location;
+ actionWithLocation:(NSString *)location; + (id)actionWithLocation:(NSString *)location;
@end @end

View file

@ -32,14 +32,14 @@ static NSURL * URLForLocation(NSString *location) {
return [NSURL URLWithString:urlString]; return [NSURL URLWithString:urlString];
} }
- initWithLocation:(NSString *)l { - (id)initWithLocation:(NSString *)l {
if ((self = [super initWithURL:URLForLocation(l)]) != nil) { if ((self = [super initWithURL:URLForLocation(l)]) != nil) {
self.location = l; self.location = l;
} }
return self; return self;
} }
+ actionWithLocation:(NSString *)location { + (id)actionWithLocation:(NSString *)location {
return [[[self alloc] initWithLocation:location] autorelease]; return [[[self alloc] initWithLocation:location] autorelease];
} }

Some files were not shown because too many files have changed in this diff Show more