1 // Copyright 2018 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 
7 #include "fxbarcode/cbc_eancode.h"
8 
9 #include <utility>
10 
11 #include "core/fxcrt/fx_memory_wrappers.h"
12 #include "fxbarcode/oned/BC_OnedEANWriter.h"
13 
CBC_EANCode(std::unique_ptr<CBC_OneDimEANWriter> pWriter)14 CBC_EANCode::CBC_EANCode(std::unique_ptr<CBC_OneDimEANWriter> pWriter)
15     : CBC_OneCode(std::move(pWriter)) {}
16 
17 CBC_EANCode::~CBC_EANCode() = default;
18 
GetOneDimEANWriter()19 CBC_OneDimEANWriter* CBC_EANCode::GetOneDimEANWriter() {
20   return static_cast<CBC_OneDimEANWriter*>(m_pBCWriter.get());
21 }
22 
Encode(WideStringView contents)23 bool CBC_EANCode::Encode(WideStringView contents) {
24   if (contents.IsEmpty() || contents.GetLength() > kMaxInputLengthBytes)
25     return false;
26 
27   BCFORMAT format = GetFormat();
28   int32_t out_width = 0;
29   int32_t out_height = 0;
30   m_renderContents = Preprocess(contents);
31   ByteString str = m_renderContents.ToUTF8();
32   auto* pWriter = GetOneDimEANWriter();
33   pWriter->InitEANWriter();
34   std::unique_ptr<uint8_t, FxFreeDeleter> data(
35       pWriter->Encode(str, format, out_width, out_height));
36   return data && pWriter->RenderResult(m_renderContents.AsStringView(),
37                                        data.get(), out_width);
38 }
39 
RenderDevice(CFX_RenderDevice * device,const CFX_Matrix * matrix)40 bool CBC_EANCode::RenderDevice(CFX_RenderDevice* device,
41                                const CFX_Matrix* matrix) {
42   return GetOneDimEANWriter()->RenderDeviceResult(
43       device, matrix, m_renderContents.AsStringView());
44 }
45 
Preprocess(WideStringView contents)46 WideString CBC_EANCode::Preprocess(WideStringView contents) {
47   auto* pWriter = GetOneDimEANWriter();
48   WideString encoded_contents = pWriter->FilterContents(contents);
49   size_t length = encoded_contents.GetLength();
50   size_t max_length = GetMaxLength();
51   if (length <= max_length) {
52     for (size_t i = 0; i < max_length - length; i++)
53       encoded_contents.InsertAtFront(L'0');
54 
55     ByteString str = encoded_contents.ToUTF8();
56     int32_t checksum = pWriter->CalcChecksum(str);
57     str += '0' + checksum;
58     encoded_contents = WideString::FromUTF8(str.AsStringView());
59   } else {
60     encoded_contents = encoded_contents.First(max_length + 1);
61   }
62 
63   return encoded_contents;
64 }
65