xref: /aosp_15_r20/external/pdfium/samples/helpers/win32/com_factory.cc (revision 3ac0a46f773bac49fa9476ec2b1cf3f8da5ec3a4)
1 // Copyright 2023 The PDFium Authors
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 "samples/helpers/win32/com_factory.h"
6 
7 #include <combaseapi.h>
8 #include <objbase.h>
9 #include <winerror.h>
10 #include <xpsobjectmodel.h>
11 
12 #include "third_party/base/check_op.h"
13 
14 ComFactory::ComFactory() = default;
15 
~ComFactory()16 ComFactory::~ComFactory() {
17   if (xps_om_object_factory_) {
18     xps_om_object_factory_->Release();
19   }
20 
21   if (initialized_) {
22     CoUninitialize();
23   }
24 }
25 
Initialize()26 bool ComFactory::Initialize() {
27   if (!initialized_) {
28     HRESULT result =
29         CoInitializeEx(nullptr, COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE);
30     DCHECK_NE(RPC_E_CHANGED_MODE, result);
31     initialized_ = SUCCEEDED(result);
32   }
33 
34   return initialized_;
35 }
36 
GetXpsOMObjectFactory()37 IXpsOMObjectFactory* ComFactory::GetXpsOMObjectFactory() {
38   if (!xps_om_object_factory_ && Initialize()) {
39     HRESULT result =
40         CoCreateInstance(__uuidof(XpsOMObjectFactory), /*pUnkOuter=*/nullptr,
41                          CLSCTX_INPROC_SERVER, __uuidof(IXpsOMObjectFactory),
42                          reinterpret_cast<LPVOID*>(&xps_om_object_factory_));
43     if (SUCCEEDED(result)) {
44       DCHECK(xps_om_object_factory_);
45     } else {
46       DCHECK(!xps_om_object_factory_);
47     }
48   }
49 
50   return xps_om_object_factory_;
51 }
52