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 
7 #ifndef FXJS_CFX_GLOBALDATA_H_
8 #define FXJS_CFX_GLOBALDATA_H_
9 
10 #include <memory>
11 #include <vector>
12 
13 #include "core/fxcrt/cfx_binarybuf.h"
14 #include "core/fxcrt/unowned_ptr.h"
15 #include "fxjs/cfx_keyvalue.h"
16 #include "third_party/base/optional.h"
17 #include "third_party/base/span.h"
18 
19 class CPDFSDK_FormFillEnvironment;
20 
21 class CFX_GlobalData {
22  public:
23   class Delegate {
24    public:
~Delegate()25     virtual ~Delegate() {}
26 
27     virtual bool StoreBuffer(pdfium::span<const uint8_t> pBuffer) = 0;
28     virtual Optional<pdfium::span<uint8_t>> LoadBuffer() = 0;
29     virtual void BufferDone() = 0;
30   };
31 
32   class Element {
33    public:
34     Element();
35     ~Element();
36 
37     CFX_KeyValue data;
38     bool bPersistent;
39   };
40 
41   static CFX_GlobalData* GetRetainedInstance(Delegate* pDelegate);
42   bool Release();
43 
44   void SetGlobalVariableNumber(ByteString propname, double dData);
45   void SetGlobalVariableBoolean(ByteString propname, bool bData);
46   void SetGlobalVariableString(ByteString propname, const ByteString& sData);
47   void SetGlobalVariableObject(
48       ByteString propname,
49       std::vector<std::unique_ptr<CFX_KeyValue>> array);
50   void SetGlobalVariableNull(ByteString propname);
51   bool SetGlobalVariablePersistent(ByteString propname, bool bPersistent);
52   bool DeleteGlobalVariable(ByteString propname);
53 
54   int32_t GetSize() const;
55   Element* GetAt(int index);
56 
57   // Exposed for testing.
58   Element* GetGlobalVariable(const ByteString& sPropname);
59 
60  private:
61   using iterator = std::vector<std::unique_ptr<Element>>::iterator;
62 
63   explicit CFX_GlobalData(Delegate* pDelegate);
64   ~CFX_GlobalData();
65 
66   bool LoadGlobalPersistentVariables();
67   bool LoadGlobalPersistentVariablesFromBuffer(pdfium::span<uint8_t> buffer);
68   bool SaveGlobalPersisitentVariables();
69 
70   iterator FindGlobalVariable(const ByteString& sPropname);
71 
72   void LoadFileBuffer(const wchar_t* sFilePath,
73                       uint8_t*& pBuffer,
74                       int32_t& nLength);
75   void WriteFileBuffer(const wchar_t* sFilePath,
76                        const char* pBuffer,
77                        int32_t nLength);
78 
79   size_t m_RefCount = 0;
80   UnownedPtr<Delegate> const m_pDelegate;
81   std::vector<std::unique_ptr<Element>> m_arrayGlobalData;
82 };
83 
84 #endif  // FXJS_CFX_GLOBALDATA_H_
85