Wrote a new ByteArray class to replace StringPiece and fixed all uses of it. Also...
[zxing.git] / core / src / com / google / zxing / qrcode / encoder / QRCode.java
1 /*
2  * Copyright 2008 ZXing authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package com.google.zxing.qrcode.encoder;
18
19 /**
20  * @author satorux@google.com (Satoru Takabayashi) - creator
21  * @author dswitkin@google.com (Daniel Switkin) - ported from C++
22  */
23 public final class QRCode {
24
25   // Magic numbers.
26   public static final int kMinVersion = 1;
27   public static final int kMaxVersion = 40;
28   // For matrix width, see 7.3.1 of JISX0510:2004 (p.5).
29   public static final int kMinMatrixWidth = 21;  // Version 1
30   public static final int kMaxMatrixWidth = 177;  // Version 40 (21 + 4 * (40 -1)).
31   public static final int kNumMaskPatterns = 8;
32
33   // See table 3 of JISX0510:2004 (p.16)
34   private static final int kNumBitsTable[][] = {
35       // NUMERIC  ALPHANUMERIC  8BIT_BYTE  KANJI
36       {       10,            9,         8,     8 },  // Version 1-9
37       {       12,           11,        16,    10 },  // Version 10-26
38       {       14,           13,        16,    12 },  // Version 27-40
39   };
40
41   // JAVAPORT: Do not remove trailing slashes yet. There are very likely conflicts with local
42   // variables and parameters which will introduce insidious bugs.
43   private int mode_;
44   private int ec_level_;
45   private int version_;
46   private int matrix_width_;
47   private int mask_pattern_;
48   private int num_total_bytes_;
49   private int num_data_bytes_;
50   private int num_ec_bytes_;
51   private int num_rs_blocks_;
52   private Matrix matrix_;
53
54
55   // They call encoding "mode". The modes are defined in 8.3 of JISX0510:2004 (p.14). It's unlikely
56   // (probably we will not support complicated modes) but if you add an item to this, please also
57   // add it to ModeToString(), GetModeCode(), GetNumBitsForLength(), Encoder.AppendBytes(), and
58   // Encoder.ChooseMode().
59   //
60   // JAVAPORT: These used to be C++ enums, but the code evaluates them as integers, and requires
61   // negative values. I don't want to take the ParsedResultType approach of a class full of statics
62   // of that class's type. The best compromise here is integer constants.
63   //
64   // Formerly enum Mode
65   public static final int MODE_UNDEFINED = -1;
66   public static final int MODE_NUMERIC = 0;
67   public static final int MODE_ALPHANUMERIC = 1;
68   public static final int MODE_8BIT_BYTE = 2;
69   public static final int MODE_KANJI = 3;  // Shift_JIS
70   // The following modes are unimplemented.
71   // MODE_ECI,
72   // MODE_MIXED,
73   // MODE_CONCATENATED,
74   // MODE_FNC1,
75   public static final int NUM_MODES = 4;
76
77   // The error correction levels are defined in the table 22 of JISX0510:2004 (p.45). It's very
78   // unlikely (we've already covered all of them!)  but if you add an item to this, please also add
79   // it to ECLevelToString() and GetECLevelCode().
80   //
81   // Formerly enum ECLevel
82   public static final int EC_LEVEL_UNDEFINED  = -1;
83   // They don't have names in the standard!
84   public static final int EC_LEVEL_L = 0;  //  7% of corruption can be recovered.
85   public static final int EC_LEVEL_M = 1;  // 15%
86   public static final int EC_LEVEL_Q = 2;  // 25%
87   public static final int EC_LEVEL_H = 3;  // 30%
88   public static final int NUM_EC_LEVELS = 4;
89
90   public QRCode() {
91     mode_ = MODE_UNDEFINED;
92     ec_level_ = EC_LEVEL_UNDEFINED;
93     version_ = -1;
94     matrix_width_ = -1;
95     mask_pattern_ = -1;
96     num_total_bytes_ = -1;
97     num_data_bytes_ = -1;
98     num_ec_bytes_ = -1;
99     num_rs_blocks_ = -1;
100     matrix_ = null;
101   }
102
103   // Mode of the QR Code.
104   public int mode() { return mode_; }
105   // Error correction level of the QR Code.
106   public int ec_level() { return ec_level_; }
107   // Version of the QR Code.  The bigger size, the bigger version.
108   public int version() { return version_; }
109   // Matrix width of the QR Code.
110   public int matrix_width() { return matrix_width_; }
111   // Mask pattern of the QR Code.
112   public int mask_pattern() { return mask_pattern_; }
113   // Number of total bytes in the QR Code.
114   public int num_total_bytes() { return num_total_bytes_; }
115   // Number of data bytes in the QR Code.
116   public int num_data_bytes() { return num_data_bytes_; }
117   // Number of error correction bytes in the QR Code.
118   public int num_ec_bytes() { return num_ec_bytes_; }
119   // Number of Reedsolomon blocks in the QR Code.
120   public int num_rs_blocks() { return num_rs_blocks_; }
121   // Matrix data of the QR Code.
122   public final Matrix matrix() { return matrix_; }
123
124   // Return the value of the module (cell) pointed by "x" and "y" in the matrix of the QR Code. They
125   // call cells in the matrix "modules". 1 represents a black cell, and 0 represents a white cell.
126   public int at(int x, int y) {
127     // The value must be zero or one.
128     int value = matrix_.get(y, x);
129     Debug.DCHECK(value == 0 || value == 1);
130     return value;
131   }
132
133   // Checks all the member variables are set properly. Returns true on success. Otherwise, returns
134   // false.
135   // JAVAPORT: Do not call EverythingIsBinary(matrix_) here as it is very expensive.
136   public boolean IsValid() {
137     return (
138         // First check if all version are not uninitialized.
139         mode_ != MODE_UNDEFINED &&
140             ec_level_ != EC_LEVEL_UNDEFINED &&
141             version_ != -1 &&
142             matrix_width_ != -1 &&
143             mask_pattern_ != -1 &&
144             num_total_bytes_ != -1 &&
145             num_data_bytes_ != -1 &&
146             num_ec_bytes_ != -1 &&
147             num_rs_blocks_ != -1 &&
148             // Then check them in other ways..
149             IsValidVersion(version_) &&
150             IsValidMode(mode_) &&
151             IsValidECLevel(ec_level_) &&
152             IsValidMatrixWidth(matrix_width_) &&
153             IsValidMaskPattern(mask_pattern_) &&
154             num_total_bytes_ == num_data_bytes_ + num_ec_bytes_ &&
155             // Matrix stuff.
156             matrix_ != null &&
157             matrix_width_ == matrix_.width() &&
158             // See 7.3.1 of JISX0510:2004 (p.5).
159             matrix_width_ == kMinMatrixWidth + (version_ - 1) * 4 &&
160             matrix_.width() == matrix_.height()); // Must be square.
161   }
162
163   // Return debug String.
164   public String toString() {
165     StringBuffer result = new StringBuffer();
166     result.append("<<QRCode\n");
167     result.append(" mode: ");
168     result.append(ModeToString(mode_));
169     result.append("\n ec_level: ");
170     result.append(ECLevelToString(ec_level_));
171     result.append("\n version: ");
172     result.append(version_);
173     result.append("\n matrix_width: ");
174     result.append(matrix_width_);
175     result.append("\n mask_pattern: ");
176     result.append(mask_pattern_);
177     result.append("\n num_total_bytes_: ");
178     result.append(num_total_bytes_);
179     result.append("\n num_data_bytes: ");
180     result.append(num_data_bytes_);
181     result.append("\n num_ec_bytes: ");
182     result.append(num_ec_bytes_);
183     result.append("\n num_rs_blocks: ");
184     result.append(num_rs_blocks_);
185     if (matrix_ == null) {
186       result.append("\n matrix: null");
187     } else {
188       result.append("\n matrix:");
189       result.append(matrix_.toString());
190     }
191     result.append("\n>>\n");
192     return result.toString();
193   }
194
195   public void set_mode(int value) {
196     mode_ = value;
197   }
198
199   public void set_ec_level(int value) {
200     ec_level_ = value;
201   }
202
203   public void set_version(int value) {
204     version_ = value;
205   }
206
207   public void set_matrix_width(int value) {
208     matrix_width_ = value;
209   }
210
211   public void set_mask_pattern(int value) {
212     mask_pattern_ = value;
213   }
214
215   public void set_num_total_bytes(int value) {
216     num_total_bytes_ = value;
217   }
218
219   public void set_num_data_bytes(int value) {
220     num_data_bytes_ = value;
221   }
222
223   public void set_num_ec_bytes(int value) {
224     num_ec_bytes_ = value;
225   }
226
227   public void set_num_rs_blocks(int value) {
228     num_rs_blocks_ = value;
229   }
230
231   // This takes ownership of the 2D array.  The 2D array will be
232   // deleted in the destructor of the class.
233   public void set_matrix(Matrix value) {
234     matrix_ = value;
235   }
236
237   // Check if "version" is valid.
238   public static boolean IsValidVersion(final int version) {
239     return version >= kMinVersion && version <= kMaxVersion;
240   }
241
242   // Check if "mask_pattern" is valid.
243   public static boolean IsValidECLevel(int ec_level) {
244     return ec_level >= 0 && ec_level < NUM_EC_LEVELS;
245   }
246
247   // Check if "mode" is valid.
248   public static boolean IsValidMode(final int mode) {
249     return mode >= 0 && mode < NUM_MODES;
250   }
251
252   // Check if "width" is valid.
253   public static boolean IsValidMatrixWidth(int width) {
254     return width >= kMinMatrixWidth && width <= kMaxMatrixWidth;
255   }
256
257   // Check if "mask_pattern" is valid.
258   public static boolean IsValidMaskPattern(int mask_pattern) {
259     return mask_pattern >= 0 && mask_pattern < kNumMaskPatterns;
260   }
261
262   // Convert "ec_level" to String for debugging.
263   public static final String ECLevelToString(int ec_level) {
264     switch (ec_level) {
265       case QRCode.EC_LEVEL_UNDEFINED:
266         return "UNDEFINED";
267       case QRCode.EC_LEVEL_L:
268         return "L";
269       case QRCode.EC_LEVEL_M:
270         return "M";
271       case QRCode.EC_LEVEL_Q:
272         return "Q";
273       case QRCode.EC_LEVEL_H:
274         return "H";
275       default:
276         break;
277     }
278     return "UNKNOWN";
279   }
280
281   // Convert "mode" to String for debugging.
282   public static final String ModeToString(int mode) {
283     switch (mode) {
284       case QRCode.MODE_UNDEFINED:
285         return "UNDEFINED";
286       case QRCode.MODE_NUMERIC:
287         return "NUMERIC";
288       case QRCode.MODE_ALPHANUMERIC:
289         return "ALPHANUMERIC";
290       case QRCode.MODE_8BIT_BYTE:
291         return "8BIT_BYTE";
292       case QRCode.MODE_KANJI:
293         return "KANJI";
294       default:
295         break;
296     }
297     return "UNKNOWN";
298   }
299
300   // Return the code of error correction level. On error, return -1. The codes of error correction
301   // levels are defined in the table 22 of JISX0510:2004 (p.45).
302   public static int GetECLevelCode(final int ec_level) {
303     switch (ec_level) {
304       case QRCode.EC_LEVEL_L:
305         return 1;
306       case QRCode.EC_LEVEL_M:
307         return 0;
308       case QRCode.EC_LEVEL_Q:
309         return 3;
310       case QRCode.EC_LEVEL_H:
311         return 2;
312       default:
313         break;
314     }
315     return -1;  // Unknown error correction level.
316   }
317
318   // Return the code of mode. On error, return -1. The codes of modes are defined in the table 2 of
319   // JISX0510:2004 (p.16).
320   public static int GetModeCode(final int mode) {
321     switch (mode) {
322       case QRCode.MODE_NUMERIC:
323         return 1;
324       case QRCode.MODE_ALPHANUMERIC:
325         return 2;
326       case QRCode.MODE_8BIT_BYTE:
327         return 4;
328       case QRCode.MODE_KANJI:
329         return 8;
330       default:
331         break;
332     }
333     return -1;  // Unknown mode.
334   }
335
336   // Return the number of bits needed for representing the length info of QR Code with "version" and
337   // "mode". On error, return -1.
338   public static int GetNumBitsForLength(int version, int mode) {
339     if (!IsValidVersion(version)) {
340       Debug.LOG_ERROR("Invalid version: " + version);
341       return -1;
342     }
343     if (!IsValidMode(mode)) {
344       Debug.LOG_ERROR("Invalid mode: " + mode);
345       return -1;
346     }
347     if (version >= 1 && version <= 9) {
348       return kNumBitsTable[0][mode];
349     } else if (version >= 10 && version <= 26) {
350       return kNumBitsTable[1][mode];
351     } else if (version >= 27 && version <= 40) {
352       return kNumBitsTable[2][mode];
353     } else {
354       Debug.LOG_ERROR("Should not reach");
355     }
356     return -1;
357   }
358
359   // Return true if the all values in the matrix are binary numbers. Otherwise, return false.
360   //
361   // JAVAPORT: This is going to be super expensive and unnecessary, we should not call this in
362   // production. I'm leaving it because it may be useful for testing. It should be removed entirely
363   // if Matrix is changed never to contain a -1.
364   private static boolean EverythingIsBinary(final Matrix matrix) {
365     for (int y = 0; y < matrix.height(); ++y) {
366       for (int x = 0; x < matrix.width(); ++x) {
367         int value = matrix.get(y, x);
368         if (!(value == 0 || value == 1)) {
369           // Found non zero/one value.
370           return false;
371         }
372       }
373     }
374     return true;
375   }
376
377 }