1 // Copyright 2018 The Chromium 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 #include "pdf/pdf_ppapi.h"
6 
7 #include <memory>
8 
9 #include "pdf/out_of_process_instance.h"
10 #include "pdf/pdf.h"
11 #include "pdf/pdf_init.h"
12 #include "ppapi/c/ppp.h"
13 #include "ppapi/cpp/private/internal_module.h"
14 #include "ppapi/cpp/private/pdf.h"
15 #include "v8/include/v8.h"
16 
17 namespace chrome_pdf {
18 
19 namespace {
20 
21 class PDFModule : public pp::Module {
22  public:
23   PDFModule();
24   ~PDFModule() override;
25 
26   // pp::Module implementation.
27   bool Init() override;
28   pp::Instance* CreateInstance(PP_Instance instance) override;
29 };
30 
31 PDFModule::PDFModule() = default;
32 
~PDFModule()33 PDFModule::~PDFModule() {
34   if (IsSDKInitializedViaPlugin()) {
35     ShutdownSDK();
36     SetIsSDKInitializedViaPlugin(false);
37   }
38 }
39 
Init()40 bool PDFModule::Init() {
41   return true;
42 }
43 
CreateInstance(PP_Instance instance)44 pp::Instance* PDFModule::CreateInstance(PP_Instance instance) {
45   if (!IsSDKInitializedViaPlugin()) {
46     v8::StartupData snapshot;
47     pp::PDF::GetV8ExternalSnapshotData(pp::InstanceHandle(instance),
48                                        &snapshot.data, &snapshot.raw_size);
49     if (snapshot.data) {
50       v8::V8::SetSnapshotDataBlob(&snapshot);
51     }
52 
53     InitializeSDK(/*enable_v8=*/true);
54     SetIsSDKInitializedViaPlugin(true);
55   }
56 
57   return new OutOfProcessInstance(instance);
58 }
59 
60 }  // namespace
61 
PPP_InitializeModule(PP_Module module_id,PPB_GetInterface get_browser_interface)62 int32_t PPP_InitializeModule(PP_Module module_id,
63                              PPB_GetInterface get_browser_interface) {
64   auto module = std::make_unique<PDFModule>();
65   if (!module->InternalInit(module_id, get_browser_interface))
66     return PP_ERROR_FAILED;
67 
68   pp::InternalSetModuleSingleton(module.release());
69   return PP_OK;
70 }
71 
PPP_ShutdownModule()72 void PPP_ShutdownModule() {
73   delete pp::Module::Get();
74   pp::InternalSetModuleSingleton(nullptr);
75 }
76 
PPP_GetInterface(const char * interface_name)77 const void* PPP_GetInterface(const char* interface_name) {
78   auto* module = pp::Module::Get();
79   return module ? module->GetPluginInterface(interface_name) : nullptr;
80 }
81 
82 }  // namespace chrome_pdf
83