1// Copyright 2014 PDFium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
6// Original code is licensed as follows:
7/*
8 * Copyright 2010 ZXing authors
9 *
10 * Licensed under the Apache License, Version 2.0 (the "License");
11 * you may not use this file except in compliance with the License.
12 * You may obtain a copy of the License at
13 *
14 *      http://www.apache.org/licenses/LICENSE-2.0
15 *
16 * Unless required by applicable law or agreed to in writing, software
17 * distributed under the License is distributed on an "AS IS" BASIS,
18 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 * See the License for the specific language governing permissions and
20 * limitations under the License.
21 */
22
23#include "fxbarcode/oned/BC_OnedCode39Writer.h"
24
25#include <memory>
26
27#include "fxbarcode/BC_Writer.h"
28#include "fxbarcode/common/BC_CommonBitMatrix.h"
29#include "fxbarcode/oned/BC_OneDimWriter.h"
30
31namespace {
32
33const char kOnedCode39Alphabet[] = {
34    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
35    'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
36    'U', 'V', 'W', 'X', 'Y', 'Z', '-', '.', ' ', '*', '$', '/', '+', '%'};
37constexpr size_t kOnedCode39AlphabetLen = FX_ArraySize(kOnedCode39Alphabet);
38
39const char kOnedCode39Checksum[] = {
40    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
41    'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
42    'U', 'V', 'W', 'X', 'Y', 'Z', '-', '.', ' ', '$', '/', '+', '%'};
43static_assert(FX_ArraySize(kOnedCode39Checksum) == 43, "Wrong size");
44
45const int16_t kOnedCode39CharacterEncoding[] = {
46    0x0034, 0x0121, 0x0061, 0x0160, 0x0031, 0x0130, 0x0070, 0x0025, 0x0124,
47    0x0064, 0x0109, 0x0049, 0x0148, 0x0019, 0x0118, 0x0058, 0x000D, 0x010C,
48    0x004C, 0x001C, 0x0103, 0x0043, 0x0142, 0x0013, 0x0112, 0x0052, 0x0007,
49    0x0106, 0x0046, 0x0016, 0x0181, 0x00C1, 0x01C0, 0x0091, 0x0190, 0x00D0,
50    0x0085, 0x0184, 0x00C4, 0x0094, 0x00A8, 0x00A2, 0x008A, 0x002A};
51static_assert(FX_ArraySize(kOnedCode39CharacterEncoding) == 44, "Wrong size");
52
53}  // namespace
54
55CBC_OnedCode39Writer::CBC_OnedCode39Writer() : m_iWideNarrRatio(3) {}
56
57CBC_OnedCode39Writer::~CBC_OnedCode39Writer() {}
58
59bool CBC_OnedCode39Writer::CheckContentValidity(
60    const WideStringView& contents) {
61  for (size_t i = 0; i < contents.GetLength(); i++) {
62    wchar_t ch = contents[i];
63    if ((ch >= L'0' && ch <= L'9') || (ch >= L'A' && ch <= L'Z') ||
64        ch == L'-' || ch == L'.' || ch == L' ' || ch == L'*' || ch == L'$' ||
65        ch == L'/' || ch == L'+' || ch == L'%') {
66      continue;
67    }
68    return false;
69  }
70  return true;
71}
72
73WideString CBC_OnedCode39Writer::FilterContents(
74    const WideStringView& contents) {
75  WideString filtercontents;
76  for (size_t i = 0; i < contents.GetLength(); i++) {
77    wchar_t ch = contents[i];
78    if (ch == L'*' && (i == 0 || i == contents.GetLength() - 1)) {
79      continue;
80    }
81    if (ch > 175) {
82      i++;
83      continue;
84    }
85    ch = Upper(ch);
86    if ((ch >= L'0' && ch <= L'9') || (ch >= L'A' && ch <= L'Z') ||
87        ch == L'-' || ch == L'.' || ch == L' ' || ch == L'*' || ch == L'$' ||
88        ch == L'/' || ch == L'+' || ch == L'%') {
89      filtercontents += ch;
90    }
91  }
92  return filtercontents;
93}
94
95WideString CBC_OnedCode39Writer::RenderTextContents(
96    const WideStringView& contents) {
97  WideString renderContents;
98  for (size_t i = 0; i < contents.GetLength(); i++) {
99    wchar_t ch = contents[i];
100    if (ch == L'*' && (i == 0 || i == contents.GetLength() - 1)) {
101      continue;
102    }
103    if (ch > 175) {
104      i++;
105      continue;
106    }
107    if ((ch >= L'0' && ch <= L'9') || (ch >= L'A' && ch <= L'Z') ||
108        (ch >= L'a' && ch <= L'z') || ch == L'-' || ch == L'.' || ch == L' ' ||
109        ch == L'*' || ch == L'$' || ch == L'/' || ch == L'+' || ch == L'%') {
110      renderContents += ch;
111    }
112  }
113  return renderContents;
114}
115
116bool CBC_OnedCode39Writer::SetTextLocation(BC_TEXT_LOC location) {
117  if (location < BC_TEXT_LOC_NONE || location > BC_TEXT_LOC_BELOWEMBED) {
118    return false;
119  }
120  m_locTextLoc = location;
121  return true;
122}
123bool CBC_OnedCode39Writer::SetWideNarrowRatio(int8_t ratio) {
124  if (ratio < 2 || ratio > 3)
125    return false;
126
127  m_iWideNarrRatio = ratio;
128  return true;
129}
130
131uint8_t* CBC_OnedCode39Writer::EncodeWithHint(const ByteString& contents,
132                                              BCFORMAT format,
133                                              int32_t& outWidth,
134                                              int32_t& outHeight,
135                                              int32_t hints) {
136  if (format != BCFORMAT_CODE_39)
137    return nullptr;
138  return CBC_OneDimWriter::EncodeWithHint(contents, format, outWidth, outHeight,
139                                          hints);
140}
141
142void CBC_OnedCode39Writer::ToIntArray(int16_t a, int8_t* toReturn) {
143  for (int32_t i = 0; i < 9; i++) {
144    toReturn[i] = (a & (1 << i)) == 0 ? 1 : m_iWideNarrRatio;
145  }
146}
147
148char CBC_OnedCode39Writer::CalcCheckSum(const ByteString& contents) {
149  if (contents.GetLength() > 80)
150    return '*';
151
152  int32_t checksum = 0;
153  for (const auto& c : contents) {
154    size_t j = 0;
155    for (; j < kOnedCode39AlphabetLen; j++) {
156      if (kOnedCode39Alphabet[j] == c) {
157        if (c != '*')
158          checksum += j;
159        break;
160      }
161    }
162    if (j >= kOnedCode39AlphabetLen)
163      return '*';
164  }
165  return kOnedCode39Checksum[checksum % FX_ArraySize(kOnedCode39Checksum)];
166}
167
168uint8_t* CBC_OnedCode39Writer::EncodeImpl(const ByteString& contents,
169                                          int32_t& outlength) {
170  char checksum = CalcCheckSum(contents);
171  if (checksum == '*')
172    return nullptr;
173
174  int8_t widths[9] = {0};
175  int32_t wideStrideNum = 3;
176  int32_t narrStrideNum = 9 - wideStrideNum;
177  ByteString encodedContents = contents;
178  if (m_bCalcChecksum)
179    encodedContents += checksum;
180  m_iContentLen = encodedContents.GetLength();
181  int32_t codeWidth = (wideStrideNum * m_iWideNarrRatio + narrStrideNum) * 2 +
182                      1 + m_iContentLen;
183  for (size_t j = 0; j < m_iContentLen; j++) {
184    for (size_t i = 0; i < kOnedCode39AlphabetLen; i++) {
185      if (kOnedCode39Alphabet[i] != encodedContents[j])
186        continue;
187
188      ToIntArray(kOnedCode39CharacterEncoding[i], widths);
189      for (size_t k = 0; k < 9; k++)
190        codeWidth += widths[k];
191    }
192  }
193  outlength = codeWidth;
194  std::unique_ptr<uint8_t, FxFreeDeleter> result(FX_Alloc(uint8_t, codeWidth));
195  ToIntArray(kOnedCode39CharacterEncoding[39], widths);
196  int32_t e = BCExceptionNO;
197  int32_t pos = AppendPattern(result.get(), 0, widths, 9, 1, e);
198  if (e != BCExceptionNO)
199    return nullptr;
200
201  int8_t narrowWhite[] = {1};
202  pos += AppendPattern(result.get(), pos, narrowWhite, 1, 0, e);
203  if (e != BCExceptionNO)
204    return nullptr;
205
206  for (int32_t l = m_iContentLen - 1; l >= 0; l--) {
207    for (size_t i = 0; i < kOnedCode39AlphabetLen; i++) {
208      if (kOnedCode39Alphabet[i] != encodedContents[l])
209        continue;
210
211      ToIntArray(kOnedCode39CharacterEncoding[i], widths);
212      pos += AppendPattern(result.get(), pos, widths, 9, 1, e);
213      if (e != BCExceptionNO)
214        return nullptr;
215    }
216    pos += AppendPattern(result.get(), pos, narrowWhite, 1, 0, e);
217    if (e != BCExceptionNO)
218      return nullptr;
219  }
220  ToIntArray(kOnedCode39CharacterEncoding[39], widths);
221  pos += AppendPattern(result.get(), pos, widths, 9, 1, e);
222  if (e != BCExceptionNO)
223    return nullptr;
224
225  auto* result_ptr = result.get();
226  for (int32_t i = 0; i < codeWidth / 2; i++) {
227    result_ptr[i] ^= result_ptr[codeWidth - 1 - i];
228    result_ptr[codeWidth - 1 - i] ^= result_ptr[i];
229    result_ptr[i] ^= result_ptr[codeWidth - 1 - i];
230  }
231  return result.release();
232}
233
234bool CBC_OnedCode39Writer::encodedContents(const WideStringView& contents,
235                                           WideString* result) {
236  *result = WideString(contents);
237  if (m_bCalcChecksum && m_bPrintChecksum) {
238    WideString checksumContent = FilterContents(contents);
239    ByteString str = checksumContent.UTF8Encode();
240    char checksum;
241    checksum = CalcCheckSum(str);
242    if (checksum == '*')
243      return false;
244    str += checksum;
245    *result += checksum;
246  }
247  return true;
248}
249
250bool CBC_OnedCode39Writer::RenderResult(const WideStringView& contents,
251                                        uint8_t* code,
252                                        int32_t codeLength) {
253  WideString encodedCon;
254  if (!encodedContents(contents, &encodedCon))
255    return false;
256  return CBC_OneDimWriter::RenderResult(encodedCon.AsStringView(), code,
257                                        codeLength);
258}
259