Browse Source

Refactoring COM code

Source commit: c04ae4cf541e8c7aae00ee7d7f8818049b808ae6
Martin Prikryl 3 days ago
parent
commit
6094b307b3

+ 21 - 0
source/core/Common.h

@@ -588,6 +588,11 @@ private:
 
 };
 //---------------------------------------------------------------------------
+// to avoid including ComObj.hpp
+namespace System { namespace Win { namespace Comobj {
+extern DELPHI_PACKAGE void __fastcall OleCheck(HRESULT Result);
+}}}
+//---------------------------------------------------------------------------
 template <typename T>
 class TComPtr
 {
@@ -601,6 +606,16 @@ public:
     Reset(nullptr);
   }
 
+  bool TryCreate(REFCLSID RClsId, DWORD ClsContext)
+  {
+    return SUCCEEDED(DoCreate(RClsId, ClsContext));
+  }
+
+  void Create(REFCLSID RClsId, DWORD ClsContext)
+  {
+    System::Win::Comobj::OleCheck(DoCreate(RClsId, ClsContext));
+  }
+
   void Reset(T * P)
   {
     if (FP != nullptr)
@@ -631,6 +646,12 @@ public:
 
 private:
   T * FP;
+
+  HRESULT DoCreate(REFCLSID RClsId, DWORD ClsContext)
+  {
+    Reset(nullptr);
+    return CoCreateInstance(RClsId, NULL, ClsContext, IID_PPV_ARGS(&FP));
+  }
 };
 //---------------------------------------------------------------------------
 typedef std::vector<UnicodeString> TUnicodeStringVector;

+ 1 - 1
source/core/RemoteFiles.cpp

@@ -3259,7 +3259,7 @@ TSynchronizeChecklistFileOperation::TSynchronizeChecklistFileOperation(
   FOnProcessedItem(OnProcessedItem),
   FToken(Token)
 {
-  OleCheck(CoCreateInstance(CLSID_FileOperation, NULL, CLSCTX_ALL, IID_PPV_ARGS(&FFileOperation)));
+  FFileOperation.Create(CLSID_FileOperation, CLSCTX_ALL);
 
   FProgressSink = new TFileOperationProgressSink(this);
   DWORD UnusedCookie;

+ 55 - 102
source/windows/Setup.cpp

@@ -717,15 +717,10 @@ void __fastcall LaunchAdvancedAssociationUI()
   }
   else
   {
-    IApplicationAssociationRegistrationUI * AppAssocRegUI;
-
-    HRESULT Result =
-      CoCreateInstance(CLSID_ApplicationAssociationRegistrationUI,
-        NULL, CLSCTX_INPROC, __uuidof(IApplicationAssociationRegistrationUI), (void**)&AppAssocRegUI);
-    if (SUCCEEDED(Result))
+    TComPtr<IApplicationAssociationRegistrationUI> AppAssocRegUI;
+    if (AppAssocRegUI.TryCreate(CLSID_ApplicationAssociationRegistrationUI, CLSCTX_INPROC))
     {
       AppAssocRegUI->LaunchAdvancedAssociationUI(AppNameString().c_str());
-      AppAssocRegUI->Release();
     }
   }
 }
@@ -1871,132 +1866,90 @@ void __fastcall SetupInitialize()
   }
 }
 //---------------------------------------------------------------------------
-static bool __fastcall AddJumpListCategory(TStrings * Names,
-  UnicodeString AdditionalParams, TStringList * Removed,
+static void AddJumpListCategory(
+  TStrings * Names, UnicodeString AdditionalParams, TStringList * Removed,
   ICustomDestinationList * DestinationList, UnicodeString CategoryName,
   int IconIndex)
 {
-  bool Result = false;
-  IObjectCollection * Collection = NULL;
-  if (SUCCEEDED(CoCreateInstance(CLSID_EnumerableObjectCollection, NULL,
-        CLSCTX_INPROC_SERVER, IID_IObjectCollection, (void**)&Collection)))
+  TComPtr<IObjectCollection> Collection;
+  if (Collection.TryCreate(CLSID_EnumerableObjectCollection, CLSCTX_INPROC_SERVER))
   {
-    try
+    AddToList(AdditionalParams, TProgramParams::FormatSwitch(JUMPLIST_SWITCH), L" ");
+
+    int Count = 0;
+    for (int Index = 0; Index < Names->Count; Index++)
     {
-      AddToList(AdditionalParams, TProgramParams::FormatSwitch(JUMPLIST_SWITCH), L" ");
+      TComPtr<IShellLink> Link(
+        CreateDesktopSessionShortCut(
+          Names->Strings[Index], L"", AdditionalParams, -1, IconIndex, true));
 
-      int Count = 0;
-      for (int Index = 0; Index < Names->Count; Index++)
+      wchar_t Desc[2048];
+      if (SUCCEEDED(Link->GetDescription(Desc, LENOF(Desc) - 1)))
       {
-        IShellLink * Link =
-          CreateDesktopSessionShortCut(
-            Names->Strings[Index], L"", AdditionalParams, -1, IconIndex, true);
-
-        wchar_t Desc[2048];
-        if (SUCCEEDED(Link->GetDescription(Desc, LENOF(Desc) - 1)))
+        if (Removed->IndexOf(Desc) < 0)
         {
-          if (Removed->IndexOf(Desc) < 0)
-          {
-            try
-            {
-              DebugCheck(SUCCEEDED(Collection->AddObject(Link)));
-              Count++;
-            }
-            __finally
-            {
-              Link->Release();
-            }
-          }
-          else
-          {
-            Names->Delete(Index);
-            Index--;
-          }
+          DebugCheck(SUCCEEDED(Collection->AddObject(Link.Get())));
+          Count++;
         }
-      }
-
-      if (Count > 0)
-      {
-        IObjectArray * Array;
-        if (SUCCEEDED(Collection->QueryInterface(IID_IObjectArray, (void**)&Array)))
+        else
         {
-          try
-          {
-            Result = SUCCEEDED(
-              DestinationList->AppendCategory(CategoryName.c_str(), Array));
-          }
-          __finally
-          {
-            Array->Release();
-          }
+          Names->Delete(Index);
+          Index--;
         }
       }
     }
-    __finally
+
+    if (Count > 0)
     {
-      Collection->Release();
+      TComPtr<IObjectArray> Array;
+      if (SUCCEEDED(Collection->QueryInterface(IID_PPV_ARGS(&Array))))
+      {
+        DestinationList->AppendCategory(CategoryName.c_str(), Array.Get());
+      }
     }
   }
-  return Result;
 }
 //---------------------------------------------------------------------------
 void __fastcall UpdateJumpList(TStrings * SessionNames, TStrings * WorkspaceNames)
 {
-  ICustomDestinationList * DestinationList = NULL;
-  TStringList * Removed = NULL;
-  try
+  TComPtr<ICustomDestinationList> DestinationList;
+  if (DestinationList.TryCreate(CLSID_DestinationList, CLSCTX_INPROC_SERVER))
   {
-    if (SUCCEEDED(CoCreateInstance(CLSID_DestinationList, NULL,
-          CLSCTX_INPROC_SERVER, IID_ICustomDestinationList, (void**)&DestinationList)))
+    unsigned int MinSlots;
+    void * ppv = NULL;
+    HRESULT Result = DestinationListBeginList(DestinationList.Get(), MinSlots, IID_IObjectArray, ppv, 50000);
+    if (SUCCEEDED(Result) && DebugAlwaysTrue(ppv != NULL))
     {
+      IObjectArray * RemovedArray = static_cast<IObjectArray *>(ppv);
 
-      unsigned int MinSlots;
-      void * ppv = NULL;
-      HRESULT Result = DestinationListBeginList(DestinationList, MinSlots, IID_IObjectArray, ppv, 50000);
-      if (SUCCEEDED(Result) && DebugAlwaysTrue(ppv != NULL))
+      unsigned int RemovedCount;
+      if (FAILED(RemovedArray->GetCount(&RemovedCount)))
       {
-        IObjectArray * RemovedArray = static_cast<IObjectArray*>(ppv);
-        Removed = new TStringList();
+        RemovedCount = 0;
+      }
 
-        unsigned int RemovedCount;
-        if (FAILED(RemovedArray->GetCount(&RemovedCount)))
+      std::unique_ptr<TStringList> Removed(new TStringList());
+      for (unsigned int Index = 0; Index < RemovedCount; Index++)
+      {
+        IShellLink * Link;
+        wchar_t Desc[2048];
+        if (SUCCEEDED(RemovedArray->GetAt(Index, IID_IShellLink, (void**)&Link)) &&
+            SUCCEEDED(Link->GetDescription(Desc, LENOF(Desc) - 1)))
         {
-          RemovedCount = 0;
-        }
-
-        for (unsigned int Index = 0; Index < RemovedCount; Index++)
-        {
-          IShellLink * Link;
-          wchar_t Desc[2048];
-          if (SUCCEEDED(RemovedArray->GetAt(Index, IID_IShellLink, (void**)&Link)) &&
-              SUCCEEDED(Link->GetDescription(Desc, LENOF(Desc) - 1)))
-          {
-            Removed->Add(Desc);
-          }
+          Removed->Add(Desc);
         }
+      }
 
-        AddJumpListCategory(
-          WorkspaceNames, L"", Removed, DestinationList,
-          LoadStr(JUMPLIST_WORKSPACES), WORKSPACE_ICON);
+      AddJumpListCategory(
+        WorkspaceNames, L"", Removed.get(), DestinationList.Get(),
+        LoadStr(JUMPLIST_WORKSPACES), WORKSPACE_ICON);
 
-        AddJumpListCategory(
-          SessionNames, TProgramParams::FormatSwitch(UPLOAD_IF_ANY_SWITCH), Removed, DestinationList,
-          LoadStr(JUMPLIST_RECENT), SITE_ICON);
+      AddJumpListCategory(
+        SessionNames, TProgramParams::FormatSwitch(UPLOAD_IF_ANY_SWITCH), Removed.get(), DestinationList.Get(),
+        LoadStr(JUMPLIST_RECENT), SITE_ICON);
 
-        if (DestinationList != NULL)
-        {
-          DestinationList->CommitList();
-        }
-      }
-    }
-  }
-  __finally
-  {
-    if (DestinationList != NULL)
-    {
-      DestinationList->Release();
+      DestinationList->CommitList();
     }
-    delete Removed;
   }
 }
 //---------------------------------------------------------------------------

+ 2 - 16
source/windows/TerminalManager.cpp

@@ -135,7 +135,6 @@ __fastcall TTerminalManager::TTerminalManager() :
   FTerminalPendingAction = tpNull;
   FDirectoryReadingStart = 0;
   FAuthenticateForm = NULL;
-  FTaskbarList = NULL;
   FAuthenticating = 0;
   FMainThread = GetCurrentThreadId();
   FChangeSection.reset(new TCriticalSection());
@@ -188,7 +187,6 @@ __fastcall TTerminalManager::~TTerminalManager()
   delete FSessionList;
   CloseAutheticateForm();
   delete FQueueSection;
-  ReleaseTaskbarList();
 }
 //---------------------------------------------------------------------------
 void __fastcall TTerminalManager::SetQueueConfiguration(TTerminalQueue * Queue)
@@ -1252,11 +1250,7 @@ void __fastcall TTerminalManager::InitTaskbarButtonCreatedMessage()
 //---------------------------------------------------------------------------
 void __fastcall TTerminalManager::CreateTaskbarList()
 {
-
-  ReleaseTaskbarList();
-
-  if(SUCCEEDED(CoCreateInstance(CLSID_TaskbarList, NULL, CLSCTX_ALL,
-        IID_ITaskbarList3, (void **) &FTaskbarList)))
+  if (FTaskbarList.TryCreate(CLSID_TaskbarList, CLSCTX_ALL))
   {
     if (ScpExplorer != NULL)
     {
@@ -1265,17 +1259,9 @@ void __fastcall TTerminalManager::CreateTaskbarList()
   }
 }
 //---------------------------------------------------------------------------
-void __fastcall TTerminalManager::ReleaseTaskbarList()
-{
-  if (FTaskbarList != NULL)
-  {
-    FTaskbarList->Release();
-  }
-}
-//---------------------------------------------------------------------------
 void __fastcall TTerminalManager::UpdateTaskbarList()
 {
-  ScpExplorer->UpdateTaskbarList(FTaskbarList);
+  ScpExplorer->UpdateTaskbarList(FTaskbarList.Get());
 }
 //---------------------------------------------------------------------------
 void __fastcall TTerminalManager::DeleteLocalFile(const UnicodeString FileName, bool Alternative, int & Deleted)

+ 1 - 2
source/windows/TerminalManager.h

@@ -165,7 +165,7 @@ private:
   std::unique_ptr<TCriticalSection> FChangeSection;
   std::vector<std::pair<TTerminalQueue *, TQueueEvent> > FQueueEvents;
   unsigned int FTaskbarButtonCreatedMessage;
-  ITaskbarList3 * FTaskbarList;
+  TComPtr<ITaskbarList3> FTaskbarList;
   int FAuthenticating;
   void * FBusyToken;
   bool FAuthenticationCancelled;
@@ -227,7 +227,6 @@ private:
   void __fastcall FileNameInputDialogInitializeRenameBaseName(
     TObject * Sender, TInputDialogData * Data);
   void __fastcall InitTaskbarButtonCreatedMessage();
-  void __fastcall ReleaseTaskbarList();
   void __fastcall CreateTaskbarList();
   void __fastcall UpdateTaskbarList();
   void __fastcall AuthenticateFormCancel(TObject * Sender);

+ 32 - 68
source/windows/Tools.cpp

@@ -525,7 +525,7 @@ IShellLink * __fastcall CreateDesktopShortCut(const UnicodeString & Name,
   const UnicodeString &File, const UnicodeString & Params, const UnicodeString & Description,
   int SpecialFolder, int IconIndex, bool Return)
 {
-  IShellLink* pLink = NULL;
+  TComPtr<IShellLink> Link;
 
   if (SpecialFolder < 0)
   {
@@ -534,83 +534,51 @@ IShellLink * __fastcall CreateDesktopShortCut(const UnicodeString & Name,
 
   try
   {
-    OleCheck(CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (void **) &pLink));
+    Link.Create(CLSID_ShellLink, CLSCTX_INPROC_SERVER);
 
-    try
-    {
-      pLink->SetPath(File.c_str());
-      pLink->SetDescription(Description.c_str());
-      pLink->SetArguments(Params.c_str());
-      pLink->SetShowCmd(SW_SHOW);
-      // Explicitly setting icon file,
-      // without this icons are not shown at least in Windows 7 jumplist
-      pLink->SetIconLocation(File.c_str(), IconIndex);
-
-      IPersistFile* pPersistFile;
-      if (!Return &&
-          SUCCEEDED(pLink->QueryInterface(IID_IPersistFile, (void **)&pPersistFile)))
-      {
-        try
-        {
-          LPMALLOC      ShellMalloc;
-          LPITEMIDLIST  DesktopPidl;
-          wchar_t DesktopDir[MAX_PATH];
-
-          OleCheck(SHGetMalloc(&ShellMalloc));
-
-          try
-          {
-            OleCheck(SHGetSpecialFolderLocation(NULL, SpecialFolder, &DesktopPidl));
-
-            OleCheck(SHGetPathFromIDList(DesktopPidl, DesktopDir));
-          }
-          __finally
-          {
-            ShellMalloc->Free(DesktopPidl);
-            ShellMalloc->Release();
-          }
+    Link->SetPath(File.c_str());
+    Link->SetDescription(Description.c_str());
+    Link->SetArguments(Params.c_str());
+    Link->SetShowCmd(SW_SHOW);
+    // Explicitly setting icon file,
+    // without this icons are not shown at least in Windows 7 jumplist
+    Link->SetIconLocation(File.c_str(), IconIndex);
 
-          WideString strShortCutLocation(DesktopDir);
-          // Name can contain even path (e.g. to create quick launch icon)
-          strShortCutLocation += UnicodeString(L"\\") + Name + L".lnk";
-          OleCheck(pPersistFile->Save(strShortCutLocation.c_bstr(), TRUE));
-        }
-        __finally
-        {
-          pPersistFile->Release();
-        }
-      }
-
-      // this is necessary for Windows 7 taskbar jump list links
-      IPropertyStore * PropertyStore;
-      if (SUCCEEDED(pLink->QueryInterface(IID_IPropertyStore, (void**)&PropertyStore)))
+    TComPtr<IPersistFile> PersistFile;
+    if (!Return &&
+        SUCCEEDED(Link->QueryInterface(IID_PPV_ARGS(&PersistFile))))
+    {
+      UnicodeString FolderPath;
+      if (::SpecialFolderLocation(SpecialFolder, FolderPath))
       {
-        PROPVARIANT Prop;
-        Prop.vt = VT_LPWSTR;
-        Prop.pwszVal = Name.c_str();
-        PropertyStore->SetValue(PKEY_Title, Prop);
-        PropertyStore->Commit();
-        PropertyStore->Release();
+        // Name can contain even path (e.g. to create quick launch icon)
+        WideString ShortCutPath = WideString(CombinePaths(FolderPath, Name + L".lnk"));
+        OleCheck(PersistFile->Save(ShortCutPath.c_bstr(), TRUE));
       }
     }
-    catch(...)
+
+    // this is necessary for Windows 7 taskbar jump list links
+    TComPtr<IPropertyStore> PropertyStore;
+    if (SUCCEEDED(Link->QueryInterface(IID_PPV_ARGS(&PropertyStore))))
     {
-      pLink->Release();
-      throw;
+      PROPVARIANT Prop;
+      Prop.vt = VT_LPWSTR;
+      Prop.pwszVal = Name.c_str();
+      PropertyStore->SetValue(PKEY_Title, Prop);
+      PropertyStore->Commit();
     }
 
     if (!Return)
     {
-      pLink->Release();
-      pLink = NULL;
+      Link.Reset(nullptr);
     }
   }
-  catch(Exception & E)
+  catch (Exception & E)
   {
     throw ExtException(&E, LoadStr(CREATE_SHORTCUT_ERROR));
   }
 
-  return pLink;
+  return Link.Detach();
 }
 //---------------------------------------------------------------------------
 UnicodeString GetIniFileParam()
@@ -1654,7 +1622,7 @@ bool __fastcall AutodetectProxy(UnicodeString & HostName, int & PortNumber)
 }
 //---------------------------------------------------------------------------
 //---------------------------------------------------------------------------
-class TWinHelpTester : public TInterfacedObject, public IWinHelpTester
+class TWinHelpTester : public TCppInterfacedObject<IWinHelpTester>
 {
 public:
   virtual bool __fastcall CanShowALink(const UnicodeString ALink, const UnicodeString FileName);
@@ -1663,11 +1631,9 @@ public:
   virtual TStringList * __fastcall GetHelpStrings(const UnicodeString ALink);
   virtual UnicodeString __fastcall GetHelpPath();
   virtual UnicodeString __fastcall GetDefaultHelpFile();
-
-  IUNKNOWN
 };
 //---------------------------------------------------------------------------
-class TCustomHelpSelector : public TInterfacedObject, public IHelpSelector
+class TCustomHelpSelector : public TCppInterfacedObject<IHelpSelector>
 {
 public:
   __fastcall TCustomHelpSelector(const UnicodeString & Name);
@@ -1675,8 +1641,6 @@ public:
   virtual int __fastcall SelectKeyword(TStrings * Keywords);
   virtual int __fastcall TableOfContents(TStrings * Contents);
 
-  IUNKNOWN
-
 private:
   UnicodeString FName;
 };

+ 0 - 16
source/windows/Tools.h

@@ -86,22 +86,6 @@ bool __fastcall DetectSystemExternalEditor(
   UnicodeString & Executable, UnicodeString & ExecutableDescription,
   UnicodeString & UsageState, bool & TryNextTime);
 //---------------------------------------------------------------------------
-#define IUNKNOWN \
-  virtual HRESULT __stdcall QueryInterface(const GUID& IID, void **Obj) \
-  { \
-    return TInterfacedObject::QueryInterface(IID, (void *)Obj); \
-  } \
-  \
-  virtual ULONG __stdcall AddRef() \
-  { \
-    return TInterfacedObject::_AddRef(); \
-  } \
-  \
-  virtual ULONG __stdcall Release() \
-  { \
-    return TInterfacedObject::_Release(); \
-  }
-//---------------------------------------------------------------------------
 void __fastcall InitializeCustomHelp(ICustomHelpViewer * HelpViewer);
 void __fastcall FinalizeCustomHelp();
 //---------------------------------------------------------------------------

+ 3 - 11
source/windows/WinConfiguration.cpp

@@ -1799,18 +1799,10 @@ bool __fastcall TWinConfiguration::GetDDExtInstalled()
     }
     else
     {
-      void * DragExtRef;
-      int CreateResult =
-        CoCreateInstance(CLSID_ShellExtension, NULL,
-          CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER, IID_IUnknown,
-          &DragExtRef);
-      bool Result = (CreateResult == S_OK);
+      TComPtr<IUnknown> DragExtRef;
+      bool Result = DragExtRef.TryCreate(CLSID_ShellExtension, CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER);
       FDDExtInstalled = (Result ? 1 : 0);
-      if (Result)
-      {
-        reinterpret_cast<IUnknown *>(DragExtRef)->Release();
-        CoFreeUnusedLibraries();
-      }
+      CoFreeUnusedLibraries();
     }
   }
   return (FDDExtInstalled > 0);

+ 1 - 3
source/windows/WinHelp.cpp

@@ -4,7 +4,7 @@
 
 #include <HelpIntfs.hpp>
 //---------------------------------------------------------------------------
-class TWebHelpSystem : public TInterfacedObject, public ICustomHelpViewer
+class TWebHelpSystem : public TCppInterfacedObject<ICustomHelpViewer>
 {
 public:
   __fastcall TWebHelpSystem(const UnicodeString & Version, const UnicodeString & Language);
@@ -18,8 +18,6 @@ public:
   virtual void __fastcall ShowTableOfContents();
   virtual void __fastcall ShowHelp(const UnicodeString HelpString);
 
-  IUNKNOWN
-
 private:
   UnicodeString FVersion;
   UnicodeString FLanguage;