Home | History | Annotate | Download | only in edit
      1 // Copyright 2017 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 "core/fpdfapi/edit/cpdf_flateencoder.h"
      8 
      9 #include <memory>
     10 
     11 #include "core/fpdfapi/parser/cpdf_name.h"
     12 #include "core/fpdfapi/parser/cpdf_number.h"
     13 #include "core/fpdfapi/parser/fpdf_parser_decode.h"
     14 
     15 CPDF_FlateEncoder::CPDF_FlateEncoder(CPDF_Stream* pStream, bool bFlateEncode)
     16     : m_dwSize(0), m_pAcc(pdfium::MakeRetain<CPDF_StreamAcc>(pStream)) {
     17   m_pAcc->LoadAllDataRaw();
     18 
     19   bool bHasFilter = pStream && pStream->HasFilter();
     20   if (bHasFilter && !bFlateEncode) {
     21     auto pDestAcc = pdfium::MakeRetain<CPDF_StreamAcc>(pStream);
     22     pDestAcc->LoadAllDataFiltered();
     23 
     24     m_dwSize = pDestAcc->GetSize();
     25     m_pData = pDestAcc->DetachData();
     26     m_pDict = ToDictionary(pStream->GetDict()->Clone());
     27     m_pDict->RemoveFor("Filter");
     28     return;
     29   }
     30   if (bHasFilter || !bFlateEncode) {
     31     m_pData = const_cast<uint8_t*>(m_pAcc->GetData());
     32     m_dwSize = m_pAcc->GetSize();
     33     m_pDict = pStream->GetDict();
     34     return;
     35   }
     36 
     37   // TODO(thestig): Move to Init() and check return value.
     38   uint8_t* buffer = nullptr;
     39   ::FlateEncode(m_pAcc->GetData(), m_pAcc->GetSize(), &buffer, &m_dwSize);
     40 
     41   m_pData = std::unique_ptr<uint8_t, FxFreeDeleter>(buffer);
     42   m_pDict = ToDictionary(pStream->GetDict()->Clone());
     43   m_pDict->SetNewFor<CPDF_Number>("Length", static_cast<int>(m_dwSize));
     44   m_pDict->SetNewFor<CPDF_Name>("Filter", "FlateDecode");
     45   m_pDict->RemoveFor("DecodeParms");
     46 }
     47 
     48 CPDF_FlateEncoder::~CPDF_FlateEncoder() {}
     49 
     50 void CPDF_FlateEncoder::CloneDict() {
     51   if (m_pDict.IsOwned())
     52     return;
     53 
     54   m_pDict = ToDictionary(m_pDict->Clone());
     55   ASSERT(m_pDict.IsOwned());
     56 }
     57