Added rendering fix from beyonddeath
[zxing.git] / csharp / qrcode / decoder / DecodedBitStreamParser.cs
1 /*\r
2 * Licensed under the Apache License, Version 2.0 (the "License");\r
3 * you may not use this file except in compliance with the License.\r
4 * You may obtain a copy of the License at\r
5 *\r
6 *      http://www.apache.org/licenses/LICENSE-2.0\r
7 *\r
8 * Unless required by applicable law or agreed to in writing, software\r
9 * distributed under the License is distributed on an "AS IS" BASIS,\r
10 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
11 * See the License for the specific language governing permissions and\r
12 * limitations under the License.\r
13 */\r
14 \r
15 using System;\r
16 using ReaderException = com.google.zxing.ReaderException;\r
17 using com.google.zxing.common;\r
18 namespace com.google.zxing.qrcode.decoder\r
19 {\r
20 \r
21     /// <summary> <p>QR Codes can encode text as bits in one of several modes, and can use multiple modes\r
22     /// in one QR Code. This class decodes the bits back into text.</p>\r
23     /// \r
24     /// <p>See ISO 18004:2006, 6.4.3 - 6.4.7</p>\r
25     /// \r
26     /// </summary>\r
27     /// <author>  srowen@google.com (Sean Owen)\r
28     /// </author>\r
29     public sealed class DecodedBitStreamParser\r
30     {\r
31 \r
32         /// <summary> See ISO 18004:2006, 6.4.4 Table 5</summary>\r
33         //UPGRADE_NOTE: Final was removed from the declaration of 'ALPHANUMERIC_CHARS '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"\r
34         private static readonly char[] ALPHANUMERIC_CHARS = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' ', '$', '%', '*', '+', '-', '.', '/', ':' };\r
35         private const System.String SHIFT_JIS = "Shift_JIS";\r
36         private static bool ASSUME_SHIFT_JIS;\r
37 \r
38         private DecodedBitStreamParser()\r
39         {\r
40         }\r
41 \r
42         internal static System.String decode(sbyte[] bytes, Version version)\r
43         {\r
44             BitSource bits = new BitSource(bytes);\r
45             System.Text.StringBuilder result = new System.Text.StringBuilder();\r
46             Mode mode;\r
47             do\r
48             {\r
49                 // While still another segment to read...\r
50                 mode = Mode.forBits(bits.readBits(4)); // mode is encoded by 4 bits\r
51                 if (!mode.Equals(Mode.TERMINATOR))\r
52                 {\r
53                     // How many characters will follow, encoded in this mode?\r
54                     int count = bits.readBits(mode.getCharacterCountBits(version));\r
55                     if (mode.Equals(Mode.NUMERIC))\r
56                     {\r
57                         decodeNumericSegment(bits, result, count);\r
58                     }\r
59                     else if (mode.Equals(Mode.ALPHANUMERIC))\r
60                     {\r
61                         decodeAlphanumericSegment(bits, result, count);\r
62                     }\r
63                     else if (mode.Equals(Mode.BYTE))\r
64                     {\r
65                         decodeByteSegment(bits, result, count);\r
66                     }\r
67                     else if (mode.Equals(Mode.KANJI))\r
68                     {\r
69                         decodeKanjiSegment(bits, result, count);\r
70                     }\r
71                     else\r
72                     {\r
73                         throw new ReaderException("Unsupported mode indicator");\r
74                     }\r
75                 }\r
76             }\r
77             while (!mode.Equals(Mode.TERMINATOR));\r
78 \r
79             // I thought it wasn't allowed to leave extra bytes after the terminator but it happens\r
80             /*\r
81             int bitsLeft = bits.available();\r
82             if (bitsLeft > 0) {\r
83             if (bitsLeft > 6 || bits.readBits(bitsLeft) != 0) {\r
84             throw new ReaderException("Excess bits or non-zero bits after terminator mode indicator");\r
85             }\r
86             }\r
87             */\r
88             return result.ToString();\r
89         }\r
90 \r
91         private static void decodeKanjiSegment(BitSource bits, System.Text.StringBuilder result, int count)\r
92         {\r
93             // Each character will require 2 bytes. Read the characters as 2-byte pairs\r
94             // and decode as Shift_JIS afterwards\r
95             sbyte[] buffer = new sbyte[2 * count];\r
96             int offset = 0;\r
97             while (count > 0)\r
98             {\r
99                 // Each 13 bits encodes a 2-byte character\r
100                 int twoBytes = bits.readBits(13);\r
101                 int assembledTwoBytes = ((twoBytes / 0x0C0) << 8) | (twoBytes % 0x0C0);\r
102                 if (assembledTwoBytes < 0x01F00)\r
103                 {\r
104                     // In the 0x8140 to 0x9FFC range\r
105                     assembledTwoBytes += 0x08140;\r
106                 }\r
107                 else\r
108                 {\r
109                     // In the 0xE040 to 0xEBBF range\r
110                     assembledTwoBytes += 0x0C140;\r
111                 }\r
112                 buffer[offset] = (sbyte)(assembledTwoBytes >> 8);\r
113                 buffer[offset + 1] = (sbyte)assembledTwoBytes;\r
114                 offset += 2;\r
115                 count--;\r
116             }\r
117             // Shift_JIS may not be supported in some environments:\r
118             try\r
119             {\r
120                 byte[] bytes = SupportClass.ToByteArray(buffer);\r
121                 //UPGRADE_TODO: The differences in the Format  of parameters for constructor 'java.lang.String.String'  may cause compilation errors.  "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'"\r
122                 result.Append(System.Text.Encoding.GetEncoding("Shift_JIS").GetString(bytes, 0, bytes.Length));\r
123             }\r
124             catch (System.IO.IOException uee)\r
125             {\r
126                 throw new ReaderException("SHIFT_JIS encoding is not supported on this device");\r
127             }\r
128         }\r
129 \r
130         private static void decodeByteSegment(BitSource bits, System.Text.StringBuilder result, int count)\r
131         {\r
132             sbyte[] readBytes = new sbyte[count];\r
133             if (count << 3 > bits.available())\r
134             {\r
135                 throw new ReaderException("Count too large: " + count);\r
136             }\r
137             for (int i = 0; i < count; i++)\r
138             {\r
139                 readBytes[i] = (sbyte)bits.readBits(8);\r
140             }\r
141             // The spec isn't clear on this mode; see\r
142             // section 6.4.5: t does not say which encoding to assuming\r
143             // upon decoding. I have seen ISO-8859-1 used as well as\r
144             // Shift_JIS -- without anything like an ECI designator to\r
145             // give a hint.\r
146             System.String encoding = guessEncoding(readBytes);\r
147             try\r
148             {\r
149                 byte[] bytes = SupportClass.ToByteArray(readBytes);\r
150                 //System.Windows.Forms.MessageBox.Show("encodings: "+ System.Text.Encoding.());\r
151                 //UPGRADE_TODO: The differences in the Format  of parameters for constructor 'java.lang.String.String'  may cause compilation errors.  "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'"\r
152                 result.Append(System.Text.Encoding.GetEncoding(encoding).GetString(bytes, 0, bytes.Length));\r
153             }\r
154             catch (System.IO.IOException uce)\r
155             {\r
156                 //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"\r
157                 throw new ReaderException(uce.ToString());\r
158             }\r
159         }\r
160 \r
161         private static void decodeAlphanumericSegment(BitSource bits, System.Text.StringBuilder result, int count)\r
162         {\r
163             // Read two characters at a time\r
164             while (count > 1)\r
165             {\r
166                 int nextTwoCharsBits = bits.readBits(11);\r
167                 result.Append(ALPHANUMERIC_CHARS[nextTwoCharsBits / 45]);\r
168                 result.Append(ALPHANUMERIC_CHARS[nextTwoCharsBits % 45]);\r
169                 count -= 2;\r
170             }\r
171             if (count == 1)\r
172             {\r
173                 // special case: one character left\r
174                 result.Append(ALPHANUMERIC_CHARS[bits.readBits(6)]);\r
175             }\r
176         }\r
177 \r
178         private static void decodeNumericSegment(BitSource bits, System.Text.StringBuilder result, int count)\r
179         {\r
180             // Read three digits at a time\r
181             while (count >= 3)\r
182             {\r
183                 // Each 10 bits encodes three digits\r
184                 int threeDigitsBits = bits.readBits(10);\r
185                 if (threeDigitsBits >= 1000)\r
186                 {\r
187                     throw new ReaderException("Illegal value for 3-digit unit: " + threeDigitsBits);\r
188                 }\r
189                 result.Append(ALPHANUMERIC_CHARS[threeDigitsBits / 100]);\r
190                 result.Append(ALPHANUMERIC_CHARS[(threeDigitsBits / 10) % 10]);\r
191                 result.Append(ALPHANUMERIC_CHARS[threeDigitsBits % 10]);\r
192                 count -= 3;\r
193             }\r
194             if (count == 2)\r
195             {\r
196                 // Two digits left over to read, encoded in 7 bits\r
197                 int twoDigitsBits = bits.readBits(7);\r
198                 if (twoDigitsBits >= 100)\r
199                 {\r
200                     throw new ReaderException("Illegal value for 2-digit unit: " + twoDigitsBits);\r
201                 }\r
202                 result.Append(ALPHANUMERIC_CHARS[twoDigitsBits / 10]);\r
203                 result.Append(ALPHANUMERIC_CHARS[twoDigitsBits % 10]);\r
204             }\r
205             else if (count == 1)\r
206             {\r
207                 // One digit left over to read\r
208                 int digitBits = bits.readBits(4);\r
209                 if (digitBits >= 10)\r
210                 {\r
211                     throw new ReaderException("Illegal value for digit unit: " + digitBits);\r
212                 }\r
213                 result.Append(ALPHANUMERIC_CHARS[digitBits]);\r
214             }\r
215         }\r
216 \r
217         private static System.String guessEncoding(sbyte[] bytes)\r
218         {\r
219             if (ASSUME_SHIFT_JIS)\r
220             {\r
221                 return SHIFT_JIS;\r
222             }\r
223             // For now, merely tries to distinguish ISO-8859-1 and Shift_JIS,\r
224             // which should be by far the most common encodings. ISO-8859-1\r
225             // should not have bytes in the 0x80 - 0x9F range, while Shift_JIS\r
226             // uses this as a first byte of a two-byte character. If we see this\r
227             // followed by a valid second byte in Shift_JIS, assume it is Shift_JIS.\r
228             int length = bytes.Length;\r
229             for (int i = 0; i < length; i++)\r
230             {\r
231                 int value_Renamed = bytes[i] & 0xFF;\r
232                 if (value_Renamed >= 0x80 && value_Renamed <= 0x9F && i < length - 1)\r
233                 {\r
234                     // ISO-8859-1 shouldn't use this, but before we decide it is Shift_JIS,\r
235                     // just double check that it is followed by a byte that's valid in\r
236                     // the Shift_JIS encoding\r
237                     int nextValue = bytes[i + 1] & 0xFF;\r
238                     if ((value_Renamed & 0x1) == 0)\r
239                     {\r
240                         // if even,\r
241                         if (nextValue >= 0x40 && nextValue <= 0x9E)\r
242                         {\r
243                             return SHIFT_JIS;\r
244                         }\r
245                     }\r
246                     else\r
247                     {\r
248                         if (nextValue >= 0x9F && nextValue <= 0x7C)\r
249                         {\r
250                             return SHIFT_JIS;\r
251                         }\r
252                     }\r
253                 }\r
254             }\r
255             return "ASCII";\r
256         }\r
257         //static DecodedBitStreamParser()\r
258         //{\r
259         //  {\r
260         //    //UPGRADE_ISSUE: Method 'java.lang.System.getProperty' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javalangSystem'"\r
261         //    System.String platformDefault = System_Renamed.getProperty("file.encoding");\r
262         //    ASSUME_SHIFT_JIS = SHIFT_JIS.ToUpper().Equals(platformDefault.ToUpper()) || "EUC-JP".ToUpper().Equals(platformDefault.ToUpper());\r
263         //  }\r
264         //}\r
265     }\r
266 }