Repository.mk | 1 dtrans/source/win32/dtobj/FmtFilter.cxx | 11 fpicker/source/win32/VistaFilePickerImpl.cxx | 13 fpicker/source/win32/VistaFilePickerImpl.hxx | 4 include/o3tl/safeCoInitUninit.hxx | 58 ++++ include/sal/log-areas.dox | 1 include/systools/win32/comtools.hxx | 74 ++++- offapi/UnoApi_offapi.mk | 7 offapi/com/sun/star/system/windows/JumpList.idl | 33 ++ offapi/com/sun/star/system/windows/JumpListItem.idl | 45 +++ offapi/com/sun/star/system/windows/XJumpList.idl | 88 ++++++ shell/Library_jumplist.mk | 37 ++ shell/Module_shell.mk | 1 shell/source/win32/SysShExec.cxx | 16 - shell/source/win32/jumplist/JumpList.cxx | 290 ++++++++++++++++++++ shell/source/win32/jumplist/jumplist.component | 17 + 16 files changed, 663 insertions(+), 33 deletions(-)
New commits: commit b54d0d262bbafbc08efd1cbc93af61b786f89821 Author: Samuel Mehrbrodt <samuel.mehrbr...@allotropia.de> AuthorDate: Mon Mar 14 10:04:17 2022 +0100 Commit: Samuel Mehrbrodt <samuel.mehrbr...@allotropia.de> CommitDate: Fri Mar 25 10:27:06 2022 +0100 Add UNO API for custom Jump Lists Allows adding custom jump list categories to Windows Task Bar Change-Id: I13b6c3ad5de386cf74e2b346f10889bc46a8ad4e diff --git a/Repository.mk b/Repository.mk index 639c0db413eb..49a46b454409 100644 --- a/Repository.mk +++ b/Repository.mk @@ -391,6 +391,7 @@ $(eval $(call gb_Helper_register_libraries_for_install,OOOLIBS,ooo, \ hyphen \ icg \ $(if $(ENABLE_JAVA),jdbc) \ + jumplist \ $(if $(ENABLE_LDAP),ldapbe2) \ $(if $(filter WNT,$(OS)),WinUserInfoBe) \ localebe1 \ diff --git a/include/sal/log-areas.dox b/include/sal/log-areas.dox index 9a0c43587bc9..40575f96e69a 100644 --- a/include/sal/log-areas.dox +++ b/include/sal/log-areas.dox @@ -625,6 +625,7 @@ certain functionality. @li @c scripting @li @c scripting.provider @li @c shell +@li @c shell.jumplist @li @c stoc @li @c store @li @c svg diff --git a/offapi/UnoApi_offapi.mk b/offapi/UnoApi_offapi.mk index c86e7d5a7800..aa85f3a525e9 100644 --- a/offapi/UnoApi_offapi.mk +++ b/offapi/UnoApi_offapi.mk @@ -3621,6 +3621,13 @@ $(eval $(call gb_UnoApi_add_idlfiles,offapi,com/sun/star/system,\ XSimpleMailMessage2 \ XSystemShellExecute \ )) + +$(eval $(call gb_UnoApi_add_idlfiles,offapi,com/sun/star/system/windows,\ + JumpList \ + JumpListItem \ + XJumpList \ +)) + $(eval $(call gb_UnoApi_add_idlfiles,offapi,com/sun/star/table,\ BorderLine \ BorderLine2 \ diff --git a/offapi/com/sun/star/system/windows/JumpList.idl b/offapi/com/sun/star/system/windows/JumpList.idl new file mode 100755 index 000000000000..82becd522b69 --- /dev/null +++ b/offapi/com/sun/star/system/windows/JumpList.idl @@ -0,0 +1,33 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef __com_sun_star_system_windows_JumpList_idl__ +#define __com_sun_star_system_windows_JumpList_idl__ + + +module com { module sun { module star { module system { module windows { + + +interface XJumpList; + +/** Specifies a Jump List service. Allows to add custom commands to the Windows Jump List. + + @since LibreOffice 7.4 + + @see com::sun::star::system::windows::XJumpList +*/ + +service JumpList : XJumpList; + + +}; }; }; }; }; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/offapi/com/sun/star/system/windows/JumpListItem.idl b/offapi/com/sun/star/system/windows/JumpListItem.idl new file mode 100755 index 000000000000..310e5551911a --- /dev/null +++ b/offapi/com/sun/star/system/windows/JumpListItem.idl @@ -0,0 +1,45 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef __com_sun_star_system_windows_JumpListItem_idl__ +#define __com_sun_star_system_windows_JumpListItem_idl__ + +#include <com/sun/star/uno/XInterface.idl> +#include <com/sun/star/lang/IllegalArgumentException.idl> +#include <com/sun/star/uno/Sequence.idl> + + +module com { module sun { module star { module system { module windows { + +/** Specifies an item for com::sun::star::system::windows::XJumpList . + + @since LibreOffice 7.4 +*/ + +struct JumpListItem +{ + /** Item name. Appears in the JumpList. Has to be unique per category. */ + string name; + + /** Item description, appears as tooltip */ + string description; + + /** Arguments to be passed to LibreOffice. + This can be a file to be loaded, or any command line parameter supported by LibreOffice, and any combination of the two. */ + string arguments; + + /** Icon to be displayed along the name. This should be a local path name like `C:\path\to\icon` */ + string iconPath; +}; + +}; }; }; }; }; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/offapi/com/sun/star/system/windows/XJumpList.idl b/offapi/com/sun/star/system/windows/XJumpList.idl new file mode 100755 index 000000000000..c483149e5dd8 --- /dev/null +++ b/offapi/com/sun/star/system/windows/XJumpList.idl @@ -0,0 +1,88 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef __com_sun_star_system_windows_XJumpList_idl__ +#define __com_sun_star_system_windows_XJumpList_idl__ + +#include <com/sun/star/uno/XInterface.idl> +#include <com/sun/star/lang/IllegalArgumentException.idl> +#include <com/sun/star/system/SystemShellExecuteException.idl> + + +module com { module sun { module star { module system { module windows { + +/** Specifies an interface for adding custom jump lists to the task bar (Windows only) + + @since LibreOffice 7.4 +*/ +interface XJumpList: com::sun::star::uno::XInterface +{ + /** Add a jump list category + + @param category + Specifies the category name. It will appear as the title of the custom jump list. + + @param jumpListItems + Specifies a list of com::sun::star::system::JumpListItem. + These will be added as entries below the category name in the custom jump list. + Make sure you don't add items which the user has removed before + (check the result of `getRemovedItems` before updating a category). + + @param application + Used to map the jump list to the correct application. Use one of the following values: + <ul> + <li>Writer</li> + <li>Calc</li> + <li>Impress</li> + <li>Draw</li> + <li>Math</li> + <li>Base</li> + <li>Startcenter</li> + </ul> + + "Startcenter" will map to the generic "LibreOffice" icon. + + @throws com::sun::star::lang::IllegalArgumentException + When an empty category name, or an invalid application name is given. + */ + void appendCategory( [in] string category, + [in] sequence<com::sun::star::system::windows::JumpListItem> jumpListItems, + [in] string application ) + raises( ::com::sun::star::lang::IllegalArgumentException ); + + /** Returns items that were removed from the jump list by the user. + + `appendCategory` will fail if you try to reinsert an item which was removed by the user before. + Use this method to learn which items were removed by the user. + + @param application + Used to map the jump list to the correct application. Use one of the following values: + <ul> + <li>Writer</li> + <li>Calc</li> + <li>Impress</li> + <li>Draw</li> + <li>Math</li> + <li>Base</li> + <li>Startcenter</li> + </ul> + + "Startcenter" will map to the generic "LibreOffice" icon. + + @return List of removed items. + */ + sequence<com::sun::star::system::windows::JumpListItem> getRemovedItems([in] string application); +}; + + +}; }; }; }; }; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/shell/Library_jumplist.mk b/shell/Library_jumplist.mk new file mode 100755 index 000000000000..943fabdd4080 --- /dev/null +++ b/shell/Library_jumplist.mk @@ -0,0 +1,37 @@ +# -*- Mode: makefile-gmake; tab-width: 4; indent-tabs-mode: t; fill-column: 100 -*- +# +# This file is part of the LibreOffice project. +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# + +$(eval $(call gb_Library_Library,jumplist)) + +$(eval $(call gb_Library_use_sdk_api,jumplist)) + +$(eval $(call gb_Library_use_libraries,jumplist,\ + comphelper \ + cppu \ + cppuhelper \ + sal \ +)) + +ifeq ($(OS),WNT) + +$(eval $(call gb_Library_use_system_win32_libs,jumplist,\ + ole32 \ + Propsys \ + shell32 \ +)) + +$(eval $(call gb_Library_set_componentfile,jumplist,shell/source/win32/jumplist/jumplist,services)) + +$(eval $(call gb_Library_add_exception_objects,jumplist,\ + shell/source/win32/jumplist/JumpList \ +)) + +endif # OS + +# vim: set noet sw=4 ts=4: diff --git a/shell/Module_shell.mk b/shell/Module_shell.mk index c0c42cc5bea5..b955ecbf695c 100644 --- a/shell/Module_shell.mk +++ b/shell/Module_shell.mk @@ -43,6 +43,7 @@ $(eval $(call gb_Module_add_targets,shell,\ Executable_senddoc \ Library_smplmail \ Library_wininetbe \ + Library_jumplist \ Executable_spsupp_helper \ )) diff --git a/shell/source/win32/jumplist/JumpList.cxx b/shell/source/win32/jumplist/JumpList.cxx new file mode 100755 index 000000000000..74874c8bc53e --- /dev/null +++ b/shell/source/win32/jumplist/JumpList.cxx @@ -0,0 +1,290 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#include <sal/config.h> + +#include <algorithm> +#include <cassert> + +#include <comphelper/sequence.hxx> +#include <cppuhelper/supportsservice.hxx> +#include <cppuhelper/compbase.hxx> + +#include <o3tl/char16_t2wchar_t.hxx> +#include <o3tl/runtimetooustring.hxx> +#include <o3tl/safeCoInitUninit.hxx> +#include <osl/file.hxx> +#include <osl/mutex.hxx> +#include <osl/process.h> +#include <sal/log.hxx> + +#include <com/sun/star/lang/IllegalArgumentException.hpp> +#include <com/sun/star/lang/XServiceInfo.hpp> +#include <com/sun/star/system/windows/JumpListItem.hpp> +#include <com/sun/star/system/windows/XJumpList.hpp> +#include <com/sun/star/uno/XComponentContext.hpp> + +#include <prewin.h> +#include <Shlobj.h> +#include <propkey.h> +#include <propvarutil.h> +#include <systools/win32/comtools.hxx> +#include <postwin.h> + +using namespace comphelper; +using namespace cppu; +using namespace css; +using namespace css::uno; +using namespace css::lang; +using namespace css::system::windows; +using namespace osl; + +using sal::systools::COMReference; +using sal::systools::COM_QUERY_THROW; +using sal::systools::ComError; +using sal::systools::ThrowIfFailed; + +class JumpListImpl : public WeakComponentImplHelper<XJumpList, XServiceInfo> +{ + Reference<XComponentContext> m_xContext; + Mutex m_aMutex; + +public: + explicit JumpListImpl(const Reference<XComponentContext>& xContext); + ~JumpListImpl(); + + // XJumpList + virtual void SAL_CALL appendCategory(const OUString& sCategory, + const Sequence<JumpListItem>& aJumpListItems, + const OUString& sDocumentService) override; + virtual Sequence<JumpListItem> + SAL_CALL getRemovedItems(const OUString& sDocumentService) override; + + // XServiceInfo + virtual OUString SAL_CALL getImplementationName() override; + virtual sal_Bool SAL_CALL supportsService(const OUString& ServiceName) override; + virtual Sequence<OUString> SAL_CALL getSupportedServiceNames() override; +}; + +JumpListImpl::JumpListImpl(const Reference<XComponentContext>& xContext) + : WeakComponentImplHelper(m_aMutex) + , m_xContext(xContext) +{ +} + +JumpListImpl::~JumpListImpl() {} + +void SAL_CALL JumpListImpl::appendCategory(const OUString& sCategory, + const Sequence<JumpListItem>& aJumpListItems, + const OUString& sApplication) +{ + if (sCategory.isEmpty()) + { + throw IllegalArgumentException("Parameter 'category' must not be empty", + static_cast<OWeakObject*>(this), 1); + } + if (sApplication != "Writer" && sApplication != "Calc" && sApplication != "Impress" + && sApplication != "Draw" && sApplication != "Math" && sApplication != "Base" + && sApplication != "Startcenter") + { + throw IllegalArgumentException( + "Parameter 'application' must be one of 'Writer', 'Calc', 'Impress', 'Draw', " + "'Math', 'Base', 'Startcenter'.", + static_cast<OWeakObject*>(this), 1); + } + OUString sApplicationID("TheDocumentFoundation.LibreOffice." + sApplication); + + try + { + COMReference<ICustomDestinationList> aDestinationList; + CoCreateInstance(CLSID_DestinationList, nullptr, CLSCTX_INPROC_SERVER, + IID_PPV_ARGS(&aDestinationList)); + + aDestinationList->SetAppID(o3tl::toW(sApplicationID.getStr())); + + UINT min_slots; + COMReference<IObjectArray> removed; + ThrowIfFailed(aDestinationList->BeginList(&min_slots, IID_PPV_ARGS(&removed)), + "BeginList failed"); + + OUString sofficeURL; + OUString sofficePath; + oslProcessError err = osl_getExecutableFile(&sofficeURL.pData); + FileBase::getSystemPathFromFileURL(sofficeURL, sofficePath); + if (err != osl_Process_E_None) + { + SAL_WARN("shell.jumplist", "osl_getExecutableFile failed"); + return; + } + // We need to run soffice.exe, not soffice.bin + sofficePath = sofficePath.replaceFirst("soffice.bin", "soffice.exe"); + + COMReference<IObjectCollection> aCollection; + CoCreateInstance(CLSID_EnumerableObjectCollection, nullptr, CLSCTX_INPROC_SERVER, + IID_PPV_ARGS(&aCollection)); + + for (auto item : aJumpListItems) + { + if (item.name.isEmpty()) + continue; + try + { + COMReference<IShellLinkW> pShellLinkItem; + CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, + IID_PPV_ARGS(&pShellLinkItem)); + + { + COMReference<IPropertyStore> pps(pShellLinkItem, COM_QUERY_THROW); + + PROPVARIANT propvar; + sal::systools::ThrowIfFailed( + InitPropVariantFromString(o3tl::toW(item.name.getStr()), &propvar), + "InitPropVariantFromString failed."); + + ThrowIfFailed(pps->SetValue(PKEY_Title, propvar), "SetValue failed."); + + ThrowIfFailed(pps->Commit(), "Commit failed."); + + PropVariantClear(&propvar); + } + ThrowIfFailed( + pShellLinkItem->SetDescription(o3tl::toW(item.description.getStr())), + OString("Setting description '" + item.description.toUtf8() + "' failed.")); + + ThrowIfFailed(pShellLinkItem->SetPath(o3tl::toW(sofficePath.getStr())), + OString("Setting path '" + sofficePath.toUtf8() + "' failed.")); + + ThrowIfFailed( + pShellLinkItem->SetArguments(o3tl::toW(item.arguments.getStr())), + OString("Setting arguments '" + item.arguments.toUtf8() + "' failed.")); + + ThrowIfFailed( + pShellLinkItem->SetIconLocation(o3tl::toW(item.iconPath.getStr()), 0), + OString("Setting icon path '" + item.iconPath.toUtf8() + "' failed.")); + + aCollection->AddObject(pShellLinkItem.get()); + } + catch (const ComError& e) + { + SAL_WARN("shell.jumplist", e.what()); + continue; + } + } + + sal::systools::COMReference<IObjectArray> pObjectArray(aCollection, COM_QUERY_THROW); + ThrowIfFailed( + aDestinationList->AppendCategory(o3tl::toW(sCategory.getStr()), pObjectArray.get()), + "AppendCategory failed. You are not allowed to immediately re-insert entries which " + "were removed by the user. Please see the output of `getRemovedItems`."); + + ThrowIfFailed(aDestinationList->CommitList(), "CommitList failed."); + } + catch (const ComError& e) + { + SAL_WARN("shell.jumplist", e.what()); + } +} + +Sequence<JumpListItem> SAL_CALL JumpListImpl::getRemovedItems(const OUString& sApplication) +{ + if (sApplication != "Writer" && sApplication != "Calc" && sApplication != "Impress" + && sApplication != "Draw" && sApplication != "Math" && sApplication != "Base" + && sApplication != "Startcenter") + { + throw IllegalArgumentException( + "Parameter 'application' must be one of 'Writer', 'Calc', 'Impress', 'Draw', " + "'Math', 'Base', 'Startcenter'.", + static_cast<OWeakObject*>(this), 1); + } + OUString sApplicationID("TheDocumentFoundation.LibreOffice." + sApplication); + + std::vector<JumpListItem> removedItems; + try + { + sal::systools::COMReference<ICustomDestinationList> aDestinationList; + CoCreateInstance(CLSID_DestinationList, nullptr, CLSCTX_INPROC_SERVER, + IID_PPV_ARGS(&aDestinationList)); + + aDestinationList->SetAppID(o3tl::toW(sApplicationID.getStr())); + + sal::systools::COMReference<IObjectArray> removed; + ThrowIfFailed(aDestinationList->GetRemovedDestinations(IID_PPV_ARGS(&removed)), + "BeginList failed"); + + UINT removed_count; + if (SUCCEEDED(removed->GetCount(&removed_count) && (removed_count > 0))) + { + JumpListItem item; + sal::systools::COMReference<IShellLinkW> pShellLinkItem; + for (UINT i = 0; i < removed_count; ++i) + { + if (SUCCEEDED(removed->GetAt(i, IID_PPV_ARGS(&pShellLinkItem)))) + { + sal::systools::COMReference<IPropertyStore> propertyStore(pShellLinkItem, + COM_QUERY_THROW); + PROPVARIANT propvar; + ThrowIfFailed(propertyStore->GetValue(PKEY_Title, &propvar), + "GetValue failed."); + item.name = o3tl::toU(PropVariantToStringWithDefault(propvar, L"")); + + ThrowIfFailed(propertyStore->GetValue(PKEY_Link_Arguments, &propvar), + "GetValue failed."); + item.arguments = o3tl::toU(PropVariantToStringWithDefault(propvar, L"")); + PropVariantClear(&propvar); + + wchar_t itemDesc[MAX_PATH]; + ThrowIfFailed(pShellLinkItem->GetDescription( + itemDesc, std::extent<decltype(itemDesc)>::value), + "GetDescription failed."); + item.description = o3tl::toU(itemDesc); + + wchar_t path[MAX_PATH]; + int icon_index; + ThrowIfFailed(pShellLinkItem->GetIconLocation( + path, std::extent<decltype(path)>::value, &icon_index), + "GetIconLocation failed."); + item.iconPath = o3tl::toU(path); + + removedItems.emplace_back(item); + } + } + } + } + catch (const ComError& e) + { + SAL_WARN("shell.jumplist", e.what()); + } + + return containerToSequence(removedItems); +} + +// XServiceInfo + +OUString SAL_CALL JumpListImpl::getImplementationName() +{ + return "com.sun.star.system.windows.JumpListImpl"; +} + +sal_Bool SAL_CALL JumpListImpl::supportsService(const OUString& ServiceName) +{ + return cppu::supportsService(this, ServiceName); +} + +Sequence<OUString> SAL_CALL JumpListImpl::getSupportedServiceNames() +{ + return { "com.sun.star.system.windows.JumpList" }; +} + +extern "C" SAL_DLLPUBLIC_EXPORT XInterface* +shell_JumpListExec_get_implementation(XComponentContext* context, Sequence<Any> const&) +{ + return acquire(new JumpListImpl(context)); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/shell/source/win32/jumplist/jumplist.component b/shell/source/win32/jumplist/jumplist.component new file mode 100755 index 000000000000..b6b6a9aa632d --- /dev/null +++ b/shell/source/win32/jumplist/jumplist.component @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * +--> + +<component loader="com.sun.star.loader.SharedLibrary" environment="@CPPU_ENV@" + xmlns="http://openoffice.org/2010/uno-components"> + <implementation name="com.sun.star.system.windows.JumpListImpl" + constructor="shell_JumpListExec_get_implementation"> + <service name="com.sun.star.system.windows.JumpList"/> + </implementation> +</component> commit 012b4a1bc3fd8deb6f04f08ab15a19c1c613795e Author: Samuel Mehrbrodt <samuel.mehrbr...@allotropia.de> AuthorDate: Wed Mar 23 14:05:53 2022 +0100 Commit: Samuel Mehrbrodt <samuel.mehrbr...@allotropia.de> CommitDate: Fri Mar 25 10:27:05 2022 +0100 Use sal::systools::COMReference in getAdoDatalink Partial backport of commit 996610352fd0fc5d57a9231fa7fb3d43533863d6 Change-Id: I1221757d54a90357c5fb8b3ee3fc967fce9c76c6 diff --git a/include/systools/win32/comtools.hxx b/include/systools/win32/comtools.hxx index 8f2d94027952..a675ed2dc6d9 100644 --- a/include/systools/win32/comtools.hxx +++ b/include/systools/win32/comtools.hxx @@ -21,6 +21,7 @@ #define INCLUDED_SYSTOOLS_WIN32_COMTOOLS_HXX #include <string> +#include <string_view> #include <stdexcept> #include <type_traits> #include <objbase.h> @@ -49,6 +50,36 @@ namespace systools HRESULT hr_; }; + /* Convert failed HRESULT to thrown ComError */ + inline void ThrowIfFailed(HRESULT hr, std::string_view msg) + { + if (FAILED(hr)) + throw ComError(std::string(msg), hr); + } + /* A guard class to call CoInitializeEx/CoUninitialize in proper pairs + * See also: o3tl::safeCoInitializeEx doing dangerous re-initialization + */ + class CoInitializeGuard + { + public: + explicit CoInitializeGuard(DWORD dwCoInit, bool bThrowOnChangeMode = false) + { + HRESULT hr = ::CoInitializeEx(nullptr, dwCoInit); + if (FAILED(hr) && (bThrowOnChangeMode || hr != RPC_E_CHANGED_MODE)) + throw ComError("CoInitializeEx failed", hr); + mbUninit = SUCCEEDED(hr); + } + CoInitializeGuard(const CoInitializeGuard&) = delete; // non-construction-copyable + void operator=(const CoInitializeGuard&) = delete; // non-copyable + ~CoInitializeGuard() + { + if (mbUninit) + CoUninitialize(); + } + private: + bool mbUninit; + }; + struct COM_QUERY_TAG {} constexpr COM_QUERY; struct COM_QUERY_THROW_TAG {} constexpr COM_QUERY_THROW; template <typename TAG> @@ -118,7 +149,7 @@ namespace systools COMReference<T2> QueryInterface(TAG) const { void* ip = nullptr; - HRESULT hr = E_FAIL; + HRESULT hr = E_POINTER; if (com_ptr_) hr = com_ptr_->QueryInterface(__uuidof(T2), &ip); if constexpr (std::is_same_v<TAG, COM_QUERY_THROW_TAG>) commit 22e386103fc49fa222fb187a8cef44300610fc49 Author: Julien Nabet <serval2...@yahoo.fr> AuthorDate: Thu Jun 4 12:27:39 2020 +0200 Commit: Samuel Mehrbrodt <samuel.mehrbr...@allotropia.de> CommitDate: Fri Mar 25 10:27:05 2022 +0100 Improve COM library management in fpicker Inspired from: author Julien Nabet <serval2...@yahoo.fr> 2020-05-29 23:58:59 +0200 committer Mike Kaganski <mike.kagan...@collabora.com> 2020-06-03 23:04:27 +0200 commit 95e5d37b6e62eb39f2d5337e124e86b3d0c3f399 (patch) tree 5488826b390c04a2b32d2f9aa43f49a64f52db3d parent 3d3cb4328ece843b3e31b8411f9d16bbedb57a7b (diff) Improve COM library management in ADO Reviewed-on: https://gerrit.libreoffice.org/c/core/+/95498 Reviewed-by: Mike Kaganski <mike.kagan...@collabora.com> Tested-by: Jenkins (cherry picked from commit 08e02ae9606f6cb7ef49745ebe177089ed6d39fa) Change-Id: If0b136cdcc89baa6bc90912d42b3ba07fa6c0efb diff --git a/fpicker/source/win32/VistaFilePickerImpl.cxx b/fpicker/source/win32/VistaFilePickerImpl.cxx index a4b5a88c5d48..1b27010df780 100644 --- a/fpicker/source/win32/VistaFilePickerImpl.cxx +++ b/fpicker/source/win32/VistaFilePickerImpl.cxx @@ -189,6 +189,7 @@ VistaFilePickerImpl::VistaFilePickerImpl() , m_bWasExecuted (false) , m_sDirectory () , m_sFilename () + , mnNbCallCoInitializeExForReinit(0) { m_hParentWindow = choose_parent_window(); } @@ -208,15 +209,7 @@ void VistaFilePickerImpl::before() // osl::Thread class initializes COm already in MTA mode because it's needed // by VCL and UNO so. There is no way to change that from outside... // but we need a STA environment... - // So we make it by try-and-error... - // If first CoInitialize will fail... we uninitialize COM initialize it new .-) - - m_hLastResult = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); - if ( FAILED(m_hLastResult) ) - { - CoUninitialize(); - m_hLastResult = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); - } + m_hLastResult = o3tl::safeCoInitializeEx(COINIT_APARTMENTTHREADED, mnNbCallCoInitializeExForReinit); } @@ -324,7 +317,7 @@ void VistaFilePickerImpl::doRequest(const RequestRef& rRequest) void VistaFilePickerImpl::after() { - CoUninitialize(); + o3tl::safeCoUninitializeReinit(COINIT_MULTITHREADED, mnNbCallCoInitializeExForReinit); } diff --git a/fpicker/source/win32/VistaFilePickerImpl.hxx b/fpicker/source/win32/VistaFilePickerImpl.hxx index 9cce75b5714f..0895a574a652 100644 --- a/fpicker/source/win32/VistaFilePickerImpl.hxx +++ b/fpicker/source/win32/VistaFilePickerImpl.hxx @@ -36,6 +36,7 @@ #include <cppuhelper/basemutex.hxx> #include <osl/thread.hxx> #include <osl/conditn.hxx> +#include <o3tl/safeCoInitUninit.hxx> #include <rtl/ustring.hxx> namespace fpicker{ @@ -326,6 +327,9 @@ class VistaFilePickerImpl : private ::cppu::BaseMutex OUString m_sFilename; + + // to put back all the inits with COINIT_MULTITHREADED if needed + int mnNbCallCoInitializeExForReinit; }; } // namespace vista diff --git a/include/o3tl/safeCoInitUninit.hxx b/include/o3tl/safeCoInitUninit.hxx new file mode 100644 index 000000000000..0ceb4a9746a2 --- /dev/null +++ b/include/o3tl/safeCoInitUninit.hxx @@ -0,0 +1,58 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#pragma once + +#if defined _WIN32 +#include <prewin.h> + +// for CoInitializeEx / CoUninitialize +#include <combaseapi.h> + +#include <postwin.h> + +// for std::abort +#include <cstdlib> + +namespace o3tl +{ +// Helpers for safe calls to CoInitializeEx and CoUninitialize in MSVC +// Indeed if a thread has been already initialized with a concurrency model +// (in LO case COINIT_APARTMENTTHREADED or COINIT_MULTITHREADED) +// CoInitializeEx can't succeed without calling first CoUninitialize +// also, CoUninitialize must be called the number of times CoInitializeEx has been called +inline HRESULT safeCoInitializeEx(DWORD dwCoInit, int& nbReinit) +{ + HRESULT hr; + while ((hr = CoInitializeEx(nullptr, dwCoInit)) == RPC_E_CHANGED_MODE) + { + // so we're in RPC_E_CHANGED_MODE case + // the pb was it was already initialized with a different concurrency model + // close this init + CoUninitialize(); + // and increment counter for dtr part + ++nbReinit; + + // and keep on the loop if there were multi initializations + } + if (FAILED(hr)) + std::abort(); + return hr; +} + +inline void safeCoUninitializeReinit(DWORD dwCoInit, int nbReinit) +{ + CoUninitialize(); + // Put back all the inits, if there were, before the use of the caller to safeCoInitializeEx + for (int i = 0; i < nbReinit; ++i) + CoInitializeEx(nullptr, dwCoInit); +} +} +#endif +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ commit 0e9579ef444ac9b000f1080394da26859691315d Author: Samuel Mehrbrodt <samuel.mehrbr...@allotropia.de> AuthorDate: Thu Mar 24 09:32:43 2022 +0100 Commit: Samuel Mehrbrodt <samuel.mehrbr...@allotropia.de> CommitDate: Fri Mar 25 10:27:05 2022 +0100 Drop ComPtr and use sal::systools::COMReference Partial backport of ed40d477b2412d4f23540052ca0748028c6103e6 Change-Id: I3a852a5172d363c2f37f8c4066e1e2f6a18e7c37 diff --git a/dtrans/source/win32/dtobj/FmtFilter.cxx b/dtrans/source/win32/dtobj/FmtFilter.cxx index 0b60cb51c109..c65512e8a4e9 100644 --- a/dtrans/source/win32/dtobj/FmtFilter.cxx +++ b/dtrans/source/win32/dtobj/FmtFilter.cxx @@ -302,15 +302,12 @@ static std::wstring getShellLinkTarget(const std::wstring& aLnkFile) try { sal::systools::COMReference<IShellLinkW> pIShellLink; - HRESULT hr = CoCreateInstance( - CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_IShellLinkW, reinterpret_cast<LPVOID*>(&pIShellLink)); - if (FAILED(hr)) - return target; + pIShellLink.CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER); - sal::systools::COMReference<IPersistFile> pIPersistFile = - pIShellLink.QueryInterface<IPersistFile>(IID_IPersistFile); + sal::systools::COMReference<IPersistFile> pIPersistFile(pIShellLink, + sal::systools::COM_QUERY_THROW); - hr = pIPersistFile->Load(aLnkFile.c_str(), STGM_READ); + HRESULT hr = pIPersistFile->Load(aLnkFile.c_str(), STGM_READ); if (FAILED(hr)) return target; diff --git a/include/systools/win32/comtools.hxx b/include/systools/win32/comtools.hxx index 8f7ce87e7636..8f2d94027952 100644 --- a/include/systools/win32/comtools.hxx +++ b/include/systools/win32/comtools.hxx @@ -22,6 +22,7 @@ #include <string> #include <stdexcept> +#include <type_traits> #include <objbase.h> namespace sal @@ -48,6 +49,12 @@ namespace systools HRESULT hr_; }; + struct COM_QUERY_TAG {} constexpr COM_QUERY; + struct COM_QUERY_THROW_TAG {} constexpr COM_QUERY_THROW; + template <typename TAG> + constexpr bool is_COM_query_tag + = std::is_same_v<TAG, COM_QUERY_TAG> || std::is_same_v<TAG, COM_QUERY_THROW_TAG>; + /* A simple COM smart pointer template */ template <typename T> class COMReference @@ -64,6 +71,13 @@ namespace systools addRef(); } + // Query from IUnknown*, using COM_QUERY or COM_QUERY_THROW tags + template <typename T2, typename TAG> + COMReference(const COMReference<T2>& p, TAG t) + : COMReference(p.QueryInterface<T>(t)) + { + } + /* Explicitly controllable whether AddRef will be called or not */ COMReference(T* comptr, bool bAddRef) : com_ptr_(comptr) @@ -100,18 +114,30 @@ namespace systools release(); } - template<typename InterfaceType> - COMReference<InterfaceType> QueryInterface(REFIID iid) + template <typename T2, typename TAG, std::enable_if_t<is_COM_query_tag<TAG>, int> = 0> + COMReference<T2> QueryInterface(TAG) const { - COMReference<InterfaceType> ip; + void* ip = nullptr; HRESULT hr = E_FAIL; if (com_ptr_) - hr = com_ptr_->QueryInterface(iid, reinterpret_cast<LPVOID*>(&ip)); + hr = com_ptr_->QueryInterface(__uuidof(T2), &ip); + if constexpr (std::is_same_v<TAG, COM_QUERY_THROW_TAG>) + if (FAILED(hr)) + throw ComError("QueryInterface failed: Interface not supported!", hr); + return { static_cast<T2*>(ip), false }; + } + + COMReference<T>& CoCreateInstance(REFCLSID clsid, IUnknown* pOuter = nullptr, + DWORD nCtx = CLSCTX_ALL) + { + clear(); + HRESULT hr = ::CoCreateInstance(clsid, pOuter, nCtx, __uuidof(T), + reinterpret_cast<void**>(&com_ptr_)); if (FAILED(hr)) - throw ComError("QueryInterface failed: Interface not supported!", hr); + throw ComError("CoCreateInstance failed!", hr); - return ip; + return *this; } T* operator->() const @@ -138,11 +164,10 @@ namespace systools return com_ptr_; } - COMReference<T>& clear() + void clear() { release(); com_ptr_ = NULL; - return *this; } bool is() const diff --git a/shell/source/win32/SysShExec.cxx b/shell/source/win32/SysShExec.cxx index 00384b8bd235..4d9ba43a6cc3 100644 --- a/shell/source/win32/SysShExec.cxx +++ b/shell/source/win32/SysShExec.cxx @@ -361,25 +361,27 @@ void SAL_CALL CSysShExec::execute( const OUString& aCommand, const OUString& aPa break; } sal::systools::COMReference<IShellLinkW> link; - auto e2 = CoCreateInstance( - CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_IShellLinkW, - reinterpret_cast<LPVOID *>(&link)); - if (FAILED(e2)) { + try + { + link.CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER); + } + catch (sal::systools::ComError& e) + { throw css::lang::IllegalArgumentException( ("XSystemShellExecute.execute, CoCreateInstance failed with " - + OUString::number(e2)), + + OUString::number(e.GetHresult())), {}, 0); } sal::systools::COMReference<IPersistFile> file; try { - file = link.QueryInterface<IPersistFile>(IID_IPersistFile); + file = link.QueryInterface<IPersistFile>(sal::systools::COM_QUERY_THROW); } catch(sal::systools::ComError & e3) { throw css::lang::IllegalArgumentException( ("XSystemShellExecute.execute, QueryInterface failed with: " + o3tl::runtimeToOUString(e3.what())), {}, 0); } - e2 = file->Load(path, STGM_READ); + HRESULT e2 = file->Load(path, STGM_READ); if (FAILED(e2)) { throw css::lang::IllegalArgumentException( ("XSystemShellExecute.execute, IPersistFile.Load failed with "