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_CJS_RUNTIME_H_
8 #define FXJS_CJS_RUNTIME_H_
9 
10 #include <memory>
11 #include <set>
12 #include <utility>
13 #include <vector>
14 
15 #include "core/fxcrt/observed_ptr.h"
16 #include "core/fxcrt/timerhandler_iface.h"
17 #include "fxjs/cfxjs_engine.h"
18 #include "fxjs/cjs_eventrecorder.h"
19 #include "fxjs/ijs_runtime.h"
20 
21 class CJS_EventContext;
22 class CPDFSDK_FormFillEnvironment;
23 
24 class CJS_Runtime final : public IJS_Runtime,
25                           public CFXJS_Engine,
26                           public Observable {
27  public:
28   using FieldEvent = std::pair<WideString, JS_EVENT_T>;
29 
30   explicit CJS_Runtime(CPDFSDK_FormFillEnvironment* pFormFillEnv);
31   ~CJS_Runtime() override;
32 
33   // IJS_Runtime:
34   CJS_Runtime* AsCJSRuntime() override;
35   IJS_EventContext* NewEventContext() override;
36   void ReleaseEventContext(IJS_EventContext* pContext) override;
37   CPDFSDK_FormFillEnvironment* GetFormFillEnv() const override;
38   Optional<IJS_Runtime::JS_Error> ExecuteScript(
39       const WideString& script) override;
40 
41   CJS_EventContext* GetCurrentEventContext() const;
42   TimerHandlerIface* GetTimerHandler() const;
43 
44   // Returns true if the event isn't already found in the set.
45   bool AddEventToSet(const FieldEvent& event);
46   void RemoveEventFromSet(const FieldEvent& event);
47 
BeginBlock()48   void BeginBlock() { m_bBlocking = true; }
EndBlock()49   void EndBlock() { m_bBlocking = false; }
IsBlocking()50   bool IsBlocking() const { return m_bBlocking; }
51 
52   // Attempt to convert the |value| into a number. If successful the number
53   // value will be returned, otherwise |value| is returned.
54   v8::Local<v8::Value> MaybeCoerceToNumber(v8::Local<v8::Value> value);
55 
56   bool GetValueByNameFromGlobalObject(ByteStringView utf8Name,
57                                       v8::Local<v8::Value>* pValue);
58   bool SetValueByNameInGlobalObject(ByteStringView utf8Name,
59                                     v8::Local<v8::Value> pValue);
60 
61  private:
62   void DefineJSObjects();
63   void SetFormFillEnvToDocument();
64 
65   std::vector<std::unique_ptr<CJS_EventContext>> m_EventContextArray;
66   ObservedPtr<CPDFSDK_FormFillEnvironment> m_pFormFillEnv;
67   bool m_bBlocking = false;
68   bool m_isolateManaged = false;
69   std::set<FieldEvent> m_FieldEventSet;
70 };
71 
72 #endif  // FXJS_CJS_RUNTIME_H_
73