diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-07 09:06:44 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-07 09:06:44 +0000 |
commit | ed5640d8b587fbcfed7dd7967f3de04b37a76f26 (patch) | |
tree | 7a5f7c6c9d02226d7471cb3cc8fbbf631b415303 /unotools/source/config | |
parent | Initial commit. (diff) | |
download | libreoffice-ed5640d8b587fbcfed7dd7967f3de04b37a76f26.tar.xz libreoffice-ed5640d8b587fbcfed7dd7967f3de04b37a76f26.zip |
Adding upstream version 4:7.4.7.upstream/4%7.4.7upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'unotools/source/config')
28 files changed, 13301 insertions, 0 deletions
diff --git a/unotools/source/config/bootstrap.cxx b/unotools/source/config/bootstrap.cxx new file mode 100644 index 000000000..ef7ba5700 --- /dev/null +++ b/unotools/source/config/bootstrap.cxx @@ -0,0 +1,720 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * 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/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <sal/config.h> + +#include <string_view> + +#include <config_folders.h> + +#include <unotools/bootstrap.hxx> + +#include <rtl/ustring.hxx> +#include <rtl/ustrbuf.hxx> +#include <sal/log.hxx> +#include <osl/file.hxx> +#include <osl/diagnose.h> + +#include <rtl/bootstrap.hxx> +#include <osl/process.h> + +// #define this to true, if remembering defaults is not supported properly +#define RTL_BOOTSTRAP_DEFAULTS_BROKEN true + +constexpr OUStringLiteral BOOTSTRAP_ITEM_PRODUCT_KEY = u"ProductKey"; +constexpr OUStringLiteral BOOTSTRAP_ITEM_VERSIONFILE = u"Location"; +constexpr OUStringLiteral BOOTSTRAP_ITEM_BUILDID = u"buildid"; + +constexpr OUStringLiteral BOOTSTRAP_ITEM_BASEINSTALLATION = u"BRAND_BASE_DIR"; +constexpr OUStringLiteral BOOTSTRAP_ITEM_USERINSTALLATION = u"UserInstallation"; + +constexpr OUStringLiteral BOOTSTRAP_ITEM_USERDIR = u"UserDataDir"; + +constexpr OUStringLiteral BOOTSTRAP_DEFAULT_BASEINSTALL = u"$SYSBINDIR/.."; + +constexpr OUStringLiteral BOOTSTRAP_DIRNAME_USERDIR = u"user"; + +typedef char const * AsciiString; + +namespace utl +{ + +// Implementation class: Bootstrap::Impl + +static OUString makeImplName() +{ + OUString uri; + rtl::Bootstrap::get( "BRAND_BASE_DIR", uri); + return uri + "/" LIBO_ETC_FOLDER "/" SAL_CONFIGFILE("bootstrap"); +} + +class Bootstrap::Impl +{ + const OUString m_aImplName; +public: // struct to cache the result of a path lookup + struct PathData + { + OUString path; + PathStatus status; + + PathData() + : status(DATA_UNKNOWN) + {} + }; +public: // data members + // base install data + PathData aBaseInstall_; + + // user install data + PathData aUserInstall_; + + // INI files + PathData aBootstrapINI_; + PathData aVersionINI_; + + // overall status + Status status_; + +public: // construction and initialization + Impl() : m_aImplName(makeImplName()) + { + initialize(); + } + + void initialize(); + + // access helper + OUString getBootstrapValue(OUString const& _sName, OUString const& _sDefault) const; + + const OUString& getImplName() const { return m_aImplName; } + +private: // implementation + bool initBaseInstallationData(rtl::Bootstrap const & _rData); + bool initUserInstallationData(rtl::Bootstrap const & _rData); +}; + +namespace +{ + Bootstrap::Impl& theImpl() + { + static Bootstrap::Impl SINGLETON; + return SINGLETON; + } +} + +const Bootstrap::Impl& Bootstrap::data() +{ + return theImpl(); +} + +bool Bootstrap::getProcessWorkingDir(OUString &rUrl) +{ + rUrl.clear(); + OUString s("$OOO_CWD"); + rtl::Bootstrap::expandMacros(s); + if (s.isEmpty()) + { + if (osl_getProcessWorkingDir(&rUrl.pData) == osl_Process_E_None) + return true; + } + else if (s[0] == '1') + { + rUrl = s.copy(1); + return true; + } + else if (s[0] == '2' && + (osl::FileBase::getFileURLFromSystemPath(s.copy(1), rUrl) == + osl::FileBase::E_None)) + { + return true; + } + return false; +} + +void Bootstrap::reloadData() +{ + theImpl().initialize(); +} + +// helper + +typedef Bootstrap::PathStatus PathStatus; + +sal_Unicode const cURLSeparator = '/'; + +// path status utility function +static PathStatus implCheckStatusOfURL(OUString const& _sURL, osl::DirectoryItem& aDirItem) +{ + using namespace osl; + + PathStatus eStatus = Bootstrap::DATA_UNKNOWN; + + if (!_sURL.isEmpty()) + { + switch( DirectoryItem::get(_sURL, aDirItem) ) + { + case DirectoryItem::E_None: // Success + eStatus = Bootstrap::PATH_EXISTS; + break; + + case DirectoryItem::E_NOENT: // No such file or directory + eStatus = Bootstrap::PATH_VALID; + break; + + case DirectoryItem::E_INVAL: // the format of the parameters was not valid + case DirectoryItem::E_NAMETOOLONG: // File name too long + case DirectoryItem::E_NOTDIR: // A component of the path prefix of path is not a directory + eStatus = Bootstrap::DATA_INVALID; + break; + + // how to handle these ? + case DirectoryItem::E_LOOP: // Too many symbolic links encountered + case DirectoryItem::E_ACCES: // permission denied + // any other error - what to do ? + default: + eStatus = Bootstrap::DATA_UNKNOWN; + break; + } + } + else + { + eStatus = Bootstrap::DATA_MISSING; + } + + return eStatus; +} + +static bool implNormalizeURL(OUString & _sURL, osl::DirectoryItem& aDirItem) +{ + using namespace osl; + + OSL_PRECOND(aDirItem.is(), "Opened DirItem required"); + + static const sal_uInt32 cosl_FileStatus_Mask = osl_FileStatus_Mask_FileURL; + + FileStatus aFileStatus(cosl_FileStatus_Mask); + + if (aDirItem.getFileStatus(aFileStatus) != DirectoryItem::E_None) + return false; + + OUString aNormalizedURL = aFileStatus.getFileURL(); + + if (aNormalizedURL.isEmpty()) + return false; + + // #109863# sal/osl returns final slash for file URLs contradicting + // the URL/URI RFCs. + if ( !aNormalizedURL.endsWith(OUStringChar(cURLSeparator)) ) + _sURL = aNormalizedURL; + else + _sURL = aNormalizedURL.copy( 0, aNormalizedURL.getLength()-1 ); + + return true; +} + +static bool implEnsureAbsolute(OUString & _rsURL) // also strips embedded dots !! +{ + using osl::File; + + OUString sBasePath; + OSL_VERIFY(Bootstrap::getProcessWorkingDir(sBasePath)); + + OUString sAbsolute; + if ( File::E_None == File::getAbsoluteFileURL(sBasePath, _rsURL, sAbsolute)) + { + _rsURL = sAbsolute; + return true; + } + else + { + OSL_FAIL("Could not get absolute file URL for URL"); + return false; + } +} + +static bool implMakeAbsoluteURL(OUString & _rsPathOrURL) +{ + using namespace osl; + + bool bURL; + + OUString sOther; + // check if it already was normalized + if ( File::E_None == File::getSystemPathFromFileURL(_rsPathOrURL, sOther) ) + { + bURL = true; + } + + else if ( File::E_None == File::getFileURLFromSystemPath(_rsPathOrURL, sOther) ) + { + _rsPathOrURL = sOther; + bURL = true; + } + else + bURL = false; + + return bURL && implEnsureAbsolute(_rsPathOrURL); +} + +static PathStatus dbgCheckStatusOfURL(OUString const& _sURL) +{ + using namespace osl; + + DirectoryItem aDirItem; + + return implCheckStatusOfURL(_sURL,aDirItem); +} + +static PathStatus checkStatusAndNormalizeURL(OUString & _sURL) +{ + using namespace osl; + + PathStatus eStatus = Bootstrap::DATA_UNKNOWN; + + if (_sURL.isEmpty()) + eStatus = Bootstrap::DATA_MISSING; + + else if ( !implMakeAbsoluteURL(_sURL) ) + eStatus = Bootstrap::DATA_INVALID; + + else + { + DirectoryItem aDirItem; + + eStatus = implCheckStatusOfURL(_sURL,aDirItem); + + if (eStatus == Bootstrap::PATH_EXISTS && !implNormalizeURL(_sURL,aDirItem)) + OSL_FAIL("Unexpected failure getting actual URL for existing object"); + } + return eStatus; +} + +// helpers to build and check a nested URL +static PathStatus getDerivedPath( + OUString& _rURL, + OUString const& _aBaseURL, PathStatus _aBaseStatus, + std::u16string_view _sRelativeURL, + rtl::Bootstrap const & _rData, OUString const& _sBootstrapParameter + ) +{ + OUString sDerivedURL; + OSL_PRECOND(!_rData.getFrom(_sBootstrapParameter,sDerivedURL),"Setting for derived path is already defined"); + OSL_PRECOND(!_sRelativeURL.empty() && _sRelativeURL[0] != cURLSeparator,"Invalid Relative URL"); + + PathStatus aStatus = _aBaseStatus; + + // do we have a base path ? + if (!_aBaseURL.isEmpty()) + { + OSL_PRECOND(!_aBaseURL.endsWith(OUStringChar(cURLSeparator)), "Unexpected: base URL ends in slash"); + + sDerivedURL = _aBaseURL + OUStringChar(cURLSeparator) + _sRelativeURL; + + // a derived (nested) URL can only exist or have a lesser status, if the parent exists + if (aStatus == Bootstrap::PATH_EXISTS) + aStatus = checkStatusAndNormalizeURL(sDerivedURL); + + else // the relative appendix must be valid + OSL_ASSERT(aStatus != Bootstrap::PATH_VALID || dbgCheckStatusOfURL(sDerivedURL) == Bootstrap::PATH_VALID); + + _rData.getFrom(_sBootstrapParameter, _rURL, sDerivedURL); + + OSL_ENSURE(sDerivedURL == _rURL,"Could not set derived URL via Bootstrap default parameter"); + SAL_WARN_IF( !(RTL_BOOTSTRAP_DEFAULTS_BROKEN || (_rData.getFrom(_sBootstrapParameter,sDerivedURL) && sDerivedURL==_rURL)), + "unotools.config", + "Use of default did not affect bootstrap value"); + } + else + { + // clear the result + _rURL = _aBaseURL; + + // if we have no data it can't be a valid path + OSL_ASSERT( aStatus > Bootstrap::PATH_VALID ); + } + + return aStatus; +} + +static PathStatus getDerivedPath( + OUString& _rURL, + Bootstrap::Impl::PathData const& _aBaseData, + std::u16string_view _sRelativeURL, + rtl::Bootstrap const & _rData, OUString const& _sBootstrapParameter + ) +{ + return getDerivedPath(_rURL,_aBaseData.path,_aBaseData.status,_sRelativeURL,_rData,_sBootstrapParameter); +} + +static OUString getExecutableBaseName() +{ + OUString sExecutable; + + if (osl_Process_E_None == osl_getExecutableFile(&sExecutable.pData)) + { + // split the executable name + sal_Int32 nSepIndex = sExecutable.lastIndexOf(cURLSeparator); + + sExecutable = sExecutable.copy(nSepIndex + 1); + + // ... and get the basename (strip the extension) + sal_Unicode const cExtensionSep = '.'; + + sal_Int32 const nExtIndex = sExecutable.lastIndexOf(cExtensionSep); + sal_Int32 const nExtLength = sExecutable.getLength() - nExtIndex - 1; + if (0 < nExtIndex && nExtLength < 4) + sExecutable = sExecutable.copy(0,nExtIndex); + } + else + SAL_WARN("unotools.config", "Cannot get executable name: osl_getExecutableFile failed"); + + return sExecutable; +} + +static Bootstrap::PathStatus updateStatus(Bootstrap::Impl::PathData & _rResult) +{ + _rResult.status = checkStatusAndNormalizeURL(_rResult.path); + return _rResult.status; +} + +static Bootstrap::PathStatus implGetBootstrapFile(rtl::Bootstrap const & _rData, Bootstrap::Impl::PathData & _rBootstrapFile) +{ + _rData.getIniName(_rBootstrapFile.path); + + return updateStatus(_rBootstrapFile); +} + +static Bootstrap::PathStatus implGetVersionFile(rtl::Bootstrap const & _rData, Bootstrap::Impl::PathData & _rVersionFile) +{ + _rData.getFrom(BOOTSTRAP_ITEM_VERSIONFILE, _rVersionFile.path); + + return updateStatus(_rVersionFile); +} + +// Error reporting + +char const IS_MISSING[] = "is missing"; +char const IS_INVALID[] = "is corrupt"; +char const PERIOD[] = ". "; + +static void addFileError(OUStringBuffer& _rBuf, std::u16string_view _aPath, AsciiString _sWhat) +{ + std::u16string_view sSimpleFileName = _aPath.substr(1 +_aPath.rfind(cURLSeparator)); + + _rBuf.append("The configuration file"); + _rBuf.append(OUString::Concat(" '") + sSimpleFileName + "' "); + _rBuf.appendAscii(_sWhat).append(PERIOD); +} + +static void addMissingDirectoryError(OUStringBuffer& _rBuf, std::u16string_view _aPath) +{ + _rBuf.append(OUString::Concat("The configuration directory '") + _aPath + "' " + + IS_MISSING + PERIOD); +} + +static void addUnexpectedError(OUStringBuffer& _rBuf, AsciiString _sExtraInfo = nullptr) +{ + if (nullptr == _sExtraInfo) + _sExtraInfo = "An internal failure occurred"; + + _rBuf.appendAscii(_sExtraInfo).append(PERIOD); +} + +static Bootstrap::FailureCode describeError(OUStringBuffer& _rBuf, Bootstrap::Impl const& _rData) +{ + Bootstrap::FailureCode eErrCode = Bootstrap::INVALID_BOOTSTRAP_DATA; + + _rBuf.append("The program cannot be started. "); + + switch (_rData.aUserInstall_.status) + { + case Bootstrap::PATH_EXISTS: + switch (_rData.aBaseInstall_.status) + { + case Bootstrap::PATH_VALID: + addMissingDirectoryError(_rBuf, _rData.aBaseInstall_.path); + eErrCode = Bootstrap::MISSING_INSTALL_DIRECTORY; + break; + + case Bootstrap::DATA_INVALID: + addUnexpectedError(_rBuf,"The installation path is invalid"); + break; + + case Bootstrap::DATA_MISSING: + addUnexpectedError(_rBuf,"The installation path is not available"); + break; + + case Bootstrap::PATH_EXISTS: // seems to be all fine (?) + addUnexpectedError(_rBuf,""); + break; + + default: OSL_ASSERT(false); + addUnexpectedError(_rBuf); + break; + } + break; + + case Bootstrap::PATH_VALID: + addMissingDirectoryError(_rBuf, _rData.aUserInstall_.path); + eErrCode = Bootstrap::MISSING_USER_DIRECTORY; + break; + + // else fall through + case Bootstrap::DATA_INVALID: + if (_rData.aVersionINI_.status == Bootstrap::PATH_EXISTS) + { + addFileError(_rBuf, _rData.aVersionINI_.path, IS_INVALID); + eErrCode = Bootstrap::INVALID_VERSION_FILE_ENTRY; + break; + } + [[fallthrough]]; + + case Bootstrap::DATA_MISSING: + switch (_rData.aVersionINI_.status) + { + case Bootstrap::PATH_EXISTS: + addFileError(_rBuf, _rData.aVersionINI_.path, "does not support the current version"); + eErrCode = Bootstrap::MISSING_VERSION_FILE_ENTRY; + break; + + case Bootstrap::PATH_VALID: + addFileError(_rBuf, _rData.aVersionINI_.path, IS_MISSING); + eErrCode = Bootstrap::MISSING_VERSION_FILE; + break; + + default: + switch (_rData.aBootstrapINI_.status) + { + case Bootstrap::PATH_EXISTS: + addFileError(_rBuf, _rData.aBootstrapINI_.path, IS_INVALID); + + if (_rData.aVersionINI_.status == Bootstrap::DATA_MISSING) + eErrCode = Bootstrap::MISSING_BOOTSTRAP_FILE_ENTRY; + else + eErrCode = Bootstrap::INVALID_BOOTSTRAP_FILE_ENTRY; + break; + + case Bootstrap::DATA_INVALID: OSL_ASSERT(false); [[fallthrough]]; + case Bootstrap::PATH_VALID: + addFileError(_rBuf, _rData.aBootstrapINI_.path, IS_MISSING); + eErrCode = Bootstrap::MISSING_BOOTSTRAP_FILE; + break; + + default: + addUnexpectedError(_rBuf); + break; + } + break; + } + break; + + default: OSL_ASSERT(false); + addUnexpectedError(_rBuf); + break; + } + + return eErrCode; +} + + +OUString Bootstrap::getProductKey() +{ + OUString const sDefaultProductKey = getExecutableBaseName(); + + return data().getBootstrapValue( BOOTSTRAP_ITEM_PRODUCT_KEY, sDefaultProductKey ); +} + +OUString Bootstrap::getProductKey(OUString const& _sDefault) +{ + return data().getBootstrapValue( BOOTSTRAP_ITEM_PRODUCT_KEY, _sDefault ); +} + +OUString Bootstrap::getBuildIdData(OUString const& _sDefault) +{ + // try to open version.ini (versionrc) + OUString uri; + rtl::Bootstrap::get( "BRAND_BASE_DIR", uri); + rtl::Bootstrap aData( uri + "/" LIBO_ETC_FOLDER "/" SAL_CONFIGFILE("version") ); + if ( aData.getHandle() == nullptr ) + // version.ini (versionrc) doesn't exist + return _sDefault; + + // read value + OUString sBuildId; + aData.getFrom(BOOTSTRAP_ITEM_BUILDID,sBuildId,_sDefault); + return sBuildId; +} + +Bootstrap::PathStatus Bootstrap::locateBaseInstallation(OUString& _rURL) +{ + Impl::PathData const& aPathData = data().aBaseInstall_; + + _rURL = aPathData.path; + return aPathData.status; +} + +Bootstrap::PathStatus Bootstrap::locateUserInstallation(OUString& _rURL) +{ + Impl::PathData const& aPathData = data().aUserInstall_; + + _rURL = aPathData.path; + return aPathData.status; +} + +Bootstrap::PathStatus Bootstrap::locateUserData(OUString& _rURL) +{ + OUString const csUserDirItem(BOOTSTRAP_ITEM_USERDIR); + + rtl::Bootstrap aData( data().getImplName() ); + + if ( aData.getFrom(csUserDirItem, _rURL) ) + { + return checkStatusAndNormalizeURL(_rURL); + } + else + { + return getDerivedPath(_rURL, data().aUserInstall_ ,BOOTSTRAP_DIRNAME_USERDIR, aData, csUserDirItem); + } +} + +Bootstrap::PathStatus Bootstrap::locateBootstrapFile(OUString& _rURL) +{ + Impl::PathData const& aPathData = data().aBootstrapINI_; + + _rURL = aPathData.path; + return aPathData.status; +} + +Bootstrap::PathStatus Bootstrap::locateVersionFile(OUString& _rURL) +{ + Impl::PathData const& aPathData = data().aVersionINI_; + + _rURL = aPathData.path; + return aPathData.status; +} + +Bootstrap::Status Bootstrap::checkBootstrapStatus(OUString& _rDiagnosticMessage, FailureCode& _rErrCode) +{ + Impl const& aData = data(); + + Status result = aData.status_; + + // maybe do further checks here + + OUStringBuffer sErrorBuffer; + if (result != DATA_OK) + _rErrCode = describeError(sErrorBuffer,aData); + + else + _rErrCode = NO_FAILURE; + + _rDiagnosticMessage = sErrorBuffer.makeStringAndClear(); + + return result; +} + + +bool Bootstrap::Impl::initBaseInstallationData(rtl::Bootstrap const & _rData) +{ + _rData.getFrom(BOOTSTRAP_ITEM_BASEINSTALLATION, aBaseInstall_.path, BOOTSTRAP_DEFAULT_BASEINSTALL); + + bool bResult = (PATH_EXISTS == updateStatus(aBaseInstall_)); + + implGetBootstrapFile(_rData, aBootstrapINI_); + + return bResult; +} + +bool Bootstrap::Impl::initUserInstallationData(rtl::Bootstrap const & _rData) +{ + if (_rData.getFrom(BOOTSTRAP_ITEM_USERINSTALLATION, aUserInstall_.path)) + { + updateStatus(aUserInstall_); + } + else + { + // should we do just this + aUserInstall_.status = DATA_MISSING; + + // ... or this - look for a single-user user directory ? + OUString const csUserDirItem(BOOTSTRAP_ITEM_USERDIR); + OUString sDummy; + // look for $BASEINSTALLATION/user only if default UserDir setting is used + if (! _rData.getFrom(csUserDirItem, sDummy)) + { + if ( PATH_EXISTS == getDerivedPath(sDummy, aBaseInstall_, BOOTSTRAP_DIRNAME_USERDIR, _rData, csUserDirItem) ) + aUserInstall_ = aBaseInstall_; + } + } + + bool bResult = (PATH_EXISTS == aUserInstall_.status); + + implGetVersionFile(_rData, aVersionINI_); + + return bResult; +} + +void Bootstrap::Impl::initialize() +{ + rtl::Bootstrap aData( m_aImplName ); + + if (!initBaseInstallationData(aData)) + { + status_ = INVALID_BASE_INSTALL; + } + else if (!initUserInstallationData(aData)) + { + status_ = INVALID_USER_INSTALL; + + if (aUserInstall_.status >= DATA_MISSING) + { + switch (aVersionINI_.status) + { + case PATH_EXISTS: + case PATH_VALID: + status_ = MISSING_USER_INSTALL; + break; + + case DATA_INVALID: + case DATA_MISSING: + status_ = INVALID_BASE_INSTALL; + break; + default: + break; + } + } + } + else + { + status_ = DATA_OK; + } +} + +OUString Bootstrap::Impl::getBootstrapValue(OUString const& _sName, OUString const& _sDefault) const +{ + rtl::Bootstrap aData( m_aImplName ); + + OUString sResult; + aData.getFrom(_sName,sResult,_sDefault); + return sResult; +} + +} // namespace utl + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/cmdoptions.cxx b/unotools/source/config/cmdoptions.cxx new file mode 100644 index 000000000..1408f22c2 --- /dev/null +++ b/unotools/source/config/cmdoptions.cxx @@ -0,0 +1,349 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * 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/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <sal/config.h> + +#include <sal/log.hxx> +#include <unotools/cmdoptions.hxx> +#include <unotools/configitem.hxx> +#include <tools/debug.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> +#include <com/sun/star/frame/XFrame.hpp> +#include <cppuhelper/weakref.hxx> + +#include "itemholder1.hxx" + +#include <algorithm> +#include <unordered_map> + +using namespace ::std; +using namespace ::utl; +using namespace ::osl; +using namespace ::com::sun::star::uno; +using namespace ::com::sun::star::beans; + +constexpr OUStringLiteral ROOTNODE_CMDOPTIONS = u"Office.Commands/Execute"; +#define PATHDELIMITER "/" + +#define SETNODE_DISABLED "Disabled" + +#define PROPERTYNAME_CMD "Command" + +namespace { + +/*-**************************************************************************************************************** + @descr support simple command option structures and operations on it +****************************************************************************************************************-*/ +class SvtCmdOptions +{ + public: + + // the only way to free memory! + void Clear() + { + m_aCommandHashMap.clear(); + } + + bool HasEntries() const + { + return ( !m_aCommandHashMap.empty() ); + } + + bool Lookup( const OUString& aCmd ) const + { + CommandHashMap::const_iterator pEntry = m_aCommandHashMap.find( aCmd ); + return ( pEntry != m_aCommandHashMap.end() ); + } + + void AddCommand( const OUString& aCmd ) + { + m_aCommandHashMap.emplace( aCmd, 0 ); + } + + private: + typedef std::unordered_map<OUString, sal_Int32> + CommandHashMap; + + CommandHashMap m_aCommandHashMap; +}; + +std::mutex& GetOwnStaticMutex() +{ + static std::mutex theCommandOptionsMutex; + return theCommandOptionsMutex; +} + +} + +typedef ::std::vector< css::uno::WeakReference< css::frame::XFrame > > SvtFrameVector; + +class SvtCommandOptions_Impl : public ConfigItem +{ + public: + + SvtCommandOptions_Impl(); + virtual ~SvtCommandOptions_Impl() override; + + /*-**************************************************************************************************** + @short called for notify of configmanager + @descr This method is called from the ConfigManager before the application ends or from the + PropertyChangeListener if the sub tree broadcasts changes. You must update your + internal values. + + @seealso baseclass ConfigItem + + @param "lPropertyNames" is the list of properties which should be updated. + *//*-*****************************************************************************************************/ + + virtual void Notify( const Sequence< OUString >& lPropertyNames ) override; + + /*-**************************************************************************************************** + @short base implementation of public interface for "SvtDynamicMenuOptions"! + @descr These class is used as static member of "SvtDynamicMenuOptions" ... + => The code exist only for one time and isn't duplicated for every instance! + *//*-*****************************************************************************************************/ + + bool HasEntries ( SvtCommandOptions::CmdOption eOption ) const; + bool Lookup ( SvtCommandOptions::CmdOption eCmdOption, const OUString& ) const; + void EstablishFrameCallback(const css::uno::Reference< css::frame::XFrame >& xFrame); + + private: + + virtual void ImplCommit() override; + + /*-**************************************************************************************************** + @short return list of key names of our configuration management which represent our module tree + @descr This method returns the current list of key names! We need it to get needed values from our + configuration management and support dynamical menu item lists! + @param "nDisabledCount", returns count of menu entries for "new" + @return A list of configuration key names is returned. + *//*-*****************************************************************************************************/ + + Sequence< OUString > impl_GetPropertyNames(); + + private: + SvtCmdOptions m_aDisabledCommands; + SvtFrameVector m_lFrames; +}; + +// constructor + +SvtCommandOptions_Impl::SvtCommandOptions_Impl() + // Init baseclasses first + : ConfigItem( ROOTNODE_CMDOPTIONS ) + // Init member then... +{ + // Get names and values of all accessible menu entries and fill internal structures. + // See impl_GetPropertyNames() for further information. + Sequence< OUString > lNames = impl_GetPropertyNames (); + Sequence< Any > lValues = GetProperties ( lNames ); + + // Safe impossible cases. + // We need values from ALL configuration keys. + // Follow assignment use order of values in relation to our list of key names! + DBG_ASSERT( !(lNames.getLength()!=lValues.getLength()), "SvtCommandOptions_Impl::SvtCommandOptions_Impl()\nI miss some values of configuration keys!\n" ); + + // Copy values from list in right order to our internal member. + // Attention: List for names and values have an internal construction pattern! + sal_Int32 nItem = 0; + OUString sCmd; + + // Get names/values for disabled commands. + for( nItem=0; nItem < lNames.getLength(); ++nItem ) + { + // Currently only one value + lValues[nItem] >>= sCmd; + m_aDisabledCommands.AddCommand( sCmd ); + } + +/*TODO: Not used in the moment! see Notify() ... + // Enable notification mechanism of our baseclass. + // We need it to get information about changes outside these class on our used configuration keys! */ + Sequence<OUString> aNotifySeq { "Disabled" }; + EnableNotification( aNotifySeq, true ); +} + +// destructor + +SvtCommandOptions_Impl::~SvtCommandOptions_Impl() +{ + assert(!IsModified()); // should have been committed +} + +// public method + +void SvtCommandOptions_Impl::Notify( const Sequence< OUString >& ) +{ + std::unique_lock aGuard( GetOwnStaticMutex() ); + + Sequence< OUString > lNames = impl_GetPropertyNames (); + Sequence< Any > lValues = GetProperties ( lNames ); + + // Safe impossible cases. + // We need values from ALL configuration keys. + // Follow assignment use order of values in relation to our list of key names! + DBG_ASSERT( !(lNames.getLength()!=lValues.getLength()), "SvtCommandOptions_Impl::Notify()\nI miss some values of configuration keys!\n" ); + + // Copy values from list in right order to our internal member. + // Attention: List for names and values have an internal construction pattern! + sal_Int32 nItem = 0; + OUString sCmd; + + m_aDisabledCommands.Clear(); + + // Get names/values for disabled commands. + for( nItem=0; nItem < lNames.getLength(); ++nItem ) + { + // Currently only one value + lValues[nItem] >>= sCmd; + m_aDisabledCommands.AddCommand( sCmd ); + } + + // don't forget to update all existing frames and her might cached dispatch objects! + // But look for already killed frames. We hold weak references instead of hard ones ... + for (SvtFrameVector::iterator pIt = m_lFrames.begin(); pIt != m_lFrames.end(); ) + { + css::uno::Reference< css::frame::XFrame > xFrame(pIt->get(), css::uno::UNO_QUERY); + if (xFrame.is()) + { + xFrame->contextChanged(); + ++pIt; + } + else + pIt = m_lFrames.erase(pIt); + } +} + +// public method + +void SvtCommandOptions_Impl::ImplCommit() +{ + SAL_WARN("unotools.config","SvtCommandOptions_Impl::ImplCommit(): Not implemented yet!"); +} + +// public method + +bool SvtCommandOptions_Impl::HasEntries( SvtCommandOptions::CmdOption eOption ) const +{ + if ( eOption == SvtCommandOptions::CMDOPTION_DISABLED ) + return m_aDisabledCommands.HasEntries(); + else + return false; +} + +// public method + +bool SvtCommandOptions_Impl::Lookup( SvtCommandOptions::CmdOption eCmdOption, const OUString& aCommand ) const +{ + switch( eCmdOption ) + { + case SvtCommandOptions::CMDOPTION_DISABLED: + { + return m_aDisabledCommands.Lookup( aCommand ); + } + default: + SAL_WARN( "unotools.config", "SvtCommandOptions_Impl::Lookup() Unknown option type given!" ); + } + + return false; +} + +// public method + +void SvtCommandOptions_Impl::EstablishFrameCallback(const css::uno::Reference< css::frame::XFrame >& xFrame) +{ + // check if frame already exists inside list + // ignore double registrations + // every frame must be notified one times only! + css::uno::WeakReference< css::frame::XFrame > xWeak(xFrame); + SvtFrameVector::const_iterator pIt = ::std::find(m_lFrames.begin(), m_lFrames.end(), xWeak); + if (pIt == m_lFrames.end()) + m_lFrames.push_back(xWeak); +} + +// private method + +Sequence< OUString > SvtCommandOptions_Impl::impl_GetPropertyNames() +{ + // First get ALL names of current existing list items in configuration! + Sequence< OUString > lDisabledItems = GetNodeNames( SETNODE_DISABLED, utl::ConfigNameFormat::LocalPath ); + + // Expand all keys + for (OUString& rItem : asNonConstRange(lDisabledItems)) + rItem = SETNODE_DISABLED PATHDELIMITER + rItem + PATHDELIMITER PROPERTYNAME_CMD; + + // Return result. + return lDisabledItems; +} + +namespace { + +std::weak_ptr<SvtCommandOptions_Impl> g_pCommandOptions; + +} + +SvtCommandOptions::SvtCommandOptions() +{ + // Global access, must be guarded (multithreading!). + std::unique_lock aGuard( GetOwnStaticMutex() ); + + m_pImpl = g_pCommandOptions.lock(); + if( !m_pImpl ) + { + m_pImpl = std::make_shared<SvtCommandOptions_Impl>(); + g_pCommandOptions = m_pImpl; + aGuard.unlock(); // because holdConfigItem will call this constructor + ItemHolder1::holdConfigItem(EItem::CmdOptions); + } +} + +SvtCommandOptions::~SvtCommandOptions() +{ + // Global access, must be guarded (multithreading!) + std::unique_lock aGuard( GetOwnStaticMutex() ); + + m_pImpl.reset(); +} + +// public method + +bool SvtCommandOptions::HasEntries( CmdOption eOption ) const +{ + std::unique_lock aGuard( GetOwnStaticMutex() ); + return m_pImpl->HasEntries( eOption ); +} + +// public method + +bool SvtCommandOptions::Lookup( CmdOption eCmdOption, const OUString& aCommandURL ) const +{ + std::unique_lock aGuard( GetOwnStaticMutex() ); + return m_pImpl->Lookup( eCmdOption, aCommandURL ); +} + +// public method + +void SvtCommandOptions::EstablishFrameCallback(const css::uno::Reference< css::frame::XFrame >& xFrame) +{ + std::unique_lock aGuard( GetOwnStaticMutex() ); + m_pImpl->EstablishFrameCallback(xFrame); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/compatibility.cxx b/unotools/source/config/compatibility.cxx new file mode 100644 index 000000000..95bcc2dc5 --- /dev/null +++ b/unotools/source/config/compatibility.cxx @@ -0,0 +1,359 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * 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/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <unotools/compatibility.hxx> +#include <unotools/configitem.hxx> +#include <unotools/syslocale.hxx> +#include <tools/debug.hxx> +#include <sal/log.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> +#include <com/sun/star/beans/PropertyValue.hpp> +#include <com/sun/star/lang/Locale.hpp> +#include <i18nlangtag/languagetag.hxx> + +#include "itemholder1.hxx" + +#include <algorithm> + +using namespace ::std; +using namespace ::utl; +using namespace ::osl; +using namespace ::com::sun::star::uno; +using namespace ::com::sun::star::beans; + +constexpr OUStringLiteral ROOTNODE_OPTIONS = u"Office.Compatibility"; +#define PATHDELIMITER "/" +#define SETNODE_ALLFILEFORMATS "AllFileFormats" + +SvtCompatibilityEntry::SvtCompatibilityEntry() + : m_aPropertyValue( SvtCompatibilityEntry::getElementCount() ) +{ + /* Should be in the start. Do not remove it. */ + setValue<OUString>( Index::Name, OUString() ); + setValue<OUString>( Index::Module, OUString() ); + + /* Editable list of default values. Sync it with the SvtCompatibilityEntry::Index enum class. */ + setValue<bool>( Index::UsePrtMetrics, false ); + setValue<bool>( Index::AddSpacing, false ); + setValue<bool>( Index::AddSpacingAtPages, false ); + setValue<bool>( Index::UseOurTabStops, false ); + setValue<bool>( Index::NoExtLeading, false ); + setValue<bool>( Index::UseLineSpacing, false ); + setValue<bool>( Index::AddTableSpacing, false ); + setValue<bool>( Index::UseObjectPositioning, false ); + setValue<bool>( Index::UseOurTextWrapping, false ); + setValue<bool>( Index::ConsiderWrappingStyle, false ); + setValue<bool>( Index::ExpandWordSpace, true ); + setValue<bool>( Index::ProtectForm, false ); + setValue<bool>( Index::MsWordTrailingBlanks, false ); + setValue<bool>( Index::SubtractFlysAnchoredAtFlys, false ); + setValue<bool>( Index::EmptyDbFieldHidesPara, true ); + setValue<bool>( Index::AddTableLineSpacing, false ); +} + +OUString SvtCompatibilityEntry::getName( const Index rIdx ) +{ + static const char* sPropertyName[] = + { + /* Should be in the start. Do not remove it. */ + "Name", + "Module", + + /* Editable list of compatibility option names. Sync it with the SvtCompatibilityEntry::Index enum class. */ + "UsePrinterMetrics", + "AddSpacing", + "AddSpacingAtPages", + "UseOurTabStopFormat", + "NoExternalLeading", + "UseLineSpacing", + "AddTableSpacing", + "UseObjectPositioning", + "UseOurTextWrapping", + "ConsiderWrappingStyle", + "ExpandWordSpace", + "ProtectForm", + "MsWordCompTrailingBlanks", + "SubtractFlysAnchoredAtFlys", + "EmptyDbFieldHidesPara", + "AddTableLineSpacing", + }; + + /* Size of sPropertyName array not equal size of the SvtCompatibilityEntry::Index enum class */ + assert( SAL_N_ELEMENTS(sPropertyName) == static_cast<int>( SvtCompatibilityEntry::getElementCount() ) ); + + return OUString::createFromAscii( sPropertyName[ static_cast<int>(rIdx) ] ); +} + +/*-**************************************************************************************************************** + @descr support simple menu structures and operations on it +****************************************************************************************************************-*/ + +/*-**************************************************************************************************** + @short base implementation of public interface for "SvtCompatibilityOptions"! + @descr These class is used as static member of "SvtCompatibilityOptions" ... + => The code exist only for one time and isn't duplicated for every instance! +*//*-*****************************************************************************************************/ +class SvtCompatibilityOptions_Impl : public ConfigItem +{ + public: + SvtCompatibilityOptions_Impl(); + virtual ~SvtCompatibilityOptions_Impl() override; + + void AppendItem( const SvtCompatibilityEntry& aItem ); + void Clear(); + + void SetDefault( SvtCompatibilityEntry::Index rIdx, bool rValue ); + bool GetDefault( SvtCompatibilityEntry::Index rIdx ) const; + + const std::vector< SvtCompatibilityEntry > & GetOptions() const { return m_aOptions; } + + /*-**************************************************************************************************** + @short called for notify of configmanager + @descr This method is called from the ConfigManager before the application ends or from the + PropertyChangeListener if the sub tree broadcasts changes. You must update your + internal values. + + @seealso baseclass ConfigItem + + @param "lPropertyNames" is the list of properties which should be updated. + *//*-*****************************************************************************************************/ + virtual void Notify( const Sequence< OUString >& lPropertyNames ) override; + + private: + virtual void ImplCommit() override; + + /*-**************************************************************************************************** + @short return list of key names of our configuration management which represent one module tree + @descr These methods return the current list of key names! We need it to get needed values from our + configuration management and support dynamical menu item lists! + @return A list of configuration key names is returned. + *//*-*****************************************************************************************************/ + Sequence< OUString > impl_GetPropertyNames( Sequence< OUString >& rItems ); + + private: + std::vector< SvtCompatibilityEntry > m_aOptions; + SvtCompatibilityEntry m_aDefOptions; +}; + +SvtCompatibilityOptions_Impl::SvtCompatibilityOptions_Impl() : ConfigItem( ROOTNODE_OPTIONS ) +{ + // Get names and values of all accessible menu entries and fill internal structures. + // See impl_GetPropertyNames() for further information. + Sequence< OUString > lNodes; + Sequence< OUString > lNames = impl_GetPropertyNames( lNodes ); + Sequence< Any > lValues = GetProperties( lNames ); + + // Safe impossible cases. + // We need values from ALL configuration keys. + // Follow assignment use order of values in relation to our list of key names! + DBG_ASSERT( !( lNames.getLength()!=lValues.getLength() ), "SvtCompatibilityOptions_Impl::SvtCompatibilityOptions_Impl()\nI miss some values of configuration keys!\n" ); + + // Get names/values for new menu. + // 4 subkeys for every item! + bool bDefaultFound = false; + sal_Int32 nDestStep = 0; + for ( const auto& rNode : std::as_const(lNodes) ) + { + SvtCompatibilityEntry aItem; + + aItem.setValue<OUString>( SvtCompatibilityEntry::Index::Name, rNode ); + + for ( int i = static_cast<int>(SvtCompatibilityEntry::Index::Module); i < static_cast<int>(SvtCompatibilityEntry::Index::INVALID); ++i ) + { + aItem.setValue( SvtCompatibilityEntry::Index(i), lValues[ nDestStep ] ); + nDestStep++; + } + + m_aOptions.push_back( aItem ); + + if ( !bDefaultFound && aItem.getValue<OUString>( SvtCompatibilityEntry::Index::Name ) == SvtCompatibilityEntry::DEFAULT_ENTRY_NAME ) + { + SvtSysLocale aSysLocale; + css::lang::Locale aLocale = aSysLocale.GetLanguageTag().getLocale(); + if ( aLocale.Language == "zh" || aLocale.Language == "ja" || aLocale.Language == "ko" ) + aItem.setValue<bool>( SvtCompatibilityEntry::Index::ExpandWordSpace, false ); + + m_aDefOptions = aItem; + bDefaultFound = true; + } + } +} + +SvtCompatibilityOptions_Impl::~SvtCompatibilityOptions_Impl() +{ + assert( !IsModified() ); // should have been committed +} + +void SvtCompatibilityOptions_Impl::AppendItem( const SvtCompatibilityEntry& aItem ) +{ + m_aOptions.push_back( aItem ); + + // default item reset? + if ( aItem.getValue<OUString>( SvtCompatibilityEntry::Index::Name ) == SvtCompatibilityEntry::DEFAULT_ENTRY_NAME ) + m_aDefOptions = aItem; + + SetModified(); +} + +void SvtCompatibilityOptions_Impl::Clear() +{ + m_aOptions.clear(); + + SetModified(); +} + +void SvtCompatibilityOptions_Impl::SetDefault( SvtCompatibilityEntry::Index rIdx, bool rValue ) +{ + /* Are not set Name and Module */ + assert( rIdx != SvtCompatibilityEntry::Index::Name && rIdx != SvtCompatibilityEntry::Index::Module ); + + m_aDefOptions.setValue<bool>( rIdx, rValue ); +} + +bool SvtCompatibilityOptions_Impl::GetDefault( SvtCompatibilityEntry::Index rIdx ) const +{ + /* Are not set Name and Module */ + assert( rIdx != SvtCompatibilityEntry::Index::Name && rIdx != SvtCompatibilityEntry::Index::Module ); + + return m_aDefOptions.getValue<bool>( rIdx ); +} + +void SvtCompatibilityOptions_Impl::Notify( const Sequence< OUString >& ) +{ + SAL_WARN( "unotools.config", "SvtCompatibilityOptions_Impl::Notify() Not implemented yet! I don't know how I can handle a dynamical list of unknown properties ..." ); +} + +void SvtCompatibilityOptions_Impl::ImplCommit() +{ + // Write all properties! + // Delete complete set first. + ClearNodeSet( SETNODE_ALLFILEFORMATS ); + + Sequence< PropertyValue > lPropertyValues( SvtCompatibilityEntry::getElementCount() - 1 ); + auto lPropertyValuesRange = asNonConstRange(lPropertyValues); + sal_uInt32 nNewCount = m_aOptions.size(); + for ( sal_uInt32 nItem = 0; nItem < nNewCount; ++nItem ) + { + SvtCompatibilityEntry aItem = m_aOptions[ nItem ]; + OUString sNode = SETNODE_ALLFILEFORMATS PATHDELIMITER + aItem.getValue<OUString>( SvtCompatibilityEntry::Index::Name ) + PATHDELIMITER; + + for ( int i = static_cast<int>(SvtCompatibilityEntry::Index::Module); i < static_cast<int>(SvtCompatibilityEntry::Index::INVALID); ++i ) + { + lPropertyValuesRange[ i - 1 ].Name = sNode + SvtCompatibilityEntry::getName( SvtCompatibilityEntry::Index(i) ); + lPropertyValuesRange[ i - 1 ].Value = aItem.getValue( SvtCompatibilityEntry::Index(i) ); + } + + SetSetProperties( SETNODE_ALLFILEFORMATS, lPropertyValues ); + } +} + +Sequence< OUString > SvtCompatibilityOptions_Impl::impl_GetPropertyNames( Sequence< OUString >& rItems ) +{ + // First get ALL names of current existing list items in configuration! + rItems = GetNodeNames( SETNODE_ALLFILEFORMATS ); + + // expand list to result list ... + Sequence< OUString > lProperties( rItems.getLength() * ( SvtCompatibilityEntry::getElementCount() - 1 ) ); + auto lPropertiesRange = asNonConstRange(lProperties); + + sal_Int32 nDestStep = 0; + // Copy entries to destination and expand every item with 2 supported sub properties. + for ( const auto& rItem : std::as_const(rItems) ) + { + OUString sFixPath = SETNODE_ALLFILEFORMATS PATHDELIMITER + rItem + PATHDELIMITER; + for ( int i = static_cast<int>(SvtCompatibilityEntry::Index::Module); i < static_cast<int>(SvtCompatibilityEntry::Index::INVALID); ++i ) + { + lPropertiesRange[ nDestStep ] = sFixPath + SvtCompatibilityEntry::getName( SvtCompatibilityEntry::Index(i) ); + nDestStep++; + } + } + + // Return result. + return lProperties; +} + +namespace +{ + std::weak_ptr<SvtCompatibilityOptions_Impl> theOptions; +} + +SvtCompatibilityOptions::SvtCompatibilityOptions() +{ + // Global access, must be guarded (multithreading!). + MutexGuard aGuard( GetOwnStaticMutex() ); + + m_pImpl = theOptions.lock(); + if ( !m_pImpl ) + { + m_pImpl = std::make_shared<SvtCompatibilityOptions_Impl>(); + theOptions = m_pImpl; + ItemHolder1::holdConfigItem( EItem::Compatibility ); + } +} + +SvtCompatibilityOptions::~SvtCompatibilityOptions() +{ + // Global access, must be guarded (multithreading!) + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pImpl.reset(); +} + +void SvtCompatibilityOptions::AppendItem( const SvtCompatibilityEntry& aItem ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pImpl->AppendItem( aItem ); +} + +void SvtCompatibilityOptions::Clear() +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pImpl->Clear(); +} + +void SvtCompatibilityOptions::SetDefault( SvtCompatibilityEntry::Index rIdx, bool rValue ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pImpl->SetDefault( rIdx, rValue ); +} + +bool SvtCompatibilityOptions::GetDefault( SvtCompatibilityEntry::Index rIdx ) const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pImpl->GetDefault( rIdx ); +} + +std::vector< SvtCompatibilityEntry > SvtCompatibilityOptions::GetList() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + + return m_pImpl->GetOptions(); +} + +namespace +{ + class theCompatibilityOptionsMutex : public rtl::Static<osl::Mutex, theCompatibilityOptionsMutex>{}; +} + +Mutex& SvtCompatibilityOptions::GetOwnStaticMutex() +{ + return theCompatibilityOptionsMutex::get(); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/configitem.cxx b/unotools/source/config/configitem.cxx new file mode 100644 index 000000000..90da75c04 --- /dev/null +++ b/unotools/source/config/configitem.cxx @@ -0,0 +1,1191 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * 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/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <sal/config.h> + +#include <sal/log.hxx> +#include <unotools/configitem.hxx> +#include <unotools/configmgr.hxx> +#include <unotools/configpaths.hxx> +#include <com/sun/star/beans/XPropertySet.hpp> +#include <com/sun/star/util/XChangesListener.hpp> +#include <com/sun/star/util/XChangesNotifier.hpp> +#include <com/sun/star/container/XHierarchicalNameAccess.hpp> +#include <com/sun/star/configuration/XTemplateContainer.hpp> +#include <com/sun/star/container/XNameContainer.hpp> +#include <com/sun/star/lang/XSingleServiceFactory.hpp> +#include <com/sun/star/lang/XServiceInfo.hpp> +#include <com/sun/star/beans/PropertyValue.hpp> +#include <com/sun/star/beans/PropertyAttribute.hpp> +#include <com/sun/star/util/XChangesBatch.hpp> +#include <o3tl/deleter.hxx> +#include <osl/diagnose.h> +#include <comphelper/sequence.hxx> +#include <comphelper/solarmutex.hxx> +#include <tools/diagnose_ex.h> + +using namespace utl; +using namespace com::sun::star::uno; +using namespace com::sun::star::util; +using namespace com::sun::star::lang; +using namespace com::sun::star::beans; +using namespace com::sun::star::container; +using namespace com::sun::star::configuration; + +#include <cppuhelper/implbase.hxx> +#include <utility> + +/* + The ConfigChangeListener_Impl receives notifications from the configuration about changes that + have happened. It forwards this notification to the ConfigItem it knows a pParent by calling its + "CallNotify" method. As ConfigItems are most probably not thread safe, the SolarMutex is acquired + before doing so. +*/ + +namespace utl{ + class ConfigChangeListener_Impl : public cppu::WeakImplHelper + < + css::util::XChangesListener + > + { + public: + ConfigItem* pParent; + const Sequence< OUString > aPropertyNames; + ConfigChangeListener_Impl(ConfigItem& rItem, const Sequence< OUString >& rNames); + + //XChangesListener + virtual void SAL_CALL changesOccurred( const ChangesEvent& Event ) override; + + //XEventListener + virtual void SAL_CALL disposing( const EventObject& Source ) override; + }; +} + +namespace { + +class ValueCounter_Impl +{ + sal_Int16& rCnt; +public: + explicit ValueCounter_Impl(sal_Int16& rCounter) + : rCnt(rCounter) + { + rCnt++; + } + ~ValueCounter_Impl() + { + OSL_ENSURE(rCnt>0, "RefCount < 0 ??"); + rCnt--; + } +}; + +} + +ConfigChangeListener_Impl::ConfigChangeListener_Impl( + ConfigItem& rItem, const Sequence< OUString >& rNames) : + pParent(&rItem), + aPropertyNames(rNames) +{ +} + +void ConfigChangeListener_Impl::changesOccurred( const ChangesEvent& rEvent ) +{ + Sequence<OUString> aChangedNames(rEvent.Changes.getLength()); + OUString* pNames = aChangedNames.getArray(); + + sal_Int32 nNotify = 0; + for(const auto& rElementChange : rEvent.Changes) + { + OUString sTemp; + rElementChange.Accessor >>= sTemp; + //true if the path is completely correct or if it is longer + //i.e ...Print/Content/Graphic and .../Print + bool bFound = std::any_of(aPropertyNames.begin(), aPropertyNames.end(), + [&sTemp](const OUString& rCheckPropertyName) { return isPrefixOfConfigurationPath(sTemp, rCheckPropertyName); }); + if(bFound) + pNames[nNotify++] = sTemp; + } + if( nNotify ) + { + ::comphelper::SolarMutex *pMutex = ::comphelper::SolarMutex::get(); + if ( pMutex ) + { + osl::Guard<comphelper::SolarMutex> aMutexGuard( pMutex ); + aChangedNames.realloc(nNotify); + pParent->CallNotify(aChangedNames); + } + } +} + +void ConfigChangeListener_Impl::disposing( const EventObject& /*rSource*/ ) +{ + pParent->RemoveChangesListener(); +} + +ConfigItem::ConfigItem(OUString aSubTree, ConfigItemMode nSetMode ) : + sSubTree(std::move(aSubTree)), + m_nMode(nSetMode), + m_bIsModified(false), + m_bEnableInternalNotification(false), + m_nInValueChange(0) +{ + if (utl::ConfigManager::IsFuzzing()) + return; + + if (nSetMode & ConfigItemMode::ReleaseTree) + ConfigManager::getConfigManager().addConfigItem(*this); + else + m_xHierarchyAccess = ConfigManager::getConfigManager().addConfigItem(*this); +} + +ConfigItem::~ConfigItem() +{ + suppress_fun_call_w_exception(RemoveChangesListener()); + ConfigManager::getConfigManager().removeConfigItem(*this); +} + +void ConfigItem::CallNotify( const css::uno::Sequence<OUString>& rPropertyNames ) +{ + // the call is forwarded to the virtual Notify() method + // it is pure virtual, so all classes deriving from ConfigItem have to decide how they + // want to notify listeners + if(m_nInValueChange <= 0 || m_bEnableInternalNotification) + Notify(rPropertyNames); +} + +void ConfigItem::impl_packLocalizedProperties( const Sequence< OUString >& lInNames , + const Sequence< Any >& lInValues , + Sequence< Any >& lOutValues ) +{ + // This method should be called for special AllLocales ConfigItem-mode only! + + sal_Int32 nSourceCounter; // used to step during input lists + sal_Int32 nSourceSize; // marks end of loop over input lists + sal_Int32 nDestinationCounter; // actual position in output lists + sal_Int32 nPropertyCounter; // counter of inner loop for Sequence< PropertyValue > + sal_Int32 nPropertiesSize; // marks end of inner loop + Sequence< OUString > lPropertyNames; // list of all locales for localized entry + Sequence< PropertyValue > lProperties; // localized values of a configuration entry packed for return + Reference< XInterface > xLocalizedNode; // if cfg entry is localized ... lInValues contains an XInterface! + + // Optimise follow algorithm ... A LITTLE BIT :-) + // There exist two different possibilities: + // i ) There exist no localized entries ... => size of lOutValues will be the same like lInNames/lInValues! + // ii) There exist some (mostly one or two) localized entries ... => size of lOutValues will be the same like lInNames/lInValues! + // ... Why? If a localized value exist - the any is filled with an XInterface object (is a SetNode-service). + // We read all his child nodes and pack it into Sequence< PropertyValue >. + // The result list we pack into the return any. We never change size of lists! + nSourceSize = lInNames.getLength(); + lOutValues.realloc( nSourceSize ); + auto plOutValues = lOutValues.getArray(); + + // Algorithm: + // Copy all names and values from in to out lists. + // Look for special localized entries ... You can detect it as "XInterface" packed into an Any. + // Use this XInterface-object to read all localized values and pack it into Sequence< PropertValue >. + // Add this list to out lists then. + + nDestinationCounter = 0; + for( nSourceCounter=0; nSourceCounter<nSourceSize; ++nSourceCounter ) + { + // If item a special localized one ... convert and pack it ... + if( lInValues[nSourceCounter].getValueTypeName() == "com.sun.star.uno.XInterface" ) + { + lInValues[nSourceCounter] >>= xLocalizedNode; + Reference< XNameContainer > xSetAccess( xLocalizedNode, UNO_QUERY ); + if( xSetAccess.is() ) + { + lPropertyNames = xSetAccess->getElementNames(); + nPropertiesSize = lPropertyNames.getLength(); + lProperties.realloc( nPropertiesSize ); + auto plProperties = lProperties.getArray(); + + for( nPropertyCounter=0; nPropertyCounter<nPropertiesSize; ++nPropertyCounter ) + { + plProperties[nPropertyCounter].Name = lPropertyNames[nPropertyCounter]; + OUString sLocaleValue; + xSetAccess->getByName( lPropertyNames[nPropertyCounter] ) >>= sLocaleValue; + plProperties[nPropertyCounter].Value <<= sLocaleValue; + } + + plOutValues[nDestinationCounter] <<= lProperties; + } + } + // ... or copy normal items to return lists directly. + else + { + plOutValues[nDestinationCounter] = lInValues[nSourceCounter]; + } + ++nDestinationCounter; + } +} + +void ConfigItem::impl_unpackLocalizedProperties( const Sequence< OUString >& lInNames , + const Sequence< Any >& lInValues , + Sequence< OUString >& lOutNames , + Sequence< Any >& lOutValues) +{ + // This method should be called for special AllLocales ConfigItem-mode only! + + sal_Int32 nSourceSize; // marks end of loop over input lists + sal_Int32 nDestinationCounter; // actual position in output lists + sal_Int32 nPropertiesSize; // marks end of inner loop + OUString sNodeName; // base name of node ( e.g. "UIName/" ) ... expand to locale ( e.g. "UIName/de" ) + Sequence< PropertyValue > lProperties; // localized values of a configuration entry gotten from lInValues-Any + + // Optimise follow algorithm ... A LITTLE BIT :-) + // There exist two different possibilities: + // i ) There exist no localized entries ... => size of lOutNames/lOutValues will be the same like lInNames/lInValues! + // ii) There exist some (mostly one or two) localized entries ... => size of lOutNames/lOutValues will be some bytes greater then lInNames/lInValues. + // => I think we should make it fast for i). ii) is a special case and mustn't be SOOOO... fast. + // We should reserve same space for output list like input ones first. + // Follow algorithm looks for these borders and change it for ii) only! + // It will be faster then a "realloc()" call in every loop ... + nSourceSize = lInNames.getLength(); + + lOutNames.realloc ( nSourceSize ); + auto plOutNames = lOutNames.getArray(); + lOutValues.realloc ( nSourceSize ); + auto plOutValues = lOutValues.getArray(); + + // Algorithm: + // Copy all names and values from const to return lists. + // Look for special localized entries ... You can detect it as Sequence< PropertyValue > packed into an Any. + // Split it ... insert PropertyValue.Name to lOutNames and PropertyValue.Value to lOutValues. + + nDestinationCounter = 0; + for( sal_Int32 nSourceCounter=0; nSourceCounter<nSourceSize; ++nSourceCounter ) + { + // If item a special localized one ... split it and insert his parts to output lists ... + if( lInValues[nSourceCounter].getValueType() == cppu::UnoType<Sequence<PropertyValue>>::get() ) + { + lInValues[nSourceCounter] >>= lProperties; + nPropertiesSize = lProperties.getLength(); + + sNodeName = lInNames[nSourceCounter] + "/"; + + if( (nDestinationCounter+nPropertiesSize) > lOutNames.getLength() ) + { + lOutNames.realloc ( nDestinationCounter+nPropertiesSize ); + plOutNames = lOutNames.getArray(); + lOutValues.realloc ( nDestinationCounter+nPropertiesSize ); + plOutValues = lOutValues.getArray(); + } + + for( const auto& rProperty : std::as_const(lProperties) ) + { + plOutNames [nDestinationCounter] = sNodeName + rProperty.Name; + plOutValues[nDestinationCounter] = rProperty.Value; + ++nDestinationCounter; + } + } + // ... or copy normal items to return lists directly. + else + { + if( (nDestinationCounter+1) > lOutNames.getLength() ) + { + lOutNames.realloc ( nDestinationCounter+1 ); + plOutNames = lOutNames.getArray(); + lOutValues.realloc ( nDestinationCounter+1 ); + plOutValues = lOutValues.getArray(); + } + + plOutNames [nDestinationCounter] = lInNames [nSourceCounter]; + plOutValues[nDestinationCounter] = lInValues[nSourceCounter]; + ++nDestinationCounter; + } + } +} + +Sequence< sal_Bool > ConfigItem::GetReadOnlyStates(const css::uno::Sequence< OUString >& rNames) +{ + sal_Int32 i; + + // size of return list is fix! + // Every item must match to length of incoming name list. + sal_Int32 nCount = rNames.getLength(); + Sequence< sal_Bool > lStates(nCount); + sal_Bool* plStates = lStates.getArray(); + + // We must be sure to return a valid information every time! + // Set default to non readonly... similar to the configuration handling of this property. + std::fill_n(plStates, lStates.getLength(), false); + + // no access - no information... + Reference< XHierarchicalNameAccess > xHierarchyAccess = GetTree(); + if (!xHierarchyAccess.is()) + return lStates; + + for (i=0; i<nCount; ++i) + { + try + { + OUString sName = rNames[i]; + OUString sPath; + OUString sProperty; + + (void)::utl::splitLastFromConfigurationPath(sName,sPath,sProperty); + if (sPath.isEmpty() && sProperty.isEmpty()) + { + OSL_FAIL("ConfigItem::IsReadonly() split failed"); + continue; + } + + Reference< XInterface > xNode; + Reference< XPropertySet > xSet; + Reference< XPropertySetInfo > xInfo; + if (!sPath.isEmpty()) + { + Any aNode = xHierarchyAccess->getByHierarchicalName(sPath); + if (!(aNode >>= xNode) || !xNode.is()) + { + OSL_FAIL("ConfigItem::IsReadonly() no set available"); + continue; + } + } + else + { + xNode = xHierarchyAccess; + } + + xSet.set(xNode, UNO_QUERY); + if (xSet.is()) + { + xInfo = xSet->getPropertySetInfo(); + OSL_ENSURE(xInfo.is(), "ConfigItem::IsReadonly() getPropertySetInfo failed ..."); + } + else + { + xInfo.set(xNode, UNO_QUERY); + OSL_ENSURE(xInfo.is(), "ConfigItem::IsReadonly() UNO_QUERY failed ..."); + } + + if (!xInfo.is()) + { + OSL_FAIL("ConfigItem::IsReadonly() no prop info available"); + continue; + } + + Property aProp = xInfo->getPropertyByName(sProperty); + plStates[i] = (aProp.Attributes & PropertyAttribute::READONLY) == PropertyAttribute::READONLY; + } + catch (const Exception&) + { + } + } + + return lStates; +} + +Sequence< Any > ConfigItem::GetProperties(const Sequence< OUString >& rNames) +{ + Reference<XHierarchicalNameAccess> xHierarchyAccess = GetTree(); + if(xHierarchyAccess.is()) + return GetProperties(xHierarchyAccess, rNames, + (m_nMode & ConfigItemMode::AllLocales ) == ConfigItemMode::AllLocales); + return Sequence< Any >(rNames.getLength()); +} + +Sequence< Any > ConfigItem::GetProperties( + css::uno::Reference<css::container::XHierarchicalNameAccess> const & xHierarchyAccess, + const Sequence< OUString >& rNames, + bool bAllLocales) +{ + Sequence< Any > aRet(rNames.getLength()); + const OUString* pNames = rNames.getConstArray(); + Any* pRet = aRet.getArray(); + for(int i = 0; i < rNames.getLength(); i++) + { + try + { + pRet[i] = xHierarchyAccess->getByHierarchicalName(pNames[i]); + } + catch (const Exception&) + { + TOOLS_WARN_EXCEPTION( + "unotools.config", + "ignoring XHierarchicalNameAccess " << pNames[i]); + } + } + + // In special mode "ALL_LOCALES" we must convert localized values to Sequence< PropertyValue >. + if(bAllLocales) + { + Sequence< Any > lValues; + impl_packLocalizedProperties( rNames, aRet, lValues ); + aRet = lValues; + } + return aRet; +} + +bool ConfigItem::PutProperties( const Sequence< OUString >& rNames, + const Sequence< Any>& rValues) +{ + ValueCounter_Impl aCounter(m_nInValueChange); + Reference<XHierarchicalNameAccess> xHierarchyAccess = GetTree(); + Reference<XNameReplace> xTopNodeReplace(xHierarchyAccess, UNO_QUERY); + bool bRet = xHierarchyAccess.is() && xTopNodeReplace.is(); + if(bRet) + { + Sequence< OUString > lNames; + Sequence< Any > lValues; + const OUString* pNames = nullptr; + const Any* pValues = nullptr; + sal_Int32 nNameCount; + if(( m_nMode & ConfigItemMode::AllLocales ) == ConfigItemMode::AllLocales ) + { + // If ConfigItem works in "ALL_LOCALES"-mode ... we must support a Sequence< PropertyValue > + // as value of a localized configuration entry! + // How we can do that? + // We must split all PropertyValues to "Sequence< OUString >" AND "Sequence< Any >"! + impl_unpackLocalizedProperties( rNames, rValues, lNames, lValues ); + pNames = lNames.getConstArray (); + pValues = lValues.getConstArray (); + nNameCount = lNames.getLength (); + } + else + { + // This is the normal mode ... + // Use given input lists directly. + pNames = rNames.getConstArray (); + pValues = rValues.getConstArray (); + nNameCount = rNames.getLength (); + } + for(int i = 0; i < nNameCount; i++) + { + try + { + OUString sNode, sProperty; + if (splitLastFromConfigurationPath(pNames[i],sNode, sProperty)) + { + Any aNode = xHierarchyAccess->getByHierarchicalName(sNode); + + Reference<XNameAccess> xNodeAcc; + aNode >>= xNodeAcc; + Reference<XNameReplace> xNodeReplace(xNodeAcc, UNO_QUERY); + Reference<XNameContainer> xNodeCont (xNodeAcc, UNO_QUERY); + + bool bExist = (xNodeAcc.is() && xNodeAcc->hasByName(sProperty)); + if (bExist && xNodeReplace.is()) + xNodeReplace->replaceByName(sProperty, pValues[i]); + else + if (!bExist && xNodeCont.is()) + xNodeCont->insertByName(sProperty, pValues[i]); + else + bRet = false; + } + else //direct value + { + xTopNodeReplace->replaceByName(sProperty, pValues[i]); + } + } + catch (css::uno::Exception &) + { + TOOLS_WARN_EXCEPTION("unotools.config", "Exception from PutProperties"); + } + } + try + { + Reference<XChangesBatch> xBatch(xHierarchyAccess, UNO_QUERY); + xBatch->commitChanges(); + } + catch (css::uno::Exception &) + { + TOOLS_WARN_EXCEPTION("unotools.config", "Exception from commitChanges"); + } + } + + return bRet; +} + +bool ConfigItem::PutProperties( + css::uno::Reference<css::container::XHierarchicalNameAccess> const & xHierarchyAccess, + const Sequence< OUString >& rNames, + const Sequence< Any>& rValues, + bool bAllLocales) +{ + Reference<XNameReplace> xTopNodeReplace(xHierarchyAccess, UNO_QUERY); + bool bRet = xTopNodeReplace.is(); + if(bRet) + { + Sequence< OUString > lNames; + Sequence< Any > lValues; + const OUString* pNames = nullptr; + const Any* pValues = nullptr; + sal_Int32 nNameCount; + if(bAllLocales) + { + // If ConfigItem works in "ALL_LOCALES"-mode ... we must support a Sequence< PropertyValue > + // as value of a localized configuration entry! + // How we can do that? + // We must split all PropertyValues to "Sequence< OUString >" AND "Sequence< Any >"! + impl_unpackLocalizedProperties( rNames, rValues, lNames, lValues ); + pNames = lNames.getConstArray (); + pValues = lValues.getConstArray (); + nNameCount = lNames.getLength (); + } + else + { + // This is the normal mode ... + // Use given input lists directly. + pNames = rNames.getConstArray (); + pValues = rValues.getConstArray (); + nNameCount = rNames.getLength (); + } + for(int i = 0; i < nNameCount; i++) + { + try + { + OUString sNode, sProperty; + if (splitLastFromConfigurationPath(pNames[i],sNode, sProperty)) + { + Any aNode = xHierarchyAccess->getByHierarchicalName(sNode); + + Reference<XNameAccess> xNodeAcc; + aNode >>= xNodeAcc; + Reference<XNameReplace> xNodeReplace(xNodeAcc, UNO_QUERY); + Reference<XNameContainer> xNodeCont (xNodeAcc, UNO_QUERY); + + bool bExist = (xNodeAcc.is() && xNodeAcc->hasByName(sProperty)); + if (bExist && xNodeReplace.is()) + xNodeReplace->replaceByName(sProperty, pValues[i]); + else + if (!bExist && xNodeCont.is()) + xNodeCont->insertByName(sProperty, pValues[i]); + else + bRet = false; + } + else //direct value + { + xTopNodeReplace->replaceByName(sProperty, pValues[i]); + } + } + catch (css::uno::Exception &) + { + TOOLS_WARN_EXCEPTION("unotools.config", "Exception from PutProperties"); + } + } + try + { + Reference<XChangesBatch> xBatch(xHierarchyAccess, UNO_QUERY); + xBatch->commitChanges(); + } + catch (css::uno::Exception &) + { + TOOLS_WARN_EXCEPTION("unotools.config", "Exception from commitChanges"); + } + } + + return bRet; +} + +void ConfigItem::DisableNotification() +{ + OSL_ENSURE( xChangeLstnr.is(), "ConfigItem::DisableNotification: notifications not enabled currently!" ); + RemoveChangesListener(); +} + +bool ConfigItem::EnableNotification(const Sequence< OUString >& rNames, + bool bEnableInternalNotification ) +{ + OSL_ENSURE(!(m_nMode & ConfigItemMode::ReleaseTree), "notification in ConfigItemMode::ReleaseTree mode not possible"); + m_bEnableInternalNotification = bEnableInternalNotification; + Reference<XHierarchicalNameAccess> xHierarchyAccess = GetTree(); + Reference<XChangesNotifier> xChgNot(xHierarchyAccess, UNO_QUERY); + if(!xChgNot.is()) + return false; + + OSL_ENSURE(!xChangeLstnr.is(), "EnableNotification already called"); + if(xChangeLstnr.is()) + xChgNot->removeChangesListener( xChangeLstnr ); + bool bRet = true; + + try + { + xChangeLstnr = new ConfigChangeListener_Impl(*this, rNames); + xChgNot->addChangesListener( xChangeLstnr ); + } + catch (const RuntimeException&) + { + bRet = false; + } + return bRet; +} + +void ConfigItem::RemoveChangesListener() +{ + Reference<XHierarchicalNameAccess> xHierarchyAccess = GetTree(); + if(!xHierarchyAccess.is()) + return; + + Reference<XChangesNotifier> xChgNot(xHierarchyAccess, UNO_QUERY); + if(xChgNot.is() && xChangeLstnr.is()) + { + try + { + xChgNot->removeChangesListener( xChangeLstnr ); + xChangeLstnr = nullptr; + } + catch (const Exception&) + { + } + } +} + +static void lcl_normalizeLocalNames(Sequence< OUString >& _rNames, ConfigNameFormat _eFormat, Reference<XInterface> const& _xParentNode) +{ + switch (_eFormat) + { + case ConfigNameFormat::LocalNode: + // unaltered - this is our input format + break; + + case ConfigNameFormat::LocalPath: + { + Reference<XTemplateContainer> xTypeContainer(_xParentNode, UNO_QUERY); + if (xTypeContainer.is()) + { + OUString sTypeName = xTypeContainer->getElementTemplateName(); + sTypeName = sTypeName.copy(sTypeName.lastIndexOf('/')+1); + + std::transform(std::cbegin(_rNames), std::cend(_rNames), _rNames.getArray(), + [&sTypeName](const OUString& rName) -> OUString { return wrapConfigurationElementName(rName,sTypeName); }); + } + else + { + Reference<XServiceInfo> xSVI(_xParentNode, UNO_QUERY); + if (xSVI.is() && xSVI->supportsService("com.sun.star.configuration.SetAccess")) + { + std::transform(std::cbegin(_rNames), std::cend(_rNames), _rNames.getArray(), + [](const OUString& rName) -> OUString { return wrapConfigurationElementName(rName); }); + } + } + } + break; + + } +} + +Sequence< OUString > ConfigItem::GetNodeNames(const OUString& rNode) +{ + ConfigNameFormat const eDefaultFormat = ConfigNameFormat::LocalNode; // CONFIG_NAME_DEFAULT; + + return GetNodeNames(rNode, eDefaultFormat); +} + +Sequence< OUString > ConfigItem::GetNodeNames(const OUString& rNode, ConfigNameFormat eFormat) +{ + Reference<XHierarchicalNameAccess> xHierarchyAccess = GetTree(); + if(xHierarchyAccess.is()) + return GetNodeNames(xHierarchyAccess, rNode, eFormat); + return Sequence< OUString >(); +} + +Sequence< OUString > ConfigItem::GetNodeNames( + css::uno::Reference<css::container::XHierarchicalNameAccess> const & xHierarchyAccess, + const OUString& rNode, + ConfigNameFormat eFormat) +{ + Sequence< OUString > aRet; + try + { + Reference<XNameAccess> xCont; + if(!rNode.isEmpty()) + { + Any aNode = xHierarchyAccess->getByHierarchicalName(rNode); + aNode >>= xCont; + } + else + xCont.set(xHierarchyAccess, UNO_QUERY); + if(xCont.is()) + { + aRet = xCont->getElementNames(); + lcl_normalizeLocalNames(aRet,eFormat,xCont); + } + + } + catch (css::uno::Exception &) + { + TOOLS_WARN_EXCEPTION("unotools.config", "Exception from GetNodeNames"); + } + return aRet; +} + +bool ConfigItem::ClearNodeSet(const OUString& rNode) +{ + ValueCounter_Impl aCounter(m_nInValueChange); + bool bRet = false; + Reference<XHierarchicalNameAccess> xHierarchyAccess = GetTree(); + if(xHierarchyAccess.is()) + bRet = ClearNodeSet(xHierarchyAccess, rNode); + return bRet; +} + +bool ConfigItem::ClearNodeSet( + css::uno::Reference<css::container::XHierarchicalNameAccess> const & xHierarchyAccess, + const OUString& rNode) +{ + bool bRet = false; + try + { + Reference<XNameContainer> xCont; + if(!rNode.isEmpty()) + { + Any aNode = xHierarchyAccess->getByHierarchicalName(rNode); + aNode >>= xCont; + } + else + xCont.set(xHierarchyAccess, UNO_QUERY); + if(!xCont.is()) + return false; + const Sequence< OUString > aNames = xCont->getElementNames(); + Reference<XChangesBatch> xBatch(xHierarchyAccess, UNO_QUERY); + for(const OUString& rName : aNames) + { + try + { + xCont->removeByName(rName); + } + catch (css::uno::Exception &) + { + TOOLS_WARN_EXCEPTION("unotools.config", "Exception from removeByName"); + } + } + xBatch->commitChanges(); + bRet = true; + } + catch (css::uno::Exception &) + { + TOOLS_WARN_EXCEPTION("unotools.config", "Exception from ClearNodeSet"); + } + return bRet; +} + +bool ConfigItem::ClearNodeElements(const OUString& rNode, Sequence< OUString > const & rElements) +{ + ValueCounter_Impl aCounter(m_nInValueChange); + bool bRet = false; + Reference<XHierarchicalNameAccess> xHierarchyAccess = GetTree(); + if(xHierarchyAccess.is()) + { + try + { + Reference<XNameContainer> xCont; + if(!rNode.isEmpty()) + { + Any aNode = xHierarchyAccess->getByHierarchicalName(rNode); + aNode >>= xCont; + } + else + xCont.set(xHierarchyAccess, UNO_QUERY); + if(!xCont.is()) + return false; + try + { + for(const OUString& rElement : rElements) + { + xCont->removeByName(rElement); + } + Reference<XChangesBatch> xBatch(xHierarchyAccess, UNO_QUERY); + xBatch->commitChanges(); + } + catch (css::uno::Exception &) + { + TOOLS_WARN_EXCEPTION("unotools.config", "Exception from commitChanges()"); + } + bRet = true; + } + catch (css::uno::Exception &) + { + TOOLS_WARN_EXCEPTION("unotools.config", "Exception from GetNodeNames()"); + } + } + return bRet; +} + +static OUString lcl_extractSetPropertyName( const OUString& rInPath, std::u16string_view rPrefix ) +{ + OUString const sSubPath = dropPrefixFromConfigurationPath( rInPath, rPrefix); + return extractFirstFromConfigurationPath( sSubPath ); +} + +static +Sequence< OUString > lcl_extractSetPropertyNames( const Sequence< PropertyValue >& rValues, std::u16string_view rPrefix ) +{ + Sequence< OUString > aSubNodeNames(rValues.getLength()); + OUString* pSubNodeNames = aSubNodeNames.getArray(); + + OUString sLastSubNode; + sal_Int32 nSubIndex = 0; + + for(const PropertyValue& rProperty : rValues) + { + OUString const sSubPath = dropPrefixFromConfigurationPath( rProperty.Name, rPrefix); + OUString const sSubNode = extractFirstFromConfigurationPath( sSubPath ); + + if(sLastSubNode != sSubNode) + { + pSubNodeNames[nSubIndex++] = sSubNode; + } + + sLastSubNode = sSubNode; + } + aSubNodeNames.realloc(nSubIndex); + + return aSubNodeNames; +} + +// Add or change properties +bool ConfigItem::SetSetProperties( + const OUString& rNode, const Sequence< PropertyValue >& rValues) +{ + ValueCounter_Impl aCounter(m_nInValueChange); + Reference<XHierarchicalNameAccess> xHierarchyAccess = GetTree(); + if(!xHierarchyAccess.is()) + return true; + return SetSetProperties(xHierarchyAccess, rNode, rValues); +} + +// Add or change properties +bool ConfigItem::SetSetProperties( + css::uno::Reference<css::container::XHierarchicalNameAccess> const & xHierarchyAccess, + const OUString& rNode, const Sequence< PropertyValue >& rValues) +{ + bool bRet = true; + Reference<XChangesBatch> xBatch(xHierarchyAccess, UNO_QUERY); + try + { + Reference<XNameContainer> xCont; + if(!rNode.isEmpty()) + { + Any aNode = xHierarchyAccess->getByHierarchicalName(rNode); + aNode >>= xCont; + } + else + xCont.set(xHierarchyAccess, UNO_QUERY); + if(!xCont.is()) + return false; + + Reference<XSingleServiceFactory> xFac(xCont, UNO_QUERY); + + if(xFac.is()) + { + const Sequence< OUString > aSubNodeNames = lcl_extractSetPropertyNames(rValues, rNode); + + for(const auto& rSubNodeName : aSubNodeNames) + { + if(!xCont->hasByName(rSubNodeName)) + { + Reference<XInterface> xInst = xFac->createInstance(); + Any aVal; aVal <<= xInst; + xCont->insertByName(rSubNodeName, aVal); + } + //set values + } + try + { + xBatch->commitChanges(); + } + catch (css::uno::Exception &) + { + TOOLS_WARN_EXCEPTION("unotools.config", "Exception from commitChanges()"); + } + + const PropertyValue* pProperties = rValues.getConstArray(); + + Sequence< OUString > aSetNames(rValues.getLength()); + OUString* pSetNames = aSetNames.getArray(); + + Sequence< Any> aSetValues(rValues.getLength()); + Any* pSetValues = aSetValues.getArray(); + + bool bEmptyNode = rNode.isEmpty(); + for(sal_Int32 k = 0; k < rValues.getLength(); k++) + { + pSetNames[k] = pProperties[k].Name.copy( bEmptyNode ? 1 : 0); + pSetValues[k] = pProperties[k].Value; + } + bRet = PutProperties(xHierarchyAccess, aSetNames, aSetValues, /*bAllLocales*/false); + } + else + { + //if no factory is available then the node contains basic data elements + for(const PropertyValue& rValue : rValues) + { + try + { + OUString sSubNode = lcl_extractSetPropertyName( rValue.Name, rNode ); + + if(xCont->hasByName(sSubNode)) + xCont->replaceByName(sSubNode, rValue.Value); + else + xCont->insertByName(sSubNode, rValue.Value); + + OSL_ENSURE( xHierarchyAccess->hasByHierarchicalName(rValue.Name), + "Invalid config path" ); + } + catch (css::uno::Exception &) + { + TOOLS_WARN_EXCEPTION("unotools.config", "Exception from insert/replaceByName()"); + } + } + xBatch->commitChanges(); + } + } + catch (const Exception&) + { + TOOLS_WARN_EXCEPTION("unotools.config", "Exception from SetSetProperties"); + bRet = false; + } + return bRet; +} + +bool ConfigItem::ReplaceSetProperties( + const OUString& rNode, const Sequence< PropertyValue >& rValues) +{ + ValueCounter_Impl aCounter(m_nInValueChange); + bool bRet = true; + Reference<XHierarchicalNameAccess> xHierarchyAccess = GetTree(); + if(xHierarchyAccess.is()) + bRet = ReplaceSetProperties(xHierarchyAccess, rNode, rValues, + ( m_nMode & ConfigItemMode::AllLocales ) == ConfigItemMode::AllLocales); + return bRet; +} + +bool ConfigItem::ReplaceSetProperties( + css::uno::Reference<css::container::XHierarchicalNameAccess> const & xHierarchyAccess, + const OUString& rNode, + const Sequence< PropertyValue >& rValues, + bool bAllLocales) +{ + bool bRet = true; + Reference<XChangesBatch> xBatch(xHierarchyAccess, UNO_QUERY); + try + { + Reference<XNameContainer> xCont; + if(!rNode.isEmpty()) + { + Any aNode = xHierarchyAccess->getByHierarchicalName(rNode); + aNode >>= xCont; + } + else + xCont.set(xHierarchyAccess, UNO_QUERY); + if(!xCont.is()) + return false; + + // JB: Change: now the same name handling for sets of simple values + const Sequence< OUString > aSubNodeNames = lcl_extractSetPropertyNames(rValues, rNode); + + Reference<XSingleServiceFactory> xFac(xCont, UNO_QUERY); + const bool isSimpleValueSet = !xFac.is(); + + //remove unknown members first + { + const Sequence<OUString> aContainerSubNodes = xCont->getElementNames(); + + for(const OUString& rContainerSubNode : aContainerSubNodes) + { + bool bFound = comphelper::findValue(aSubNodeNames, rContainerSubNode) != -1; + if(!bFound) + try + { + xCont->removeByName(rContainerSubNode); + } + catch (const Exception&) + { + if (isSimpleValueSet) + { + try + { + // #i37322#: fallback action: replace with <void/> + xCont->replaceByName(rContainerSubNode, Any()); + // fallback successful: continue looping + continue; + } + catch (Exception &) + {} // propagate original exception, if fallback fails + } + throw; + } + } + try { xBatch->commitChanges(); } + catch (css::uno::Exception &) + { + TOOLS_WARN_EXCEPTION("unotools.config", "Exception from commitChanges"); + } + } + + if(xFac.is()) // !isSimpleValueSet + { + for(const OUString& rSubNodeName : aSubNodeNames) + { + if(!xCont->hasByName(rSubNodeName)) + { + //create if not available + Reference<XInterface> xInst = xFac->createInstance(); + Any aVal; aVal <<= xInst; + xCont->insertByName(rSubNodeName, aVal); + } + } + try { xBatch->commitChanges(); } + catch (css::uno::Exception &) + { + TOOLS_WARN_EXCEPTION("unotools.config", "Exception from commitChanges"); + } + + const PropertyValue* pProperties = rValues.getConstArray(); + + Sequence< OUString > aSetNames(rValues.getLength()); + OUString* pSetNames = aSetNames.getArray(); + + Sequence< Any> aSetValues(rValues.getLength()); + Any* pSetValues = aSetValues.getArray(); + + bool bEmptyNode = rNode.isEmpty(); + for(sal_Int32 k = 0; k < rValues.getLength(); k++) + { + pSetNames[k] = pProperties[k].Name.copy( bEmptyNode ? 1 : 0); + pSetValues[k] = pProperties[k].Value; + } + bRet = PutProperties(xHierarchyAccess, aSetNames, aSetValues, bAllLocales); + } + else + { + //if no factory is available then the node contains basic data elements + for(const PropertyValue& rValue : rValues) + { + try + { + OUString sSubNode = lcl_extractSetPropertyName( rValue.Name, rNode ); + + if(xCont->hasByName(sSubNode)) + xCont->replaceByName(sSubNode, rValue.Value); + else + xCont->insertByName(sSubNode, rValue.Value); + } + catch (css::uno::Exception &) + { + TOOLS_WARN_EXCEPTION("unotools.config", "Exception from insert/replaceByName"); + } + } + xBatch->commitChanges(); + } + } + catch (const Exception& ) + { + TOOLS_WARN_EXCEPTION("unotools.config", "Exception from ReplaceSetProperties"); + bRet = false; + } + return bRet; +} + +bool ConfigItem::AddNode(const OUString& rNode, const OUString& rNewNode) +{ + ValueCounter_Impl aCounter(m_nInValueChange); + bool bRet = true; + Reference<XHierarchicalNameAccess> xHierarchyAccess = GetTree(); + if(xHierarchyAccess.is()) + { + Reference<XChangesBatch> xBatch(xHierarchyAccess, UNO_QUERY); + try + { + Reference<XNameContainer> xCont; + if(!rNode.isEmpty()) + { + Any aNode = xHierarchyAccess->getByHierarchicalName(rNode); + aNode >>= xCont; + } + else + xCont.set(xHierarchyAccess, UNO_QUERY); + if(!xCont.is()) + return false; + + Reference<XSingleServiceFactory> xFac(xCont, UNO_QUERY); + + if(xFac.is()) + { + if(!xCont->hasByName(rNewNode)) + { + Reference<XInterface> xInst = xFac->createInstance(); + Any aVal; aVal <<= xInst; + xCont->insertByName(rNewNode, aVal); + } + try + { + xBatch->commitChanges(); + } + catch (css::uno::Exception &) + { + TOOLS_WARN_EXCEPTION("unotools.config", "Exception from commitChanges"); + } + } + else + { + //if no factory is available then the node contains basic data elements + try + { + if(!xCont->hasByName(rNewNode)) + xCont->insertByName(rNewNode, Any()); + } + catch (css::uno::Exception &) + { + TOOLS_WARN_EXCEPTION("unotools.config", "Exception from AddNode"); + } + } + xBatch->commitChanges(); + } + catch (const Exception&) + { + DBG_UNHANDLED_EXCEPTION("unotools.config"); + bRet = false; + } + } + return bRet; +} + + +void ConfigItem::SetModified() +{ + m_bIsModified = true; +} + +void ConfigItem::ClearModified() +{ + m_bIsModified = false; +} + +Reference< XHierarchicalNameAccess> ConfigItem::GetTree() +{ + Reference< XHierarchicalNameAccess> xRet; + if (utl::ConfigManager::IsFuzzing()) + return xRet; + if(!m_xHierarchyAccess.is()) + xRet = ConfigManager::acquireTree(*this); + else + xRet = m_xHierarchyAccess; + return xRet; +} + +void ConfigItem::Commit() +{ + ImplCommit(); + ClearModified(); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/configmgr.cxx b/unotools/source/config/configmgr.cxx new file mode 100644 index 000000000..f3aef792e --- /dev/null +++ b/unotools/source/config/configmgr.cxx @@ -0,0 +1,193 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * 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/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <sal/config.h> + +#include <com/sun/star/beans/NamedValue.hpp> +#include <com/sun/star/container/XHierarchicalNameAccess.hpp> +#include <com/sun/star/configuration/theDefaultProvider.hpp> +#include <com/sun/star/lang/XMultiServiceFactory.hpp> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Reference.hxx> +#include <com/sun/star/uno/Sequence.hxx> +#include <i18nlangtag/languagetag.hxx> +#include <officecfg/Setup.hxx> +#include <rtl/ustring.hxx> +#include <sal/log.hxx> +#include <unotools/configitem.hxx> +#include <unotools/configmgr.hxx> +#include <comphelper/processfactory.hxx> + +namespace { + +class RegisterConfigItemHelper { +public: + RegisterConfigItemHelper( + utl::ConfigManager & manager, utl::ConfigItem & item): + manager_(manager), item_(&item) + { + manager.registerConfigItem(item_); + } + + ~RegisterConfigItemHelper() { + if (item_ != nullptr) { + manager_.removeConfigItem(*item_); + } + } + + void keep() { item_ = nullptr; } + +private: + utl::ConfigManager & manager_; + utl::ConfigItem * item_; + + RegisterConfigItemHelper(const RegisterConfigItemHelper&) = delete; + RegisterConfigItemHelper& operator=(const RegisterConfigItemHelper&) = delete; +}; + +css::uno::Reference< css::lang::XMultiServiceFactory > +getConfigurationProvider() { + return css::configuration::theDefaultProvider::get( comphelper::getProcessComponentContext() ); +} + +} + +OUString utl::ConfigManager::getAboutBoxProductVersion() { + return officecfg::Setup::Product::ooSetupVersionAboutBox::get(); +} + +OUString utl::ConfigManager::getAboutBoxProductVersionSuffix() { + return officecfg::Setup::Product::ooSetupVersionAboutBoxSuffix::get(); +} + +OUString utl::ConfigManager::getDefaultCurrency() { + return officecfg::Setup::L10N::ooSetupCurrency::get(); +} + +OUString utl::ConfigManager::getUILocale() { + return officecfg::Setup::L10N::ooLocale::get(); +} + +OUString utl::ConfigManager::getWorkLocale() { + return officecfg::Setup::L10N::ooSetupSystemLocale::get(); +} + +OUString utl::ConfigManager::getProductExtension() { + return officecfg::Setup::Product::ooSetupExtension::get(); +} + +OUString utl::ConfigManager::getProductName() { + return officecfg::Setup::Product::ooName::get(); +} + +OUString utl::ConfigManager::getProductVersion() { + return officecfg::Setup::Product::ooSetupVersion::get(); +} + +OUString utl::ConfigManager::getVendor() { + return officecfg::Setup::Product::ooVendor::get(); +} + +void utl::ConfigManager::storeConfigItems() { + getConfigManager().doStoreConfigItems(); +} + +utl::ConfigManager & utl::ConfigManager::getConfigManager() { + static utl::ConfigManager theConfigManager; + return theConfigManager; +} + +css::uno::Reference< css::container::XHierarchicalNameAccess > +utl::ConfigManager::acquireTree(utl::ConfigItem const & item) { + css::uno::Sequence< css::uno::Any > args{ css::uno::Any(css::beans::NamedValue( + "nodepath", + css::uno::Any("/org.openoffice." + item.GetSubTreeName()))) }; + if (item.GetMode() & ConfigItemMode::AllLocales) { + args.realloc(2); + args.getArray()[1] <<= css::beans::NamedValue("locale", css::uno::Any(OUString("*"))); + } + return css::uno::Reference< css::container::XHierarchicalNameAccess >( + getConfigurationProvider()->createInstanceWithArguments( + "com.sun.star.configuration.ConfigurationUpdateAccess", + args), + css::uno::UNO_QUERY_THROW); +} + +css::uno::Reference< css::container::XHierarchicalNameAccess > +utl::ConfigManager::acquireTree(std::u16string_view rSubTreeName) { + css::uno::Sequence< css::uno::Any > args{ css::uno::Any(css::beans::NamedValue( + "nodepath", + css::uno::Any(OUString::Concat(u"/org.openoffice.") + rSubTreeName))) }; + return css::uno::Reference< css::container::XHierarchicalNameAccess >( + getConfigurationProvider()->createInstanceWithArguments( + "com.sun.star.configuration.ConfigurationUpdateAccess", + args), + css::uno::UNO_QUERY_THROW); +} + +utl::ConfigManager::ConfigManager() {} + +utl::ConfigManager::~ConfigManager() { + SAL_WARN_IF(!items_.empty(), "unotools.config", "ConfigManager not empty"); +} + +css::uno::Reference< css::container::XHierarchicalNameAccess > +utl::ConfigManager::addConfigItem(utl::ConfigItem & item) { + RegisterConfigItemHelper reg(*this, item); + css::uno::Reference< css::container::XHierarchicalNameAccess > tree( + acquireTree(item)); + reg.keep(); + return tree; +} + +void utl::ConfigManager::removeConfigItem(utl::ConfigItem & item) { + items_.erase(std::remove(items_.begin(), items_.end(), &item), items_.end()); +} + +void utl::ConfigManager::registerConfigItem(utl::ConfigItem * item) { + assert(item != nullptr); + items_.push_back(item); +} + +void utl::ConfigManager::doStoreConfigItems() { + for (auto const& item : items_) + { + if (item->IsModified()) { + item->Commit(); + item->ClearModified(); + } + } +} + +static bool bIsFuzzing = false; + +#if !defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) +bool utl::ConfigManager::IsFuzzing() +{ + return bIsFuzzing; +} +#endif + +void utl::ConfigManager::EnableFuzzing() +{ + bIsFuzzing = true; + LanguageTag::disable_lt_tag_parse(); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/confignode.cxx b/unotools/source/config/confignode.cxx new file mode 100644 index 000000000..85aa6c3ba --- /dev/null +++ b/unotools/source/config/confignode.cxx @@ -0,0 +1,562 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * 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/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <unotools/confignode.hxx> +#include <unotools/configpaths.hxx> +#include <tools/diagnose_ex.h> +#include <osl/diagnose.h> +#include <sal/log.hxx> +#include <com/sun/star/configuration/theDefaultProvider.hpp> +#include <com/sun/star/lang/XSingleServiceFactory.hpp> +#include <com/sun/star/lang/XComponent.hpp> +#include <com/sun/star/util/XChangesBatch.hpp> +#include <com/sun/star/util/XStringEscape.hpp> +#include <com/sun/star/lang/XServiceInfo.hpp> +#include <com/sun/star/container/XNamed.hpp> +#include <com/sun/star/container/XNameContainer.hpp> +#include <com/sun/star/container/XHierarchicalNameAccess.hpp> +#include <comphelper/namedvaluecollection.hxx> + +namespace utl +{ + + using namespace ::com::sun::star::uno; + using namespace ::com::sun::star::lang; + using namespace ::com::sun::star::util; + using namespace ::com::sun::star::beans; + using namespace ::com::sun::star::container; + using namespace ::com::sun::star::configuration; + + //= OConfigurationNode + + OConfigurationNode::OConfigurationNode(const Reference< XInterface >& _rxNode ) + :m_bEscapeNames(false) + { + OSL_ENSURE(_rxNode.is(), "OConfigurationNode::OConfigurationNode: invalid node interface!"); + if (_rxNode.is()) + { + // collect all interfaces necessary + m_xHierarchyAccess.set(_rxNode, UNO_QUERY); + m_xDirectAccess.set(_rxNode, UNO_QUERY); + + // reset _all_ interfaces if _one_ of them is not supported + if (!m_xHierarchyAccess.is() || !m_xDirectAccess.is()) + { + m_xHierarchyAccess = nullptr; + m_xDirectAccess = nullptr; + } + + // now for the non-critical interfaces + m_xReplaceAccess.set(_rxNode, UNO_QUERY); + m_xContainerAccess.set(_rxNode, UNO_QUERY); + } + + Reference< XComponent > xConfigNodeComp(m_xDirectAccess, UNO_QUERY); + if (xConfigNodeComp.is()) + startComponentListening(xConfigNodeComp); + + if (isValid()) + m_bEscapeNames = isSetNode() && Reference< XStringEscape >::query(m_xDirectAccess).is(); + } + + OConfigurationNode::OConfigurationNode(const OConfigurationNode& _rSource) + : OEventListenerAdapter() + , m_xHierarchyAccess(_rSource.m_xHierarchyAccess) + , m_xDirectAccess(_rSource.m_xDirectAccess) + , m_xReplaceAccess(_rSource.m_xReplaceAccess) + , m_xContainerAccess(_rSource.m_xContainerAccess) + , m_bEscapeNames(_rSource.m_bEscapeNames) + { + Reference< XComponent > xConfigNodeComp(m_xDirectAccess, UNO_QUERY); + if (xConfigNodeComp.is()) + startComponentListening(xConfigNodeComp); + } + + OConfigurationNode::OConfigurationNode(OConfigurationNode&& _rSource) + : OEventListenerAdapter() + , m_xHierarchyAccess(std::move(_rSource.m_xHierarchyAccess)) + , m_xDirectAccess(std::move(_rSource.m_xDirectAccess)) + , m_xReplaceAccess(std::move(_rSource.m_xReplaceAccess)) + , m_xContainerAccess(std::move(_rSource.m_xContainerAccess)) + , m_bEscapeNames(std::move(_rSource.m_bEscapeNames)) + { + Reference< XComponent > xConfigNodeComp(m_xDirectAccess, UNO_QUERY); + if (xConfigNodeComp.is()) + startComponentListening(xConfigNodeComp); + } + + OConfigurationNode& OConfigurationNode::operator=(const OConfigurationNode& _rSource) + { + stopAllComponentListening(); + + m_xHierarchyAccess = _rSource.m_xHierarchyAccess; + m_xDirectAccess = _rSource.m_xDirectAccess; + m_xContainerAccess = _rSource.m_xContainerAccess; + m_xReplaceAccess = _rSource.m_xReplaceAccess; + m_bEscapeNames = _rSource.m_bEscapeNames; + + Reference< XComponent > xConfigNodeComp(m_xDirectAccess, UNO_QUERY); + if (xConfigNodeComp.is()) + startComponentListening(xConfigNodeComp); + + return *this; + } + + OConfigurationNode& OConfigurationNode::operator=(OConfigurationNode&& _rSource) + { + stopAllComponentListening(); + + m_xHierarchyAccess = std::move(_rSource.m_xHierarchyAccess); + m_xDirectAccess = std::move(_rSource.m_xDirectAccess); + m_xContainerAccess = std::move(_rSource.m_xContainerAccess); + m_xReplaceAccess = std::move(_rSource.m_xReplaceAccess); + m_bEscapeNames = std::move(_rSource.m_bEscapeNames); + + Reference< XComponent > xConfigNodeComp(m_xDirectAccess, UNO_QUERY); + if (xConfigNodeComp.is()) + startComponentListening(xConfigNodeComp); + + return *this; + } + + void OConfigurationNode::_disposing( const EventObject& _rSource ) + { + Reference< XComponent > xDisposingSource(_rSource.Source, UNO_QUERY); + Reference< XComponent > xConfigNodeComp(m_xDirectAccess, UNO_QUERY); + if (xDisposingSource.get() == xConfigNodeComp.get()) + clear(); + } + + OUString OConfigurationNode::getLocalName() const + { + OUString sLocalName; + try + { + Reference< XNamed > xNamed( m_xDirectAccess, UNO_QUERY_THROW ); + sLocalName = xNamed->getName(); + } + catch( const Exception& ) + { + DBG_UNHANDLED_EXCEPTION("unotools"); + } + return sLocalName; + } + + OUString OConfigurationNode::normalizeName(const OUString& _rName, NAMEORIGIN _eOrigin) const + { + OUString sName(_rName); + if (m_bEscapeNames) + { + Reference< XStringEscape > xEscaper(m_xDirectAccess, UNO_QUERY); + if (xEscaper.is() && !sName.isEmpty()) + { + try + { + if (NO_CALLER == _eOrigin) + sName = xEscaper->escapeString(sName); + else + sName = xEscaper->unescapeString(sName); + } + catch(Exception&) + { + DBG_UNHANDLED_EXCEPTION("unotools"); + } + } + } + return sName; + } + + Sequence< OUString > OConfigurationNode::getNodeNames() const noexcept + { + OSL_ENSURE(m_xDirectAccess.is(), "OConfigurationNode::getNodeNames: object is invalid!"); + Sequence< OUString > aReturn; + if (m_xDirectAccess.is()) + { + try + { + aReturn = m_xDirectAccess->getElementNames(); + // normalize the names + std::transform(std::cbegin(aReturn), std::cend(aReturn), aReturn.getArray(), + [this](const OUString& rName) -> OUString { return normalizeName(rName, NO_CONFIGURATION); }); + } + catch(Exception&) + { + TOOLS_WARN_EXCEPTION( "unotools", "OConfigurationNode::getNodeNames"); + } + } + + return aReturn; + } + + bool OConfigurationNode::removeNode(const OUString& _rName) const noexcept + { + OSL_ENSURE(m_xContainerAccess.is(), "OConfigurationNode::removeNode: object is invalid!"); + if (m_xContainerAccess.is()) + { + try + { + OUString sName = normalizeName(_rName, NO_CALLER); + m_xContainerAccess->removeByName(sName); + return true; + } + catch (NoSuchElementException&) + { + SAL_WARN( "unotools", "OConfigurationNode::removeNode: there is no element named: " << _rName ); + } + catch(Exception&) + { + TOOLS_WARN_EXCEPTION( "unotools", "OConfigurationNode::removeNode"); + } + } + return false; + } + + OConfigurationNode OConfigurationNode::insertNode(const OUString& _rName,const Reference< XInterface >& _xNode) const noexcept + { + if(_xNode.is()) + { + try + { + OUString sName = normalizeName(_rName, NO_CALLER); + m_xContainerAccess->insertByName(sName, Any(_xNode)); + // if we're here, all was ok ... + return OConfigurationNode( _xNode ); + } + catch(const Exception&) + { + DBG_UNHANDLED_EXCEPTION("unotools"); + } + + // dispose the child if it has already been created, but could not be inserted + Reference< XComponent > xChildComp(_xNode, UNO_QUERY); + if (xChildComp.is()) + try { xChildComp->dispose(); } catch(Exception&) { } + } + + return OConfigurationNode(); + } + + OConfigurationNode OConfigurationNode::createNode(const OUString& _rName) const noexcept + { + Reference< XSingleServiceFactory > xChildFactory(m_xContainerAccess, UNO_QUERY); + OSL_ENSURE(xChildFactory.is(), "OConfigurationNode::createNode: object is invalid or read-only!"); + + if (xChildFactory.is()) // implies m_xContainerAccess.is() + { + Reference< XInterface > xNewChild; + try + { + xNewChild = xChildFactory->createInstance(); + } + catch(const Exception&) + { + DBG_UNHANDLED_EXCEPTION("unotools"); + } + return insertNode(_rName,xNewChild); + } + + return OConfigurationNode(); + } + + OConfigurationNode OConfigurationNode::openNode(const OUString& _rPath) const noexcept + { + OSL_ENSURE(m_xDirectAccess.is(), "OConfigurationNode::openNode: object is invalid!"); + OSL_ENSURE(m_xHierarchyAccess.is(), "OConfigurationNode::openNode: object is invalid!"); + try + { + OUString sNormalized = normalizeName(_rPath, NO_CALLER); + + Reference< XInterface > xNode; + if (m_xDirectAccess.is() && m_xDirectAccess->hasByName(sNormalized)) + { + xNode.set( + m_xDirectAccess->getByName(sNormalized), css::uno::UNO_QUERY); + if (!xNode.is()) + OSL_FAIL("OConfigurationNode::openNode: could not open the node!"); + } + else if (m_xHierarchyAccess.is()) + { + xNode.set( + m_xHierarchyAccess->getByHierarchicalName(_rPath), + css::uno::UNO_QUERY); + if (!xNode.is()) + OSL_FAIL("OConfigurationNode::openNode: could not open the node!"); + } + if (xNode.is()) + return OConfigurationNode( xNode ); + } + catch(const NoSuchElementException&) + { + SAL_WARN( "unotools", "OConfigurationNode::openNode: there is no element named " << _rPath ); + } + catch(Exception&) + { + TOOLS_WARN_EXCEPTION( "unotools", "OConfigurationNode::openNode: caught an exception while retrieving the node!"); + } + return OConfigurationNode(); + } + + bool OConfigurationNode::isSetNode() const + { + bool bIsSet = false; + Reference< XServiceInfo > xSI(m_xHierarchyAccess, UNO_QUERY); + if (xSI.is()) + { + try { bIsSet = xSI->supportsService("com.sun.star.configuration.SetAccess"); } + catch(Exception&) { } + } + return bIsSet; + } + + bool OConfigurationNode::hasByHierarchicalName( const OUString& _rName ) const noexcept + { + OSL_ENSURE( m_xHierarchyAccess.is(), "OConfigurationNode::hasByHierarchicalName: no hierarchy access!" ); + try + { + if ( m_xHierarchyAccess.is() ) + { + OUString sName = normalizeName( _rName, NO_CALLER ); + return m_xHierarchyAccess->hasByHierarchicalName( sName ); + } + } + catch(Exception&) + { + } + return false; + } + + bool OConfigurationNode::hasByName(const OUString& _rName) const noexcept + { + OSL_ENSURE(m_xDirectAccess.is(), "OConfigurationNode::hasByName: object is invalid!"); + try + { + OUString sName = normalizeName(_rName, NO_CALLER); + if (m_xDirectAccess.is()) + return m_xDirectAccess->hasByName(sName); + } + catch(Exception&) + { + } + return false; + } + + bool OConfigurationNode::setNodeValue(const OUString& _rPath, const Any& _rValue) const noexcept + { + bool bResult = false; + + OSL_ENSURE(m_xReplaceAccess.is(), "OConfigurationNode::setNodeValue: object is invalid!"); + if (m_xReplaceAccess.is()) + { + try + { + // check if _rPath is a level-1 path + OUString sNormalizedName = normalizeName(_rPath, NO_CALLER); + if (m_xReplaceAccess->hasByName(sNormalizedName)) + { + m_xReplaceAccess->replaceByName(sNormalizedName, _rValue); + bResult = true; + } + + // check if the name refers to an indirect descendant + else if (m_xHierarchyAccess.is() && m_xHierarchyAccess->hasByHierarchicalName(_rPath)) + { + OSL_ASSERT(!_rPath.isEmpty()); + + OUString sParentPath, sLocalName; + + if ( splitLastFromConfigurationPath(_rPath, sParentPath, sLocalName) ) + { + OConfigurationNode aParentAccess = openNode(sParentPath); + if (aParentAccess.isValid()) + bResult = aParentAccess.setNodeValue(sLocalName, _rValue); + } + else + { + m_xReplaceAccess->replaceByName(sLocalName, _rValue); + bResult = true; + } + } + + } + catch(Exception&) + { + TOOLS_WARN_EXCEPTION( "unotools", "OConfigurationNode::setNodeValue: could not replace the value"); + } + + } + return bResult; + } + + Any OConfigurationNode::getNodeValue(const OUString& _rPath) const noexcept + { + OSL_ENSURE(m_xDirectAccess.is(), "OConfigurationNode::hasByName: object is invalid!"); + OSL_ENSURE(m_xHierarchyAccess.is(), "OConfigurationNode::hasByName: object is invalid!"); + Any aReturn; + try + { + OUString sNormalizedPath = normalizeName(_rPath, NO_CALLER); + if (m_xDirectAccess.is() && m_xDirectAccess->hasByName(sNormalizedPath) ) + { + aReturn = m_xDirectAccess->getByName(sNormalizedPath); + } + else if (m_xHierarchyAccess.is()) + { + aReturn = m_xHierarchyAccess->getByHierarchicalName(_rPath); + } + } + catch(const NoSuchElementException&) + { + DBG_UNHANDLED_EXCEPTION("unotools"); + } + return aReturn; + } + + void OConfigurationNode::clear() noexcept + { + m_xHierarchyAccess.clear(); + m_xDirectAccess.clear(); + m_xReplaceAccess.clear(); + m_xContainerAccess.clear(); + } + + //= helper + + namespace + { + + Reference< XMultiServiceFactory > lcl_getConfigProvider( const Reference<XComponentContext> & i_rContext ) + { + try + { + Reference< XMultiServiceFactory > xProvider = theDefaultProvider::get( i_rContext ); + return xProvider; + } + catch ( const Exception& ) + { + DBG_UNHANDLED_EXCEPTION("unotools"); + } + return nullptr; + } + + Reference< XInterface > lcl_createConfigurationRoot( const Reference< XMultiServiceFactory >& i_rxConfigProvider, + const OUString& i_rNodePath, const bool i_bUpdatable, const sal_Int32 i_nDepth ) + { + ENSURE_OR_RETURN( i_rxConfigProvider.is(), "invalid provider", nullptr ); + try + { + ::comphelper::NamedValueCollection aArgs; + aArgs.put( "nodepath", i_rNodePath ); + aArgs.put( "depth", i_nDepth ); + + OUString sAccessService( i_bUpdatable ? + OUString( "com.sun.star.configuration.ConfigurationUpdateAccess" ) : + OUString( "com.sun.star.configuration.ConfigurationAccess" )); + + Reference< XInterface > xRoot( + i_rxConfigProvider->createInstanceWithArguments( sAccessService, aArgs.getWrappedPropertyValues() ), + UNO_SET_THROW + ); + return xRoot; + } + catch ( const Exception& ) + { + DBG_UNHANDLED_EXCEPTION("unotools"); + } + return nullptr; + } + } + + OConfigurationTreeRoot::OConfigurationTreeRoot( const Reference< XInterface >& _rxRootNode ) + :OConfigurationNode( _rxRootNode ) + ,m_xCommitter( _rxRootNode, UNO_QUERY ) + { + } + + OConfigurationTreeRoot::OConfigurationTreeRoot( const Reference<XComponentContext> & i_rContext, const OUString& i_rNodePath, const bool i_bUpdatable ) + :OConfigurationNode( lcl_createConfigurationRoot( lcl_getConfigProvider( i_rContext ), + i_rNodePath, i_bUpdatable, -1 ) ) + ,m_xCommitter() + { + if ( i_bUpdatable ) + { + m_xCommitter.set( getUNONode(), UNO_QUERY ); + OSL_ENSURE( m_xCommitter.is(), "OConfigurationTreeRoot::OConfigurationTreeRoot: could not create an updatable node!" ); + } + } + + void OConfigurationTreeRoot::clear() noexcept + { + OConfigurationNode::clear(); + m_xCommitter.clear(); + } + + bool OConfigurationTreeRoot::commit() const noexcept + { + OSL_ENSURE(isValid(), "OConfigurationTreeRoot::commit: object is invalid!"); + if (!isValid()) + return false; + OSL_ENSURE(m_xCommitter.is(), "OConfigurationTreeRoot::commit: I'm a readonly node!"); + if (!m_xCommitter.is()) + return false; + + try + { + m_xCommitter->commitChanges(); + return true; + } + catch(const Exception&) + { + DBG_UNHANDLED_EXCEPTION("unotools"); + } + return false; + } + + OConfigurationTreeRoot OConfigurationTreeRoot::createWithProvider(const Reference< XMultiServiceFactory >& _rxConfProvider, const OUString& _rPath, sal_Int32 _nDepth, CREATION_MODE _eMode) + { + Reference< XInterface > xRoot( lcl_createConfigurationRoot( + _rxConfProvider, _rPath, _eMode != CM_READONLY, _nDepth ) ); + if ( xRoot.is() ) + return OConfigurationTreeRoot( xRoot ); + return OConfigurationTreeRoot(); + } + + OConfigurationTreeRoot OConfigurationTreeRoot::createWithComponentContext( const Reference< XComponentContext >& _rxContext, const OUString& _rPath, sal_Int32 _nDepth, CREATION_MODE _eMode ) + { + return createWithProvider( lcl_getConfigProvider( _rxContext ), _rPath, _nDepth, _eMode ); + } + + OConfigurationTreeRoot OConfigurationTreeRoot::tryCreateWithComponentContext( const Reference< XComponentContext >& rxContext, + const OUString& _rPath, sal_Int32 _nDepth , CREATION_MODE _eMode ) + { + OSL_ENSURE( rxContext.is(), "OConfigurationTreeRoot::tryCreateWithComponentContext: invalid XComponentContext!" ); + try + { + Reference< XMultiServiceFactory > xConfigFactory = theDefaultProvider::get( rxContext ); + return createWithProvider( xConfigFactory, _rPath, _nDepth, _eMode ); + } + catch(const Exception&) + { + // silence this, 'cause the contract of this method states "no assertions" + } + return OConfigurationTreeRoot(); + } + +} // namespace utl + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/configpaths.cxx b/unotools/source/config/configpaths.cxx new file mode 100644 index 000000000..8efdf19b5 --- /dev/null +++ b/unotools/source/config/configpaths.cxx @@ -0,0 +1,285 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * 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/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <sal/config.h> + +#include <string_view> + +#include <unotools/configpaths.hxx> +#include <rtl/ustring.hxx> +#include <rtl/ustrbuf.hxx> +#include <osl/diagnose.h> +#include <o3tl/string_view.hxx> + +namespace utl +{ + +static +void lcl_resolveCharEntities(OUString & aLocalString) +{ + sal_Int32 nEscapePos=aLocalString.indexOf('&'); + if (nEscapePos < 0) return; + + OUStringBuffer aResult; + sal_Int32 nStart = 0; + + do + { + sal_Unicode ch = 0; + if (aLocalString.match("&",nEscapePos)) + ch = '&'; + + else if (aLocalString.match("'",nEscapePos)) + ch = '\''; + + else if (aLocalString.match(""",nEscapePos)) + ch = '"'; + + OSL_ENSURE(ch,"Configuration path contains '&' that is not part of a valid character escape"); + if (ch) + { + aResult.append(aLocalString.subView(nStart,nEscapePos-nStart) + OUStringChar(ch)); + + sal_Int32 nEscapeEnd=aLocalString.indexOf(';',nEscapePos); + nStart = nEscapeEnd+1; + nEscapePos=aLocalString.indexOf('&',nStart); + } + else + { + nEscapePos=aLocalString.indexOf('&',nEscapePos+1); + } + } + while ( nEscapePos > 0); + + aResult.append(aLocalString.subView(nStart)); + + aLocalString = aResult.makeStringAndClear(); +} + +bool splitLastFromConfigurationPath(OUString const& _sInPath, + OUString& _rsOutPath, + OUString& _rsLocalName) +{ + sal_Int32 nStart,nEnd; + + sal_Int32 nPos = _sInPath.getLength()-1; + + // strip trailing slash + if (nPos > 0 && _sInPath[ nPos ] == '/') + { + OSL_FAIL("Invalid config path: trailing '/' is not allowed"); + --nPos; + } + + // check for predicate ['xxx'] or ["yyy"] + if (nPos > 0 && _sInPath[ nPos ] == ']') + { + sal_Unicode chQuote = _sInPath[--nPos]; + + if (chQuote == '\'' || chQuote == '\"') + { + nEnd = nPos; + nPos = _sInPath.lastIndexOf(chQuote,nEnd); + nStart = nPos + 1; + --nPos; // nPos = rInPath.lastIndexOf('[',nPos); + } + else // allow [xxx] + { + nEnd = nPos + 1; + nPos = _sInPath.lastIndexOf('[',nEnd); + nStart = nPos + 1; + } + + OSL_ENSURE(nPos >= 0 && _sInPath[nPos] == '[', "Invalid config path: unmatched quotes or brackets"); + if (nPos >= 0 && _sInPath[nPos] == '[') + { + nPos = _sInPath.lastIndexOf('/',nPos); + } + else // defined behavior for invalid paths + { + nStart = 0; + nEnd = _sInPath.getLength(); + nPos = -1; + } + + } + else + { + nEnd = nPos+1; + nPos = _sInPath.lastIndexOf('/',nEnd); + nStart = nPos + 1; + } + OSL_ASSERT( -1 <= nPos && + nPos < nStart && + nStart < nEnd && + nEnd <= _sInPath.getLength() ); + + OSL_ASSERT(nPos == -1 || _sInPath[nPos] == '/'); + OSL_ENSURE(nPos != 0 , "Invalid config child path: immediate child of root"); + + _rsLocalName = _sInPath.copy(nStart, nEnd-nStart); + _rsOutPath = (nPos > 0) ? _sInPath.copy(0,nPos) : OUString(); + lcl_resolveCharEntities(_rsLocalName); + + return nPos >= 0; +} + +OUString extractFirstFromConfigurationPath(OUString const& _sInPath, OUString* _sOutPath) +{ + sal_Int32 nSep = _sInPath.indexOf('/'); + sal_Int32 nBracket = _sInPath.indexOf('['); + + sal_Int32 nStart = nBracket + 1; + sal_Int32 nEnd = nSep; + + if (0 <= nBracket) // found a bracket-quoted relative path + { + if (nSep < 0 || nBracket < nSep) // and the separator comes after it + { + sal_Unicode chQuote = _sInPath[nStart]; + if (chQuote == '\'' || chQuote == '\"') + { + ++nStart; + nEnd = _sInPath.indexOf(chQuote, nStart+1); + nBracket = nEnd+1; + } + else + { + nEnd = _sInPath.indexOf(']',nStart); + nBracket = nEnd; + } + OSL_ENSURE(nEnd > nStart && _sInPath[nBracket] == ']', "Invalid config path: improper mismatch of quote or bracket"); + OSL_ENSURE((nBracket+1 == _sInPath.getLength() && nSep == -1) || (_sInPath[nBracket+1] == '/' && nSep == nBracket+1), "Invalid config path: brackets not followed by slash"); + } + else // ... but our initial element name is in simple form + nStart = 0; + } + + OUString sResult = (nEnd >= 0) ? _sInPath.copy(nStart, nEnd-nStart) : _sInPath; + lcl_resolveCharEntities(sResult); + + if (_sOutPath != nullptr) + { + *_sOutPath = (nSep >= 0) ? _sInPath.copy(nSep + 1) : OUString(); + } + + return sResult; +} + +// find the position after the prefix in the nested path +static sal_Int32 lcl_findPrefixEnd(std::u16string_view _sNestedPath, std::u16string_view _sPrefixPath) +{ + // TODO: currently handles only exact prefix matches + size_t nPrefixLength = _sPrefixPath.size(); + + OSL_ENSURE(nPrefixLength == 0 || _sPrefixPath[nPrefixLength-1] != '/', + "Cannot handle slash-terminated prefix paths"); + + bool bIsPrefix; + if (_sNestedPath.size() > nPrefixLength) + { + bIsPrefix = _sNestedPath[nPrefixLength] == '/' && + o3tl::starts_with(_sNestedPath, _sPrefixPath); + ++nPrefixLength; + } + else if (_sNestedPath.size() == nPrefixLength) + { + bIsPrefix = _sNestedPath == _sPrefixPath; + } + else + { + bIsPrefix = false; + } + + return bIsPrefix ? nPrefixLength : 0; +} + +bool isPrefixOfConfigurationPath(std::u16string_view _sNestedPath, + std::u16string_view _sPrefixPath) +{ + return _sPrefixPath.empty() || lcl_findPrefixEnd(_sNestedPath,_sPrefixPath) != 0; +} + +OUString dropPrefixFromConfigurationPath(OUString const& _sNestedPath, + std::u16string_view _sPrefixPath) +{ + if ( sal_Int32 nPrefixEnd = lcl_findPrefixEnd(_sNestedPath,_sPrefixPath) ) + { + return _sNestedPath.copy(nPrefixEnd); + } + else + { + OSL_ENSURE(_sPrefixPath.empty(), "Path does not start with expected prefix"); + + return _sNestedPath; + } +} + +static +OUString lcl_wrapName(std::u16string_view _sContent, const OUString& _sType) +{ + const sal_Unicode * const pBeginContent = _sContent.data(); + const sal_Unicode * const pEndContent = pBeginContent + _sContent.size(); + + OSL_PRECOND(!_sType.isEmpty(), "Unexpected config type name: empty"); + OSL_PRECOND(pBeginContent <= pEndContent, "Invalid config name: empty"); + + if (pBeginContent == pEndContent) + return _sType; + + OUStringBuffer aNormalized(_sType.getLength() + _sContent.size() + 4); // reserve approximate size initially + + // prefix: type, opening bracket and quote + aNormalized.append( _sType + "['" ); + + // content: copy over each char and handle escaping + for(const sal_Unicode* pCur = pBeginContent; pCur != pEndContent; ++pCur) + { + // append (escape if needed) + switch(*pCur) + { + case u'&' : aNormalized.append( "&" ); break; + case u'\'': aNormalized.append( "'" ); break; + case u'\"': aNormalized.append( """ ); break; + + default: aNormalized.append( *pCur ); + } + } + + // suffix: closing quote and bracket + aNormalized.append( "']" ); + + return aNormalized.makeStringAndClear(); +} + +OUString wrapConfigurationElementName(std::u16string_view _sElementName) +{ + return lcl_wrapName(_sElementName, "*" ); +} + +OUString wrapConfigurationElementName(std::u16string_view _sElementName, + OUString const& _sTypeName) +{ + // todo: check that _sTypeName is valid + return lcl_wrapName(_sElementName, _sTypeName); +} + +} // namespace utl + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/configvaluecontainer.cxx b/unotools/source/config/configvaluecontainer.cxx new file mode 100644 index 000000000..10abeaf12 --- /dev/null +++ b/unotools/source/config/configvaluecontainer.cxx @@ -0,0 +1,304 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * 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/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <sal/config.h> + +#include <sal/log.hxx> +#include <unotools/configvaluecontainer.hxx> +#include <unotools/confignode.hxx> +#include <uno/data.h> +#include <algorithm> +#include <utility> +#include <vector> + +namespace utl +{ + + using namespace ::com::sun::star::uno; + using namespace ::com::sun::star::lang; + + //= NodeValueAccessor + + namespace { + + enum class LocationType + { + SimplyObjectInstance, + Unbound + }; + + } + + struct NodeValueAccessor + { + private: + OUString sRelativePath; // the relative path of the node + LocationType eLocationType; // the type of location where the value is stored + void* pLocation; // the pointer to the location + Type aDataType; // the type object pointed to by pLocation + + public: + explicit NodeValueAccessor( OUString _aNodePath ); + + void bind( void* _pLocation, const Type& _rType ); + + bool isBound( ) const { return ( LocationType::Unbound != eLocationType ) && ( nullptr != pLocation ); } + const OUString& getPath( ) const { return sRelativePath; } + LocationType getLocType( ) const { return eLocationType; } + void* getLocation( ) const { return pLocation; } + const Type& getDataType( ) const { return aDataType; } + + bool operator == ( const NodeValueAccessor& rhs ) const; + }; + + NodeValueAccessor::NodeValueAccessor( OUString _aNodePath ) + :sRelativePath(std::move( _aNodePath )) + ,eLocationType( LocationType::Unbound ) + ,pLocation( nullptr ) + { + } + + bool NodeValueAccessor::operator == ( const NodeValueAccessor& rhs ) const + { + return ( sRelativePath == rhs.sRelativePath ) + && ( eLocationType == rhs.eLocationType ) + && ( pLocation == rhs.pLocation ); + } + + void NodeValueAccessor::bind( void* _pLocation, const Type& _rType ) + { + SAL_WARN_IF(isBound(), "unotools.config", "NodeValueAccessor::bind: already bound!"); + + eLocationType = LocationType::SimplyObjectInstance; + pLocation = _pLocation; + aDataType = _rType; + } + + static + void lcl_copyData( const NodeValueAccessor& _rAccessor, const Any& _rData, ::osl::Mutex& _rMutex ) + { + ::osl::MutexGuard aGuard( _rMutex ); + + SAL_WARN_IF(!_rAccessor.isBound(), "unotools.config", "::utl::lcl_copyData: invalid accessor!"); + switch ( _rAccessor.getLocType() ) + { + case LocationType::SimplyObjectInstance: + { + if ( _rData.hasValue() ) + { + // assign the value + bool bSuccess = uno_type_assignData( + _rAccessor.getLocation(), _rAccessor.getDataType().getTypeLibType(), + const_cast< void* >( _rData.getValue() ), _rData.getValueType().getTypeLibType(), + cpp_queryInterface, cpp_acquire, cpp_release + ); + SAL_WARN_IF(!bSuccess, "unotools.config", + "::utl::lcl_copyData( Accessor, Any ): could not assign the data (node path: \"" << _rAccessor.getPath() << "\""); + } + else { + SAL_INFO("unotools.config", "::utl::lcl_copyData: NULL value lost!"); + } + } + break; + default: + break; + } + } + + static + void lcl_copyData( Any& _rData, const NodeValueAccessor& _rAccessor, ::osl::Mutex& _rMutex ) + { + ::osl::MutexGuard aGuard( _rMutex ); + + SAL_WARN_IF(!_rAccessor.isBound(), "unotools.config", "::utl::lcl_copyData: invalid accessor!" ); + switch ( _rAccessor.getLocType() ) + { + case LocationType::SimplyObjectInstance: + // a simple setValue... + _rData.setValue( _rAccessor.getLocation(), _rAccessor.getDataType() ); + break; + + default: + break; + } + } + + //= functors on NodeValueAccessor instances + + namespace { + + /// base class for functors synchronizing between exchange locations and config sub nodes + struct SubNodeAccess + { + protected: + const OConfigurationNode& m_rRootNode; + ::osl::Mutex& m_rMutex; + + public: + SubNodeAccess( const OConfigurationNode& _rRootNode, ::osl::Mutex& _rMutex ) + :m_rRootNode( _rRootNode ) + ,m_rMutex( _rMutex ) + { + } + }; + + struct UpdateFromConfig : public SubNodeAccess + { + public: + UpdateFromConfig( const OConfigurationNode& _rRootNode, ::osl::Mutex& _rMutex ) : SubNodeAccess( _rRootNode, _rMutex ) { } + + void operator() ( NodeValueAccessor const & _rAccessor ) + { + ::utl::lcl_copyData( _rAccessor, m_rRootNode.getNodeValue( _rAccessor.getPath( ) ), m_rMutex ); + } + }; + + struct UpdateToConfig : public SubNodeAccess + { + public: + UpdateToConfig( const OConfigurationNode& _rRootNode, ::osl::Mutex& _rMutex ) : SubNodeAccess( _rRootNode, _rMutex ) { } + + void operator() ( NodeValueAccessor const & _rAccessor ) + { + Any aNewValue; + lcl_copyData( aNewValue, _rAccessor, m_rMutex ); + m_rRootNode.setNodeValue( _rAccessor.getPath( ), aNewValue ); + } + }; + + } + + //= OConfigurationValueContainerImpl + + struct OConfigurationValueContainerImpl + { + Reference< XComponentContext > xORB; // the service factory + ::osl::Mutex& rMutex; // the mutex for accessing the data containers + OConfigurationTreeRoot aConfigRoot; // the configuration node we're accessing + + std::vector<NodeValueAccessor> aAccessors; // the accessors to the node values + + OConfigurationValueContainerImpl( const Reference< XComponentContext >& _rxORB, ::osl::Mutex& _rMutex ) + :xORB( _rxORB ) + ,rMutex( _rMutex ) + { + } + }; + + //= OConfigurationValueContainer + + OConfigurationValueContainer::OConfigurationValueContainer( + const Reference< XComponentContext >& _rxORB, ::osl::Mutex& _rAccessSafety, + const char* _pConfigLocation, const sal_Int32 _nLevels ) + :m_pImpl( new OConfigurationValueContainerImpl( _rxORB, _rAccessSafety ) ) + { + implConstruct( OUString::createFromAscii( _pConfigLocation ), _nLevels ); + } + + OConfigurationValueContainer::~OConfigurationValueContainer() + { + } + + void OConfigurationValueContainer::implConstruct( const OUString& _rConfigLocation, + const sal_Int32 _nLevels ) + { + SAL_WARN_IF(m_pImpl->aConfigRoot.isValid(), "unotools.config", "OConfigurationValueContainer::implConstruct: already initialized!"); + + // create the configuration node we're about to work with + m_pImpl->aConfigRoot = OConfigurationTreeRoot::createWithComponentContext( + m_pImpl->xORB, + _rConfigLocation, + _nLevels + ); + SAL_WARN_IF(!m_pImpl->aConfigRoot.isValid(), "unotools.config", + "Could not access the configuration node located at " << _rConfigLocation); + } + + void OConfigurationValueContainer::registerExchangeLocation( const char* _pRelativePath, + void* _pContainer, const Type& _rValueType ) + { + // checks... + SAL_WARN_IF(!_pContainer, "unotools.config", + "OConfigurationValueContainer::registerExchangeLocation: invalid container location!"); + SAL_WARN_IF(!( (TypeClass_CHAR == _rValueType.getTypeClass( ) ) + || ( TypeClass_BOOLEAN == _rValueType.getTypeClass( ) ) + || ( TypeClass_BYTE == _rValueType.getTypeClass( ) ) + || ( TypeClass_SHORT == _rValueType.getTypeClass( ) ) + || ( TypeClass_LONG == _rValueType.getTypeClass( ) ) + || ( TypeClass_DOUBLE == _rValueType.getTypeClass( ) ) + || ( TypeClass_STRING == _rValueType.getTypeClass( ) ) + || ( TypeClass_SEQUENCE == _rValueType.getTypeClass( ) )), + "unotools.config", + "OConfigurationValueContainer::registerExchangeLocation: invalid type!" ); + + // build an accessor for this container + NodeValueAccessor aNewAccessor( OUString::createFromAscii( _pRelativePath ) ); + aNewAccessor.bind( _pContainer, _rValueType ); + + // insert it into our structure + implRegisterExchangeLocation( aNewAccessor ); + } + + void OConfigurationValueContainer::read( ) + { + std::for_each( + m_pImpl->aAccessors.begin(), + m_pImpl->aAccessors.end(), + UpdateFromConfig( m_pImpl->aConfigRoot, m_pImpl->rMutex ) + ); + } + + void OConfigurationValueContainer::commit() + { + // write the current values in the exchange locations + std::for_each( + m_pImpl->aAccessors.begin(), + m_pImpl->aAccessors.end(), + UpdateToConfig( m_pImpl->aConfigRoot, m_pImpl->rMutex ) + ); + + // commit the changes done + m_pImpl->aConfigRoot.commit( ); + } + + void OConfigurationValueContainer::implRegisterExchangeLocation( const NodeValueAccessor& _rAccessor ) + { + // some checks + SAL_WARN_IF(m_pImpl->aConfigRoot.isValid() && !m_pImpl->aConfigRoot.hasByHierarchicalName(_rAccessor.getPath()), + "unotools.config", + "OConfigurationValueContainer::implRegisterExchangeLocation: invalid relative path!" ); + + // another check (should be the first container for this node) + SAL_WARN_IF(!(m_pImpl->aAccessors.end() == ::std::find( + m_pImpl->aAccessors.begin(), + m_pImpl->aAccessors.end(), + _rAccessor)), + "unotools.config", + "OConfigurationValueContainer::implRegisterExchangeLocation: already registered a container for this subnode!" ); + + // remember the accessor + m_pImpl->aAccessors.push_back( _rAccessor ); + + // and initially fill the value + lcl_copyData( _rAccessor, m_pImpl->aConfigRoot.getNodeValue( _rAccessor.getPath() ), m_pImpl->rMutex ); + } + +} // namespace utl + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/defaultoptions.cxx b/unotools/source/config/defaultoptions.cxx new file mode 100644 index 000000000..127cc6858 --- /dev/null +++ b/unotools/source/config/defaultoptions.cxx @@ -0,0 +1,119 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * 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/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <sal/config.h> + +#include <osl/file.hxx> +#include <unotools/defaultoptions.hxx> +#include <unotools/pathoptions.hxx> +#include <com/sun/star/uno/Sequence.hxx> +#include <rtl/ustrbuf.hxx> +#include <officecfg/Office/Common.hxx> + +namespace SvtDefaultOptions +{ + +OUString GetDefaultPath( SvtPathOptions::Paths nId ) +{ + SvtPathOptions aPathOpt; + auto seqToPath = [&aPathOpt] (const css::uno::Sequence<OUString> & rSeq) + { + // single paths + sal_Int32 nCount = rSeq.getLength(); + OUStringBuffer aFullPathBuf(nCount * 40); + for ( sal_Int32 nPosition = 0; nPosition < nCount; ++nPosition ) + { + aFullPathBuf.append(aPathOpt.SubstituteVariable( rSeq[ nPosition ] )); + if ( nPosition < nCount-1 ) + aFullPathBuf.append(";"); + } + return aFullPathBuf.makeStringAndClear(); + }; + + OUString aRet; + switch (nId) + { + case SvtPathOptions::Paths::AddIn: + aRet = aPathOpt.SubstituteVariable(officecfg::Office::Common::Path::Default::Addin::get()); break; + case SvtPathOptions::Paths::AutoCorrect: + aRet = seqToPath(officecfg::Office::Common::Path::Default::AutoCorrect::get()); break; + case SvtPathOptions::Paths::AutoText: + aRet = seqToPath(officecfg::Office::Common::Path::Default::AutoText::get()); break; + case SvtPathOptions::Paths::Backup: + aRet = aPathOpt.SubstituteVariable(officecfg::Office::Common::Path::Default::Backup::get()); break; + case SvtPathOptions::Paths::Basic: + aRet = seqToPath(officecfg::Office::Common::Path::Default::Basic::get()); break; + case SvtPathOptions::Paths::Bitmap: + aRet = aPathOpt.SubstituteVariable(officecfg::Office::Common::Path::Default::Bitmap::get()); break; + case SvtPathOptions::Paths::Config: + aRet = aPathOpt.SubstituteVariable(officecfg::Office::Common::Path::Default::Config::get()); break; + case SvtPathOptions::Paths::Dictionary: + aRet = aPathOpt.SubstituteVariable(officecfg::Office::Common::Path::Default::Dictionary::get()); break; + case SvtPathOptions::Paths::Favorites: + aRet = aPathOpt.SubstituteVariable(officecfg::Office::Common::Path::Default::Favorite::get()); break; + case SvtPathOptions::Paths::Filter: + aRet = aPathOpt.SubstituteVariable(officecfg::Office::Common::Path::Default::Filter::get()); break; + case SvtPathOptions::Paths::Gallery: + aRet = seqToPath(officecfg::Office::Common::Path::Default::Gallery::get()); break; + case SvtPathOptions::Paths::Graphic: + aRet = aPathOpt.SubstituteVariable(officecfg::Office::Common::Path::Default::Graphic::get()); break; + case SvtPathOptions::Paths::Help: + aRet = aPathOpt.SubstituteVariable(officecfg::Office::Common::Path::Default::Help::get()); break; + case SvtPathOptions::Paths::Linguistic: + aRet = aPathOpt.SubstituteVariable(officecfg::Office::Common::Path::Default::Linguistic::get()); break; + case SvtPathOptions::Paths::Module: + aRet = aPathOpt.SubstituteVariable(officecfg::Office::Common::Path::Default::Module::get()); break; + case SvtPathOptions::Paths::Palette: + aRet = aPathOpt.SubstituteVariable(officecfg::Office::Common::Path::Default::Palette::get()); break; + case SvtPathOptions::Paths::Plugin: + aRet = seqToPath(officecfg::Office::Common::Path::Default::Plugin::get()); break; + case SvtPathOptions::Paths::Temp: + aRet = aPathOpt.SubstituteVariable(officecfg::Office::Common::Path::Default::Temp::get()); break; + case SvtPathOptions::Paths::Template: + aRet = seqToPath(officecfg::Office::Common::Path::Default::Template::get()); break; + case SvtPathOptions::Paths::UserConfig: + aRet = aPathOpt.SubstituteVariable(officecfg::Office::Common::Path::Default::UserConfig::get()); break; + case SvtPathOptions::Paths::Work: + aRet = aPathOpt.SubstituteVariable(officecfg::Office::Common::Path::Default::Work::get()); break; + case SvtPathOptions::Paths::Classification: + aRet = aPathOpt.SubstituteVariable(officecfg::Office::Common::Path::Default::Classification::get()); break; + default: + assert(false); + } + + + if ( nId == SvtPathOptions::Paths::AddIn || + nId == SvtPathOptions::Paths::Filter || + nId == SvtPathOptions::Paths::Help || + nId == SvtPathOptions::Paths::Module || + nId == SvtPathOptions::Paths::Plugin ) + { + OUString aTmp; + osl::FileBase::getFileURLFromSystemPath( aRet, aTmp ); + aRet = aTmp; + } + + return aRet; +} + +} // namespace + + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/docinfohelper.cxx b/unotools/source/config/docinfohelper.cxx new file mode 100644 index 000000000..6b36fb21b --- /dev/null +++ b/unotools/source/config/docinfohelper.cxx @@ -0,0 +1,110 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * 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/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <rtl/ustrbuf.hxx> +#include <unotools/configmgr.hxx> +#include <unotools/bootstrap.hxx> +#include <unotools/docinfohelper.hxx> +#include <rtl/bootstrap.hxx> +#include <officecfg/Office/Common.hxx> + +using namespace ::com::sun::star; + +namespace utl +{ + +OUString DocInfoHelper::GetGeneratorString() +{ + static const OUString sGenerator = []() + { + OUString aResultOverride = officecfg::Office::Common::Save::Document::GeneratorOverride::get(); + if( !aResultOverride.isEmpty()) + return aResultOverride; + + OUStringBuffer aResult(128); + + // First product: branded name + version + // version is <product_versions>_<product_extension>$<platform> + + // plain product name + OUString aValue( utl::ConfigManager::getProductName() ); + if ( !aValue.isEmpty() ) + { + aResult.append( aValue.replace( ' ', '_' ) ); + aResult.append( '/' ); + + aValue = utl::ConfigManager::getProductVersion(); + if ( !aValue.isEmpty() ) + { + aResult.append( aValue.replace( ' ', '_' ) ); + + aValue = utl::ConfigManager::getProductExtension(); + if ( !aValue.isEmpty() ) + { + aResult.append( aValue.replace( ' ', '_' ) ); + } + } + + OUString os( "$_OS" ); + OUString arch( "$_ARCH" ); + ::rtl::Bootstrap::expandMacros(os); + ::rtl::Bootstrap::expandMacros(arch); + aResult.append( '$' ); + aResult.append( os ); + aResult.append( '_' ); + aResult.append( arch ); + aResult.append( ' ' ); + } + + // second product: LibreOffice_project/<build_information> + // build_information has '(' and '[' encoded as '$', ')' and ']' ignored + // and ':' replaced by '-' + { + aResult.append( "LibreOffice_project/" ); + OUString aBuildId( Bootstrap::getBuildIdData( OUString() ) ); + for( sal_Int32 i=0; i < aBuildId.getLength(); i++ ) + { + sal_Unicode c = aBuildId[i]; + switch( c ) + { + case '(': + case '[': + aResult.append( '$' ); + break; + case ')': + case ']': + break; + case ':': + aResult.append( '-' ); + break; + default: + aResult.append( c ); + break; + } + } + } + + return aResult.makeStringAndClear(); + }(); + return sGenerator; +} + +} // end of namespace utl + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/dynamicmenuoptions.cxx b/unotools/source/config/dynamicmenuoptions.cxx new file mode 100644 index 000000000..60c07baac --- /dev/null +++ b/unotools/source/config/dynamicmenuoptions.cxx @@ -0,0 +1,339 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * 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/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <sal/config.h> + +#include <o3tl/string_view.hxx> +#include <unotools/dynamicmenuoptions.hxx> +#include <tools/debug.hxx> +#include <unotools/configmgr.hxx> +#include <unotools/configitem.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> + +#include <vector> +#include <algorithm> +#include <string_view> + +using namespace ::com::sun::star::uno; +using namespace ::com::sun::star::beans; + +constexpr OUStringLiteral DYNAMICMENU_PROPERTYNAME_URL = u"URL"; +constexpr OUStringLiteral DYNAMICMENU_PROPERTYNAME_TITLE = u"Title"; +constexpr OUStringLiteral DYNAMICMENU_PROPERTYNAME_IMAGEIDENTIFIER = u"ImageIdentifier"; +constexpr OUStringLiteral DYNAMICMENU_PROPERTYNAME_TARGETNAME = u"TargetName"; + +constexpr OUStringLiteral PATHDELIMITER = u"/"; + +constexpr OUStringLiteral SETNODE_NEWMENU = u"New"; +constexpr OUStringLiteral SETNODE_WIZARDMENU = u"Wizard"; + +#define PROPERTYNAME_URL DYNAMICMENU_PROPERTYNAME_URL +#define PROPERTYNAME_TITLE DYNAMICMENU_PROPERTYNAME_TITLE +#define PROPERTYNAME_IMAGEIDENTIFIER DYNAMICMENU_PROPERTYNAME_IMAGEIDENTIFIER +#define PROPERTYNAME_TARGETNAME DYNAMICMENU_PROPERTYNAME_TARGETNAME + +#define PROPERTYCOUNT 4 + +constexpr std::u16string_view PATHPREFIX_SETUP = u"m"; + +namespace +{ +/*-**************************************************************************************************************** + @descr support simple menu structures and operations on it +****************************************************************************************************************-*/ +struct SvtDynMenu +{ + // append setup written menu entry + // Don't touch name of entry. It was defined by setup and must be the same every time! + // Look for double menu entries here too... may be some separator items are superfluous... + void AppendSetupEntry( const SvtDynMenuEntry& rEntry ) + { + if( lSetupEntries.empty() || lSetupEntries.rbegin()->sURL != rEntry.sURL ) + lSetupEntries.push_back( rEntry ); + } + + // convert internal list to external format + // for using it on right menus really + // Notice: We build a property list with 4 entries and set it on result list then. + // Separator entries will be packed in another way then normal entries! We define + // special string "sSeparator" to perform too ... + std::vector< SvtDynMenuEntry > GetList() const + { + sal_Int32 nSetupCount = static_cast<sal_Int32>(lSetupEntries.size()); + sal_Int32 nUserCount = static_cast<sal_Int32>(lUserEntries.size()); + sal_Int32 nStep = 0; + std::vector< SvtDynMenuEntry > lResult ( nSetupCount+nUserCount ); + OUString sSeparator ( "private:separator" ); + + for( const auto& pList : {&lSetupEntries, &lUserEntries} ) + { + for( const auto& rItem : *pList ) + { + SvtDynMenuEntry entry; + if( rItem.sURL == sSeparator ) + { + entry.sURL = sSeparator; + } + else + { + entry = rItem; + } + lResult[nStep] = entry; + ++nStep; + } + } + return lResult; + } + +private: + std::vector< SvtDynMenuEntry > lSetupEntries; + std::vector< SvtDynMenuEntry > lUserEntries; +}; + +} + +namespace SvtDynamicMenuOptions +{ + +static Sequence< OUString > lcl_GetPropertyNames( + css::uno::Reference<css::container::XHierarchicalNameAccess> const & xHierarchyAccess, + sal_uInt32& nNewCount, sal_uInt32& nWizardCount ); + +std::vector< SvtDynMenuEntry > GetMenu( EDynamicMenuType eMenu ) +{ + SvtDynMenu aNewMenu; + SvtDynMenu aWizardMenu; + + Reference<css::container::XHierarchicalNameAccess> xHierarchyAccess = utl::ConfigManager::acquireTree(u"Office.Common/Menus/"); + + // Get names and values of all accessible menu entries and fill internal structures. + // See impl_GetPropertyNames() for further information. + sal_uInt32 nNewCount = 0; + sal_uInt32 nWizardCount = 0; + Sequence< OUString > lNames = lcl_GetPropertyNames ( xHierarchyAccess, nNewCount , + nWizardCount ); + Sequence< Any > lValues = utl::ConfigItem::GetProperties( xHierarchyAccess, lNames, /*bAllLocales*/false ); + + // Safe impossible cases. + // We need values from ALL configuration keys. + // Follow assignment use order of values in relation to our list of key names! + DBG_ASSERT( !(lNames.getLength()!=lValues.getLength()), "SvtDynamicMenuOptions_Impl::SvtDynamicMenuOptions_Impl()\nI miss some values of configuration keys!\n" ); + + // Copy values from list in right order to our internal member. + // Attention: List for names and values have an internal construction pattern! + + // first "New" menu ... + // Name Value + // /New/1/URL "private:factory/swriter" + // /New/1/Title "New Writer Document" + // /New/1/ImageIdentifier "icon_writer" + // /New/1/TargetName "_blank" + + // /New/2/URL "private:factory/scalc" + // /New/2/Title "New Calc Document" + // /New/2/ImageIdentifier "icon_calc" + // /New/2/TargetName "_blank" + + // second "Wizard" menu ... + // /Wizard/1/URL "file://b" + // /Wizard/1/Title "PaintSomething" + // /Wizard/1/ImageIdentifier "icon_?" + // /Wizard/1/TargetName "_self" + + // ... and so on ... + + sal_uInt32 nItem = 0; + sal_uInt32 nPosition = 0; + + // Get names/values for new menu. + // 4 subkeys for every item! + for( nItem=0; nItem<nNewCount; ++nItem ) + { + SvtDynMenuEntry aItem; + lValues[nPosition] >>= aItem.sURL; + ++nPosition; + lValues[nPosition] >>= aItem.sTitle; + ++nPosition; + lValues[nPosition] >>= aItem.sImageIdentifier; + ++nPosition; + lValues[nPosition] >>= aItem.sTargetName; + ++nPosition; + aNewMenu.AppendSetupEntry( aItem ); + } + + // Attention: Don't reset nPosition here! + + // Get names/values for wizard menu. + // 4 subkeys for every item! + for( nItem=0; nItem<nWizardCount; ++nItem ) + { + SvtDynMenuEntry aItem; + lValues[nPosition] >>= aItem.sURL; + ++nPosition; + lValues[nPosition] >>= aItem.sTitle; + ++nPosition; + lValues[nPosition] >>= aItem.sImageIdentifier; + ++nPosition; + lValues[nPosition] >>= aItem.sTargetName; + ++nPosition; + aWizardMenu.AppendSetupEntry( aItem ); + } + + std::vector< SvtDynMenuEntry > lReturn; + switch( eMenu ) + { + case EDynamicMenuType::NewMenu : + lReturn = aNewMenu.GetList(); + break; + + case EDynamicMenuType::WizardMenu : + lReturn = aWizardMenu.GetList(); + break; + } + return lReturn; +} + +static void lcl_SortAndExpandPropertyNames( const Sequence< OUString >& lSource, + Sequence< OUString >& lDestination, std::u16string_view sSetNode ); + +/*-**************************************************************************************************** + @short return list of key names of our configuration management which represent our module tree + @descr This method returns the current list of key names! We need it to get needed values from our + configuration management and support dynamical menu item lists! + @param "nNewCount" , returns count of menu entries for "new" + @param "nWizardCount" , returns count of menu entries for "wizard" + @return A list of configuration key names is returned. +*//*-*****************************************************************************************************/ +static Sequence< OUString > lcl_GetPropertyNames( + css::uno::Reference<css::container::XHierarchicalNameAccess> const & xHierarchyAccess, + sal_uInt32& nNewCount, sal_uInt32& nWizardCount ) +{ + // First get ALL names of current existing list items in configuration! + Sequence< OUString > lNewItems = utl::ConfigItem::GetNodeNames( xHierarchyAccess, SETNODE_NEWMENU, utl::ConfigNameFormat::LocalPath ); + Sequence< OUString > lWizardItems = utl::ConfigItem::GetNodeNames( xHierarchyAccess, SETNODE_WIZARDMENU, utl::ConfigNameFormat::LocalPath ); + + // Get information about list counts ... + nNewCount = lNewItems.getLength(); + nWizardCount = lWizardItems.getLength(); + + // Sort and expand all three list to result list ... + Sequence< OUString > lProperties; + lcl_SortAndExpandPropertyNames( lNewItems , lProperties, SETNODE_NEWMENU ); + lcl_SortAndExpandPropertyNames( lWizardItems , lProperties, SETNODE_WIZARDMENU ); + + // Return result. + return lProperties; +} + +/*-**************************************************************************************************** + @short sort given source list and expand it for all well known properties to destination + @descr We must support sets of entries with count inside the name .. but some of them could be missing! + e.g. s1-s2-s3-s0-u1-s6-u5-u7 + Then we must sort it by name and expand it to the follow one: + sSetNode/s0/URL + sSetNode/s0/Title + sSetNode/s0/... + sSetNode/s1/URL + sSetNode/s1/Title + sSetNode/s1/... + ... + sSetNode/s6/URL + sSetNode/s6/Title + sSetNode/s6/... + sSetNode/u1/URL + sSetNode/u1/Title + sSetNode/u1/... + ... + sSetNode/u7/URL + sSetNode/u7/Title + sSetNode/u7/... + Rules: We start with all setup written entries names "sx" and x=[0..n]. + Then we handle all "ux" items. Inside these blocks we sort it ascending by number. + + @attention We add these expanded list to the end of given "lDestination" list! + So we must start on "lDestination.getLength()". + Reallocation of memory of destination list is done by us! + + @seealso method impl_GetPropertyNames() + + @param "lSource" , original list (e.g. [m1-m2-m3-m6-m0] ) + @param "lDestination" , destination of operation + @param "sSetNode" , name of configuration set to build complete path + @return A list of configuration key names is returned. +*//*-*****************************************************************************************************/ + +static void lcl_SortAndExpandPropertyNames( const Sequence< OUString >& lSource , + Sequence< OUString >& lDestination , + std::u16string_view sSetNode ) +{ + struct CountWithPrefixSort + { + bool operator() ( std::u16string_view s1, std::u16string_view s2 ) const + { + // Get order numbers from entry name without prefix. + // e.g. "m10" => 10 + // "m5" => 5 + sal_Int32 n1 = o3tl::toInt32(s1.substr( 1 )); + sal_Int32 n2 = o3tl::toInt32(s2.substr( 1 )); + // MUST be in [0,1] ... because it's a difference between + // insert-positions of given entries in sorted list! + return( n1<n2 ); + } + }; + struct SelectByPrefix + { + bool operator() ( std::u16string_view s ) const + { + // Prefer setup written entries by check first letter of given string. It must be a "s". + return o3tl::starts_with( s, PATHPREFIX_SETUP ); + } + }; + + std::vector< OUString > lTemp; + sal_Int32 nSourceCount = lSource.getLength(); + sal_Int32 nDestinationStep = lDestination.getLength(); // start on end of current list ...! + + lDestination.realloc( (nSourceCount*PROPERTYCOUNT)+nDestinationStep ); // get enough memory for copy operations after nDestination ... + auto plDestination = lDestination.getArray(); + + // Copy all items to temp. vector to use fast sort operations :-) + lTemp.insert( lTemp.end(), lSource.begin(), lSource.end() ); + + // Sort all entries by number ... + std::stable_sort( lTemp.begin(), lTemp.end(), CountWithPrefixSort() ); + // and split into setup & user written entries! + std::stable_partition( lTemp.begin(), lTemp.end(), SelectByPrefix() ); + + // Copy sorted entries to destination and expand every item with + // 4 supported sub properties. + for( const auto& rItem : lTemp ) + { + OUString sFixPath(OUString::Concat(sSetNode) + PATHDELIMITER + rItem + PATHDELIMITER); + plDestination[nDestinationStep++] = sFixPath + PROPERTYNAME_URL; + plDestination[nDestinationStep++] = sFixPath + PROPERTYNAME_TITLE; + plDestination[nDestinationStep++] = sFixPath + PROPERTYNAME_IMAGEIDENTIFIER; + plDestination[nDestinationStep++] = sFixPath + PROPERTYNAME_TARGETNAME; + } +} + + +} // namespace SvtDynamicMenuOptions + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/eventcfg.cxx b/unotools/source/config/eventcfg.cxx new file mode 100644 index 000000000..a92618a81 --- /dev/null +++ b/unotools/source/config/eventcfg.cxx @@ -0,0 +1,381 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * 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/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <sal/config.h> + +#include <comphelper/propertyvalue.hxx> +#include <unotools/eventcfg.hxx> +#include <unotools/configmgr.hxx> +#include <unotools/configitem.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> +#include <com/sun/star/beans/PropertyValue.hpp> +#include <o3tl/enumarray.hxx> +#include <o3tl/enumrange.hxx> +#include <rtl/ref.hxx> +#include <sal/log.hxx> + +#include "itemholder1.hxx" + +#include <algorithm> +#include <unordered_map> + +using namespace ::std; +using namespace ::utl; +using namespace ::osl; +using namespace ::com::sun::star::uno; +using namespace ::com::sun::star; + +#define PATHDELIMITER "/" +#define SETNODE_BINDINGS "Bindings" +#define PROPERTYNAME_BINDINGURL "BindingURL" + +static o3tl::enumarray<GlobalEventId, const char*> pEventAsciiNames = +{ +"OnStartApp", +"OnCloseApp", +"OnCreate", +"OnNew", +"OnLoadFinished", +"OnLoad", +"OnPrepareUnload", +"OnUnload", +"OnSave", +"OnSaveDone", +"OnSaveFailed", +"OnSaveAs", +"OnSaveAsDone", +"OnSaveAsFailed", +"OnCopyTo", +"OnCopyToDone", +"OnCopyToFailed", +"OnFocus", +"OnUnfocus", +"OnPrint", +"OnViewCreated", +"OnPrepareViewClosing", +"OnViewClosed", +"OnModifyChanged", +"OnTitleChanged", +"OnVisAreaChanged", +"OnModeChanged", +"OnStorageChanged" +}; + +typedef std::unordered_map< OUString, OUString > EventBindingHash; +typedef o3tl::enumarray< GlobalEventId, OUString > SupportedEventsVector; + +static std::mutex& GetOwnStaticMutex() +{ + static std::mutex INSTANCE; + return INSTANCE; +} + +class GlobalEventConfig_Impl : public utl::ConfigItem +{ +private: + EventBindingHash m_eventBindingHash; + SupportedEventsVector m_supportedEvents; + + void initBindingInfo(); + + virtual void ImplCommit() override; + +public: + GlobalEventConfig_Impl( ); + virtual ~GlobalEventConfig_Impl( ) override; + + void Notify( const css::uno::Sequence<OUString>& aPropertyNames) override; + + /// @throws css::lang::IllegalArgumentException + /// @throws css::container::NoSuchElementException + /// @throws css::lang::WrappedTargetException + /// @throws css::uno::RuntimeException + void replaceByName( const OUString& aName, const css::uno::Any& aElement ); + /// @throws css::container::NoSuchElementException + /// @throws css::lang::WrappedTargetException + /// @throws css::uno::RuntimeException + css::uno::Sequence < css::beans::PropertyValue > getByName( const OUString& aName ); + /// @throws css::uno::RuntimeException + css::uno::Sequence< OUString > getElementNames( ); + /// @throws css::uno::RuntimeException + bool hasByName( const OUString& aName ); + /// @throws css::uno::RuntimeException + static css::uno::Type const & getElementType( ); + /// @throws css::uno::RuntimeException + bool hasElements() const; + OUString const & GetEventName( GlobalEventId nID ) const; +}; + + +GlobalEventConfig_Impl::GlobalEventConfig_Impl() + : ConfigItem( "Office.Events/ApplicationEvents", ConfigItemMode::NONE ) +{ + // the supported event names + for (const GlobalEventId id : o3tl::enumrange<GlobalEventId>()) + m_supportedEvents[id] = OUString::createFromAscii( pEventAsciiNames[id] ); + + initBindingInfo(); + +/*TODO: Not used in the moment! see Notify() ... + // Enable notification mechanism of our baseclass. + // We need it to get information about changes outside these class on our used configuration keys! */ + Sequence<OUString> aNotifySeq { "Events" }; + EnableNotification( aNotifySeq, true ); +} + +// destructor + +GlobalEventConfig_Impl::~GlobalEventConfig_Impl() +{ + assert(!IsModified()); // should have been committed +} + +OUString const & GlobalEventConfig_Impl::GetEventName( GlobalEventId nIndex ) const +{ + return m_supportedEvents[nIndex]; +} + +// public method + +void GlobalEventConfig_Impl::Notify( const Sequence< OUString >& ) +{ + std::unique_lock aGuard( GetOwnStaticMutex() ); + + initBindingInfo(); +} + +// public method + +void GlobalEventConfig_Impl::ImplCommit() +{ + //DF need to check it this is correct?? + SAL_INFO("unotools", "In GlobalEventConfig_Impl::ImplCommit"); + // clear the existing nodes + ClearNodeSet( SETNODE_BINDINGS ); + OUString sNode; + //step through the list of events + for(const auto& rEntry : m_eventBindingHash) + { + //no point in writing out empty bindings! + if(rEntry.second.isEmpty() ) + continue; + sNode = SETNODE_BINDINGS PATHDELIMITER "BindingType['" + + rEntry.first + + "']" PATHDELIMITER PROPERTYNAME_BINDINGURL; + SAL_INFO("unotools", "writing binding for: " << sNode); + //write the data to the registry + SetSetProperties(SETNODE_BINDINGS,{ comphelper::makePropertyValue(sNode, rEntry.second) }); + } +} + +// private method + +void GlobalEventConfig_Impl::initBindingInfo() +{ + // Get ALL names of current existing list items in configuration! + const Sequence< OUString > lEventNames = GetNodeNames( SETNODE_BINDINGS, utl::ConfigNameFormat::LocalPath ); + + OUString aSetNode = SETNODE_BINDINGS PATHDELIMITER; + OUString aCommandKey = PATHDELIMITER PROPERTYNAME_BINDINGURL; + + // Expand all keys + Sequence< OUString > lMacros(1); + auto plMacros = lMacros.getArray(); + for (const auto& rEventName : lEventNames ) + { + plMacros[0] = aSetNode + rEventName + aCommandKey; + SAL_INFO("unotools", "reading binding for: " << lMacros[0]); + Sequence< Any > lValues = GetProperties( lMacros ); + if( lValues.hasElements() ) + { + OUString sMacroURL; + lValues[0] >>= sMacroURL; + sal_Int32 startIndex = rEventName.indexOf('\''); + sal_Int32 endIndex = rEventName.lastIndexOf('\''); + if( startIndex >=0 && endIndex > 0 ) + { + startIndex++; + OUString eventName = rEventName.copy(startIndex,endIndex-startIndex); + m_eventBindingHash[ eventName ] = sMacroURL; + } + } + } +} + +void GlobalEventConfig_Impl::replaceByName( const OUString& aName, const Any& aElement ) +{ + Sequence< beans::PropertyValue > props; + //DF should we prepopulate the hash with a list of valid event Names? + if( !( aElement >>= props ) ) + { + throw lang::IllegalArgumentException( OUString(), + Reference< XInterface > (), 2); + } + OUString macroURL; + for( const auto& rProp : std::as_const(props) ) + { + if ( rProp.Name == "Script" ) + rProp.Value >>= macroURL; + } + m_eventBindingHash[ aName ] = macroURL; + SetModified(); +} + +css::uno::Sequence < css::beans::PropertyValue > GlobalEventConfig_Impl::getByName( const OUString& aName ) +{ + static constexpr OUStringLiteral sEventType = u"EventType"; + static constexpr OUStringLiteral sScript = u"Script"; + Sequence< beans::PropertyValue > props(2); + auto pProps = props.getArray(); + pProps[0].Name = sEventType; + pProps[0].Value <<= OUString(sScript); + pProps[1].Name = sScript; + EventBindingHash::const_iterator it = m_eventBindingHash.find( aName ); + if( it != m_eventBindingHash.end() ) + { + pProps[1].Value <<= it->second; + } + else + { + // not yet accessed - is it a supported name? + SupportedEventsVector::iterator pos = ::std::find( + m_supportedEvents.begin(), m_supportedEvents.end(), aName ); + if ( pos == m_supportedEvents.end() ) + throw container::NoSuchElementException( aName ); + + pProps[1].Value <<= OUString(); + } + return props; +} + +Sequence< OUString > GlobalEventConfig_Impl::getElementNames( ) +{ + return uno::Sequence< OUString >(m_supportedEvents.data(), SupportedEventsVector::size()); +} + +bool GlobalEventConfig_Impl::hasByName( const OUString& aName ) +{ + if ( m_eventBindingHash.find( aName ) != m_eventBindingHash.end() ) + return true; + + // never accessed before - is it supported in general? + SupportedEventsVector::iterator pos = ::std::find( + m_supportedEvents.begin(), m_supportedEvents.end(), aName ); + return pos != m_supportedEvents.end(); +} + +Type const & GlobalEventConfig_Impl::getElementType( ) +{ + //DF definitely not sure about this?? + return cppu::UnoType<Sequence<beans::PropertyValue>>::get(); +} + +bool GlobalEventConfig_Impl::hasElements() const +{ + return !m_eventBindingHash.empty(); +} + +// and now the wrapper + +//initialize static member +GlobalEventConfig_Impl* GlobalEventConfig::m_pImpl = nullptr; +sal_Int32 GlobalEventConfig::m_nRefCount = 0; + +GlobalEventConfig::GlobalEventConfig() +{ + // Global access, must be guarded (multithreading!). + std::unique_lock aGuard( GetOwnStaticMutex() ); + // Increase our refcount ... + ++m_nRefCount; + // ... and initialize our data container only if it not already exist! + if( m_pImpl == nullptr ) + { + m_pImpl = new GlobalEventConfig_Impl; + aGuard.unlock(); + ItemHolder1::holdConfigItem(EItem::EventConfig); + } +} + +GlobalEventConfig::~GlobalEventConfig() +{ + // Global access, must be guarded (multithreading!) + std::unique_lock aGuard( GetOwnStaticMutex() ); + // Decrease our refcount. + --m_nRefCount; + // If last instance was deleted ... + // we must destroy our static data container! + if( m_nRefCount <= 0 ) + { + delete m_pImpl; + m_pImpl = nullptr; + } +} + +Reference< container::XNameReplace > SAL_CALL GlobalEventConfig::getEvents() +{ + std::unique_lock aGuard( GetOwnStaticMutex() ); + Reference< container::XNameReplace > ret(this); + return ret; +} + +void SAL_CALL GlobalEventConfig::replaceByName( const OUString& aName, const Any& aElement ) +{ + std::unique_lock aGuard( GetOwnStaticMutex() ); + m_pImpl->replaceByName( aName, aElement ); +} +Any SAL_CALL GlobalEventConfig::getByName( const OUString& aName ) +{ + return Any(getByName2(aName)); +} +css::uno::Sequence < css::beans::PropertyValue > GlobalEventConfig::getByName2( const OUString& aName ) +{ + std::unique_lock aGuard( GetOwnStaticMutex() ); + return m_pImpl->getByName( aName ); +} +Sequence< OUString > SAL_CALL GlobalEventConfig::getElementNames( ) +{ + std::unique_lock aGuard( GetOwnStaticMutex() ); + return m_pImpl->getElementNames( ); +} +sal_Bool SAL_CALL GlobalEventConfig::hasByName( const OUString& aName ) +{ + std::unique_lock aGuard( GetOwnStaticMutex() ); + return m_pImpl->hasByName( aName ); +} +Type SAL_CALL GlobalEventConfig::getElementType( ) +{ + std::unique_lock aGuard( GetOwnStaticMutex() ); + return GlobalEventConfig_Impl::getElementType( ); +} +sal_Bool SAL_CALL GlobalEventConfig::hasElements( ) +{ + std::unique_lock aGuard( GetOwnStaticMutex() ); + return m_pImpl->hasElements( ); +} + +OUString GlobalEventConfig::GetEventName( GlobalEventId nIndex ) +{ + if (utl::ConfigManager::IsFuzzing()) + return OUString(); + static rtl::Reference<GlobalEventConfig> createImpl(new GlobalEventConfig); + return GlobalEventConfig::m_pImpl->GetEventName( nIndex ); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/fltrcfg.cxx b/unotools/source/config/fltrcfg.cxx new file mode 100644 index 000000000..323cfe0c3 --- /dev/null +++ b/unotools/source/config/fltrcfg.cxx @@ -0,0 +1,677 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * 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/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <o3tl/any.hxx> +#include <o3tl/typed_flags_set.hxx> +#include <unotools/fltrcfg.hxx> +#include <tools/debug.hxx> +#include <osl/diagnose.h> + +#include <com/sun/star/uno/Sequence.hxx> + +using namespace utl; +using namespace com::sun::star::uno; + +namespace { + +enum class ConfigFlags { + NONE = 0x0000000, + WordCode = 0x0000001, + WordStorage = 0x0000002, + ExcelCode = 0x0000004, + ExcelStorage = 0x0000008, + PowerPointCode = 0x0000010, + PowerPointStorage = 0x0000020, + MathLoad = 0x0000100, + MathSave = 0x0000200, + WriterLoad = 0x0000400, + WriterSave = 0x0000800, + CalcLoad = 0x0001000, + CalcSave = 0x0002000, + ImpressLoad = 0x0004000, + ImpressSave = 0x0008000, + ExcelExecTbl = 0x0010000, + EnablePowerPointPreview = 0x0020000, + EnableExcelPreview = 0x0040000, + EnableWordPreview = 0x0080000, + UseEnhancedFields = 0x0100000, + WordWbctbl = 0x0200000, + SmartArtShapeLoad = 0x0400000, + CharBackgroundToHighlighting = 0x8000000, + CreateMSOLockFiles = 0x2000000, + VisioLoad = 0x4000000, +}; + +} + +namespace o3tl { + template<> struct typed_flags<ConfigFlags> : is_typed_flags<ConfigFlags, 0xe7fff3f> {}; +} + +namespace { + +class SvtAppFilterOptions_Impl : public utl::ConfigItem +{ +private: + bool bLoadVBA; + bool bSaveVBA; + +protected: + virtual void ImplCommit() override; + +public: + explicit SvtAppFilterOptions_Impl(const OUString& rRoot) : + utl::ConfigItem(rRoot), + bLoadVBA(false), + bSaveVBA(false) {} + virtual ~SvtAppFilterOptions_Impl() override; + virtual void Notify( const css::uno::Sequence<OUString>& aPropertyNames) override; + void Load(); + + bool IsLoad() const {return bLoadVBA;} + void SetLoad(bool bSet) + { + if(bSet != bLoadVBA) + SetModified(); + bLoadVBA = bSet; + } + bool IsSave() const {return bSaveVBA;} + void SetSave(bool bSet) + { + if(bSet != bSaveVBA) + SetModified(); + bSaveVBA = bSet; + } +}; + +} + +SvtAppFilterOptions_Impl::~SvtAppFilterOptions_Impl() +{ + assert(!IsModified()); // should have been committed +} + +void SvtAppFilterOptions_Impl::ImplCommit() +{ + PutProperties( + {"Load", "Save"}, {css::uno::Any(bLoadVBA), css::uno::Any(bSaveVBA)}); +} + +void SvtAppFilterOptions_Impl::Notify( const Sequence< OUString >& ) +{ + // no listeners supported yet +} + +void SvtAppFilterOptions_Impl::Load() +{ + Sequence<Any> aValues = GetProperties({ "Load", "Save" }); + const Any* pValues = aValues.getConstArray(); + + if(pValues[0].hasValue()) + bLoadVBA = *o3tl::doAccess<bool>(pValues[0]); + if(pValues[1].hasValue()) + bSaveVBA = *o3tl::doAccess<bool>(pValues[1]); +} + +namespace { + +class SvtWriterFilterOptions_Impl : public SvtAppFilterOptions_Impl +{ +private: + bool bLoadExecutable; + + virtual void ImplCommit() override; + +public: + explicit SvtWriterFilterOptions_Impl(const OUString& rRoot) : + SvtAppFilterOptions_Impl(rRoot), + bLoadExecutable(false) + {} + void Load(); + + bool IsLoadExecutable() const {return bLoadExecutable;} + void SetLoadExecutable(bool bSet) + { + if(bSet != bLoadExecutable) + SetModified(); + bLoadExecutable = bSet; + } +}; + +} + +void SvtWriterFilterOptions_Impl::ImplCommit() +{ + SvtAppFilterOptions_Impl::ImplCommit(); + + PutProperties({ "Executable" }, { Any(bLoadExecutable) }); +} + +void SvtWriterFilterOptions_Impl::Load() +{ + SvtAppFilterOptions_Impl::Load(); + + Sequence<OUString> aNames { "Executable" }; + + Sequence<Any> aValues = GetProperties(aNames); + const Any* pValues = aValues.getConstArray(); + if(pValues[0].hasValue()) + bLoadExecutable = *o3tl::doAccess<bool>(pValues[0]); +} + +namespace { + +class SvtCalcFilterOptions_Impl : public SvtAppFilterOptions_Impl +{ +private: + bool bLoadExecutable; + + virtual void ImplCommit() override; + +public: + explicit SvtCalcFilterOptions_Impl(const OUString& rRoot) : + SvtAppFilterOptions_Impl(rRoot), + bLoadExecutable(false) + {} + void Load(); + + bool IsLoadExecutable() const {return bLoadExecutable;} + void SetLoadExecutable(bool bSet) + { + if(bSet != bLoadExecutable) + SetModified(); + bLoadExecutable = bSet; + } +}; + +} + +void SvtCalcFilterOptions_Impl::ImplCommit() +{ + SvtAppFilterOptions_Impl::ImplCommit(); + + PutProperties({ "Executable" }, { Any(bLoadExecutable) }); +} + +void SvtCalcFilterOptions_Impl::Load() +{ + SvtAppFilterOptions_Impl::Load(); + + Sequence<OUString> aNames { "Executable" }; + + Sequence<Any> aValues = GetProperties(aNames); + const Any* pValues = aValues.getConstArray(); + if(pValues[0].hasValue()) + bLoadExecutable = *o3tl::doAccess<bool>(pValues[0]); +} + +struct SvtFilterOptions_Impl +{ + ConfigFlags nFlags; + SvtWriterFilterOptions_Impl aWriterCfg; + SvtCalcFilterOptions_Impl aCalcCfg; + SvtAppFilterOptions_Impl aImpressCfg; + + SvtFilterOptions_Impl() : + aWriterCfg("Office.Writer/Filter/Import/VBA"), + aCalcCfg("Office.Calc/Filter/Import/VBA"), + aImpressCfg("Office.Impress/Filter/Import/VBA") + { + nFlags = ConfigFlags::WordCode | + ConfigFlags::WordStorage | + ConfigFlags::ExcelCode | + ConfigFlags::ExcelStorage | + ConfigFlags::PowerPointCode | + ConfigFlags::PowerPointStorage | + ConfigFlags::MathLoad | + ConfigFlags::MathSave | + ConfigFlags::WriterLoad | + ConfigFlags::WriterSave | + ConfigFlags::CalcLoad | + ConfigFlags::CalcSave | + ConfigFlags::ImpressLoad | + ConfigFlags::ImpressSave | + ConfigFlags::UseEnhancedFields | + ConfigFlags::SmartArtShapeLoad | + ConfigFlags::CharBackgroundToHighlighting| + ConfigFlags::CreateMSOLockFiles; + Load(); + } + + void SetFlag( ConfigFlags nFlag, bool bSet ); + bool IsFlag( ConfigFlags nFlag ) const; + void Load() + { + aWriterCfg.Load(); + aCalcCfg.Load(); + aImpressCfg.Load(); + } +}; + +void SvtFilterOptions_Impl::SetFlag( ConfigFlags nFlag, bool bSet ) +{ + switch(nFlag) + { + case ConfigFlags::WordCode: aWriterCfg.SetLoad(bSet);break; + case ConfigFlags::WordStorage: aWriterCfg.SetSave(bSet);break; + case ConfigFlags::WordWbctbl: aWriterCfg.SetLoadExecutable(bSet);break; + case ConfigFlags::ExcelCode: aCalcCfg.SetLoad(bSet);break; + case ConfigFlags::ExcelStorage: aCalcCfg.SetSave(bSet);break; + case ConfigFlags::ExcelExecTbl: aCalcCfg.SetLoadExecutable(bSet);break; + case ConfigFlags::PowerPointCode: aImpressCfg.SetLoad(bSet);break; + case ConfigFlags::PowerPointStorage: aImpressCfg.SetSave(bSet);break; + default: + if( bSet ) + nFlags |= nFlag; + else + nFlags &= ~nFlag; + } +} + +bool SvtFilterOptions_Impl::IsFlag( ConfigFlags nFlag ) const +{ + bool bRet; + switch(nFlag) + { + case ConfigFlags::WordCode : bRet = aWriterCfg.IsLoad();break; + case ConfigFlags::WordStorage : bRet = aWriterCfg.IsSave();break; + case ConfigFlags::WordWbctbl : bRet = aWriterCfg.IsLoadExecutable();break; + case ConfigFlags::ExcelCode : bRet = aCalcCfg.IsLoad();break; + case ConfigFlags::ExcelStorage : bRet = aCalcCfg.IsSave();break; + case ConfigFlags::ExcelExecTbl : bRet = aCalcCfg.IsLoadExecutable();break; + case ConfigFlags::PowerPointCode : bRet = aImpressCfg.IsLoad();break; + case ConfigFlags::PowerPointStorage : bRet = aImpressCfg.IsSave();break; + default: + bRet = bool(nFlags & nFlag ); + } + return bRet; +} + +namespace { + +const Sequence<OUString>& GetPropertyNames() +{ + static Sequence<OUString> const aNames + { + "Import/MathTypeToMath", // 0 + "Import/WinWordToWriter", // 1 + "Import/PowerPointToImpress", // 2 + "Import/ExcelToCalc", // 3 + "Export/MathToMathType", // 4 + "Export/WriterToWinWord", // 5 + "Export/ImpressToPowerPoint", // 6 + "Export/CalcToExcel", // 7 + "Export/EnablePowerPointPreview", // 8 + "Export/EnableExcelPreview", // 9 + "Export/EnableWordPreview", // 10 + "Import/ImportWWFieldsAsEnhancedFields", // 11 + "Import/SmartArtToShapes", // 12 + "Export/CharBackgroundToHighlighting", // 13 + "Import/CreateMSOLockFiles", // 14 + "Import/VisioToDraw" // 15 + }; + return aNames; +} + +} + +SvtFilterOptions::SvtFilterOptions() : + ConfigItem( "Office.Common/Filter/Microsoft" ), + pImpl(new SvtFilterOptions_Impl) +{ + EnableNotification(GetPropertyNames()); + Load(); +} + +SvtFilterOptions::~SvtFilterOptions() +{ +} + +static ConfigFlags lcl_GetFlag(sal_Int32 nProp) +{ + ConfigFlags nFlag = ConfigFlags::NONE; + switch(nProp) + { + case 0: nFlag = ConfigFlags::MathLoad; break; + case 1: nFlag = ConfigFlags::WriterLoad; break; + case 2: nFlag = ConfigFlags::ImpressLoad; break; + case 3: nFlag = ConfigFlags::CalcLoad; break; + case 4: nFlag = ConfigFlags::MathSave; break; + case 5: nFlag = ConfigFlags::WriterSave; break; + case 6: nFlag = ConfigFlags::ImpressSave; break; + case 7: nFlag = ConfigFlags::CalcSave; break; + case 8: nFlag = ConfigFlags::EnablePowerPointPreview; break; + case 9: nFlag = ConfigFlags::EnableExcelPreview; break; + case 10: nFlag = ConfigFlags::EnableWordPreview; break; + case 11: nFlag = ConfigFlags::UseEnhancedFields; break; + case 12: nFlag = ConfigFlags::SmartArtShapeLoad; break; + case 13: nFlag = ConfigFlags::CharBackgroundToHighlighting; break; + case 14: nFlag = ConfigFlags::CreateMSOLockFiles; break; + case 15: + nFlag = ConfigFlags::VisioLoad; + break; + + default: OSL_FAIL("illegal value"); + } + return nFlag; +} + +void SvtFilterOptions::Notify( const Sequence<OUString>& ) +{ + Load(); +} + +void SvtFilterOptions::ImplCommit() +{ + const Sequence<OUString>& aNames = GetPropertyNames(); + Sequence<Any> aValues(aNames.getLength()); + Any* pValues = aValues.getArray(); + + for(int nProp = 0; nProp < aNames.getLength(); nProp++) + { + ConfigFlags nFlag = lcl_GetFlag(nProp); + pValues[nProp] <<= pImpl->IsFlag(nFlag); + + } + PutProperties(aNames, aValues); +} + +void SvtFilterOptions::Load() +{ + pImpl->Load(); + const Sequence<OUString>& rNames = GetPropertyNames(); + Sequence<Any> aValues = GetProperties(rNames); + const Any* pValues = aValues.getConstArray(); + DBG_ASSERT(aValues.getLength() == rNames.getLength(), "GetProperties failed"); + if(aValues.getLength() == rNames.getLength()) + { + for(int nProp = 0; nProp < rNames.getLength(); nProp++) + { + if(pValues[nProp].hasValue()) + { + bool bVal = *o3tl::doAccess<bool>(pValues[nProp]); + ConfigFlags nFlag = lcl_GetFlag(nProp); + pImpl->SetFlag( nFlag, bVal); + } + } + } +} + +void SvtFilterOptions::SetLoadWordBasicCode( bool bFlag ) +{ + pImpl->SetFlag( ConfigFlags::WordCode, bFlag ); + SetModified(); +} + +bool SvtFilterOptions::IsLoadWordBasicCode() const +{ + return pImpl->IsFlag( ConfigFlags::WordCode ); +} + +void SvtFilterOptions::SetLoadWordBasicExecutable( bool bFlag ) +{ + pImpl->SetFlag( ConfigFlags::WordWbctbl, bFlag ); + SetModified(); +} + +bool SvtFilterOptions::IsLoadWordBasicExecutable() const +{ + return pImpl->IsFlag( ConfigFlags::WordWbctbl ); +} + +void SvtFilterOptions::SetLoadWordBasicStorage( bool bFlag ) +{ + pImpl->SetFlag( ConfigFlags::WordStorage, bFlag ); + SetModified(); +} + +bool SvtFilterOptions::IsLoadWordBasicStorage() const +{ + return pImpl->IsFlag( ConfigFlags::WordStorage ); +} + +void SvtFilterOptions::SetLoadExcelBasicCode( bool bFlag ) +{ + pImpl->SetFlag( ConfigFlags::ExcelCode, bFlag ); + SetModified(); +} + +bool SvtFilterOptions::IsLoadExcelBasicCode() const +{ + return pImpl->IsFlag( ConfigFlags::ExcelCode ); +} + +void SvtFilterOptions::SetLoadExcelBasicExecutable( bool bFlag ) +{ + pImpl->SetFlag( ConfigFlags::ExcelExecTbl, bFlag ); + SetModified(); +} + +bool SvtFilterOptions::IsLoadExcelBasicExecutable() const +{ + return pImpl->IsFlag( ConfigFlags::ExcelExecTbl ); +} + +void SvtFilterOptions::SetLoadExcelBasicStorage( bool bFlag ) +{ + pImpl->SetFlag( ConfigFlags::ExcelStorage, bFlag ); + SetModified(); +} + +bool SvtFilterOptions::IsLoadExcelBasicStorage() const +{ + return pImpl->IsFlag( ConfigFlags::ExcelStorage ); +} + +void SvtFilterOptions::SetLoadPPointBasicCode( bool bFlag ) +{ + pImpl->SetFlag( ConfigFlags::PowerPointCode, bFlag ); + SetModified(); +} + +bool SvtFilterOptions::IsLoadPPointBasicCode() const +{ + return pImpl->IsFlag( ConfigFlags::PowerPointCode ); +} + +void SvtFilterOptions::SetLoadPPointBasicStorage( bool bFlag ) +{ + pImpl->SetFlag( ConfigFlags::PowerPointStorage, bFlag ); + SetModified(); +} + +bool SvtFilterOptions::IsLoadPPointBasicStorage() const +{ + return pImpl->IsFlag( ConfigFlags::PowerPointStorage ); +} + +bool SvtFilterOptions::IsMathType2Math() const +{ + return pImpl->IsFlag( ConfigFlags::MathLoad ); +} + +void SvtFilterOptions::SetMathType2Math( bool bFlag ) +{ + pImpl->SetFlag( ConfigFlags::MathLoad, bFlag ); + SetModified(); +} + +bool SvtFilterOptions::IsMath2MathType() const +{ + return pImpl->IsFlag( ConfigFlags::MathSave ); +} + +void SvtFilterOptions::SetMath2MathType( bool bFlag ) +{ + pImpl->SetFlag( ConfigFlags::MathSave, bFlag ); + SetModified(); +} + +bool SvtFilterOptions::IsWinWord2Writer() const +{ + return pImpl->IsFlag( ConfigFlags::WriterLoad ); +} + +void SvtFilterOptions::SetWinWord2Writer( bool bFlag ) +{ + pImpl->SetFlag( ConfigFlags::WriterLoad, bFlag ); + SetModified(); +} + +bool SvtFilterOptions::IsWriter2WinWord() const +{ + return pImpl->IsFlag( ConfigFlags::WriterSave ); +} + +void SvtFilterOptions::SetWriter2WinWord( bool bFlag ) +{ + pImpl->SetFlag( ConfigFlags::WriterSave, bFlag ); + SetModified(); +} + +bool SvtFilterOptions::IsUseEnhancedFields() const +{ + return pImpl->IsFlag( ConfigFlags::UseEnhancedFields ); +} + +bool SvtFilterOptions::IsExcel2Calc() const +{ + return pImpl->IsFlag( ConfigFlags::CalcLoad ); +} + +void SvtFilterOptions::SetExcel2Calc( bool bFlag ) +{ + pImpl->SetFlag( ConfigFlags::CalcLoad, bFlag ); + SetModified(); +} + +bool SvtFilterOptions::IsCalc2Excel() const +{ + return pImpl->IsFlag( ConfigFlags::CalcSave ); +} + +void SvtFilterOptions::SetCalc2Excel( bool bFlag ) +{ + pImpl->SetFlag( ConfigFlags::CalcSave, bFlag ); + SetModified(); +} + +bool SvtFilterOptions::IsPowerPoint2Impress() const +{ + return pImpl->IsFlag( ConfigFlags::ImpressLoad ); +} + +void SvtFilterOptions::SetPowerPoint2Impress( bool bFlag ) +{ + pImpl->SetFlag( ConfigFlags::ImpressLoad, bFlag ); + SetModified(); +} + +bool SvtFilterOptions::IsImpress2PowerPoint() const +{ + return pImpl->IsFlag( ConfigFlags::ImpressSave ); +} + +void SvtFilterOptions::SetImpress2PowerPoint( bool bFlag ) +{ + pImpl->SetFlag( ConfigFlags::ImpressSave, bFlag ); + SetModified(); +} + +bool SvtFilterOptions::IsSmartArt2Shape() const +{ + return pImpl->IsFlag( ConfigFlags::SmartArtShapeLoad ); +} + +void SvtFilterOptions::SetSmartArt2Shape( bool bFlag ) +{ + pImpl->SetFlag( ConfigFlags::SmartArtShapeLoad, bFlag ); + SetModified(); +} + +bool SvtFilterOptions::IsVisio2Draw() const { return pImpl->IsFlag(ConfigFlags::VisioLoad); } + +void SvtFilterOptions::SetVisio2Draw(bool bFlag) +{ + pImpl->SetFlag(ConfigFlags::VisioLoad, bFlag); + SetModified(); +} + +namespace +{ + class theFilterOptions + : public rtl::Static<SvtFilterOptions, theFilterOptions> + { + }; +} + +SvtFilterOptions& SvtFilterOptions::Get() +{ + return theFilterOptions::get(); +} + +bool SvtFilterOptions::IsEnablePPTPreview() const +{ + return pImpl->IsFlag( ConfigFlags::EnablePowerPointPreview ); +} + +bool SvtFilterOptions::IsEnableCalcPreview() const +{ + return pImpl->IsFlag( ConfigFlags::EnableExcelPreview ); +} + +bool SvtFilterOptions::IsEnableWordPreview() const +{ + return pImpl->IsFlag( ConfigFlags::EnableWordPreview ); +} + +bool SvtFilterOptions::IsCharBackground2Highlighting() const +{ + return pImpl->IsFlag( ConfigFlags::CharBackgroundToHighlighting ); +} + +bool SvtFilterOptions::IsCharBackground2Shading() const +{ + return !pImpl->IsFlag( ConfigFlags::CharBackgroundToHighlighting ); +} + +void SvtFilterOptions::SetCharBackground2Highlighting() +{ + pImpl->SetFlag( ConfigFlags::CharBackgroundToHighlighting, true ); + SetModified(); +} + +void SvtFilterOptions::SetCharBackground2Shading() +{ + pImpl->SetFlag( ConfigFlags::CharBackgroundToHighlighting, false ); + SetModified(); +} + +bool SvtFilterOptions::IsMSOLockFileCreationIsEnabled() const +{ + return pImpl->IsFlag( ConfigFlags::CreateMSOLockFiles ); +} + +void SvtFilterOptions::EnableMSOLockFileCreation(bool bEnable) +{ + pImpl->SetFlag( ConfigFlags::CreateMSOLockFiles, bEnable ); + SetModified(); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/fontcfg.cxx b/unotools/source/config/fontcfg.cxx new file mode 100644 index 000000000..0a8ab40b3 --- /dev/null +++ b/unotools/source/config/fontcfg.cxx @@ -0,0 +1,1077 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * 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/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <i18nlangtag/mslangid.hxx> +#include <i18nlangtag/languagetag.hxx> +#include <o3tl/any.hxx> +#include <unotools/configmgr.hxx> +#include <unotools/fontcfg.hxx> +#include <unotools/fontdefs.hxx> +#include <comphelper/processfactory.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> +#include <com/sun/star/configuration/theDefaultProvider.hpp> +#include <com/sun/star/container/XNameAccess.hpp> +#include <comphelper/propertysequence.hxx> +#include <unotools/syslocale.hxx> +#include <rtl/ustrbuf.hxx> +#include <osl/diagnose.h> +#include <sal/macros.h> +#include <sal/log.hxx> + +#include <string.h> +#include <algorithm> + +using namespace utl; +using namespace com::sun::star::uno; +using namespace com::sun::star::lang; +using namespace com::sun::star::beans; +using namespace com::sun::star::container; +using namespace com::sun::star::configuration; + +/* + * DefaultFontConfiguration + */ + +static const char* getKeyType( DefaultFontType nKeyType ) +{ + switch( nKeyType ) + { + case DefaultFontType::CJK_DISPLAY: return "CJK_DISPLAY"; + case DefaultFontType::CJK_HEADING: return "CJK_HEADING"; + case DefaultFontType::CJK_PRESENTATION: return "CJK_PRESENTATION"; + case DefaultFontType::CJK_SPREADSHEET: return "CJK_SPREADSHEET"; + case DefaultFontType::CJK_TEXT: return "CJK_TEXT"; + case DefaultFontType::CTL_DISPLAY: return "CTL_DISPLAY"; + case DefaultFontType::CTL_HEADING: return "CTL_HEADING"; + case DefaultFontType::CTL_PRESENTATION: return "CTL_PRESENTATION"; + case DefaultFontType::CTL_SPREADSHEET: return "CTL_SPREADSHEET"; + case DefaultFontType::CTL_TEXT: return "CTL_TEXT"; + case DefaultFontType::FIXED: return "FIXED"; + case DefaultFontType::LATIN_DISPLAY: return "LATIN_DISPLAY"; + case DefaultFontType::LATIN_FIXED: return "LATIN_FIXED"; + case DefaultFontType::LATIN_HEADING: return "LATIN_HEADING"; + case DefaultFontType::LATIN_PRESENTATION: return "LATIN_PRESENTATION"; + case DefaultFontType::LATIN_SPREADSHEET: return "LATIN_SPREADSHEET"; + case DefaultFontType::LATIN_TEXT: return "LATIN_TEXT"; + case DefaultFontType::SANS: return "SANS"; + case DefaultFontType::SANS_UNICODE: return "SANS_UNICODE"; + case DefaultFontType::SERIF: return "SERIF"; + case DefaultFontType::SYMBOL: return "SYMBOL"; + case DefaultFontType::UI_FIXED: return "UI_FIXED"; + case DefaultFontType::UI_SANS: return "UI_SANS"; + default: + OSL_FAIL( "unmatched type" ); + return ""; + } +} + +DefaultFontConfiguration& DefaultFontConfiguration::get() +{ + static DefaultFontConfiguration theDefaultFontConfiguration; + return theDefaultFontConfiguration; +} + +DefaultFontConfiguration::DefaultFontConfiguration() +{ + if (utl::ConfigManager::IsFuzzing()) + return; + // create configuration hierarchical access name + try + { + // get service provider + m_xConfigProvider = theDefaultProvider::get(comphelper::getProcessComponentContext()); + Sequence<Any> aArgs(comphelper::InitAnyPropertySequence( + { + {"nodepath", Any(OUString( "/org.openoffice.VCL/DefaultFonts" ))} + })); + m_xConfigAccess = + Reference< XNameAccess >( + m_xConfigProvider->createInstanceWithArguments( "com.sun.star.configuration.ConfigurationAccess", + aArgs ), + UNO_QUERY ); + if( m_xConfigAccess.is() ) + { + const Sequence< OUString > aLocales = m_xConfigAccess->getElementNames(); + // fill config hash with empty interfaces + for( const OUString& rLocaleString : aLocales ) + { + // Feed through LanguageTag for casing. + OUString aLoc( LanguageTag( rLocaleString, true).getBcp47( false)); + m_aConfig[ aLoc ] = LocaleAccess(); + m_aConfig[ aLoc ].aConfigLocaleString = rLocaleString; + } + } + } + catch (const Exception&) + { + // configuration is awry + m_xConfigProvider.clear(); + m_xConfigAccess.clear(); + } + SAL_INFO("unotools.config", "config provider: " << m_xConfigProvider.is() + << ", config access: " << m_xConfigAccess.is()); +} + +DefaultFontConfiguration::~DefaultFontConfiguration() +{ + // release all nodes + m_aConfig.clear(); + // release top node + m_xConfigAccess.clear(); + // release config provider + m_xConfigProvider.clear(); +} + +OUString DefaultFontConfiguration::tryLocale( const OUString& rBcp47, const OUString& rType ) const +{ + OUString aRet; + + std::unordered_map< OUString, LocaleAccess >::const_iterator it = m_aConfig.find( rBcp47 ); + if( it != m_aConfig.end() ) + { + if( !it->second.xAccess.is() ) + { + try + { + Reference< XNameAccess > xNode; + if ( m_xConfigAccess->hasByName( it->second.aConfigLocaleString ) ) + { + Any aAny = m_xConfigAccess->getByName( it->second.aConfigLocaleString ); + if( aAny >>= xNode ) + it->second.xAccess = xNode; + } + } + catch (const NoSuchElementException&) + { + } + catch (const WrappedTargetException&) + { + } + } + if( it->second.xAccess.is() ) + { + try + { + if ( it->second.xAccess->hasByName( rType ) ) + { + Any aAny = it->second.xAccess->getByName( rType ); + aAny >>= aRet; + } + } + catch (const NoSuchElementException&) + { + } + catch (const WrappedTargetException&) + { + } + } + } + + return aRet; +} + +OUString DefaultFontConfiguration::getDefaultFont( const LanguageTag& rLanguageTag, DefaultFontType nType ) const +{ + OUString aType = OUString::createFromAscii( getKeyType( nType ) ); + // Try the simple cases first without constructing fallbacks. + OUString aRet = tryLocale( rLanguageTag.getBcp47(), aType ); + if (aRet.isEmpty()) + { + if (rLanguageTag.isIsoLocale()) + { + if (!rLanguageTag.getCountry().isEmpty()) + { + aRet = tryLocale( rLanguageTag.getLanguage(), aType ); + } + } + else + { + ::std::vector< OUString > aFallbacks( rLanguageTag.getFallbackStrings( false)); + for (const auto& rFallback : aFallbacks) + { + aRet = tryLocale( rFallback, aType ); + if (!aRet.isEmpty()) + break; + } + } + } + if( aRet.isEmpty() ) + { + aRet = tryLocale( "en", aType ); + } + return aRet; +} + +OUString DefaultFontConfiguration::getUserInterfaceFont( const LanguageTag& rLanguageTag ) const +{ + LanguageTag aLanguageTag( rLanguageTag); + if( aLanguageTag.isSystemLocale() ) + aLanguageTag = SvtSysLocale().GetUILanguageTag(); + + OUString aUIFont = getDefaultFont( aLanguageTag, DefaultFontType::UI_SANS ); + + if( !aUIFont.isEmpty() ) + return aUIFont; + + // fallback mechanism (either no configuration or no entry in configuration + + static constexpr OUStringLiteral FALLBACKFONT_UI_SANS = u"Andale Sans UI;Albany;Albany AMT;Tahoma;Arial Unicode MS;Arial;Nimbus Sans L;Bitstream Vera Sans;gnu-unifont;Interface User;Geneva;WarpSans;Dialog;Swiss;Lucida;Helvetica;Charcoal;Chicago;MS Sans Serif;Helv;Times;Times New Roman;Interface System"; + static constexpr OUStringLiteral FALLBACKFONT_UI_SANS_LATIN2 = u"Andale Sans UI;Albany;Albany AMT;Tahoma;Arial Unicode MS;Arial;Nimbus Sans L;Luxi Sans;Bitstream Vera Sans;Interface User;Geneva;WarpSans;Dialog;Swiss;Lucida;Helvetica;Charcoal;Chicago;MS Sans Serif;Helv;Times;Times New Roman;Interface System"; + static constexpr OUStringLiteral FALLBACKFONT_UI_SANS_ARABIC = u"Tahoma;Traditional Arabic;Simplified Arabic;Lucidasans;Lucida Sans;Supplement;Andale Sans UI;clearlyU;Interface User;Arial Unicode MS;Lucida Sans Unicode;WarpSans;Geneva;MS Sans Serif;Helv;Dialog;Albany;Lucida;Helvetica;Charcoal;Chicago;Arial;Helmet;Interface System;Sans Serif"; + static constexpr OUStringLiteral FALLBACKFONT_UI_SANS_THAI = u"OONaksit;Tahoma;Lucidasans;Arial Unicode MS"; + static constexpr OUStringLiteral FALLBACKFONT_UI_SANS_KOREAN = u"Noto Sans KR;Noto Sans CJK KR;Noto Serif KR;Noto Serif CJK KR;Source Han Sans KR;NanumGothic;NanumBarunGothic;NanumBarunGothic YetHangul;KoPubWorld Dotum;Malgun Gothic;Apple SD Gothic Neo;Dotum;DotumChe;Gulim;GulimChe;Batang;BatangChe;Apple Gothic;UnDotum;Baekmuk Gulim;Arial Unicode MS;Lucida Sans Unicode;gnu-unifont;Andale Sans UI"; + static constexpr OUStringLiteral FALLBACKFONT_UI_SANS_JAPANESE = u"Noto Sans CJK JP;Noto Sans JP;Source Han Sans;Source Han Sans JP;Yu Gothic UI;Yu Gothic;YuGothic;Hiragino Sans;Hiragino Kaku Gothic ProN;Hiragino Kaku Gothic Pro;Hiragino Kaku Gothic StdN;Meiryo UI;Meiryo;IPAexGothic;IPAPGothic;IPAGothic;MS UI Gothic;MS PGothic;MS Gothic;Osaka;Unifont;gnu-unifont;Arial Unicode MS;Interface System"; + static constexpr OUStringLiteral FALLBACKFONT_UI_SANS_CHINSIM = u"Andale Sans UI;Arial Unicode MS;ZYSong18030;AR PL SungtiL GB;AR PL KaitiM GB;SimSun;Lucida Sans Unicode;Fangsong;Hei;Song;Kai;Ming;gnu-unifont;Interface User;"; + static constexpr OUStringLiteral FALLBACKFONT_UI_SANS_CHINTRD = u"Andale Sans UI;Arial Unicode MS;AR PL Mingti2L Big5;AR PL KaitiM Big5;Kai;PMingLiU;MingLiU;Ming;Lucida Sans Unicode;gnu-unifont;Interface User;"; + + const OUString aLanguage( aLanguageTag.getLanguage()); + + // optimize font list for some locales, as long as Andale Sans UI does not support them + if( aLanguage == "ar" || aLanguage == "he" || aLanguage == "iw" ) + { + return FALLBACKFONT_UI_SANS_ARABIC; + } + else if ( aLanguage == "th" ) + { + return FALLBACKFONT_UI_SANS_THAI; + } + else if ( aLanguage == "ko" ) + { + return FALLBACKFONT_UI_SANS_KOREAN; + } + else if ( aLanguage == "ja" ) + { + return FALLBACKFONT_UI_SANS_JAPANESE; + } + else if( aLanguage == "cs" || + aLanguage == "hu" || + aLanguage == "pl" || + aLanguage == "ro" || + aLanguage == "rm" || + aLanguage == "hr" || + aLanguage == "sk" || + aLanguage == "sl" || + aLanguage == "sb") + { + return FALLBACKFONT_UI_SANS_LATIN2; + } + else + { + const Locale& aLocale( aLanguageTag.getLocale()); + if (MsLangId::isTraditionalChinese(aLocale)) + return FALLBACKFONT_UI_SANS_CHINTRD; + else if (MsLangId::isSimplifiedChinese(aLocale)) + return FALLBACKFONT_UI_SANS_CHINSIM; + } + + return FALLBACKFONT_UI_SANS; +} + +/* + * FontSubstConfigItem::get + */ + +FontSubstConfiguration& FontSubstConfiguration::get() +{ + static FontSubstConfiguration theFontSubstConfiguration; + return theFontSubstConfiguration; +} + +/* + * FontSubstConfigItem::FontSubstConfigItem + */ + +FontSubstConfiguration::FontSubstConfiguration() : + maSubstHash( 300 ), + maLanguageTag("en") +{ + if (utl::ConfigManager::IsFuzzing()) + return; + try + { + // get service provider + Reference< XComponentContext > xContext( comphelper::getProcessComponentContext() ); + // create configuration hierarchical access name + m_xConfigProvider = theDefaultProvider::get( xContext ); + Sequence<Any> aArgs(comphelper::InitAnyPropertySequence( + { + {"nodepath", Any(OUString( "/org.openoffice.VCL/FontSubstitutions" ))} + })); + m_xConfigAccess = + Reference< XNameAccess >( + m_xConfigProvider->createInstanceWithArguments( "com.sun.star.configuration.ConfigurationAccess", + aArgs ), + UNO_QUERY ); + if( m_xConfigAccess.is() ) + { + const Sequence< OUString > aLocales = m_xConfigAccess->getElementNames(); + // fill config hash with empty interfaces + for( const OUString& rLocaleString : aLocales ) + { + // Feed through LanguageTag for casing. + OUString aLoc( LanguageTag( rLocaleString, true).getBcp47( false)); + m_aSubst[ aLoc ] = LocaleSubst(); + m_aSubst[ aLoc ].aConfigLocaleString = rLocaleString; + } + } + } + catch (const Exception&) + { + // configuration is awry + m_xConfigProvider.clear(); + m_xConfigAccess.clear(); + } + SAL_INFO("unotools.config", "config provider: " << m_xConfigProvider.is() + << ", config access: " << m_xConfigAccess.is()); + + if( maLanguageTag.isSystemLocale() ) + maLanguageTag = SvtSysLocale().GetUILanguageTag(); +} + +/* + * FontSubstConfigItem::~FontSubstConfigItem + */ + +FontSubstConfiguration::~FontSubstConfiguration() +{ + // release config access + m_xConfigAccess.clear(); + // release config provider + m_xConfigProvider.clear(); +} + +/* + * FontSubstConfigItem::getMapName + */ + +const char* const aImplKillLeadingList[] = +{ + "microsoft", + "monotype", + "linotype", + "baekmuk", + "adobe", + "nimbus", + "zycjk", + "itc", + "sun", + "amt", + "ms", + "mt", + "cg", + "hg", + "fz", + "ipa", + "sazanami", + "kochi", + nullptr +}; + +const char* const aImplKillTrailingList[] = +{ + "microsoft", + "monotype", + "linotype", + "adobe", + "nimbus", + "itc", + "sun", + "amt", + "ms", + "mt", + "clm", + // Scripts, for compatibility with older versions + "we", + "cyr", + "tur", + "wt", + "greek", + "wl", + // CJK extensions + "gb", + "big5", + "pro", + "z01", + "z02", + "z03", + "z13", + "b01", + "w3x12", + // Old Printer Fontnames + "5cpi", + "6cpi", + "7cpi", + "8cpi", + "9cpi", + "10cpi", + "11cpi", + "12cpi", + "13cpi", + "14cpi", + "15cpi", + "16cpi", + "18cpi", + "24cpi", + "scale", + "pc", + nullptr +}; + +const char* const aImplKillTrailingWithExceptionsList[] = +{ + "ce", "monospace", "oldface", nullptr, + "ps", "caps", nullptr, + nullptr +}; + +namespace { + +struct ImplFontAttrWeightSearchData +{ + const char* mpStr; + FontWeight meWeight; +}; + +} + +ImplFontAttrWeightSearchData const aImplWeightAttrSearchList[] = +{ +// the attribute names are ordered by "first match wins" +// e.g. "semilight" should wins over "semi" +{ "extrablack", WEIGHT_BLACK }, +{ "ultrablack", WEIGHT_BLACK }, +{ "ultrabold", WEIGHT_ULTRABOLD }, +{ "semibold", WEIGHT_SEMIBOLD }, +{ "semilight", WEIGHT_SEMILIGHT }, +{ "semi", WEIGHT_SEMIBOLD }, +{ "demi", WEIGHT_SEMIBOLD }, +{ "black", WEIGHT_BLACK }, +{ "bold", WEIGHT_BOLD }, +{ "heavy", WEIGHT_BLACK }, +{ "ultralight", WEIGHT_ULTRALIGHT }, +{ "light", WEIGHT_LIGHT }, +{ "medium", WEIGHT_MEDIUM }, +{ nullptr, WEIGHT_DONTKNOW }, +}; + +namespace { + +struct ImplFontAttrWidthSearchData +{ + const char* mpStr; + FontWidth meWidth; +}; + +} + +ImplFontAttrWidthSearchData const aImplWidthAttrSearchList[] = +{ +{ "narrow", WIDTH_CONDENSED }, +{ "semicondensed", WIDTH_SEMI_CONDENSED }, +{ "ultracondensed", WIDTH_ULTRA_CONDENSED }, +{ "semiexpanded", WIDTH_SEMI_EXPANDED }, +{ "ultraexpanded", WIDTH_ULTRA_EXPANDED }, +{ "expanded", WIDTH_EXPANDED }, +{ "wide", WIDTH_ULTRA_EXPANDED }, +{ "condensed", WIDTH_CONDENSED }, +{ "cond", WIDTH_CONDENSED }, +{ "cn", WIDTH_CONDENSED }, +{ nullptr, WIDTH_DONTKNOW }, +}; + +namespace { + +struct ImplFontAttrTypeSearchData +{ + const char* mpStr; + ImplFontAttrs mnType; +}; + +} + +ImplFontAttrTypeSearchData const aImplTypeAttrSearchList[] = +{ +{ "monotype", ImplFontAttrs::None }, +{ "linotype", ImplFontAttrs::None }, +{ "titling", ImplFontAttrs::Titling }, +{ "captitals", ImplFontAttrs::Capitals }, +{ "captital", ImplFontAttrs::Capitals }, +{ "caps", ImplFontAttrs::Capitals }, +{ "italic", ImplFontAttrs::Italic }, +{ "oblique", ImplFontAttrs::Italic }, +{ "rounded", ImplFontAttrs::Rounded }, +{ "outline", ImplFontAttrs::Outline }, +{ "shadow", ImplFontAttrs::Shadow }, +{ "handwriting", ImplFontAttrs::Handwriting | ImplFontAttrs::Script }, +{ "hand", ImplFontAttrs::Handwriting | ImplFontAttrs::Script }, +{ "signet", ImplFontAttrs::Handwriting | ImplFontAttrs::Script }, +{ "script", ImplFontAttrs::BrushScript | ImplFontAttrs::Script }, +{ "calligraphy", ImplFontAttrs::Chancery | ImplFontAttrs::Script }, +{ "chancery", ImplFontAttrs::Chancery | ImplFontAttrs::Script }, +{ "corsiva", ImplFontAttrs::Chancery | ImplFontAttrs::Script }, +{ "gothic", ImplFontAttrs::SansSerif | ImplFontAttrs::Gothic }, +{ "schoolbook", ImplFontAttrs::Serif | ImplFontAttrs::Schoolbook }, +{ "schlbk", ImplFontAttrs::Serif | ImplFontAttrs::Schoolbook }, +{ "typewriter", ImplFontAttrs::Typewriter | ImplFontAttrs::Fixed }, +{ "lineprinter", ImplFontAttrs::Typewriter | ImplFontAttrs::Fixed }, +{ "monospaced", ImplFontAttrs::Fixed }, +{ "monospace", ImplFontAttrs::Fixed }, +{ "mono", ImplFontAttrs::Fixed }, +{ "fixed", ImplFontAttrs::Fixed }, +{ "sansserif", ImplFontAttrs::SansSerif }, +{ "sans", ImplFontAttrs::SansSerif }, +{ "swiss", ImplFontAttrs::SansSerif }, +{ "serif", ImplFontAttrs::Serif }, +{ "bright", ImplFontAttrs::Serif }, +{ "symbols", ImplFontAttrs::Symbol }, +{ "symbol", ImplFontAttrs::Symbol }, +{ "dingbats", ImplFontAttrs::Symbol }, +{ "dings", ImplFontAttrs::Symbol }, +{ "ding", ImplFontAttrs::Symbol }, +{ "bats", ImplFontAttrs::Symbol }, +{ "math", ImplFontAttrs::Symbol }, +{ "oldstyle", ImplFontAttrs::OtherStyle }, +{ "oldface", ImplFontAttrs::OtherStyle }, +{ "old", ImplFontAttrs::OtherStyle }, +{ "new", ImplFontAttrs::None }, +{ "modern", ImplFontAttrs::None }, +{ "lucida", ImplFontAttrs::None }, +{ "regular", ImplFontAttrs::None }, +{ "extended", ImplFontAttrs::None }, +{ "extra", ImplFontAttrs::OtherStyle }, +{ "ext", ImplFontAttrs::None }, +{ "scalable", ImplFontAttrs::None }, +{ "scale", ImplFontAttrs::None }, +{ "nimbus", ImplFontAttrs::None }, +{ "adobe", ImplFontAttrs::None }, +{ "itc", ImplFontAttrs::None }, +{ "amt", ImplFontAttrs::None }, +{ "mt", ImplFontAttrs::None }, +{ "ms", ImplFontAttrs::None }, +{ "cpi", ImplFontAttrs::None }, +{ "no", ImplFontAttrs::None }, +{ nullptr, ImplFontAttrs::None }, +}; + +static bool ImplKillLeading( OUString& rName, const char* const* ppStr ) +{ + for(; *ppStr; ++ppStr ) + { + const char* pStr = *ppStr; + const sal_Unicode* pNameStr = rName.getStr(); + while ( (*pNameStr == static_cast<sal_Unicode>(static_cast<unsigned char>(*pStr))) && *pStr ) + { + pNameStr++; + pStr++; + } + if ( !*pStr ) + { + sal_Int32 nLen = static_cast<sal_Int32>(pNameStr - rName.getStr()); + rName = rName.copy(nLen); + return true; + } + } + + // special case for Baekmuk + // TODO: allow non-ASCII KillLeading list + const sal_Unicode* pNameStr = rName.getStr(); + if( (pNameStr[0]==0xBC31) && (pNameStr[1]==0xBC35) ) + { + sal_Int32 nLen = (pNameStr[2]==0x0020) ? 3 : 2; + rName = rName.copy(nLen); + return true; + } + + return false; +} + +static sal_Int32 ImplIsTrailing( std::u16string_view rName, const char* pStr ) +{ + size_t nStrLen = strlen( pStr ); + if( nStrLen >= rName.size() ) + return 0; + + const sal_Unicode* pEndName = rName.data() + rName.size(); + const sal_Unicode* pNameStr = pEndName - nStrLen; + do if( *(pNameStr++) != *(pStr++) ) + return 0; + while( *pStr ); + + return nStrLen; +} + +static bool ImplKillTrailing( OUString& rName, const char* const* ppStr ) +{ + for(; *ppStr; ++ppStr ) + { + sal_Int32 nTrailLen = ImplIsTrailing( rName, *ppStr ); + if( nTrailLen ) + { + rName = rName.copy(0, rName.getLength() - nTrailLen ); + return true; + } + } + + return false; +} + +static bool ImplKillTrailingWithExceptions( OUString& rName, const char* const* ppStr ) +{ + for(; *ppStr; ++ppStr ) + { + sal_Int32 nTrailLen = ImplIsTrailing( rName, *ppStr ); + if( nTrailLen ) + { + // check string match against string exceptions + while( *++ppStr ) + if( ImplIsTrailing( rName, *ppStr ) ) + return false; + + rName = rName.copy(0, rName.getLength() - nTrailLen ); + return true; + } + else + { + // skip exception strings + while( *++ppStr ) {} + } + } + + return false; +} + +static bool ImplFindAndErase( OUString& rName, const char* pStr ) +{ + sal_Int32 nLen = static_cast<sal_Int32>(strlen(pStr)); + sal_Int32 nPos = rName.indexOfAsciiL(pStr, nLen ); + if ( nPos < 0 ) + return false; + + OUStringBuffer sBuff(rName); + sBuff.remove(nPos, nLen); + rName = sBuff.makeStringAndClear(); + return true; +} + +void FontSubstConfiguration::getMapName( const OUString& rOrgName, OUString& rShortName, + OUString& rFamilyName, FontWeight& rWeight, + FontWidth& rWidth, ImplFontAttrs& rType ) +{ + rShortName = rOrgName; + + // TODO: get rid of the crazy O(N*strlen) searches below + // they should be possible in O(strlen) + + // Kill leading vendor names and other unimportant data + ImplKillLeading( rShortName, aImplKillLeadingList ); + + // Kill trailing vendor names and other unimportant data + ImplKillTrailing( rShortName, aImplKillTrailingList ); + ImplKillTrailingWithExceptions( rShortName, aImplKillTrailingWithExceptionsList ); + + rFamilyName = rShortName; + + // Kill attributes from the name and update the data + // Weight + const ImplFontAttrWeightSearchData* pWeightList = aImplWeightAttrSearchList; + while ( pWeightList->mpStr ) + { + if ( ImplFindAndErase( rFamilyName, pWeightList->mpStr ) ) + { + if ( (rWeight == WEIGHT_DONTKNOW) || (rWeight == WEIGHT_NORMAL) ) + rWeight = pWeightList->meWeight; + break; + } + pWeightList++; + } + + // Width + const ImplFontAttrWidthSearchData* pWidthList = aImplWidthAttrSearchList; + while ( pWidthList->mpStr ) + { + if ( ImplFindAndErase( rFamilyName, pWidthList->mpStr ) ) + { + if ( (rWidth == WIDTH_DONTKNOW) || (rWidth == WIDTH_NORMAL) ) + rWidth = pWidthList->meWidth; + break; + } + pWidthList++; + } + + // Type + rType = ImplFontAttrs::None; + const ImplFontAttrTypeSearchData* pTypeList = aImplTypeAttrSearchList; + while ( pTypeList->mpStr ) + { + if ( ImplFindAndErase( rFamilyName, pTypeList->mpStr ) ) + rType |= pTypeList->mnType; + pTypeList++; + } + + // Remove numbers + // TODO: also remove localized and fullwidth digits + sal_Int32 i = 0; + OUStringBuffer sBuff(rFamilyName); + while ( i < sBuff.getLength() ) + { + sal_Unicode c = sBuff[ i ]; + if ( (c >= 0x0030) && (c <= 0x0039) ) + sBuff.remove(i, 1); + else + i++; + } +} + +namespace { + +struct StrictStringSort +{ + bool operator()( const FontNameAttr& rLeft, const FontNameAttr& rRight ) + { return rLeft.Name.compareTo( rRight.Name ) < 0; } +}; + +} + +// The entries in this table must match the bits in the ImplFontAttrs enum. + +const char* const pAttribNames[] = +{ + "default", + "standard", + "normal", + "symbol", + "fixed", + "sansserif", + "serif", + "decorative", + "special", + "italic", + "title", + "capitals", + "cjk", + "cjk_jp", + "cjk_sc", + "cjk_tc", + "cjk_kr", + "ctl", + "nonelatin", + "full", + "outline", + "shadow", + "rounded", + "typewriter", + "script", + "handwriting", + "chancery", + "comic", + "brushscript", + "gothic", + "schoolbook", + "other" +}; + +namespace { + +struct enum_convert +{ + const char* pName; + int nEnum; +}; + +} + +const enum_convert pWeightNames[] = +{ + { "normal", WEIGHT_NORMAL }, + { "medium", WEIGHT_MEDIUM }, + { "bold", WEIGHT_BOLD }, + { "black", WEIGHT_BLACK }, + { "semibold", WEIGHT_SEMIBOLD }, + { "light", WEIGHT_LIGHT }, + { "semilight", WEIGHT_SEMILIGHT }, + { "ultrabold", WEIGHT_ULTRABOLD }, + { "semi", WEIGHT_SEMIBOLD }, + { "demi", WEIGHT_SEMIBOLD }, + { "heavy", WEIGHT_BLACK }, + { "unknown", WEIGHT_DONTKNOW }, + { "thin", WEIGHT_THIN }, + { "ultralight", WEIGHT_ULTRALIGHT } +}; + +const enum_convert pWidthNames[] = +{ + { "normal", WIDTH_NORMAL }, + { "condensed", WIDTH_CONDENSED }, + { "expanded", WIDTH_EXPANDED }, + { "unknown", WIDTH_DONTKNOW }, + { "ultracondensed", WIDTH_ULTRA_CONDENSED }, + { "extracondensed", WIDTH_EXTRA_CONDENSED }, + { "semicondensed", WIDTH_SEMI_CONDENSED }, + { "semiexpanded", WIDTH_SEMI_EXPANDED }, + { "extraexpanded", WIDTH_EXTRA_EXPANDED }, + { "ultraexpanded", WIDTH_ULTRA_EXPANDED } +}; + +void FontSubstConfiguration::fillSubstVector( const css::uno::Reference< XNameAccess >& rFont, + const OUString& rType, + std::vector< OUString >& rSubstVector ) const +{ + try + { + Any aAny = rFont->getByName( rType ); + if( auto pLine = o3tl::tryAccess<OUString>(aAny) ) + { + sal_Int32 nLength = pLine->getLength(); + if( nLength ) + { + const sal_Unicode* pStr = pLine->getStr(); + sal_Int32 nTokens = 0; + // count tokens + while( nLength-- ) + { + if( *pStr++ == ';' ) + nTokens++; + } + rSubstVector.clear(); + // optimize performance, heap fragmentation + rSubstVector.reserve( nTokens ); + sal_Int32 nIndex = 0; + while( nIndex != -1 ) + { + OUString aSubst( pLine->getToken( 0, ';', nIndex ) ); + if( !aSubst.isEmpty() ) + { + auto itPair = maSubstHash.insert( aSubst ); + if (!itPair.second) + aSubst = *itPair.first; + rSubstVector.push_back( aSubst ); + } + } + } + } + } + catch (const NoSuchElementException&) + { + } + catch (const WrappedTargetException&) + { + } +} + +FontWeight FontSubstConfiguration::getSubstWeight( const css::uno::Reference< XNameAccess >& rFont, + const OUString& rType ) const +{ + int weight = -1; + try + { + Any aAny = rFont->getByName( rType ); + if( auto pLine = o3tl::tryAccess<OUString>(aAny) ) + { + if( !pLine->isEmpty() ) + { + for( weight=SAL_N_ELEMENTS(pWeightNames)-1; weight >= 0; weight-- ) + if( pLine->equalsIgnoreAsciiCaseAscii( pWeightNames[weight].pName ) ) + break; + } + SAL_WARN_IF(weight < 0, "unotools.config", "Error: invalid weight " << *pLine); + } + } + catch (const NoSuchElementException&) + { + } + catch (const WrappedTargetException&) + { + } + return static_cast<FontWeight>( weight >= 0 ? pWeightNames[weight].nEnum : WEIGHT_DONTKNOW ); +} + +FontWidth FontSubstConfiguration::getSubstWidth( const css::uno::Reference< XNameAccess >& rFont, + const OUString& rType ) const +{ + int width = -1; + try + { + Any aAny = rFont->getByName( rType ); + if( auto pLine = o3tl::tryAccess<OUString>(aAny) ) + { + if( !pLine->isEmpty() ) + { + for( width=SAL_N_ELEMENTS(pWidthNames)-1; width >= 0; width-- ) + if( pLine->equalsIgnoreAsciiCaseAscii( pWidthNames[width].pName ) ) + break; + } + SAL_WARN_IF( width < 0, "unotools.config", "Error: invalid width " << *pLine); + } + } + catch (const NoSuchElementException&) + { + } + catch (const WrappedTargetException&) + { + } + return static_cast<FontWidth>( width >= 0 ? pWidthNames[width].nEnum : WIDTH_DONTKNOW ); +} + +ImplFontAttrs FontSubstConfiguration::getSubstType( const css::uno::Reference< XNameAccess >& rFont, + const OUString& rType ) const +{ + sal_uInt32 type = 0; + try + { + Any aAny = rFont->getByName( rType ); + auto pLine = o3tl::tryAccess<OUString>(aAny); + if( !pLine ) + return ImplFontAttrs::None; + if( pLine->isEmpty() ) + return ImplFontAttrs::None; + sal_Int32 nIndex = 0; + while( nIndex != -1 ) + { + OUString aToken( pLine->getToken( 0, ',', nIndex ) ); + for( int k = 0; k < 32; k++ ) + if( aToken.equalsIgnoreAsciiCaseAscii( pAttribNames[k] ) ) + { + type |= sal_uInt32(1) << k; + break; + } + } + assert(((type & ~o3tl::typed_flags<ImplFontAttrs>::mask) == 0) && "invalid font attributes"); + } + catch (const NoSuchElementException&) + { + } + catch (const WrappedTargetException&) + { + } + + return static_cast<ImplFontAttrs>(type); +} + +void FontSubstConfiguration::readLocaleSubst( const OUString& rBcp47 ) const +{ + std::unordered_map< OUString, LocaleSubst >::const_iterator it = m_aSubst.find( rBcp47 ); + if( it == m_aSubst.end() ) + return; + + if( it->second.bConfigRead ) + return; + + it->second.bConfigRead = true; + Reference< XNameAccess > xNode; + try + { + Any aAny = m_xConfigAccess->getByName( it->second.aConfigLocaleString ); + aAny >>= xNode; + } + catch (const NoSuchElementException&) + { + } + catch (const WrappedTargetException&) + { + } + if( !xNode.is() ) + return; + + const Sequence< OUString > aFonts = xNode->getElementNames(); + int nFonts = aFonts.getLength(); + // improve performance, heap fragmentation + it->second.aSubstAttributes.reserve( nFonts ); + + // strings for subst retrieval, construct only once + OUString const aSubstFontsStr ( "SubstFonts" ); + OUString const aSubstFontsMSStr ( "SubstFontsMS" ); + OUString const aSubstWeightStr ( "FontWeight" ); + OUString const aSubstWidthStr ( "FontWidth" ); + OUString const aSubstTypeStr ( "FontType" ); + for( const OUString& rFontName : aFonts ) + { + Reference< XNameAccess > xFont; + try + { + Any aAny = xNode->getByName( rFontName ); + aAny >>= xFont; + } + catch (const NoSuchElementException&) + { + } + catch (const WrappedTargetException&) + { + } + if( ! xFont.is() ) + { + SAL_WARN("unotools.config", "did not get font attributes for " << rFontName); + continue; + } + + FontNameAttr aAttr; + // read subst attributes from config + aAttr.Name = rFontName; + fillSubstVector( xFont, aSubstFontsStr, aAttr.Substitutions ); + fillSubstVector( xFont, aSubstFontsMSStr, aAttr.MSSubstitutions ); + aAttr.Weight = getSubstWeight( xFont, aSubstWeightStr ); + aAttr.Width = getSubstWidth( xFont, aSubstWidthStr ); + aAttr.Type = getSubstType( xFont, aSubstTypeStr ); + + // finally insert this entry + it->second.aSubstAttributes.push_back( aAttr ); + } + std::sort( it->second.aSubstAttributes.begin(), it->second.aSubstAttributes.end(), StrictStringSort() ); +} + +const FontNameAttr* FontSubstConfiguration::getSubstInfo( const OUString& rFontName ) const +{ + if( rFontName.isEmpty() ) + return nullptr; + + // search if a (language dep.) replacement table for the given font exists + // fallback is english + OUString aSearchFont( rFontName.toAsciiLowerCase() ); + FontNameAttr aSearchAttr; + aSearchAttr.Name = aSearchFont; + + ::std::vector< OUString > aFallbacks( maLanguageTag.getFallbackStrings( true)); + if (maLanguageTag.getLanguage() != "en") + aFallbacks.emplace_back("en"); + + for (const auto& rFallback : aFallbacks) + { + std::unordered_map< OUString, LocaleSubst >::const_iterator lang = m_aSubst.find( rFallback ); + if( lang != m_aSubst.end() ) + { + if( ! lang->second.bConfigRead ) + readLocaleSubst( rFallback ); + // try to find an exact match + // because the list is sorted this will also find fontnames of the form searchfontname* + std::vector< FontNameAttr >::const_iterator it = ::std::lower_bound( lang->second.aSubstAttributes.begin(), lang->second.aSubstAttributes.end(), aSearchAttr, StrictStringSort() ); + if( it != lang->second.aSubstAttributes.end()) + { + const FontNameAttr& rFoundAttr = *it; + // a search for "abcblack" may match with an entry for "abc" + // the reverse is not a good idea (e.g. #i112731# alba->albani) + if( rFoundAttr.Name.getLength() <= aSearchFont.getLength() ) + if( aSearchFont.startsWith( rFoundAttr.Name)) + return &rFoundAttr; + } + } + } + return nullptr; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/historyoptions.cxx b/unotools/source/config/historyoptions.cxx new file mode 100644 index 000000000..db5ef4087 --- /dev/null +++ b/unotools/source/config/historyoptions.cxx @@ -0,0 +1,442 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * 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/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <unotools/historyoptions.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> + +#include <com/sun/star/beans/XPropertySet.hpp> +#include <com/sun/star/container/XNameAccess.hpp> +#include <com/sun/star/container/XNameContainer.hpp> +#include <com/sun/star/lang/XSingleServiceFactory.hpp> +#include <comphelper/configurationhelper.hxx> +#include <comphelper/processfactory.hxx> +#include <tools/diagnose_ex.h> +#include <optional> + +using namespace ::com::sun::star; +using namespace ::com::sun::star::uno; +using namespace ::com::sun::star::beans; + +namespace { + constexpr OUStringLiteral s_sItemList = u"ItemList"; + constexpr OUStringLiteral s_sOrderList = u"OrderList"; + constexpr OUStringLiteral s_sHistoryItemRef = u"HistoryItemRef"; + constexpr OUStringLiteral s_sFilter = u"Filter"; + constexpr OUStringLiteral s_sTitle = u"Title"; + constexpr OUStringLiteral s_sPassword = u"Password"; + constexpr OUStringLiteral s_sThumbnail = u"Thumbnail"; + constexpr OUStringLiteral s_sReadOnly = u"ReadOnly"; +} + +static uno::Reference<container::XNameAccess> GetConfig(); +static uno::Reference<container::XNameAccess> GetCommonXCU(); +static uno::Reference<container::XNameAccess> GetListAccess( + uno::Reference<container::XNameAccess> const & xCfg, + EHistoryType eHistory); +static void TruncateList( + const uno::Reference<container::XNameAccess>& xCfg, + const uno::Reference<container::XNameAccess>& xList, + sal_uInt32 nSize); +static sal_uInt32 GetCapacity(const uno::Reference<container::XNameAccess>& xCommonXCU, EHistoryType eHistory); + +namespace SvtHistoryOptions +{ + +void Clear( EHistoryType eHistory ) +{ + try + { + uno::Reference<container::XNameAccess> xCfg = GetConfig(); + uno::Reference<container::XNameAccess> xListAccess(GetListAccess(xCfg, eHistory)); + + // clear ItemList + uno::Reference<container::XNameContainer> xNode; + xListAccess->getByName(s_sItemList) >>= xNode; + Sequence<OUString> aStrings(xNode->getElementNames()); + + for (const auto& rString : std::as_const(aStrings)) + xNode->removeByName(rString); + + // clear OrderList + xListAccess->getByName(s_sOrderList) >>= xNode; + aStrings = xNode->getElementNames(); + + for (const auto& rString : std::as_const(aStrings)) + xNode->removeByName(rString); + + ::comphelper::ConfigurationHelper::flush(xCfg); + } + catch(const uno::Exception&) + { + DBG_UNHANDLED_EXCEPTION("unotools.config"); + } +} + +std::vector< HistoryItem > GetList( EHistoryType eHistory ) +{ + std::vector< HistoryItem > aRet; + try + { + uno::Reference<container::XNameAccess> xCfg = GetConfig(); + uno::Reference<container::XNameAccess> xCommonXCU = GetCommonXCU(); + uno::Reference<container::XNameAccess> xListAccess(GetListAccess(xCfg, eHistory)); + + TruncateList(xCfg, xListAccess, GetCapacity(xCommonXCU, eHistory)); + + uno::Reference<container::XNameAccess> xItemList; + uno::Reference<container::XNameAccess> xOrderList; + xListAccess->getByName(s_sItemList) >>= xItemList; + xListAccess->getByName(s_sOrderList) >>= xOrderList; + + const sal_Int32 nLength = xOrderList->getElementNames().getLength(); + aRet.reserve(nLength); + + for (sal_Int32 nItem = 0; nItem < nLength; ++nItem) + { + try + { + OUString sUrl; + uno::Reference<beans::XPropertySet> xSet; + xOrderList->getByName(OUString::number(nItem)) >>= xSet; + xSet->getPropertyValue(s_sHistoryItemRef) >>= sUrl; + + xItemList->getByName(sUrl) >>= xSet; + HistoryItem aItem; + aItem.sURL = sUrl; + xSet->getPropertyValue(s_sFilter) >>= aItem.sFilter; + xSet->getPropertyValue(s_sTitle) >>= aItem.sTitle; + xSet->getPropertyValue(s_sPassword) >>= aItem.sPassword; + xSet->getPropertyValue(s_sThumbnail) >>= aItem.sThumbnail; + xSet->getPropertyValue(s_sReadOnly) >>= aItem.isReadOnly; + aRet.push_back(aItem); + } + catch(const uno::Exception&) + { + // <https://bugs.libreoffice.org/show_bug.cgi?id=46074> + // "FILEOPEN: No Recent Documents..." discusses a problem + // with corrupted /org.openoffice.Office/Histories/Histories + // configuration items; to work around that problem, simply + // ignore such corrupted individual items here, so that at + // least newly added items are successfully reported back + // from this function: + DBG_UNHANDLED_EXCEPTION("unotools.config"); + } + } + } + catch(const uno::Exception&) + { + DBG_UNHANDLED_EXCEPTION("unotools.config"); + } + return aRet; +} + +void AppendItem(EHistoryType eHistory, + const OUString& sURL, const OUString& sFilter, const OUString& sTitle, + const std::optional<OUString>& sThumbnail, + ::std::optional<bool> const oIsReadOnly) +{ + try + { + uno::Reference<container::XNameAccess> xCfg = GetConfig(); + uno::Reference<container::XNameAccess> xCommonXCU = GetCommonXCU(); + uno::Reference<container::XNameAccess> xListAccess(GetListAccess(xCfg, eHistory)); + + TruncateList(xCfg, xListAccess, GetCapacity(xCommonXCU, eHistory)); + + sal_Int32 nMaxSize = GetCapacity(xCommonXCU, eHistory); + if (nMaxSize == 0) + return; + + uno::Reference<container::XNameContainer> xItemList; + uno::Reference<container::XNameContainer> xOrderList; + xListAccess->getByName(s_sItemList) >>= xItemList; + xListAccess->getByName(s_sOrderList) >>= xOrderList; + sal_Int32 nLength = xOrderList->getElementNames().getLength(); + + // The item to be appended already exists + if (xItemList->hasByName(sURL)) + { + uno::Reference<beans::XPropertySet> xSet; + xItemList->getByName(sURL) >>= xSet; + if (sThumbnail) + { + // update the thumbnail + xSet->setPropertyValue(s_sThumbnail, uno::Any(*sThumbnail)); + } + if (oIsReadOnly) + { + xSet->setPropertyValue(s_sReadOnly, uno::Any(*oIsReadOnly)); + } + + for (sal_Int32 i=0; i<nLength; ++i) + { + OUString aItem; + xOrderList->getByName(OUString::number(i)) >>= xSet; + xSet->getPropertyValue(s_sHistoryItemRef) >>= aItem; + + if (aItem == sURL) + { + for (sal_Int32 j = i - 1; j >= 0; --j) + { + uno::Reference<beans::XPropertySet> xPrevSet; + uno::Reference<beans::XPropertySet> xNextSet; + xOrderList->getByName(OUString::number(j+1)) >>= xPrevSet; + xOrderList->getByName(OUString::number(j)) >>= xNextSet; + + OUString sTemp; + xNextSet->getPropertyValue(s_sHistoryItemRef) >>= sTemp; + xPrevSet->setPropertyValue(s_sHistoryItemRef, uno::Any(sTemp)); + } + xOrderList->getByName(OUString::number(0)) >>= xSet; + xSet->setPropertyValue(s_sHistoryItemRef, uno::Any(aItem)); + break; + } + } + + ::comphelper::ConfigurationHelper::flush(xCfg); + } + else // The item to be appended does not exist yet + { + uno::Reference<beans::XPropertySet> xSet; + uno::Reference<lang::XSingleServiceFactory> xFac; + uno::Reference<uno::XInterface> xInst; + uno::Reference<beans::XPropertySet> xPrevSet; + uno::Reference<beans::XPropertySet> xNextSet; + + // Append new item to OrderList. + if ( nLength == nMaxSize ) + { + OUString sRemove; + xOrderList->getByName(OUString::number(nLength-1)) >>= xSet; + xSet->getPropertyValue(s_sHistoryItemRef) >>= sRemove; + try + { + xItemList->removeByName(sRemove); + } + catch (container::NoSuchElementException &) + { + // <https://bugs.libreoffice.org/show_bug.cgi?id=46074> + // "FILEOPEN: No Recent Documents..." discusses a problem + // with corrupted /org.openoffice.Office/Histories/Histories + // configuration items; to work around that problem, simply + // ignore such corrupted individual items here, so that at + // least newly added items are successfully added: + if (!sRemove.isEmpty()) + { + throw; + } + } + } + if (nLength != nMaxSize) + { + xFac.set(xOrderList, uno::UNO_QUERY); + xInst = xFac->createInstance(); + OUString sPush = OUString::number(nLength++); + xOrderList->insertByName(sPush, uno::Any(xInst)); + } + for (sal_Int32 j=nLength-1; j>0; --j) + { + xOrderList->getByName( OUString::number(j) ) >>= xPrevSet; + xOrderList->getByName( OUString::number(j-1) ) >>= xNextSet; + OUString sTemp; + xNextSet->getPropertyValue(s_sHistoryItemRef) >>= sTemp; + xPrevSet->setPropertyValue(s_sHistoryItemRef, uno::Any(sTemp)); + } + xOrderList->getByName( OUString::number(0) ) >>= xSet; + xSet->setPropertyValue(s_sHistoryItemRef, uno::Any(sURL)); + + // Append the item to ItemList. + xFac.set(xItemList, uno::UNO_QUERY); + xInst = xFac->createInstance(); + xItemList->insertByName(sURL, uno::Any(xInst)); + + xSet.set(xInst, uno::UNO_QUERY); + xSet->setPropertyValue(s_sFilter, uno::Any(sFilter)); + xSet->setPropertyValue(s_sTitle, uno::Any(sTitle)); + xSet->setPropertyValue(s_sPassword, uno::Any(OUString())); + xSet->setPropertyValue(s_sThumbnail, uno::Any(sThumbnail.value_or(OUString()))); + if (oIsReadOnly) + { + xSet->setPropertyValue(s_sReadOnly, uno::Any(*oIsReadOnly)); + } + + ::comphelper::ConfigurationHelper::flush(xCfg); + } + } + catch(const uno::Exception&) + { + DBG_UNHANDLED_EXCEPTION("unotools.config"); + } +} + +void DeleteItem(EHistoryType eHistory, const OUString& sURL) +{ + try + { + uno::Reference<container::XNameAccess> xCfg = GetConfig(); + uno::Reference<container::XNameAccess> xListAccess(GetListAccess(xCfg, eHistory)); + + uno::Reference<container::XNameContainer> xItemList; + uno::Reference<container::XNameContainer> xOrderList; + xListAccess->getByName(s_sItemList) >>= xItemList; + xListAccess->getByName(s_sOrderList) >>= xOrderList; + sal_Int32 nLength = xOrderList->getElementNames().getLength(); + + // if it does not exist, nothing to do + if (!xItemList->hasByName(sURL)) + return; + + // it's the last one, just clear the lists + if (nLength == 1) + { + Clear(eHistory); + return; + } + + // find it in the OrderList + sal_Int32 nFromWhere = 0; + for (; nFromWhere < nLength - 1; ++nFromWhere) + { + uno::Reference<beans::XPropertySet> xSet; + OUString aItem; + xOrderList->getByName(OUString::number(nFromWhere)) >>= xSet; + xSet->getPropertyValue(s_sHistoryItemRef) >>= aItem; + + if (aItem == sURL) + break; + } + + // and shift the rest of the items in OrderList accordingly + for (sal_Int32 i = nFromWhere; i < nLength - 1; ++i) + { + uno::Reference<beans::XPropertySet> xPrevSet; + uno::Reference<beans::XPropertySet> xNextSet; + xOrderList->getByName(OUString::number(i)) >>= xPrevSet; + xOrderList->getByName(OUString::number(i + 1)) >>= xNextSet; + + OUString sTemp; + xNextSet->getPropertyValue(s_sHistoryItemRef) >>= sTemp; + xPrevSet->setPropertyValue(s_sHistoryItemRef, uno::Any(sTemp)); + } + xOrderList->removeByName(OUString::number(nLength - 1)); + + // and finally remove it from the ItemList + xItemList->removeByName(sURL); + + ::comphelper::ConfigurationHelper::flush(xCfg); + } + catch (const uno::Exception&) + { + DBG_UNHANDLED_EXCEPTION("unotools.config"); + } +} + +} // namespace + + +static uno::Reference<container::XNameAccess> GetConfig() +{ + return uno::Reference<container::XNameAccess>( + ::comphelper::ConfigurationHelper::openConfig( + ::comphelper::getProcessComponentContext(), + "org.openoffice.Office.Histories/Histories", + ::comphelper::EConfigurationModes::Standard), + uno::UNO_QUERY_THROW); +} + +static uno::Reference<container::XNameAccess> GetCommonXCU() +{ + return uno::Reference<container::XNameAccess>( + ::comphelper::ConfigurationHelper::openConfig( + ::comphelper::getProcessComponentContext(), + "org.openoffice.Office.Common/History", + ::comphelper::EConfigurationModes::Standard), + uno::UNO_QUERY_THROW); +} + +static uno::Reference<container::XNameAccess> GetListAccess( + const uno::Reference<container::XNameAccess>& xCfg, + EHistoryType eHistory) +{ + uno::Reference<container::XNameAccess> xListAccess; + switch (eHistory) + { + case EHistoryType::PickList: + xCfg->getByName("PickList") >>= xListAccess; + break; + + case EHistoryType::HelpBookmarks: + xCfg->getByName("HelpBookmarks") >>= xListAccess; + break; + } + return xListAccess; +} + +static void TruncateList( + const uno::Reference<container::XNameAccess>& xCfg, + const uno::Reference<container::XNameAccess>& xList, + sal_uInt32 nSize) +{ + uno::Reference<container::XNameContainer> xItemList; + uno::Reference<container::XNameContainer> xOrderList; + xList->getByName(s_sOrderList) >>= xOrderList; + xList->getByName(s_sItemList) >>= xItemList; + + const sal_uInt32 nLength = xOrderList->getElementNames().getLength(); + if (nSize >= nLength) + return; + + for (sal_uInt32 i=nLength-1; i>=nSize; --i) + { + uno::Reference<beans::XPropertySet> xSet; + OUString sTmp; + const OUString sRemove = OUString::number(i); + xOrderList->getByName(sRemove) >>= xSet; + xSet->getPropertyValue(s_sHistoryItemRef) >>= sTmp; + xItemList->removeByName(sTmp); + xOrderList->removeByName(sRemove); + } + + ::comphelper::ConfigurationHelper::flush(xCfg); +} + + + +static sal_uInt32 GetCapacity(const uno::Reference<container::XNameAccess>& xCommonXCU, EHistoryType eHistory) +{ + uno::Reference<beans::XPropertySet> xListAccess(xCommonXCU, uno::UNO_QUERY_THROW); + + sal_uInt32 nSize = 0; + + switch (eHistory) + { + case EHistoryType::PickList: + xListAccess->getPropertyValue("PickListSize") >>= nSize; + break; + + case EHistoryType::HelpBookmarks: + xListAccess->getPropertyValue("HelpBookmarkSize") >>= nSize; + break; + } + + return nSize; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/itemholder1.cxx b/unotools/source/config/itemholder1.cxx new file mode 100644 index 000000000..88ab89449 --- /dev/null +++ b/unotools/source/config/itemholder1.cxx @@ -0,0 +1,150 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * 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/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include "itemholder1.hxx" + +#include <comphelper/processfactory.hxx> +#include <com/sun/star/lang/XComponent.hpp> +#include <com/sun/star/configuration/theDefaultProvider.hpp> + +#include <unotools/useroptions.hxx> +#include <unotools/cmdoptions.hxx> +#include <unotools/compatibility.hxx> +#include <unotools/lingucfg.hxx> +#include <unotools/moduleoptions.hxx> +#include <unotools/pathoptions.hxx> +#include <unotools/options.hxx> +#include <unotools/syslocaleoptions.hxx> +#include <rtl/ref.hxx> +#include <osl/diagnose.h> +#include <tools/diagnose_ex.h> + +ItemHolder1::ItemHolder1() +{ + try + { + css::uno::Reference< css::uno::XComponentContext > xContext = ::comphelper::getProcessComponentContext(); + css::uno::Reference< css::lang::XComponent > xCfg( + css::configuration::theDefaultProvider::get( xContext ), + css::uno::UNO_QUERY_THROW ); + xCfg->addEventListener(static_cast< css::lang::XEventListener* >(this)); + } +#ifdef DBG_UTIL + catch(const css::uno::Exception&) + { + static bool bMessage = true; + if(bMessage) + { + bMessage = false; + TOOLS_WARN_EXCEPTION( "unotools", "CreateInstance with arguments"); + } + } +#else + catch(css::uno::Exception&){} +#endif +} + +ItemHolder1::~ItemHolder1() +{ + impl_releaseAllItems(); +} + +void ItemHolder1::holdConfigItem(EItem eItem) +{ + static rtl::Reference<ItemHolder1> pHolder = new ItemHolder1(); + pHolder->impl_addItem(eItem); +} + +void SAL_CALL ItemHolder1::disposing(const css::lang::EventObject&) +{ + css::uno::Reference< css::uno::XInterface > xSelfHold(static_cast< css::lang::XEventListener* >(this), css::uno::UNO_QUERY); + impl_releaseAllItems(); +} + +void ItemHolder1::impl_addItem(EItem eItem) +{ + std::scoped_lock aLock(m_aLock); + + for ( auto const & rInfo : m_lItems ) + { + if (rInfo.eItem == eItem) + return; + } + + TItemInfo aNewItem; + aNewItem.eItem = eItem; + impl_newItem(aNewItem); + if (aNewItem.pItem) + m_lItems.emplace_back(std::move(aNewItem)); +} + +void ItemHolder1::impl_releaseAllItems() +{ + std::vector< TItemInfo > items; + { + std::scoped_lock aLock(m_aLock); + items.swap(m_lItems); + } + + // items will be freed when the block exits +} + +void ItemHolder1::impl_newItem(TItemInfo& rItem) +{ + switch(rItem.eItem) + { + case EItem::CmdOptions : + rItem.pItem.reset( new SvtCommandOptions() ); + break; + + case EItem::Compatibility : + rItem.pItem.reset( new SvtCompatibilityOptions() ); + break; + + case EItem::EventConfig : + //rItem.pItem.reset( new GlobalEventConfig() ); + break; + + case EItem::LinguConfig : + rItem.pItem.reset( new SvtLinguConfig() ); + break; + + case EItem::ModuleOptions : + rItem.pItem.reset( new SvtModuleOptions() ); + break; + + case EItem::PathOptions : + rItem.pItem.reset( new SvtPathOptions() ); + break; + + case EItem::UserOptions : + rItem.pItem.reset( new SvtUserOptions() ); + break; + + case EItem::SysLocaleOptions : + rItem.pItem.reset( new SvtSysLocaleOptions() ); + break; + + default: + OSL_FAIL( "unknown item type" ); + break; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/itemholder1.hxx b/unotools/source/config/itemholder1.hxx new file mode 100644 index 000000000..8e61bb551 --- /dev/null +++ b/unotools/source/config/itemholder1.hxx @@ -0,0 +1,60 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * 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/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#pragma once + +#include <unotools/itemholderbase.hxx> +#include <cppuhelper/implbase.hxx> +#include <com/sun/star/lang/XEventListener.hpp> +#include <mutex> + +class ItemHolder1 : public ::cppu::WeakImplHelper< css::lang::XEventListener > +{ + + // member + private: + + std::mutex m_aLock; + std::vector<TItemInfo> m_lItems; + + // c++ interface + public: + + ItemHolder1(); + virtual ~ItemHolder1() override; + static void holdConfigItem(EItem eItem); + + // uno interface + public: + + virtual void SAL_CALL disposing(const css::lang::EventObject& aEvent) override; + + // helper + private: + + void impl_addItem(EItem eItem); + void impl_releaseAllItems(); + static void impl_newItem(TItemInfo& rItem); +}; + +// namespaces + +#undef css + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/lingucfg.cxx b/unotools/source/config/lingucfg.cxx new file mode 100644 index 000000000..a38fb51b6 --- /dev/null +++ b/unotools/source/config/lingucfg.cxx @@ -0,0 +1,1180 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * 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/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <sal/config.h> + +#include <com/sun/star/lang/Locale.hpp> +#include <com/sun/star/lang/XMultiServiceFactory.hpp> +#include <com/sun/star/beans/PropertyValue.hpp> +#include <com/sun/star/configuration/theDefaultProvider.hpp> +#include <com/sun/star/container/XNameAccess.hpp> +#include <com/sun/star/util/XChangesBatch.hpp> +#include <sal/log.hxx> +#include <tools/diagnose_ex.h> +#include <i18nlangtag/mslangid.hxx> +#include <i18nlangtag/languagetag.hxx> +#include <tools/debug.hxx> +#include <unotools/configitem.hxx> +#include <unotools/lingucfg.hxx> +#include <unotools/linguprops.hxx> +#include <sal/macros.h> +#include <comphelper/getexpandeduri.hxx> +#include <comphelper/processfactory.hxx> +#include <o3tl/string_view.hxx> +#include <mutex> + +#include "itemholder1.hxx" + +using namespace com::sun::star; + +constexpr OUStringLiteral FILE_PROTOCOL = u"file:///"; + +namespace +{ + std::mutex& theSvtLinguConfigItemMutex() + { + static std::mutex SINGLETON; + return SINGLETON; + } +} + +static bool lcl_SetLocale( LanguageType &rLanguage, const uno::Any &rVal ) +{ + bool bSucc = false; + + lang::Locale aNew; + if (rVal >>= aNew) // conversion successful? + { + LanguageType nNew = LanguageTag::convertToLanguageType( aNew, false); + if (nNew != rLanguage) + { + rLanguage = nNew; + bSucc = true; + } + } + return bSucc; +} + +static OUString lcl_LanguageToCfgLocaleStr( LanguageType nLanguage ) +{ + OUString aRes; + if (LANGUAGE_SYSTEM != nLanguage) + aRes = LanguageTag::convertToBcp47( nLanguage ); + return aRes; +} + +static LanguageType lcl_CfgAnyToLanguage( const uno::Any &rVal ) +{ + OUString aTmp; + rVal >>= aTmp; + return (aTmp.isEmpty()) ? LANGUAGE_SYSTEM : LanguageTag::convertToLanguageTypeWithFallback( aTmp ); +} + +SvtLinguOptions::SvtLinguOptions() + : bROActiveDics(false) + , bROActiveConvDics(false) + , nHyphMinLeading(2) + , nHyphMinTrailing(2) + , nHyphMinWordLength(0) + , bROHyphMinLeading(false) + , bROHyphMinTrailing(false) + , bROHyphMinWordLength(false) + , nDefaultLanguage(LANGUAGE_NONE) + , nDefaultLanguage_CJK(LANGUAGE_NONE) + , nDefaultLanguage_CTL(LANGUAGE_NONE) + , bRODefaultLanguage(false) + , bRODefaultLanguage_CJK(false) + , bRODefaultLanguage_CTL(false) + , bIsSpellSpecial(true) + , bIsSpellAuto(false) + , bIsSpellReverse(false) + , bROIsSpellSpecial(false) + , bROIsSpellAuto(false) + , bROIsSpellReverse(false) + , bIsHyphSpecial(true) + , bIsHyphAuto(false) + , bROIsHyphSpecial(false) + , bROIsHyphAuto(false) + , bIsUseDictionaryList(true) + , bIsIgnoreControlCharacters(true) + , bROIsUseDictionaryList(false) + , bROIsIgnoreControlCharacters(false) + , bIsSpellWithDigits(false) + , bIsSpellUpperCase(false) + , bIsSpellCapitalization(true) + , bROIsSpellWithDigits(false) + , bROIsSpellUpperCase(false) + , bROIsSpellCapitalization(false) + , bIsIgnorePostPositionalWord(true) + , bIsAutoCloseDialog(false) + , bIsShowEntriesRecentlyUsedFirst(false) + , bIsAutoReplaceUniqueEntries(false) + , bIsDirectionToSimplified(true) + , bIsUseCharacterVariants(false) + , bIsTranslateCommonTerms(false) + , bIsReverseMapping(false) + , bROIsIgnorePostPositionalWord(false) + , bROIsAutoCloseDialog(false) + , bROIsShowEntriesRecentlyUsedFirst(false) + , bROIsAutoReplaceUniqueEntries(false) + , bROIsDirectionToSimplified(false) + , bROIsUseCharacterVariants(false) + , bROIsTranslateCommonTerms(false) + , bROIsReverseMapping(false) + , nDataFilesChangedCheckValue(0) + , bRODataFilesChangedCheckValue(false) + , bIsGrammarAuto(false) + , bIsGrammarInteractive(false) + , bROIsGrammarAuto(false) + , bROIsGrammarInteractive(false) +{ +} + +class SvtLinguConfigItem : public utl::ConfigItem +{ + SvtLinguOptions aOpt; + + static bool GetHdlByName( sal_Int32 &rnHdl, std::u16string_view rPropertyName, bool bFullPropName = false ); + static uno::Sequence< OUString > GetPropertyNames(); + void LoadOptions( const uno::Sequence< OUString > &rProperyNames ); + bool SaveOptions( const uno::Sequence< OUString > &rProperyNames ); + + SvtLinguConfigItem(const SvtLinguConfigItem&) = delete; + SvtLinguConfigItem& operator=(const SvtLinguConfigItem&) = delete; + virtual void ImplCommit() override; + +public: + SvtLinguConfigItem(); + + // utl::ConfigItem + virtual void Notify( const css::uno::Sequence< OUString > &rPropertyNames ) override; + + // make some protected functions of utl::ConfigItem public + using utl::ConfigItem::GetNodeNames; + using utl::ConfigItem::GetProperties; + //using utl::ConfigItem::PutProperties; + //using utl::ConfigItem::SetSetProperties; + using utl::ConfigItem::ReplaceSetProperties; + //using utl::ConfigItem::GetReadOnlyStates; + + css::uno::Any + GetProperty( std::u16string_view rPropertyName ) const; + css::uno::Any + GetProperty( sal_Int32 nPropertyHandle ) const; + + bool SetProperty( std::u16string_view rPropertyName, + const css::uno::Any &rValue ); + bool SetProperty( sal_Int32 nPropertyHandle, + const css::uno::Any &rValue ); + + void GetOptions( SvtLinguOptions& ) const; + + bool IsReadOnly( std::u16string_view rPropertyName ) const; + bool IsReadOnly( sal_Int32 nPropertyHandle ) const; +}; + +SvtLinguConfigItem::SvtLinguConfigItem() : + utl::ConfigItem( "Office.Linguistic" ) +{ + const uno::Sequence< OUString > &rPropertyNames = GetPropertyNames(); + LoadOptions( rPropertyNames ); + ClearModified(); + + // request notify events when properties change + EnableNotification( rPropertyNames ); +} + +void SvtLinguConfigItem::Notify( const uno::Sequence< OUString > &rPropertyNames ) +{ + { + std::unique_lock aGuard(theSvtLinguConfigItemMutex()); + LoadOptions( rPropertyNames ); + } + NotifyListeners(ConfigurationHints::NONE); +} + +void SvtLinguConfigItem::ImplCommit() +{ + SaveOptions( GetPropertyNames() ); +} + +namespace { + +struct NamesToHdl +{ + const char *pFullPropName; // full qualified name as used in configuration + OUString aPropName; // property name only (atom) of above + sal_Int32 nHdl; // numeric handle representing the property +}; + +} + +NamesToHdl const aNamesToHdl[] = +{ +{/* 0 */ "General/DefaultLocale", UPN_DEFAULT_LOCALE, UPH_DEFAULT_LOCALE}, +{/* 1 */ "General/DictionaryList/ActiveDictionaries", UPN_ACTIVE_DICTIONARIES, UPH_ACTIVE_DICTIONARIES}, +{/* 2 */ "General/DictionaryList/IsUseDictionaryList", UPN_IS_USE_DICTIONARY_LIST, UPH_IS_USE_DICTIONARY_LIST}, +{/* 3 */ "General/IsIgnoreControlCharacters", UPN_IS_IGNORE_CONTROL_CHARACTERS, UPH_IS_IGNORE_CONTROL_CHARACTERS}, +{/* 5 */ "General/DefaultLocale_CJK", UPN_DEFAULT_LOCALE_CJK, UPH_DEFAULT_LOCALE_CJK}, +{/* 6 */ "General/DefaultLocale_CTL", UPN_DEFAULT_LOCALE_CTL, UPH_DEFAULT_LOCALE_CTL}, + +{/* 7 */ "SpellChecking/IsSpellUpperCase", UPN_IS_SPELL_UPPER_CASE, UPH_IS_SPELL_UPPER_CASE}, +{/* 8 */ "SpellChecking/IsSpellWithDigits", UPN_IS_SPELL_WITH_DIGITS, UPH_IS_SPELL_WITH_DIGITS}, +{/* 9 */ "SpellChecking/IsSpellCapitalization", UPN_IS_SPELL_CAPITALIZATION, UPH_IS_SPELL_CAPITALIZATION}, +{/* 10 */ "SpellChecking/IsSpellAuto", UPN_IS_SPELL_AUTO, UPH_IS_SPELL_AUTO}, +{/* 11 */ "SpellChecking/IsSpellSpecial", UPN_IS_SPELL_SPECIAL, UPH_IS_SPELL_SPECIAL}, +{/* 14 */ "SpellChecking/IsReverseDirection", UPN_IS_WRAP_REVERSE, UPH_IS_WRAP_REVERSE}, + +{/* 15 */ "Hyphenation/MinLeading", UPN_HYPH_MIN_LEADING, UPH_HYPH_MIN_LEADING}, +{/* 16 */ "Hyphenation/MinTrailing", UPN_HYPH_MIN_TRAILING, UPH_HYPH_MIN_TRAILING}, +{/* 17 */ "Hyphenation/MinWordLength", UPN_HYPH_MIN_WORD_LENGTH, UPH_HYPH_MIN_WORD_LENGTH}, +{/* 18 */ "Hyphenation/IsHyphSpecial", UPN_IS_HYPH_SPECIAL, UPH_IS_HYPH_SPECIAL}, +{/* 19 */ "Hyphenation/IsHyphAuto", UPN_IS_HYPH_AUTO, UPH_IS_HYPH_AUTO}, + +{/* 20 */ "TextConversion/ActiveConversionDictionaries", UPN_ACTIVE_CONVERSION_DICTIONARIES, UPH_ACTIVE_CONVERSION_DICTIONARIES}, +{/* 21 */ "TextConversion/IsIgnorePostPositionalWord", UPN_IS_IGNORE_POST_POSITIONAL_WORD, UPH_IS_IGNORE_POST_POSITIONAL_WORD}, +{/* 22 */ "TextConversion/IsAutoCloseDialog", UPN_IS_AUTO_CLOSE_DIALOG, UPH_IS_AUTO_CLOSE_DIALOG}, +{/* 23 */ "TextConversion/IsShowEntriesRecentlyUsedFirst", UPN_IS_SHOW_ENTRIES_RECENTLY_USED_FIRST, UPH_IS_SHOW_ENTRIES_RECENTLY_USED_FIRST}, +{/* 24 */ "TextConversion/IsAutoReplaceUniqueEntries", UPN_IS_AUTO_REPLACE_UNIQUE_ENTRIES, UPH_IS_AUTO_REPLACE_UNIQUE_ENTRIES}, +{/* 25 */ "TextConversion/IsDirectionToSimplified", UPN_IS_DIRECTION_TO_SIMPLIFIED, UPH_IS_DIRECTION_TO_SIMPLIFIED}, +{/* 26 */ "TextConversion/IsUseCharacterVariants", UPN_IS_USE_CHARACTER_VARIANTS, UPH_IS_USE_CHARACTER_VARIANTS}, +{/* 27 */ "TextConversion/IsTranslateCommonTerms", UPN_IS_TRANSLATE_COMMON_TERMS, UPH_IS_TRANSLATE_COMMON_TERMS}, +{/* 28 */ "TextConversion/IsReverseMapping", UPN_IS_REVERSE_MAPPING, UPH_IS_REVERSE_MAPPING}, + +{/* 29 */ "ServiceManager/DataFilesChangedCheckValue", UPN_DATA_FILES_CHANGED_CHECK_VALUE, UPH_DATA_FILES_CHANGED_CHECK_VALUE}, + +{/* 30 */ "GrammarChecking/IsAutoCheck", UPN_IS_GRAMMAR_AUTO, UPH_IS_GRAMMAR_AUTO}, +{/* 31 */ "GrammarChecking/IsInteractiveCheck", UPN_IS_GRAMMAR_INTERACTIVE, UPH_IS_GRAMMAR_INTERACTIVE}, + + /* similar to entry 0 (thus no own configuration entry) but with different property name and type */ +{ nullptr, UPN_DEFAULT_LANGUAGE, UPH_DEFAULT_LANGUAGE}, + +{ nullptr, "", -1} +}; + +uno::Sequence< OUString > SvtLinguConfigItem::GetPropertyNames() +{ + uno::Sequence< OUString > aNames; + + sal_Int32 nMax = SAL_N_ELEMENTS(aNamesToHdl); + + aNames.realloc( nMax ); + OUString *pNames = aNames.getArray(); + sal_Int32 nIdx = 0; + for (sal_Int32 i = 0; i < nMax; ++i) + { + const char *pFullPropName = aNamesToHdl[i].pFullPropName; + if (pFullPropName) + pNames[ nIdx++ ] = OUString::createFromAscii( pFullPropName ); + } + aNames.realloc( nIdx ); + + return aNames; +} + +bool SvtLinguConfigItem::GetHdlByName( + sal_Int32 &rnHdl, + std::u16string_view rPropertyName, + bool bFullPropName ) +{ + NamesToHdl const *pEntry = &aNamesToHdl[0]; + + if (bFullPropName) + { + while (pEntry && pEntry->pFullPropName != nullptr) + { + if (o3tl::equalsAscii(rPropertyName, pEntry->pFullPropName )) + { + rnHdl = pEntry->nHdl; + break; + } + ++pEntry; + } + return pEntry && pEntry->pFullPropName != nullptr; + } + else + { + while (pEntry && pEntry->pFullPropName != nullptr) + { + if (rPropertyName == pEntry->aPropName ) + { + rnHdl = pEntry->nHdl; + break; + } + ++pEntry; + } + return pEntry && pEntry->pFullPropName != nullptr; + } +} + +uno::Any SvtLinguConfigItem::GetProperty( std::u16string_view rPropertyName ) const +{ + sal_Int32 nHdl; + return GetHdlByName( nHdl, rPropertyName ) ? GetProperty( nHdl ) : uno::Any(); +} + +uno::Any SvtLinguConfigItem::GetProperty( sal_Int32 nPropertyHandle ) const +{ + std::unique_lock aGuard(theSvtLinguConfigItemMutex()); + + uno::Any aRes; + + const sal_Int16 *pnVal = nullptr; + const LanguageType *plVal = nullptr; + const bool *pbVal = nullptr; + const sal_Int32 *pnInt32Val = nullptr; + + const SvtLinguOptions &rOpt = const_cast< SvtLinguConfigItem * >(this)->aOpt; + switch (nPropertyHandle) + { + case UPH_IS_USE_DICTIONARY_LIST : pbVal = &rOpt.bIsUseDictionaryList; break; + case UPH_IS_IGNORE_CONTROL_CHARACTERS : pbVal = &rOpt.bIsIgnoreControlCharacters; break; + case UPH_IS_HYPH_AUTO : pbVal = &rOpt.bIsHyphAuto; break; + case UPH_IS_HYPH_SPECIAL : pbVal = &rOpt.bIsHyphSpecial; break; + case UPH_IS_SPELL_AUTO : pbVal = &rOpt.bIsSpellAuto; break; + case UPH_IS_SPELL_SPECIAL : pbVal = &rOpt.bIsSpellSpecial; break; + case UPH_IS_WRAP_REVERSE : pbVal = &rOpt.bIsSpellReverse; break; + case UPH_DEFAULT_LANGUAGE : plVal = &rOpt.nDefaultLanguage; break; + case UPH_IS_SPELL_CAPITALIZATION : pbVal = &rOpt.bIsSpellCapitalization; break; + case UPH_IS_SPELL_WITH_DIGITS : pbVal = &rOpt.bIsSpellWithDigits; break; + case UPH_IS_SPELL_UPPER_CASE : pbVal = &rOpt.bIsSpellUpperCase; break; + case UPH_HYPH_MIN_LEADING : pnVal = &rOpt.nHyphMinLeading; break; + case UPH_HYPH_MIN_TRAILING : pnVal = &rOpt.nHyphMinTrailing; break; + case UPH_HYPH_MIN_WORD_LENGTH : pnVal = &rOpt.nHyphMinWordLength; break; + case UPH_ACTIVE_DICTIONARIES : + { + aRes <<= rOpt.aActiveDics; + break; + } + case UPH_ACTIVE_CONVERSION_DICTIONARIES : + { + aRes <<= rOpt.aActiveConvDics; + break; + } + case UPH_DEFAULT_LOCALE : + { + aRes <<= LanguageTag::convertToLocale( rOpt.nDefaultLanguage, false); + break; + } + case UPH_DEFAULT_LOCALE_CJK : + { + aRes <<= LanguageTag::convertToLocale( rOpt.nDefaultLanguage_CJK, false); + break; + } + case UPH_DEFAULT_LOCALE_CTL : + { + aRes <<= LanguageTag::convertToLocale( rOpt.nDefaultLanguage_CTL, false); + break; + } + case UPH_IS_IGNORE_POST_POSITIONAL_WORD : pbVal = &rOpt.bIsIgnorePostPositionalWord; break; + case UPH_IS_AUTO_CLOSE_DIALOG : pbVal = &rOpt.bIsAutoCloseDialog; break; + case UPH_IS_SHOW_ENTRIES_RECENTLY_USED_FIRST : pbVal = &rOpt.bIsShowEntriesRecentlyUsedFirst; break; + case UPH_IS_AUTO_REPLACE_UNIQUE_ENTRIES : pbVal = &rOpt.bIsAutoReplaceUniqueEntries; break; + + case UPH_IS_DIRECTION_TO_SIMPLIFIED: pbVal = &rOpt.bIsDirectionToSimplified; break; + case UPH_IS_USE_CHARACTER_VARIANTS : pbVal = &rOpt.bIsUseCharacterVariants; break; + case UPH_IS_TRANSLATE_COMMON_TERMS : pbVal = &rOpt.bIsTranslateCommonTerms; break; + case UPH_IS_REVERSE_MAPPING : pbVal = &rOpt.bIsReverseMapping; break; + + case UPH_DATA_FILES_CHANGED_CHECK_VALUE : pnInt32Val = &rOpt.nDataFilesChangedCheckValue; break; + case UPH_IS_GRAMMAR_AUTO: pbVal = &rOpt.bIsGrammarAuto; break; + case UPH_IS_GRAMMAR_INTERACTIVE: pbVal = &rOpt.bIsGrammarInteractive; break; + default : + SAL_WARN( "unotools.config", "unexpected property handle" ); + } + + if (pbVal) + aRes <<= *pbVal; + else if (pnVal) + aRes <<= *pnVal; + else if (plVal) + aRes <<= static_cast<sal_Int16>(static_cast<sal_uInt16>(*plVal)); + else if (pnInt32Val) + aRes <<= *pnInt32Val; + + return aRes; +} + +bool SvtLinguConfigItem::SetProperty( std::u16string_view rPropertyName, const uno::Any &rValue ) +{ + bool bSucc = false; + sal_Int32 nHdl; + if (GetHdlByName( nHdl, rPropertyName )) + bSucc = SetProperty( nHdl, rValue ); + return bSucc; +} + +bool SvtLinguConfigItem::SetProperty( sal_Int32 nPropertyHandle, const uno::Any &rValue ) +{ + std::unique_lock aGuard(theSvtLinguConfigItemMutex()); + + bool bSucc = false; + if (!rValue.hasValue()) + return bSucc; + + bool bMod = false; + + sal_Int16 *pnVal = nullptr; + LanguageType *plVal = nullptr; + bool *pbVal = nullptr; + sal_Int32 *pnInt32Val = nullptr; + + SvtLinguOptions &rOpt = aOpt; + switch (nPropertyHandle) + { + case UPH_IS_USE_DICTIONARY_LIST : pbVal = &rOpt.bIsUseDictionaryList; break; + case UPH_IS_IGNORE_CONTROL_CHARACTERS : pbVal = &rOpt.bIsIgnoreControlCharacters; break; + case UPH_IS_HYPH_AUTO : pbVal = &rOpt.bIsHyphAuto; break; + case UPH_IS_HYPH_SPECIAL : pbVal = &rOpt.bIsHyphSpecial; break; + case UPH_IS_SPELL_AUTO : pbVal = &rOpt.bIsSpellAuto; break; + case UPH_IS_SPELL_SPECIAL : pbVal = &rOpt.bIsSpellSpecial; break; + case UPH_IS_WRAP_REVERSE : pbVal = &rOpt.bIsSpellReverse; break; + case UPH_DEFAULT_LANGUAGE : plVal = &rOpt.nDefaultLanguage; break; + case UPH_IS_SPELL_CAPITALIZATION : pbVal = &rOpt.bIsSpellCapitalization; break; + case UPH_IS_SPELL_WITH_DIGITS : pbVal = &rOpt.bIsSpellWithDigits; break; + case UPH_IS_SPELL_UPPER_CASE : pbVal = &rOpt.bIsSpellUpperCase; break; + case UPH_HYPH_MIN_LEADING : pnVal = &rOpt.nHyphMinLeading; break; + case UPH_HYPH_MIN_TRAILING : pnVal = &rOpt.nHyphMinTrailing; break; + case UPH_HYPH_MIN_WORD_LENGTH : pnVal = &rOpt.nHyphMinWordLength; break; + case UPH_ACTIVE_DICTIONARIES : + { + rValue >>= rOpt.aActiveDics; + bMod = true; + break; + } + case UPH_ACTIVE_CONVERSION_DICTIONARIES : + { + rValue >>= rOpt.aActiveConvDics; + bMod = true; + break; + } + case UPH_DEFAULT_LOCALE : + { + bSucc = lcl_SetLocale( rOpt.nDefaultLanguage, rValue ); + bMod = bSucc; + break; + } + case UPH_DEFAULT_LOCALE_CJK : + { + bSucc = lcl_SetLocale( rOpt.nDefaultLanguage_CJK, rValue ); + bMod = bSucc; + break; + } + case UPH_DEFAULT_LOCALE_CTL : + { + bSucc = lcl_SetLocale( rOpt.nDefaultLanguage_CTL, rValue ); + bMod = bSucc; + break; + } + case UPH_IS_IGNORE_POST_POSITIONAL_WORD : pbVal = &rOpt.bIsIgnorePostPositionalWord; break; + case UPH_IS_AUTO_CLOSE_DIALOG : pbVal = &rOpt.bIsAutoCloseDialog; break; + case UPH_IS_SHOW_ENTRIES_RECENTLY_USED_FIRST : pbVal = &rOpt.bIsShowEntriesRecentlyUsedFirst; break; + case UPH_IS_AUTO_REPLACE_UNIQUE_ENTRIES : pbVal = &rOpt.bIsAutoReplaceUniqueEntries; break; + + case UPH_IS_DIRECTION_TO_SIMPLIFIED : pbVal = &rOpt.bIsDirectionToSimplified; break; + case UPH_IS_USE_CHARACTER_VARIANTS : pbVal = &rOpt.bIsUseCharacterVariants; break; + case UPH_IS_TRANSLATE_COMMON_TERMS : pbVal = &rOpt.bIsTranslateCommonTerms; break; + case UPH_IS_REVERSE_MAPPING : pbVal = &rOpt.bIsReverseMapping; break; + + case UPH_DATA_FILES_CHANGED_CHECK_VALUE : pnInt32Val = &rOpt.nDataFilesChangedCheckValue; break; + case UPH_IS_GRAMMAR_AUTO: pbVal = &rOpt.bIsGrammarAuto; break; + case UPH_IS_GRAMMAR_INTERACTIVE: pbVal = &rOpt.bIsGrammarInteractive; break; + default : + SAL_WARN( "unotools.config", "unexpected property handle" ); + } + + if (pbVal) + { + bool bNew = bool(); + if (rValue >>= bNew) + { + if (bNew != *pbVal) + { + *pbVal = bNew; + bMod = true; + } + bSucc = true; + } + } + else if (pnVal) + { + sal_Int16 nNew = sal_Int16(); + if (rValue >>= nNew) + { + if (nNew != *pnVal) + { + *pnVal = nNew; + bMod = true; + } + bSucc = true; + } + } + else if (plVal) + { + sal_Int16 nNew = sal_Int16(); + if (rValue >>= nNew) + { + if (nNew != static_cast<sal_uInt16>(*plVal)) + { + *plVal = LanguageType(static_cast<sal_uInt16>(nNew)); + bMod = true; + } + bSucc = true; + } + } + else if (pnInt32Val) + { + sal_Int32 nNew = sal_Int32(); + if (rValue >>= nNew) + { + if (nNew != *pnInt32Val) + { + *pnInt32Val = nNew; + bMod = true; + } + bSucc = true; + } + } + + if (bMod) + SetModified(); + + NotifyListeners(ConfigurationHints::NONE); + return bSucc; +} + +void SvtLinguConfigItem::GetOptions(SvtLinguOptions &rOptions) const +{ + std::unique_lock aGuard(theSvtLinguConfigItemMutex()); + rOptions = aOpt; +} + +void SvtLinguConfigItem::LoadOptions( const uno::Sequence< OUString > &rProperyNames ) +{ + bool bRes = false; + + const OUString *pProperyNames = rProperyNames.getConstArray(); + sal_Int32 nProps = rProperyNames.getLength(); + + const uno::Sequence< uno::Any > aValues = GetProperties( rProperyNames ); + const uno::Sequence< sal_Bool > aROStates = GetReadOnlyStates( rProperyNames ); + + if (nProps && aValues.getLength() == nProps && aROStates.getLength() == nProps) + { + SvtLinguOptions &rOpt = aOpt; + + const uno::Any *pValue = aValues.getConstArray(); + const sal_Bool *pROStates = aROStates.getConstArray(); + for (sal_Int32 i = 0; i < nProps; ++i) + { + const uno::Any &rVal = pValue[i]; + sal_Int32 nPropertyHandle(0); + GetHdlByName( nPropertyHandle, pProperyNames[i], true ); + switch ( nPropertyHandle ) + { + case UPH_DEFAULT_LOCALE : + { rOpt.bRODefaultLanguage = pROStates[i]; rOpt.nDefaultLanguage = lcl_CfgAnyToLanguage( rVal ); } break; + case UPH_ACTIVE_DICTIONARIES : + { rOpt.bROActiveDics = pROStates[i]; rVal >>= rOpt.aActiveDics; } break; + case UPH_IS_USE_DICTIONARY_LIST : + { rOpt.bROIsUseDictionaryList = pROStates[i]; rVal >>= rOpt.bIsUseDictionaryList; } break; + case UPH_IS_IGNORE_CONTROL_CHARACTERS : + { rOpt.bROIsIgnoreControlCharacters = pROStates[i]; rVal >>= rOpt.bIsIgnoreControlCharacters; } break; + case UPH_DEFAULT_LOCALE_CJK : + { rOpt.bRODefaultLanguage_CJK = pROStates[i]; rOpt.nDefaultLanguage_CJK = lcl_CfgAnyToLanguage( rVal ); } break; + case UPH_DEFAULT_LOCALE_CTL : + { rOpt.bRODefaultLanguage_CTL = pROStates[i]; rOpt.nDefaultLanguage_CTL = lcl_CfgAnyToLanguage( rVal ); } break; + + case UPH_IS_SPELL_UPPER_CASE : + { rOpt.bROIsSpellUpperCase = pROStates[i]; rVal >>= rOpt.bIsSpellUpperCase; } break; + case UPH_IS_SPELL_WITH_DIGITS : + { rOpt.bROIsSpellWithDigits = pROStates[i]; rVal >>= rOpt.bIsSpellWithDigits; } break; + case UPH_IS_SPELL_CAPITALIZATION : + { rOpt.bROIsSpellCapitalization = pROStates[i]; rVal >>= rOpt.bIsSpellCapitalization; } break; + case UPH_IS_SPELL_AUTO : + { rOpt.bROIsSpellAuto = pROStates[i]; rVal >>= rOpt.bIsSpellAuto; } break; + case UPH_IS_SPELL_SPECIAL : + { rOpt.bROIsSpellSpecial = pROStates[i]; rVal >>= rOpt.bIsSpellSpecial; } break; + case UPH_IS_WRAP_REVERSE : + { rOpt.bROIsSpellReverse = pROStates[i]; rVal >>= rOpt.bIsSpellReverse; } break; + + case UPH_HYPH_MIN_LEADING : + { rOpt.bROHyphMinLeading = pROStates[i]; rVal >>= rOpt.nHyphMinLeading; } break; + case UPH_HYPH_MIN_TRAILING : + { rOpt.bROHyphMinTrailing = pROStates[i]; rVal >>= rOpt.nHyphMinTrailing; } break; + case UPH_HYPH_MIN_WORD_LENGTH : + { rOpt.bROHyphMinWordLength = pROStates[i]; rVal >>= rOpt.nHyphMinWordLength; } break; + case UPH_IS_HYPH_SPECIAL : + { rOpt.bROIsHyphSpecial = pROStates[i]; rVal >>= rOpt.bIsHyphSpecial; } break; + case UPH_IS_HYPH_AUTO : + { rOpt.bROIsHyphAuto = pROStates[i]; rVal >>= rOpt.bIsHyphAuto; } break; + + case UPH_ACTIVE_CONVERSION_DICTIONARIES : { rOpt.bROActiveConvDics = pROStates[i]; rVal >>= rOpt.aActiveConvDics; } break; + + case UPH_IS_IGNORE_POST_POSITIONAL_WORD : + { rOpt.bROIsIgnorePostPositionalWord = pROStates[i]; rVal >>= rOpt.bIsIgnorePostPositionalWord; } break; + case UPH_IS_AUTO_CLOSE_DIALOG : + { rOpt.bROIsAutoCloseDialog = pROStates[i]; rVal >>= rOpt.bIsAutoCloseDialog; } break; + case UPH_IS_SHOW_ENTRIES_RECENTLY_USED_FIRST : + { rOpt.bROIsShowEntriesRecentlyUsedFirst = pROStates[i]; rVal >>= rOpt.bIsShowEntriesRecentlyUsedFirst; } break; + case UPH_IS_AUTO_REPLACE_UNIQUE_ENTRIES : + { rOpt.bROIsAutoReplaceUniqueEntries = pROStates[i]; rVal >>= rOpt.bIsAutoReplaceUniqueEntries; } break; + + case UPH_IS_DIRECTION_TO_SIMPLIFIED : + { + rOpt.bROIsDirectionToSimplified = pROStates[i]; + if( ! (rVal >>= rOpt.bIsDirectionToSimplified) ) + { + //default is locale dependent: + if (MsLangId::isTraditionalChinese(rOpt.nDefaultLanguage_CJK)) + { + rOpt.bIsDirectionToSimplified = false; + } + else + { + rOpt.bIsDirectionToSimplified = true; + } + } + } break; + case UPH_IS_USE_CHARACTER_VARIANTS : + { rOpt.bROIsUseCharacterVariants = pROStates[i]; rVal >>= rOpt.bIsUseCharacterVariants; } break; + case UPH_IS_TRANSLATE_COMMON_TERMS : + { rOpt.bROIsTranslateCommonTerms = pROStates[i]; rVal >>= rOpt.bIsTranslateCommonTerms; } break; + case UPH_IS_REVERSE_MAPPING : + { rOpt.bROIsReverseMapping = pROStates[i]; rVal >>= rOpt.bIsReverseMapping; } break; + + case UPH_DATA_FILES_CHANGED_CHECK_VALUE : + { rOpt.bRODataFilesChangedCheckValue = pROStates[i]; rVal >>= rOpt.nDataFilesChangedCheckValue; } break; + + case UPH_IS_GRAMMAR_AUTO: + { rOpt.bROIsGrammarAuto = pROStates[i]; rVal >>= rOpt.bIsGrammarAuto; } + break; + case UPH_IS_GRAMMAR_INTERACTIVE: + { rOpt.bROIsGrammarInteractive = pROStates[i]; rVal >>= rOpt.bIsGrammarInteractive; } + break; + + default: + SAL_WARN( "unotools.config", "unexpected case" ); + } + } + + bRes = true; + } + DBG_ASSERT( bRes, "LoadOptions failed" ); +} + +bool SvtLinguConfigItem::SaveOptions( const uno::Sequence< OUString > &rProperyNames ) +{ + if (!IsModified()) + return true; + + std::unique_lock aGuard(theSvtLinguConfigItemMutex()); + + bool bRet = false; + + sal_Int32 nProps = rProperyNames.getLength(); + uno::Sequence< uno::Any > aValues( nProps ); + uno::Any *pValue = aValues.getArray(); + + if (nProps && aValues.getLength() == nProps) + { + const SvtLinguOptions &rOpt = aOpt; + + OUString aTmp( lcl_LanguageToCfgLocaleStr( rOpt.nDefaultLanguage ) ); + *pValue++ <<= aTmp; // 0 + *pValue++ <<= rOpt.aActiveDics; // 1 + *pValue++ <<= rOpt.bIsUseDictionaryList; // 2 + *pValue++ <<= rOpt.bIsIgnoreControlCharacters; // 3 + aTmp = lcl_LanguageToCfgLocaleStr( rOpt.nDefaultLanguage_CJK ); + *pValue++ <<= aTmp; // 5 + aTmp = lcl_LanguageToCfgLocaleStr( rOpt.nDefaultLanguage_CTL ); + *pValue++ <<= aTmp; // 6 + + *pValue++ <<= rOpt.bIsSpellUpperCase; // 7 + *pValue++ <<= rOpt.bIsSpellWithDigits; // 8 + *pValue++ <<= rOpt.bIsSpellCapitalization; // 9 + *pValue++ <<= rOpt.bIsSpellAuto; // 10 + *pValue++ <<= rOpt.bIsSpellSpecial; // 11 + *pValue++ <<= rOpt.bIsSpellReverse; // 14 + + *pValue++ <<= rOpt.nHyphMinLeading; // 15 + *pValue++ <<= rOpt.nHyphMinTrailing; // 16 + *pValue++ <<= rOpt.nHyphMinWordLength; // 17 + *pValue++ <<= rOpt.bIsHyphSpecial; // 18 + *pValue++ <<= rOpt.bIsHyphAuto; // 19 + + *pValue++ <<= rOpt.aActiveConvDics; // 20 + + *pValue++ <<= rOpt.bIsIgnorePostPositionalWord; // 21 + *pValue++ <<= rOpt.bIsAutoCloseDialog; // 22 + *pValue++ <<= rOpt.bIsShowEntriesRecentlyUsedFirst; // 23 + *pValue++ <<= rOpt.bIsAutoReplaceUniqueEntries; // 24 + + *pValue++ <<= rOpt.bIsDirectionToSimplified; // 25 + *pValue++ <<= rOpt.bIsUseCharacterVariants; // 26 + *pValue++ <<= rOpt.bIsTranslateCommonTerms; // 27 + *pValue++ <<= rOpt.bIsReverseMapping; // 28 + + *pValue++ <<= rOpt.nDataFilesChangedCheckValue; // 29 + *pValue++ <<= rOpt.bIsGrammarAuto; // 30 + *pValue++ <<= rOpt.bIsGrammarInteractive; // 31 + + bRet |= PutProperties( rProperyNames, aValues ); + } + + if (bRet) + ClearModified(); + + return bRet; +} + +bool SvtLinguConfigItem::IsReadOnly( std::u16string_view rPropertyName ) const +{ + bool bReadOnly = false; + sal_Int32 nHdl; + if (GetHdlByName( nHdl, rPropertyName )) + bReadOnly = IsReadOnly( nHdl ); + return bReadOnly; +} + +bool SvtLinguConfigItem::IsReadOnly( sal_Int32 nPropertyHandle ) const +{ + std::unique_lock aGuard(theSvtLinguConfigItemMutex()); + + bool bReadOnly = false; + + const SvtLinguOptions &rOpt = const_cast< SvtLinguConfigItem * >(this)->aOpt; + switch(nPropertyHandle) + { + case UPH_IS_USE_DICTIONARY_LIST : bReadOnly = rOpt.bROIsUseDictionaryList; break; + case UPH_IS_IGNORE_CONTROL_CHARACTERS : bReadOnly = rOpt.bROIsIgnoreControlCharacters; break; + case UPH_IS_HYPH_AUTO : bReadOnly = rOpt.bROIsHyphAuto; break; + case UPH_IS_HYPH_SPECIAL : bReadOnly = rOpt.bROIsHyphSpecial; break; + case UPH_IS_SPELL_AUTO : bReadOnly = rOpt.bROIsSpellAuto; break; + case UPH_IS_SPELL_SPECIAL : bReadOnly = rOpt.bROIsSpellSpecial; break; + case UPH_IS_WRAP_REVERSE : bReadOnly = rOpt.bROIsSpellReverse; break; + case UPH_DEFAULT_LANGUAGE : bReadOnly = rOpt.bRODefaultLanguage; break; + case UPH_IS_SPELL_CAPITALIZATION : bReadOnly = rOpt.bROIsSpellCapitalization; break; + case UPH_IS_SPELL_WITH_DIGITS : bReadOnly = rOpt.bROIsSpellWithDigits; break; + case UPH_IS_SPELL_UPPER_CASE : bReadOnly = rOpt.bROIsSpellUpperCase; break; + case UPH_HYPH_MIN_LEADING : bReadOnly = rOpt.bROHyphMinLeading; break; + case UPH_HYPH_MIN_TRAILING : bReadOnly = rOpt.bROHyphMinTrailing; break; + case UPH_HYPH_MIN_WORD_LENGTH : bReadOnly = rOpt.bROHyphMinWordLength; break; + case UPH_ACTIVE_DICTIONARIES : bReadOnly = rOpt.bROActiveDics; break; + case UPH_ACTIVE_CONVERSION_DICTIONARIES : bReadOnly = rOpt.bROActiveConvDics; break; + case UPH_DEFAULT_LOCALE : bReadOnly = rOpt.bRODefaultLanguage; break; + case UPH_DEFAULT_LOCALE_CJK : bReadOnly = rOpt.bRODefaultLanguage_CJK; break; + case UPH_DEFAULT_LOCALE_CTL : bReadOnly = rOpt.bRODefaultLanguage_CTL; break; + case UPH_IS_IGNORE_POST_POSITIONAL_WORD : bReadOnly = rOpt.bROIsIgnorePostPositionalWord; break; + case UPH_IS_AUTO_CLOSE_DIALOG : bReadOnly = rOpt.bROIsAutoCloseDialog; break; + case UPH_IS_SHOW_ENTRIES_RECENTLY_USED_FIRST : bReadOnly = rOpt.bROIsShowEntriesRecentlyUsedFirst; break; + case UPH_IS_AUTO_REPLACE_UNIQUE_ENTRIES : bReadOnly = rOpt.bROIsAutoReplaceUniqueEntries; break; + case UPH_IS_DIRECTION_TO_SIMPLIFIED : bReadOnly = rOpt.bROIsDirectionToSimplified; break; + case UPH_IS_USE_CHARACTER_VARIANTS : bReadOnly = rOpt.bROIsUseCharacterVariants; break; + case UPH_IS_TRANSLATE_COMMON_TERMS : bReadOnly = rOpt.bROIsTranslateCommonTerms; break; + case UPH_IS_REVERSE_MAPPING : bReadOnly = rOpt.bROIsReverseMapping; break; + case UPH_DATA_FILES_CHANGED_CHECK_VALUE : bReadOnly = rOpt.bRODataFilesChangedCheckValue; break; + case UPH_IS_GRAMMAR_AUTO: bReadOnly = rOpt.bROIsGrammarAuto; break; + case UPH_IS_GRAMMAR_INTERACTIVE: bReadOnly = rOpt.bROIsGrammarInteractive; break; + default : + SAL_WARN( "unotools.config", "unexpected property handle" ); + } + return bReadOnly; +} + +static SvtLinguConfigItem *pCfgItem = nullptr; +static sal_Int32 nCfgItemRefCount = 0; + +constexpr OUStringLiteral aG_Dictionaries = u"Dictionaries"; + +SvtLinguConfig::SvtLinguConfig() +{ + // Global access, must be guarded (multithreading) + std::unique_lock aGuard(theSvtLinguConfigItemMutex()); + ++nCfgItemRefCount; +} + +SvtLinguConfig::~SvtLinguConfig() +{ + if (pCfgItem && pCfgItem->IsModified()) + pCfgItem->Commit(); + + std::unique_lock aGuard(theSvtLinguConfigItemMutex()); + + if (--nCfgItemRefCount <= 0) + { + delete pCfgItem; + pCfgItem = nullptr; + } +} + +SvtLinguConfigItem & SvtLinguConfig::GetConfigItem() +{ + // Global access, must be guarded (multithreading) + std::unique_lock aGuard(theSvtLinguConfigItemMutex()); + if (!pCfgItem) + { + pCfgItem = new SvtLinguConfigItem; + aGuard.unlock(); + ItemHolder1::holdConfigItem(EItem::LinguConfig); + } + return *pCfgItem; +} + +uno::Sequence< OUString > SvtLinguConfig::GetNodeNames( const OUString &rNode ) const +{ + return GetConfigItem().GetNodeNames( rNode ); +} + +uno::Sequence< uno::Any > SvtLinguConfig::GetProperties( const uno::Sequence< OUString > &rNames ) const +{ + return GetConfigItem().GetProperties(rNames); +} + +bool SvtLinguConfig::ReplaceSetProperties( + const OUString &rNode, const uno::Sequence< beans::PropertyValue >& rValues ) +{ + return GetConfigItem().ReplaceSetProperties( rNode, rValues ); +} + +uno::Any SvtLinguConfig::GetProperty( std::u16string_view rPropertyName ) const +{ + return GetConfigItem().GetProperty( rPropertyName ); +} + +uno::Any SvtLinguConfig::GetProperty( sal_Int32 nPropertyHandle ) const +{ + return GetConfigItem().GetProperty( nPropertyHandle ); +} + +bool SvtLinguConfig::SetProperty( std::u16string_view rPropertyName, const uno::Any &rValue ) +{ + return GetConfigItem().SetProperty( rPropertyName, rValue ); +} + +bool SvtLinguConfig::SetProperty( sal_Int32 nPropertyHandle, const uno::Any &rValue ) +{ + return GetConfigItem().SetProperty( nPropertyHandle, rValue ); +} + +void SvtLinguConfig::GetOptions( SvtLinguOptions &rOptions ) const +{ + GetConfigItem().GetOptions(rOptions); +} + +bool SvtLinguConfig::IsReadOnly( std::u16string_view rPropertyName ) const +{ + return GetConfigItem().IsReadOnly( rPropertyName ); +} + +bool SvtLinguConfig::GetElementNamesFor( + const OUString &rNodeName, + uno::Sequence< OUString > &rElementNames ) const +{ + bool bSuccess = false; + try + { + uno::Reference< container::XNameAccess > xNA( GetMainUpdateAccess(), uno::UNO_QUERY_THROW ); + xNA.set( xNA->getByName("ServiceManager"), uno::UNO_QUERY_THROW ); + xNA.set( xNA->getByName( rNodeName ), uno::UNO_QUERY_THROW ); + rElementNames = xNA->getElementNames(); + bSuccess = true; + } + catch (uno::Exception &) + { + } + return bSuccess; +} + +bool SvtLinguConfig::GetSupportedDictionaryFormatsFor( + const OUString &rSetName, + const OUString &rSetEntry, + uno::Sequence< OUString > &rFormatList ) const +{ + if (rSetName.isEmpty() || rSetEntry.isEmpty()) + return false; + bool bSuccess = false; + try + { + uno::Reference< container::XNameAccess > xNA( GetMainUpdateAccess(), uno::UNO_QUERY_THROW ); + xNA.set( xNA->getByName("ServiceManager"), uno::UNO_QUERY_THROW ); + xNA.set( xNA->getByName( rSetName ), uno::UNO_QUERY_THROW ); + xNA.set( xNA->getByName( rSetEntry ), uno::UNO_QUERY_THROW ); + if (xNA->getByName( "SupportedDictionaryFormats" ) >>= rFormatList) + bSuccess = true; + DBG_ASSERT( rFormatList.hasElements(), "supported dictionary format list is empty" ); + } + catch (uno::Exception &) + { + } + return bSuccess; +} + +static bool lcl_GetFileUrlFromOrigin( + OUString /*out*/ &rFileUrl, + const OUString &rOrigin ) +{ + OUString aURL( + comphelper::getExpandedUri( + comphelper::getProcessComponentContext(), rOrigin)); + if (aURL.startsWith( FILE_PROTOCOL )) + { + rFileUrl = aURL; + return true; + } + else + { + SAL_WARN( + "unotools.config", "not a file URL, <" << aURL << ">" ); + return false; + } +} + +bool SvtLinguConfig::GetDictionaryEntry( + const OUString &rNodeName, + SvtLinguConfigDictionaryEntry &rDicEntry ) const +{ + if (rNodeName.isEmpty()) + return false; + bool bSuccess = false; + try + { + uno::Reference< container::XNameAccess > xNA( GetMainUpdateAccess(), uno::UNO_QUERY_THROW ); + xNA.set( xNA->getByName("ServiceManager"), uno::UNO_QUERY_THROW ); + xNA.set( xNA->getByName( aG_Dictionaries ), uno::UNO_QUERY_THROW ); + xNA.set( xNA->getByName( rNodeName ), uno::UNO_QUERY_THROW ); + + // read group data... + uno::Sequence< OUString > aLocations; + OUString aFormatName; + uno::Sequence< OUString > aLocaleNames; + bSuccess = (xNA->getByName( "Locations" ) >>= aLocations) && + (xNA->getByName( "Format" ) >>= aFormatName) && + (xNA->getByName( "Locales" ) >>= aLocaleNames); + DBG_ASSERT( aLocations.hasElements(), "Dictionary locations not set" ); + DBG_ASSERT( !aFormatName.isEmpty(), "Dictionary format name not set" ); + DBG_ASSERT( aLocaleNames.hasElements(), "No locales set for the dictionary" ); + + // if successful continue + if (bSuccess) + { + // get file URL's for the locations + for (OUString& rLocation : asNonConstRange(aLocations)) + { + if (!lcl_GetFileUrlFromOrigin( rLocation, rLocation )) + bSuccess = false; + } + + // if everything was fine return the result + if (bSuccess) + { + rDicEntry.aLocations = aLocations; + rDicEntry.aFormatName = aFormatName; + rDicEntry.aLocaleNames = aLocaleNames; + } + } + } + catch (uno::Exception &) + { + } + return bSuccess; +} + +uno::Sequence< OUString > SvtLinguConfig::GetDisabledDictionaries() const +{ + uno::Sequence< OUString > aResult; + try + { + uno::Reference< container::XNameAccess > xNA( GetMainUpdateAccess(), uno::UNO_QUERY_THROW ); + xNA.set( xNA->getByName("ServiceManager"), uno::UNO_QUERY_THROW ); + xNA->getByName( "DisabledDictionaries" ) >>= aResult; + } + catch (uno::Exception &) + { + } + return aResult; +} + +std::vector< SvtLinguConfigDictionaryEntry > SvtLinguConfig::GetActiveDictionariesByFormat( + std::u16string_view rFormatName ) const +{ + std::vector< SvtLinguConfigDictionaryEntry > aRes; + if (rFormatName.empty()) + return aRes; + + try + { + uno::Sequence< OUString > aElementNames; + GetElementNamesFor( aG_Dictionaries, aElementNames ); + + const uno::Sequence< OUString > aDisabledDics( GetDisabledDictionaries() ); + + SvtLinguConfigDictionaryEntry aDicEntry; + for (const OUString& rElementName : std::as_const(aElementNames)) + { + // does dictionary match the format we are looking for? + if (GetDictionaryEntry( rElementName, aDicEntry ) && + aDicEntry.aFormatName == rFormatName) + { + // check if it is active or not + bool bDicIsActive = std::none_of(aDisabledDics.begin(), aDisabledDics.end(), + [&rElementName](const OUString& rDic) { return rDic == rElementName; }); + + if (bDicIsActive) + { + DBG_ASSERT( !aDicEntry.aFormatName.isEmpty(), + "FormatName not set" ); + DBG_ASSERT( aDicEntry.aLocations.hasElements(), + "Locations not set" ); + DBG_ASSERT( aDicEntry.aLocaleNames.hasElements(), + "Locales not set" ); + aRes.push_back( aDicEntry ); + } + } + } + } + catch (uno::Exception &) + { + } + + return aRes; +} + +uno::Reference< util::XChangesBatch > const & SvtLinguConfig::GetMainUpdateAccess() const +{ + if (!m_xMainUpdateAccess.is()) + { + try + { + // get configuration provider + uno::Reference< uno::XComponentContext > xContext = comphelper::getProcessComponentContext(); + uno::Reference< lang::XMultiServiceFactory > xConfigurationProvider = + configuration::theDefaultProvider::get( xContext ); + + // get configuration update access + beans::PropertyValue aValue; + aValue.Name = "nodepath"; + aValue.Value <<= OUString("org.openoffice.Office.Linguistic"); + uno::Sequence< uno::Any > aProps{ uno::Any(aValue) }; + m_xMainUpdateAccess.set( + xConfigurationProvider->createInstanceWithArguments( + "com.sun.star.configuration.ConfigurationUpdateAccess", aProps), + uno::UNO_QUERY_THROW ); + } + catch (uno::Exception &) + { + } + } + + return m_xMainUpdateAccess; +} + +OUString SvtLinguConfig::GetVendorImageUrl_Impl( + const OUString &rServiceImplName, + const OUString &rImageName ) const +{ + OUString aRes; + try + { + uno::Reference< container::XNameAccess > xImagesNA( GetMainUpdateAccess(), uno::UNO_QUERY_THROW ); + xImagesNA.set( xImagesNA->getByName("Images"), uno::UNO_QUERY_THROW ); + + uno::Reference< container::XNameAccess > xNA( xImagesNA->getByName("ServiceNameEntries"), uno::UNO_QUERY_THROW ); + xNA.set( xNA->getByName( rServiceImplName ), uno::UNO_QUERY_THROW ); + uno::Any aAny(xNA->getByName("VendorImagesNode")); + OUString aVendorImagesNode; + if (aAny >>= aVendorImagesNode) + { + xNA = xImagesNA; + xNA.set( xNA->getByName("VendorImages"), uno::UNO_QUERY_THROW ); + xNA.set( xNA->getByName( aVendorImagesNode ), uno::UNO_QUERY_THROW ); + aAny = xNA->getByName( rImageName ); + OUString aTmp; + if (aAny >>= aTmp) + { + if (lcl_GetFileUrlFromOrigin( aTmp, aTmp )) + aRes = aTmp; + } + } + } + catch (uno::Exception &) + { + DBG_UNHANDLED_EXCEPTION("unotools"); + } + return aRes; +} + +OUString SvtLinguConfig::GetSpellAndGrammarContextSuggestionImage( + const OUString &rServiceImplName +) const +{ + OUString aRes; + if (!rServiceImplName.isEmpty()) + { + aRes = GetVendorImageUrl_Impl( rServiceImplName, "SpellAndGrammarContextMenuSuggestionImage" ); + } + return aRes; +} + +OUString SvtLinguConfig::GetSpellAndGrammarContextDictionaryImage( + const OUString &rServiceImplName +) const +{ + OUString aRes; + if (!rServiceImplName.isEmpty()) + { + aRes = GetVendorImageUrl_Impl( rServiceImplName, "SpellAndGrammarContextMenuDictionaryImage" ); + } + return aRes; +} + +OUString SvtLinguConfig::GetSynonymsContextImage( + const OUString &rServiceImplName +) const +{ + OUString aRes; + if (!rServiceImplName.isEmpty()) + { + OUString aPath( GetVendorImageUrl_Impl( rServiceImplName, "SynonymsContextMenuImage" ) ); + aRes = aPath; + } + return aRes; +} + +bool SvtLinguConfig::HasGrammarChecker() const +{ + bool bRes = false; + + try + { + uno::Reference< container::XNameAccess > xNA( GetMainUpdateAccess(), uno::UNO_QUERY_THROW ); + xNA.set( xNA->getByName("ServiceManager"), uno::UNO_QUERY_THROW ); + xNA.set( xNA->getByName("GrammarCheckerList"), uno::UNO_QUERY_THROW ); + + uno::Sequence< OUString > aElementNames( xNA->getElementNames() ); + bRes = aElementNames.hasElements(); + } + catch (const uno::Exception&) + { + } + + return bRes; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/moduleoptions.cxx b/unotools/source/config/moduleoptions.cxx new file mode 100644 index 000000000..858d2d09e --- /dev/null +++ b/unotools/source/config/moduleoptions.cxx @@ -0,0 +1,1117 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * 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/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <sal/config.h> + +#include <string_view> + +#include <unotools/moduleoptions.hxx> +#include <comphelper/sequenceashashmap.hxx> +#include <unotools/configitem.hxx> +#include <comphelper/processfactory.hxx> +#include <comphelper/sequence.hxx> +#include <osl/diagnose.h> +#include <o3tl/enumarray.hxx> +#include <o3tl/string_view.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> +#include <com/sun/star/beans/PropertyValue.hpp> +#include <com/sun/star/container/XNameAccess.hpp> +#include <com/sun/star/frame/XModel.hpp> +#include <com/sun/star/lang/XServiceInfo.hpp> +#include <com/sun/star/document/XTypeDetection.hpp> +#include <com/sun/star/util/PathSubstitution.hpp> +#include <com/sun/star/util/XStringSubstitution.hpp> + +#include "itemholder1.hxx" + +/*-************************************************************************************************************ + @descr These values are used to define necessary keys from our configuration management to support + all functionality of these implementation. + It's a fast way to make changes if some keys change its name or location! + + Property handle are necessary to specify right position in return list of configuration + for asked values. We ask it with a list of properties to get its values. The returned list + has the same order like our given name list! + e.g.: + NAMELIST[ PROPERTYHANDLE_xxx ] => VALUELIST[ PROPERTYHANDLE_xxx ] +*//*-*************************************************************************************************************/ +constexpr OUStringLiteral ROOTNODE_FACTORIES = u"Setup/Office/Factories"; +#define PATHSEPARATOR "/" + +// Attention: The property "ooSetupFactoryEmptyDocumentURL" is read from configuration but not used! There is +// special code that uses hard coded strings to return them. +#define PROPERTYNAME_SHORTNAME "ooSetupFactoryShortName" +#define PROPERTYNAME_TEMPLATEFILE "ooSetupFactoryTemplateFile" +#define PROPERTYNAME_WINDOWATTRIBUTES "ooSetupFactoryWindowAttributes" +#define PROPERTYNAME_EMPTYDOCUMENTURL "ooSetupFactoryEmptyDocumentURL" +#define PROPERTYNAME_DEFAULTFILTER "ooSetupFactoryDefaultFilter" +#define PROPERTYNAME_ICON "ooSetupFactoryIcon" + +#define PROPERTYHANDLE_SHORTNAME 0 +#define PROPERTYHANDLE_TEMPLATEFILE 1 +#define PROPERTYHANDLE_WINDOWATTRIBUTES 2 +#define PROPERTYHANDLE_EMPTYDOCUMENTURL 3 +#define PROPERTYHANDLE_DEFAULTFILTER 4 +#define PROPERTYHANDLE_ICON 5 + +#define PROPERTYCOUNT 6 + +constexpr OUStringLiteral FACTORYNAME_WRITER = u"com.sun.star.text.TextDocument"; +constexpr OUStringLiteral FACTORYNAME_WRITERWEB = u"com.sun.star.text.WebDocument"; +constexpr OUStringLiteral FACTORYNAME_WRITERGLOBAL = u"com.sun.star.text.GlobalDocument"; +constexpr OUStringLiteral FACTORYNAME_CALC = u"com.sun.star.sheet.SpreadsheetDocument"; +constexpr OUStringLiteral FACTORYNAME_DRAW = u"com.sun.star.drawing.DrawingDocument"; +constexpr OUStringLiteral FACTORYNAME_IMPRESS = u"com.sun.star.presentation.PresentationDocument"; +constexpr OUStringLiteral FACTORYNAME_MATH = u"com.sun.star.formula.FormulaProperties"; +constexpr OUStringLiteral FACTORYNAME_CHART = u"com.sun.star.chart2.ChartDocument"; +constexpr OUStringLiteral FACTORYNAME_DATABASE = u"com.sun.star.sdb.OfficeDatabaseDocument"; +constexpr OUStringLiteral FACTORYNAME_STARTMODULE = u"com.sun.star.frame.StartModule"; +constexpr OUStringLiteral FACTORYNAME_BASIC = u"com.sun.star.script.BasicIDE"; + +#define FACTORYCOUNT 11 + +namespace { + +/*-************************************************************************************************************ + @descr This struct hold information about one factory. We declare a complete array which can hold infos + for all well known factories. Values of enum "EFactory" (see header!) are directly used as index! + So we can support a fast access on this information. +*//*-*************************************************************************************************************/ +struct FactoryInfo +{ + public: + + // initialize empty struct + FactoryInfo() + { + free(); + } + + // easy way to reset struct member! + void free() + { + bInstalled = false; + sFactory.clear(); + sTemplateFile.clear(); + sDefaultFilter.clear(); + nIcon = 0; + bChangedTemplateFile = false; + bChangedDefaultFilter = false; + bDefaultFilterReadonly = false; + } + + // returns list of properties, which has changed only! + // We use given value of sNodeBase to build full qualified paths ... + // Last sign of it must be "/". because we use it directly, without any additional things! + css::uno::Sequence< css::beans::PropertyValue > getChangedProperties( std::u16string_view sNodeBase ) + { + // a) reserve memory for max. count of changed properties + // b) add names and values of changed ones only and count it + // c) resize return list by using count + css::uno::Sequence< css::beans::PropertyValue > lProperties ( 4 ); + auto plProperties = lProperties.getArray(); + sal_Int8 nRealyChanged = 0; + + if( bChangedTemplateFile ) + { + plProperties[nRealyChanged].Name + = OUString::Concat(sNodeBase) + PROPERTYNAME_TEMPLATEFILE; + + if ( !sTemplateFile.isEmpty() ) + { + plProperties[nRealyChanged].Value + <<= getStringSubstitution() + ->reSubstituteVariables( sTemplateFile ); + } + else + { + plProperties[nRealyChanged].Value <<= sTemplateFile; + } + + ++nRealyChanged; + } + if( bChangedDefaultFilter ) + { + plProperties[nRealyChanged].Name + = OUString::Concat(sNodeBase) + PROPERTYNAME_DEFAULTFILTER; + plProperties[nRealyChanged].Value <<= sDefaultFilter; + ++nRealyChanged; + } + + // Don't forget to reset changed flags! Otherwise we save it again and again and ... + bChangedTemplateFile = false; + bChangedDefaultFilter = false; + + lProperties.realloc( nRealyChanged ); + return lProperties; + } + + // We must support setting AND marking of changed values. + // That's why we can't make our member public. We must use get/set/init methods + // to control access on it! + bool getInstalled () const { return bInstalled; }; + const OUString& getFactory () const { return sFactory; }; + const OUString& getTemplateFile () const { return sTemplateFile; }; + const OUString& getDefaultFilter () const { return sDefaultFilter; }; + bool isDefaultFilterReadonly() const { return bDefaultFilterReadonly; } + sal_Int32 getIcon () const { return nIcon; }; + + // If you call set-methods - we check for changes of values and mark it. + // But if you wish to set it without that... you must initialize it! + void initInstalled () { bInstalled = true; } + void initFactory ( const OUString& sNewFactory ) { sFactory = sNewFactory; } + void initDefaultFilter ( const OUString& sNewDefaultFilter ) { sDefaultFilter = sNewDefaultFilter; } + void setDefaultFilterReadonly( const bool bVal){bDefaultFilterReadonly = bVal;} + void initIcon ( sal_Int32 nNewIcon ) { nIcon = nNewIcon; } + + void initTemplateFile( const OUString& sNewTemplateFile ) + { + if ( !sNewTemplateFile.isEmpty() ) + { + sTemplateFile= getStringSubstitution()->substituteVariables( sNewTemplateFile, false ); + } + else + { + sTemplateFile = sNewTemplateFile; + } + } + + void setTemplateFile( const OUString& sNewTemplateFile ) + { + if( sTemplateFile != sNewTemplateFile ) + { + sTemplateFile = sNewTemplateFile; + bChangedTemplateFile = true; + } + }; + + void setDefaultFilter( const OUString& sNewDefaultFilter ) + { + if( sDefaultFilter != sNewDefaultFilter ) + { + sDefaultFilter = sNewDefaultFilter; + bChangedDefaultFilter = true; + } + }; + + private: + css::uno::Reference< css::util::XStringSubstitution > const & getStringSubstitution() + { + if ( !xSubstVars.is() ) + { + xSubstVars.set( css::util::PathSubstitution::create(::comphelper::getProcessComponentContext()) ); + } + return xSubstVars; + } + + bool bInstalled; + OUString sFactory; + OUString sTemplateFile; + OUString sDefaultFilter; + sal_Int32 nIcon; + + bool bChangedTemplateFile :1; + bool bChangedDefaultFilter :1; + bool bDefaultFilterReadonly :1; + + css::uno::Reference< css::util::XStringSubstitution > xSubstVars; +}; + +} + +class SvtModuleOptions_Impl : public ::utl::ConfigItem +{ + + // public methods + + public: + + // constructor / destructor + + SvtModuleOptions_Impl(); + virtual ~SvtModuleOptions_Impl() override; + + // override methods of baseclass + + virtual void Notify( const css::uno::Sequence< OUString >& lPropertyNames ) override; + + // public interface + + bool IsModuleInstalled ( SvtModuleOptions::EModule eModule ) const; + css::uno::Sequence < OUString > GetAllServiceNames(); + OUString const & GetFactoryName ( SvtModuleOptions::EFactory eFactory ) const; + OUString const & GetFactoryStandardTemplate( SvtModuleOptions::EFactory eFactory ) const; + static OUString GetFactoryEmptyDocumentURL( SvtModuleOptions::EFactory eFactory ); + OUString const & GetFactoryDefaultFilter ( SvtModuleOptions::EFactory eFactory ) const; + bool IsDefaultFilterReadonly( SvtModuleOptions::EFactory eFactory ) const; + sal_Int32 GetFactoryIcon ( SvtModuleOptions::EFactory eFactory ) const; + static bool ClassifyFactoryByName ( std::u16string_view sName , + SvtModuleOptions::EFactory& eFactory ); + void SetFactoryStandardTemplate( SvtModuleOptions::EFactory eFactory , + const OUString& sTemplate ); + void SetFactoryDefaultFilter ( SvtModuleOptions::EFactory eFactory , + const OUString& sFilter ); + void MakeReadonlyStatesAvailable(); + + // private methods + + private: + static css::uno::Sequence< OUString > impl_ExpandSetNames ( const css::uno::Sequence< OUString >& lSetNames ); + void impl_Read ( const css::uno::Sequence< OUString >& lSetNames ); + + virtual void ImplCommit() override; + + // private member + + private: + o3tl::enumarray<SvtModuleOptions::EFactory, FactoryInfo> m_lFactories; + bool m_bReadOnlyStatesWellKnown; +}; + +/*-************************************************************************************************************ + @short default ctor + @descr We open our configuration here and read all necessary values from it. + These values are cached till everyone call Commit(). Then we write changed ones back to cfg. + + @seealso baseclass ConfigItem + @seealso method impl_Read() + @threadsafe no +*//*-*************************************************************************************************************/ +SvtModuleOptions_Impl::SvtModuleOptions_Impl() + : ::utl::ConfigItem( ROOTNODE_FACTORIES ) + , m_bReadOnlyStatesWellKnown( false ) +{ + // First initialize list of factory infos! Otherwise we couldn't guarantee right working of these class. + for( auto & rFactory : m_lFactories ) + rFactory.free(); + + // Get name list of all existing set node names in configuration to read her properties in impl_Read(). + // These list is a list of long names of our factories. + const css::uno::Sequence< OUString > lFactories = GetNodeNames( OUString() ); + impl_Read( lFactories ); + + // Enable notification for changes by using configuration directly. + // So we can update our internal values immediately. + EnableNotification( lFactories ); +} + +SvtModuleOptions_Impl::~SvtModuleOptions_Impl() +{ + assert(!IsModified()); // should have been committed +} + +/*-************************************************************************************************************ + @short called for notify of configmanager + @descr This method is called from the ConfigManager before application ends or from the + PropertyChangeListener if the sub tree broadcasts changes. You must update our + internal values. + + @attention We are registered for pure set node names only. So we can use our internal method "impl_Read()" to + update our info list. Because - this method expand given name list to full qualified property list + and use it to read the values. These values are filled into our internal member list m_lFactories + at right position. + + @seealso method impl_Read() + + @param "lNames" is the list of set node entries which should be updated. + @threadsafe no +*//*-*************************************************************************************************************/ +void SvtModuleOptions_Impl::Notify( const css::uno::Sequence< OUString >& ) +{ + OSL_FAIL( "SvtModuleOptions_Impl::Notify() Not implemented yet!" ); +} + +/*-**************************************************************************************************** + @short write changes to configuration + @descr This method writes the changed values into the sub tree + and should always called in our destructor to guarantee consistency of config data. + + @attention We clear complete set in configuration first and write it completely new! So we don't must + distinguish between existing, added or removed elements. Our internal cached values + are the only and right ones. + + @seealso baseclass ConfigItem + @threadsafe no +*//*-*****************************************************************************************************/ +void SvtModuleOptions_Impl::ImplCommit() +{ + // Reserve memory for ALL possible factory properties! + // Step over all factories and get her really changed values only. + // Build list of these ones and use it for commit. + css::uno::Sequence< css::beans::PropertyValue > lCommitProperties( FACTORYCOUNT*PROPERTYCOUNT ); + sal_Int32 nRealCount = 0; + OUString sBasePath; + for( FactoryInfo & rInfo : m_lFactories ) + { + // These path is used to build full qualified property names... + // See pInfo->getChangedProperties() for further information + sBasePath = PATHSEPARATOR + rInfo.getFactory() + PATHSEPARATOR; + + const css::uno::Sequence< css::beans::PropertyValue > lChangedProperties = rInfo.getChangedProperties ( sBasePath ); + std::copy(lChangedProperties.begin(), lChangedProperties.end(), std::next(lCommitProperties.getArray(), nRealCount)); + nRealCount += lChangedProperties.getLength(); + } + // Resize commit list to real size. + // If nothing to do - suppress calling of configuration... + // It could be too expensive :-) + if( nRealCount > 0 ) + { + lCommitProperties.realloc( nRealCount ); + SetSetProperties( OUString(), lCommitProperties ); + } +} + +/*-**************************************************************************************************** + @short access method to get internal values + @descr These methods implement easy access to our internal values. + You give us right enum value to specify which module interest you ... we return right information. + + @attention Some people use any value as enum ... but we support in header specified values only! + We use it directly as index in our internal list. If enum value isn't right - we crash with an + "index out of range"!!! Please use me right - otherwise there is no guarantee. + @param "eModule" , index in list - specify module + @return Queried information. + + @onerror We return default values. (mostly "not installed"!) + @threadsafe no +*//*-*****************************************************************************************************/ +bool SvtModuleOptions_Impl::IsModuleInstalled( SvtModuleOptions::EModule eModule ) const +{ + switch( eModule ) + { + case SvtModuleOptions::EModule::WRITER: + return m_lFactories[SvtModuleOptions::EFactory::WRITER].getInstalled(); + case SvtModuleOptions::EModule::WEB: + return m_lFactories[SvtModuleOptions::EFactory::WRITERWEB].getInstalled(); + case SvtModuleOptions::EModule::GLOBAL: + return m_lFactories[SvtModuleOptions::EFactory::WRITERGLOBAL].getInstalled(); + case SvtModuleOptions::EModule::CALC: + return m_lFactories[SvtModuleOptions::EFactory::CALC].getInstalled(); + case SvtModuleOptions::EModule::DRAW: + return m_lFactories[SvtModuleOptions::EFactory::DRAW].getInstalled(); + case SvtModuleOptions::EModule::IMPRESS: + return m_lFactories[SvtModuleOptions::EFactory::IMPRESS].getInstalled(); + case SvtModuleOptions::EModule::MATH: + return m_lFactories[SvtModuleOptions::EFactory::MATH].getInstalled(); + case SvtModuleOptions::EModule::CHART: + return m_lFactories[SvtModuleOptions::EFactory::CHART].getInstalled(); + case SvtModuleOptions::EModule::STARTMODULE: + return m_lFactories[SvtModuleOptions::EFactory::STARTMODULE].getInstalled(); + case SvtModuleOptions::EModule::BASIC: + return true; // Couldn't be deselected by setup yet! + case SvtModuleOptions::EModule::DATABASE: + return m_lFactories[SvtModuleOptions::EFactory::DATABASE].getInstalled(); + } + + return false; +} + +css::uno::Sequence < OUString > SvtModuleOptions_Impl::GetAllServiceNames() +{ + std::vector<OUString> aVec; + + for( const auto & rFactory : m_lFactories ) + if( rFactory.getInstalled() ) + aVec.push_back( rFactory.getFactory() ); + + return comphelper::containerToSequence(aVec); +} + +OUString const & SvtModuleOptions_Impl::GetFactoryName( SvtModuleOptions::EFactory eFactory ) const +{ + return m_lFactories[eFactory].getFactory(); +} + +OUString SvtModuleOptions::GetFactoryShortName(SvtModuleOptions::EFactory eFactory) +{ + // Attention: Hard configured yet ... because it's not fine to make changes possible by xml file yet. + // But it's good to plan further possibilities! + + //return m_lFactories[eFactory].sShortName; + + OUString sShortName; + switch( eFactory ) + { + case SvtModuleOptions::EFactory::WRITER : sShortName = "swriter"; + break; + case SvtModuleOptions::EFactory::WRITERWEB: sShortName = "swriter/web"; + break; + case SvtModuleOptions::EFactory::WRITERGLOBAL: sShortName = "swriter/GlobalDocument"; + break; + case SvtModuleOptions::EFactory::CALC : sShortName = "scalc"; + break; + case SvtModuleOptions::EFactory::DRAW : sShortName = "sdraw"; + break; + case SvtModuleOptions::EFactory::IMPRESS : sShortName = "simpress"; + break; + case SvtModuleOptions::EFactory::MATH : sShortName = "smath"; + break; + case SvtModuleOptions::EFactory::CHART : sShortName = "schart"; + break; + case SvtModuleOptions::EFactory::BASIC : sShortName = "sbasic"; + break; + case SvtModuleOptions::EFactory::DATABASE : sShortName = "sdatabase"; + break; + case SvtModuleOptions::EFactory::STARTMODULE : sShortName = "startmodule"; + break; + default: + OSL_FAIL( "unknown factory" ); + break; + } + + return sShortName; +} + +OUString const & SvtModuleOptions_Impl::GetFactoryStandardTemplate( SvtModuleOptions::EFactory eFactory ) const +{ + return m_lFactories[eFactory].getTemplateFile(); +} + +OUString SvtModuleOptions_Impl::GetFactoryEmptyDocumentURL( SvtModuleOptions::EFactory eFactory ) +{ + // Attention: Hard configured yet ... because it's not fine to make changes possible by xml file yet. + // But it's good to plan further possibilities! + + //return m_lFactories[eFactory].getEmptyDocumentURL(); + + OUString sURL; + switch( eFactory ) + { + case SvtModuleOptions::EFactory::WRITER : sURL = "private:factory/swriter"; + break; + case SvtModuleOptions::EFactory::WRITERWEB : sURL = "private:factory/swriter/web"; + break; + case SvtModuleOptions::EFactory::WRITERGLOBAL : sURL = "private:factory/swriter/GlobalDocument"; + break; + case SvtModuleOptions::EFactory::CALC : sURL = "private:factory/scalc"; + break; + case SvtModuleOptions::EFactory::DRAW : sURL = "private:factory/sdraw"; + break; + case SvtModuleOptions::EFactory::IMPRESS : sURL = "private:factory/simpress?slot=6686"; + break; + case SvtModuleOptions::EFactory::MATH : sURL = "private:factory/smath"; + break; + case SvtModuleOptions::EFactory::CHART : sURL = "private:factory/schart"; + break; + case SvtModuleOptions::EFactory::BASIC : sURL = "private:factory/sbasic"; + break; + case SvtModuleOptions::EFactory::DATABASE : sURL = "private:factory/sdatabase?Interactive"; + break; + default: + OSL_FAIL( "unknown factory" ); + break; + } + return sURL; +} + +OUString const & SvtModuleOptions_Impl::GetFactoryDefaultFilter( SvtModuleOptions::EFactory eFactory ) const +{ + return m_lFactories[eFactory].getDefaultFilter(); +} + +bool SvtModuleOptions_Impl::IsDefaultFilterReadonly( SvtModuleOptions::EFactory eFactory ) const +{ + return m_lFactories[eFactory].isDefaultFilterReadonly(); +} + +sal_Int32 SvtModuleOptions_Impl::GetFactoryIcon( SvtModuleOptions::EFactory eFactory ) const +{ + return m_lFactories[eFactory].getIcon(); +} + +void SvtModuleOptions_Impl::SetFactoryStandardTemplate( SvtModuleOptions::EFactory eFactory , + const OUString& sTemplate ) +{ + m_lFactories[eFactory].setTemplateFile( sTemplate ); + SetModified(); +} + +void SvtModuleOptions_Impl::SetFactoryDefaultFilter( SvtModuleOptions::EFactory eFactory, + const OUString& sFilter ) +{ + m_lFactories[eFactory].setDefaultFilter( sFilter ); + SetModified(); +} + +/*-************************************************************************************************************ + @short return list of key names of our configuration management which represent our module tree + @descr You give use a list of current existing set node names .. and we expand it for all + well known properties which are necessary for this implementation. + These full expanded list should be used to get values of this properties. + + @seealso ctor + @return List of all relative addressed properties of given set entry names. + + @onerror List will be empty. + @threadsafe no +*//*-*************************************************************************************************************/ +css::uno::Sequence< OUString > SvtModuleOptions_Impl::impl_ExpandSetNames( const css::uno::Sequence< OUString >& lSetNames ) +{ + sal_Int32 nCount = lSetNames.getLength(); + css::uno::Sequence< OUString > lPropNames ( nCount*PROPERTYCOUNT ); + OUString* pPropNames = lPropNames.getArray(); + sal_Int32 nPropStart = 0; + + for( const auto& rSetName : lSetNames ) + { + pPropNames[nPropStart+PROPERTYHANDLE_SHORTNAME ] = rSetName + PATHSEPARATOR PROPERTYNAME_SHORTNAME; + pPropNames[nPropStart+PROPERTYHANDLE_TEMPLATEFILE ] = rSetName + PATHSEPARATOR PROPERTYNAME_TEMPLATEFILE; + pPropNames[nPropStart+PROPERTYHANDLE_WINDOWATTRIBUTES] = rSetName + PATHSEPARATOR PROPERTYNAME_WINDOWATTRIBUTES; + pPropNames[nPropStart+PROPERTYHANDLE_EMPTYDOCUMENTURL] = rSetName + PATHSEPARATOR PROPERTYNAME_EMPTYDOCUMENTURL; + pPropNames[nPropStart+PROPERTYHANDLE_DEFAULTFILTER ] = rSetName + PATHSEPARATOR PROPERTYNAME_DEFAULTFILTER; + pPropNames[nPropStart+PROPERTYHANDLE_ICON ] = rSetName + PATHSEPARATOR PROPERTYNAME_ICON; + nPropStart += PROPERTYCOUNT; + } + + return lPropNames; +} + +/*-************************************************************************************************************ + @short helper to classify given factory by name + @descr Every factory has its own long and short name. So we can match right enum value for internal using. + + @attention We change in/out parameter "eFactory" in every case! But you should use it only, if return value is sal_True! + Algorithm: Set out-parameter to probably value ... and check the longname. + If it matches with these factory - break operation and return true AND right set parameter. + Otherwise try next one and so on. If no factory was found return false. Out parameter eFactory + is set to last tried value but shouldn't be used! Because our return value is false! + @param "sLongName" , long name of factory, which should be classified + @return "eFactory" , right enum value, which match given long name + and true for successfully classification, false otherwise + + @onerror We return false. + @threadsafe no +*//*-*************************************************************************************************************/ +bool SvtModuleOptions_Impl::ClassifyFactoryByName( std::u16string_view sName, SvtModuleOptions::EFactory& eFactory ) +{ + bool bState; + + eFactory = SvtModuleOptions::EFactory::WRITER; + bState = ( sName == FACTORYNAME_WRITER ); + + if( !bState ) + { + eFactory = SvtModuleOptions::EFactory::WRITERWEB; + bState = ( sName == FACTORYNAME_WRITERWEB ); + } + // no else! + if( !bState ) + { + eFactory = SvtModuleOptions::EFactory::WRITERGLOBAL; + bState = ( sName == FACTORYNAME_WRITERGLOBAL ); + } + // no else! + if( !bState ) + { + eFactory = SvtModuleOptions::EFactory::CALC; + bState = ( sName == FACTORYNAME_CALC ); + } + // no else! + if( !bState ) + { + eFactory = SvtModuleOptions::EFactory::DRAW; + bState = ( sName == FACTORYNAME_DRAW ); + } + // no else! + if( !bState ) + { + eFactory = SvtModuleOptions::EFactory::IMPRESS; + bState = ( sName == FACTORYNAME_IMPRESS ); + } + // no else! + if( !bState ) + { + eFactory = SvtModuleOptions::EFactory::MATH; + bState = ( sName == FACTORYNAME_MATH ); + } + // no else! + if( !bState ) + { + eFactory = SvtModuleOptions::EFactory::CHART; + bState = ( sName == FACTORYNAME_CHART ); + } + // no else! + if( !bState ) + { + eFactory = SvtModuleOptions::EFactory::DATABASE; + bState = ( sName == FACTORYNAME_DATABASE ); + } + // no else! + if( !bState ) + { + eFactory = SvtModuleOptions::EFactory::STARTMODULE; + bState = ( sName == FACTORYNAME_STARTMODULE); + } + // no else! + if( !bState ) + { + eFactory = SvtModuleOptions::EFactory::BASIC; + bState = ( sName == FACTORYNAME_BASIC); + } + + return bState; +} + +/*-************************************************************************************************************ + @short read factory configuration + @descr Give us a list of pure factory names (long names!) which can be used as + direct set node names... and we read her property values and fill internal list. + These method can be used by initial reading at ctor and later updating by "Notify()". + + @seealso ctor + @seealso method Notify() + + @param "lFactories" is the list of set node entries which should be read. + @onerror We do nothing. + @threadsafe no +*//*-*************************************************************************************************************/ +void SvtModuleOptions_Impl::impl_Read( const css::uno::Sequence< OUString >& lFactories ) +{ + // Expand every set node name in lFactories to full qualified paths to its properties + // and get right values from configuration. + const css::uno::Sequence< OUString > lProperties = impl_ExpandSetNames( lFactories ); + const css::uno::Sequence< css::uno::Any > lValues = GetProperties( lProperties ); + + // Safe impossible cases. + // We need values from ALL configuration keys. + // Follow assignment use order of values in relation to our list of key names! + OSL_ENSURE( !(lProperties.getLength()!=lValues.getLength()), "SvtModuleOptions_Impl::impl_Read()\nI miss some values of configuration keys!" ); + + // Algorithm: We step over all given factory names and classify it. These enum value can be used as direct index + // in our member list m_lFactories! VAriable nPropertyStart marks start position of every factory + // and her properties in expanded property/value list. The defines PROPERTHANDLE_xxx are used as offset values + // added to nPropertyStart. So we can address every property relative in these lists. + // If we found any valid values ... we reset all existing information for corresponding m_lFactories-entry and + // use a pointer to these struct in memory directly to set new values. + // But we set it only, if bInstalled is true. Otherwise all other values of a factory can be undeclared .. They + // shouldn't be used then. + // Attention: If a propertyset of a factory will be ignored we must step to next start position of next factory infos! + // see "nPropertyStart += PROPERTYCOUNT" ... + + sal_Int32 nPropertyStart = 0; + FactoryInfo* pInfo = nullptr; + SvtModuleOptions::EFactory eFactory; + + for( const OUString& sFactoryName : lFactories ) + { + if( ClassifyFactoryByName( sFactoryName, eFactory ) ) + { + OUString sTemp; + sal_Int32 nTemp = 0; + + pInfo = &(m_lFactories[eFactory]); + pInfo->free(); + + pInfo->initInstalled(); + pInfo->initFactory ( sFactoryName ); + + if (lValues[nPropertyStart+PROPERTYHANDLE_TEMPLATEFILE] >>= sTemp) + pInfo->initTemplateFile( sTemp ); + if (lValues[nPropertyStart+PROPERTYHANDLE_DEFAULTFILTER ] >>= sTemp) + pInfo->initDefaultFilter( sTemp ); + if (lValues[nPropertyStart+PROPERTYHANDLE_ICON] >>= nTemp) + pInfo->initIcon( nTemp ); + } + nPropertyStart += PROPERTYCOUNT; + } +} + +void SvtModuleOptions_Impl::MakeReadonlyStatesAvailable() +{ + if (m_bReadOnlyStatesWellKnown) + return; + + css::uno::Sequence< OUString > lFactories = GetNodeNames(OUString()); + for (OUString& rFactory : asNonConstRange(lFactories)) + rFactory += PATHSEPARATOR PROPERTYNAME_DEFAULTFILTER; + + css::uno::Sequence< sal_Bool > lReadonlyStates = GetReadOnlyStates(lFactories); + sal_Int32 c = lFactories.getLength(); + for (sal_Int32 i=0; i<c; ++i) + { + const OUString& rFactoryName = std::as_const(lFactories)[i]; + SvtModuleOptions::EFactory eFactory; + + if (!ClassifyFactoryByName(rFactoryName, eFactory)) + continue; + + FactoryInfo& rInfo = m_lFactories[eFactory]; + rInfo.setDefaultFilterReadonly(lReadonlyStates[i]); + } + + m_bReadOnlyStatesWellKnown = true; +} + +namespace { + //global + std::weak_ptr<SvtModuleOptions_Impl> g_pModuleOptions; + +std::mutex& impl_GetOwnStaticMutex() +{ + static std::mutex s_Mutex; + return s_Mutex; +} +} + +/*-************************************************************************************************************ + @short standard constructor and destructor + @descr This will initialize an instance with default values. We initialize/deinitialize our static data + container and create a static mutex, which is used for threadsafe code in further time of this object. + + @seealso method impl_GetOwnStaticMutex() + @threadsafe yes +*//*-*************************************************************************************************************/ +SvtModuleOptions::SvtModuleOptions() +{ + // no need to take the mutex yet, shared_ptr/weak_ptr are thread-safe + m_pImpl = g_pModuleOptions.lock(); + if( m_pImpl ) + return; + + // take the mutex, so we don't accidentally create more than one + std::unique_lock aGuard( impl_GetOwnStaticMutex() ); + + m_pImpl = g_pModuleOptions.lock(); + if( !m_pImpl ) + { + m_pImpl = std::make_shared<SvtModuleOptions_Impl>(); + g_pModuleOptions = m_pImpl; + aGuard.unlock(); // because holdConfigItem will call this constructor + ItemHolder1::holdConfigItem(EItem::ModuleOptions); + } +} + +SvtModuleOptions::~SvtModuleOptions() +{ + m_pImpl.reset(); +} + +/*-************************************************************************************************************ + @short access to configuration data + @descr This methods allow read/write access to configuration values. + They are threadsafe. All calls are forwarded to impl-data-container. See there for further information! + + @seealso method impl_GetOwnStaticMutex() + @threadsafe yes +*//*-*************************************************************************************************************/ +bool SvtModuleOptions::IsModuleInstalled( EModule eModule ) const +{ + // doesn't need mutex, never modified + return m_pImpl->IsModuleInstalled( eModule ); +} + +const OUString & SvtModuleOptions::GetFactoryName( EFactory eFactory ) const +{ + // doesn't need mutex, never modified + return m_pImpl->GetFactoryName( eFactory ); +} + +OUString SvtModuleOptions::GetFactoryStandardTemplate( EFactory eFactory ) const +{ + std::unique_lock aGuard( impl_GetOwnStaticMutex() ); + return m_pImpl->GetFactoryStandardTemplate( eFactory ); +} + +OUString SvtModuleOptions::GetFactoryEmptyDocumentURL( EFactory eFactory ) const +{ + std::unique_lock aGuard( impl_GetOwnStaticMutex() ); + return SvtModuleOptions_Impl::GetFactoryEmptyDocumentURL( eFactory ); +} + +OUString SvtModuleOptions::GetFactoryDefaultFilter( EFactory eFactory ) const +{ + std::unique_lock aGuard( impl_GetOwnStaticMutex() ); + return m_pImpl->GetFactoryDefaultFilter( eFactory ); +} + +bool SvtModuleOptions::IsDefaultFilterReadonly( EFactory eFactory ) const +{ + std::unique_lock aGuard( impl_GetOwnStaticMutex() ); + m_pImpl->MakeReadonlyStatesAvailable(); + return m_pImpl->IsDefaultFilterReadonly( eFactory ); +} + +sal_Int32 SvtModuleOptions::GetFactoryIcon( EFactory eFactory ) const +{ + std::unique_lock aGuard( impl_GetOwnStaticMutex() ); + return m_pImpl->GetFactoryIcon( eFactory ); +} + +bool SvtModuleOptions::ClassifyFactoryByName( std::u16string_view sName , + EFactory& eFactory ) +{ + // We don't need any mutex here ... because we don't use any member here! + return SvtModuleOptions_Impl::ClassifyFactoryByName( sName, eFactory ); +} + +void SvtModuleOptions::SetFactoryStandardTemplate( EFactory eFactory , + const OUString& sTemplate ) +{ + std::unique_lock aGuard( impl_GetOwnStaticMutex() ); + m_pImpl->SetFactoryStandardTemplate( eFactory, sTemplate ); +} + +void SvtModuleOptions::SetFactoryDefaultFilter( EFactory eFactory, + const OUString& sFilter ) +{ + std::unique_lock aGuard( impl_GetOwnStaticMutex() ); + m_pImpl->SetFactoryDefaultFilter( eFactory, sFilter ); +} + +bool SvtModuleOptions::IsMath() const +{ + // doesn't need mutex, never modified + return m_pImpl->IsModuleInstalled( EModule::MATH ); +} + +bool SvtModuleOptions::IsChart() const +{ + // doesn't need mutex, never modified + return m_pImpl->IsModuleInstalled( EModule::CHART ); +} + +bool SvtModuleOptions::IsCalc() const +{ + // doesn't need mutex, never modified + return m_pImpl->IsModuleInstalled( EModule::CALC ); +} + +bool SvtModuleOptions::IsDraw() const +{ + // doesn't need mutex, never modified + return m_pImpl->IsModuleInstalled( EModule::DRAW ); +} + +bool SvtModuleOptions::IsWriter() const +{ + std::unique_lock aGuard( impl_GetOwnStaticMutex() ); + return m_pImpl->IsModuleInstalled( EModule::WRITER ); +} + +bool SvtModuleOptions::IsImpress() const +{ + // doesn't need mutex, never modified + return m_pImpl->IsModuleInstalled( EModule::IMPRESS ); +} + +bool SvtModuleOptions::IsDataBase() const +{ + // doesn't need mutex, never modified + return m_pImpl->IsModuleInstalled( EModule::DATABASE ); +} + +OUString SvtModuleOptions::GetModuleName( EModule eModule ) const +{ + switch( eModule ) + { + case SvtModuleOptions::EModule::WRITER : { return "Writer"; } + case SvtModuleOptions::EModule::WEB : { return "Web"; } + case SvtModuleOptions::EModule::GLOBAL : { return "Global"; } + case SvtModuleOptions::EModule::CALC : { return "Calc"; } + case SvtModuleOptions::EModule::DRAW : { return "Draw"; } + case SvtModuleOptions::EModule::IMPRESS : { return "Impress"; } + case SvtModuleOptions::EModule::MATH : { return "Math"; } + case SvtModuleOptions::EModule::CHART : { return "Chart"; } + case SvtModuleOptions::EModule::BASIC : { return "Basic"; } + case SvtModuleOptions::EModule::DATABASE : { return "Database"; } + default: + OSL_FAIL( "unknown module" ); + break; + } + + return OUString(); +} + +SvtModuleOptions::EFactory SvtModuleOptions::ClassifyFactoryByShortName(std::u16string_view sName) +{ + if ( sName == u"swriter" ) + return EFactory::WRITER; + if (o3tl::equalsIgnoreAsciiCase(sName, u"swriter/Web")) // sometimes they are registered for swriter/web :-( + return EFactory::WRITERWEB; + if (o3tl::equalsIgnoreAsciiCase(sName, u"swriter/GlobalDocument")) // sometimes they are registered for swriter/globaldocument :-( + return EFactory::WRITERGLOBAL; + if ( sName == u"scalc" ) + return EFactory::CALC; + if ( sName == u"sdraw" ) + return EFactory::DRAW; + if ( sName == u"simpress" ) + return EFactory::IMPRESS; + if ( sName == u"schart" ) + return EFactory::CHART; + if ( sName == u"smath" ) + return EFactory::MATH; + if ( sName == u"sbasic" ) + return EFactory::BASIC; + if ( sName == u"sdatabase" ) + return EFactory::DATABASE; + + return EFactory::UNKNOWN_FACTORY; +} + +SvtModuleOptions::EFactory SvtModuleOptions::ClassifyFactoryByServiceName(std::u16string_view sName) +{ + if (sName == FACTORYNAME_WRITERGLOBAL) + return EFactory::WRITERGLOBAL; + if (sName == FACTORYNAME_WRITERWEB) + return EFactory::WRITERWEB; + if (sName == FACTORYNAME_WRITER) + return EFactory::WRITER; + if (sName == FACTORYNAME_CALC) + return EFactory::CALC; + if (sName == FACTORYNAME_DRAW) + return EFactory::DRAW; + if (sName == FACTORYNAME_IMPRESS) + return EFactory::IMPRESS; + if (sName == FACTORYNAME_MATH) + return EFactory::MATH; + if (sName == FACTORYNAME_CHART) + return EFactory::CHART; + if (sName == FACTORYNAME_DATABASE) + return EFactory::DATABASE; + if (sName == FACTORYNAME_STARTMODULE) + return EFactory::STARTMODULE; + if (sName == FACTORYNAME_BASIC) + return EFactory::BASIC; + + return EFactory::UNKNOWN_FACTORY; +} + +SvtModuleOptions::EFactory SvtModuleOptions::ClassifyFactoryByURL(const OUString& sURL , + const css::uno::Sequence< css::beans::PropertyValue >& lMediaDescriptor) +{ + css::uno::Reference< css::uno::XComponentContext > xContext = ::comphelper::getProcessComponentContext(); + + css::uno::Reference< css::container::XNameAccess > xFilterCfg; + css::uno::Reference< css::container::XNameAccess > xTypeCfg; + try + { + xFilterCfg.set( + xContext->getServiceManager()->createInstanceWithContext("com.sun.star.document.FilterFactory", xContext), css::uno::UNO_QUERY); + xTypeCfg.set( + xContext->getServiceManager()->createInstanceWithContext("com.sun.star.document.TypeDetection", xContext), css::uno::UNO_QUERY); + } + catch(const css::uno::RuntimeException&) + { throw; } + catch(const css::uno::Exception&) + { return EFactory::UNKNOWN_FACTORY; } + + ::comphelper::SequenceAsHashMap stlDesc(lMediaDescriptor); + + // is there already a filter inside the descriptor? + OUString sFilterName = stlDesc.getUnpackedValueOrDefault("FilterName", OUString()); + if (!sFilterName.isEmpty()) + { + try + { + ::comphelper::SequenceAsHashMap stlFilterProps (xFilterCfg->getByName(sFilterName)); + OUString sDocumentService = stlFilterProps.getUnpackedValueOrDefault("DocumentService", OUString()); + SvtModuleOptions::EFactory eApp = SvtModuleOptions::ClassifyFactoryByServiceName(sDocumentService); + + if (eApp != EFactory::UNKNOWN_FACTORY) + return eApp; + } + catch(const css::uno::RuntimeException&) + { throw; } + catch(const css::uno::Exception&) + { /* do nothing here ... may the following code can help!*/ } + } + + // is there already a type inside the descriptor? + OUString sTypeName = stlDesc.getUnpackedValueOrDefault("TypeName", OUString()); + if (sTypeName.isEmpty()) + { + // no :-( + // start flat detection of URL + css::uno::Reference< css::document::XTypeDetection > xDetect(xTypeCfg, css::uno::UNO_QUERY); + sTypeName = xDetect->queryTypeByURL(sURL); + } + + if (sTypeName.isEmpty()) + return EFactory::UNKNOWN_FACTORY; + + // yes - there is a type info + // Try to find the preferred filter. + try + { + ::comphelper::SequenceAsHashMap stlTypeProps (xTypeCfg->getByName(sTypeName)); + OUString sPreferredFilter = stlTypeProps.getUnpackedValueOrDefault("PreferredFilter", OUString()); + ::comphelper::SequenceAsHashMap stlFilterProps (xFilterCfg->getByName(sPreferredFilter)); + OUString sDocumentService = stlFilterProps.getUnpackedValueOrDefault("DocumentService", OUString()); + SvtModuleOptions::EFactory eApp = SvtModuleOptions::ClassifyFactoryByServiceName(sDocumentService); + + if (eApp != EFactory::UNKNOWN_FACTORY) + return eApp; + } + catch(const css::uno::RuntimeException&) + { throw; } + catch(const css::uno::Exception&) + { /* do nothing here ... may the following code can help!*/ } + + // no filter/no type/no detection result => no fun :-) + return EFactory::UNKNOWN_FACTORY; +} + +SvtModuleOptions::EFactory SvtModuleOptions::ClassifyFactoryByModel(const css::uno::Reference< css::frame::XModel >& xModel) +{ + css::uno::Reference< css::lang::XServiceInfo > xInfo(xModel, css::uno::UNO_QUERY); + if (!xInfo.is()) + return EFactory::UNKNOWN_FACTORY; + + const css::uno::Sequence< OUString > lServices = xInfo->getSupportedServiceNames(); + + for (const OUString& rService : lServices) + { + SvtModuleOptions::EFactory eApp = SvtModuleOptions::ClassifyFactoryByServiceName(rService); + if (eApp != EFactory::UNKNOWN_FACTORY) + return eApp; + } + + return EFactory::UNKNOWN_FACTORY; +} + +css::uno::Sequence < OUString > SvtModuleOptions::GetAllServiceNames() +{ + std::unique_lock aGuard( impl_GetOwnStaticMutex() ); + return m_pImpl->GetAllServiceNames(); +} + +OUString SvtModuleOptions::GetDefaultModuleName() const +{ + OUString aModule; + if (m_pImpl->IsModuleInstalled(SvtModuleOptions::EModule::WRITER)) + aModule = GetFactoryShortName(SvtModuleOptions::EFactory::WRITER); + else if (m_pImpl->IsModuleInstalled(SvtModuleOptions::EModule::CALC)) + aModule = GetFactoryShortName(SvtModuleOptions::EFactory::CALC); + else if (m_pImpl->IsModuleInstalled(SvtModuleOptions::EModule::IMPRESS)) + aModule = GetFactoryShortName(SvtModuleOptions::EFactory::IMPRESS); + else if (m_pImpl->IsModuleInstalled(SvtModuleOptions::EModule::DATABASE)) + aModule = GetFactoryShortName(SvtModuleOptions::EFactory::DATABASE); + else if (m_pImpl->IsModuleInstalled(SvtModuleOptions::EModule::DRAW)) + aModule = GetFactoryShortName(SvtModuleOptions::EFactory::DRAW); + else if (m_pImpl->IsModuleInstalled(SvtModuleOptions::EModule::WEB)) + aModule = GetFactoryShortName(SvtModuleOptions::EFactory::WRITERWEB); + else if (m_pImpl->IsModuleInstalled(SvtModuleOptions::EModule::GLOBAL)) + aModule = GetFactoryShortName(SvtModuleOptions::EFactory::WRITERGLOBAL); + else if (m_pImpl->IsModuleInstalled(SvtModuleOptions::EModule::MATH)) + aModule = GetFactoryShortName(SvtModuleOptions::EFactory::MATH); + return aModule; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/options.cxx b/unotools/source/config/options.cxx new file mode 100644 index 000000000..4da44fa27 --- /dev/null +++ b/unotools/source/config/options.cxx @@ -0,0 +1,114 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * 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/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <sal/config.h> +#include <unotools/options.hxx> + +#include <algorithm> + +using utl::detail::Options; +using utl::ConfigurationBroadcaster; + +utl::ConfigurationListener::~ConfigurationListener() {} + +ConfigurationBroadcaster::ConfigurationBroadcaster() +: m_nBroadcastBlocked( 0 ) +, m_nBlockedHint( ConfigurationHints::NONE ) +{ +} + +ConfigurationBroadcaster::ConfigurationBroadcaster(ConfigurationBroadcaster const & rSource) +: mpList( rSource.mpList ? new IMPL_ConfigurationListenerList(*rSource.mpList) : nullptr ) +, m_nBroadcastBlocked( rSource.m_nBroadcastBlocked ) +, m_nBlockedHint( rSource.m_nBlockedHint ) +{ +} + +ConfigurationBroadcaster::~ConfigurationBroadcaster() +{ +} + +ConfigurationBroadcaster & ConfigurationBroadcaster::operator =( + ConfigurationBroadcaster const & other) +{ + if (&other != this) { + mpList.reset( + other.mpList == nullptr ? nullptr : new IMPL_ConfigurationListenerList(*other.mpList)); + m_nBroadcastBlocked = other.m_nBroadcastBlocked; + m_nBlockedHint = other.m_nBlockedHint; + } + return *this; +} + +void ConfigurationBroadcaster::AddListener( utl::ConfigurationListener* pListener ) +{ + if ( !mpList ) + mpList.reset(new IMPL_ConfigurationListenerList); + mpList->push_back( pListener ); +} + +void ConfigurationBroadcaster::RemoveListener( utl::ConfigurationListener const * pListener ) +{ + if ( mpList ) { + auto it = std::find(mpList->begin(), mpList->end(), pListener); + if ( it != mpList->end() ) + mpList->erase( it ); + } +} + +void ConfigurationBroadcaster::NotifyListeners( ConfigurationHints nHint ) +{ + if ( m_nBroadcastBlocked ) + m_nBlockedHint |= nHint; + else + { + nHint |= m_nBlockedHint; + m_nBlockedHint = ConfigurationHints::NONE; + if ( mpList ) { + for ( size_t n = 0; n < mpList->size(); n++ ) + (*mpList)[ n ]->ConfigurationChanged( this, nHint ); + } + } +} + +void ConfigurationBroadcaster::BlockBroadcasts( bool bBlock ) +{ + if ( bBlock ) + ++m_nBroadcastBlocked; + else if ( m_nBroadcastBlocked ) + { + if ( --m_nBroadcastBlocked == 0 ) + NotifyListeners( ConfigurationHints::NONE ); + } +} + +Options::Options() +{ +} + +Options::~Options() +{ +} + +void Options::ConfigurationChanged( ConfigurationBroadcaster*, ConfigurationHints nHint ) +{ + NotifyListeners( nHint ); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/optionsdlg.cxx b/unotools/source/config/optionsdlg.cxx new file mode 100644 index 000000000..cc5ee7a60 --- /dev/null +++ b/unotools/source/config/optionsdlg.cxx @@ -0,0 +1,152 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * 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/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <unotools/optionsdlg.hxx> +#include <unotools/configitem.hxx> +#include <unotools/configmgr.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> + +#include <cassert> + +using namespace com::sun::star::beans; +using namespace com::sun::star::uno; + +constexpr OUStringLiteral ROOT_NODE = u"OptionsDialogGroups"; +constexpr OUStringLiteral PAGES_NODE = u"Pages"; +constexpr OUStringLiteral OPTIONS_NODE = u"Options"; + +namespace { + enum NodeType{ NT_Group, NT_Page, NT_Option }; +} +constexpr OUStringLiteral g_sPathDelimiter = u"/"; +static void ReadNode( + const Reference<css::container::XHierarchicalNameAccess>& xHierarchyAccess, + SvtOptionsDialogOptions::OptionNodeList & aOptionNodeList, + std::u16string_view _rNode, NodeType _eType ); + + +SvtOptionsDialogOptions::SvtOptionsDialogOptions() +{ + Reference<css::container::XHierarchicalNameAccess> xHierarchyAccess = utl::ConfigManager::acquireTree(u"Office.OptionsDialog"); + const Sequence< OUString > aNodeSeq = utl::ConfigItem::GetNodeNames( xHierarchyAccess, ROOT_NODE, utl::ConfigNameFormat::LocalPath); + OUString sNode( ROOT_NODE + g_sPathDelimiter ); + for ( const auto& rNode : aNodeSeq ) + { + OUString sSubNode( sNode + rNode ); + ReadNode( xHierarchyAccess, m_aOptionNodeList, sSubNode, NT_Group ); + } +} + + +static void ReadNode( + const Reference<css::container::XHierarchicalNameAccess>& xHierarchyAccess, + SvtOptionsDialogOptions::OptionNodeList & aOptionNodeList, + std::u16string_view _rNode, NodeType _eType ) +{ + OUString sNode( _rNode + g_sPathDelimiter ); + OUString sSet; + sal_Int32 nLen = 0; + switch ( _eType ) + { + case NT_Group : + { + sSet = PAGES_NODE; + nLen = 2; + break; + } + + case NT_Page : + { + sSet = OPTIONS_NODE; + nLen = 2; + break; + } + + case NT_Option : + { + nLen = 1; + break; + } + } + + assert(nLen > 0); + + Sequence< OUString > lResult( nLen ); + auto plResult = lResult.getArray(); + plResult[0] = sNode + "Hide"; + if ( _eType != NT_Option ) + plResult[1] = sNode + sSet; + + Sequence< Any > aValues = utl::ConfigItem::GetProperties( xHierarchyAccess, lResult, /*bAllLocales*/false ); + bool bHide = false; + if ( aValues[0] >>= bHide ) + aOptionNodeList.emplace( sNode, bHide ); + + if ( _eType != NT_Option ) + { + OUString sNodes( sNode + sSet ); + const Sequence< OUString > aNodes = utl::ConfigItem::GetNodeNames( xHierarchyAccess, sNodes, utl::ConfigNameFormat::LocalPath ); + for ( const auto& rNode : aNodes ) + { + OUString sSubNodeName( sNodes + g_sPathDelimiter + rNode ); + ReadNode( xHierarchyAccess, aOptionNodeList, sSubNodeName, _eType == NT_Group ? NT_Page : NT_Option ); + } + } +} + +static OUString getGroupPath( std::u16string_view _rGroup ) +{ + return OUString( OUString::Concat(ROOT_NODE) + "/" + _rGroup + "/" ); +} +static OUString getPagePath( std::u16string_view _rPage ) +{ + return OUString( OUString::Concat(PAGES_NODE) + "/" + _rPage + "/" ); +} +static OUString getOptionPath( std::u16string_view _rOption ) +{ + return OUString( OUString::Concat(OPTIONS_NODE) + "/" + _rOption + "/" ); +} + +bool SvtOptionsDialogOptions::IsHidden( const OUString& _rPath ) const +{ + bool bRet = false; + OptionNodeList::const_iterator pIter = m_aOptionNodeList.find( _rPath ); + if ( pIter != m_aOptionNodeList.end() ) + bRet = pIter->second; + return bRet; +} + +bool SvtOptionsDialogOptions::IsGroupHidden( std::u16string_view _rGroup ) const +{ + return IsHidden( getGroupPath( _rGroup ) ); +} + +bool SvtOptionsDialogOptions::IsPageHidden( std::u16string_view _rPage, std::u16string_view _rGroup ) const +{ + return IsHidden( getGroupPath( _rGroup ) + getPagePath( _rPage ) ); +} + +bool SvtOptionsDialogOptions::IsOptionHidden( + std::u16string_view _rOption, std::u16string_view _rPage, std::u16string_view _rGroup ) const +{ + return IsHidden( getGroupPath( _rGroup ) + getPagePath( _rPage ) + getOptionPath( _rOption ) ); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/pathoptions.cxx b/unotools/source/config/pathoptions.cxx new file mode 100644 index 000000000..c1a536270 --- /dev/null +++ b/unotools/source/config/pathoptions.cxx @@ -0,0 +1,851 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * 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/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <sal/config.h> + +#include <sal/log.hxx> +#include <unotools/pathoptions.hxx> +#include <tools/diagnose_ex.h> +#include <tools/urlobj.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> +#include <osl/mutex.hxx> +#include <osl/file.hxx> + +#include <unotools/ucbhelper.hxx> +#include <comphelper/getexpandeduri.hxx> +#include <comphelper/processfactory.hxx> +#include <com/sun/star/beans/XFastPropertySet.hpp> +#include <com/sun/star/beans/XPropertySetInfo.hpp> +#include <com/sun/star/util/thePathSettings.hpp> +#include <com/sun/star/util/PathSubstitution.hpp> +#include <com/sun/star/util/XStringSubstitution.hpp> +#include <com/sun/star/util/theMacroExpander.hpp> +#include <o3tl/enumarray.hxx> +#include <o3tl/string_view.hxx> + +#include "itemholder1.hxx" + +#include <set> +#include <unordered_map> + +using namespace osl; +using namespace utl; +using namespace com::sun::star::uno; +using namespace com::sun::star::beans; +using namespace com::sun::star::util; +using namespace com::sun::star::lang; + +#define SEARCHPATH_DELIMITER ';' +#define SIGN_STARTVARIABLE "$(" +#define SIGN_ENDVARIABLE ")" + +// Supported variables by the old SvtPathOptions implementation +#define SUBSTITUTE_INSTPATH "$(instpath)" +#define SUBSTITUTE_PROGPATH "$(progpath)" +#define SUBSTITUTE_USERPATH "$(userpath)" +#define SUBSTITUTE_PATH "$(path)" + +#define STRPOS_NOTFOUND -1 + +typedef std::unordered_map<OUString, sal_Int32> NameToHandleMap; + +typedef std::set<OUString> VarNameSet; + +// class SvtPathOptions_Impl --------------------------------------------- +class SvtPathOptions_Impl +{ + private: + // Local variables to return const references + o3tl::enumarray< SvtPathOptions::Paths, OUString > m_aPathArray; + Reference< XFastPropertySet > m_xPathSettings; + Reference< XStringSubstitution > m_xSubstVariables; + Reference< XMacroExpander > m_xMacroExpander; + mutable std::unordered_map<SvtPathOptions::Paths, sal_Int32> + m_aMapEnumToPropHandle; + VarNameSet m_aSystemPathVarNames; + + OUString m_aEmptyString; + mutable std::mutex m_aMutex; + + public: + SvtPathOptions_Impl(); + + // get the paths, not const because of using a mutex + const OUString& GetPath( SvtPathOptions::Paths ); + const OUString& GetAddinPath() { return GetPath( SvtPathOptions::Paths::AddIn ); } + const OUString& GetAutoCorrectPath() { return GetPath( SvtPathOptions::Paths::AutoCorrect ); } + const OUString& GetAutoTextPath() { return GetPath( SvtPathOptions::Paths::AutoText ); } + const OUString& GetBackupPath() { return GetPath( SvtPathOptions::Paths::Backup ); } + const OUString& GetBasicPath() { return GetPath( SvtPathOptions::Paths::Basic ); } + const OUString& GetBitmapPath() { return GetPath( SvtPathOptions::Paths::Bitmap ); } + const OUString& GetConfigPath() { return GetPath( SvtPathOptions::Paths::Config ); } + const OUString& GetDictionaryPath() { return GetPath( SvtPathOptions::Paths::Dictionary ); } + const OUString& GetFavoritesPath() { return GetPath( SvtPathOptions::Paths::Favorites ); } + const OUString& GetFilterPath() { return GetPath( SvtPathOptions::Paths::Filter ); } + const OUString& GetGalleryPath() { return GetPath( SvtPathOptions::Paths::Gallery ); } + const OUString& GetGraphicPath() { return GetPath( SvtPathOptions::Paths::Graphic ); } + const OUString& GetHelpPath() { return GetPath( SvtPathOptions::Paths::Help ); } + const OUString& GetLinguisticPath() { return GetPath( SvtPathOptions::Paths::Linguistic ); } + const OUString& GetModulePath() { return GetPath( SvtPathOptions::Paths::Module ); } + const OUString& GetPalettePath() { return GetPath( SvtPathOptions::Paths::Palette ); } + const OUString& GetIconsetPath() { return GetPath( SvtPathOptions::Paths::IconSet); } + const OUString& GetPluginPath() { return GetPath( SvtPathOptions::Paths::Plugin ); } + const OUString& GetStoragePath() { return GetPath( SvtPathOptions::Paths::Storage ); } + const OUString& GetTempPath() { return GetPath( SvtPathOptions::Paths::Temp ); } + const OUString& GetTemplatePath() { return GetPath( SvtPathOptions::Paths::Template ); } + const OUString& GetUserConfigPath() { return GetPath( SvtPathOptions::Paths::UserConfig ); } + const OUString& GetWorkPath() { return GetPath( SvtPathOptions::Paths::Work ); } + const OUString& GetUIConfigPath() { return GetPath( SvtPathOptions::Paths::UIConfig ); } + const OUString& GetFingerprintPath() { return GetPath( SvtPathOptions::Paths::Fingerprint ); } + const OUString& GetNumbertextPath() { return GetPath( SvtPathOptions::Paths::NumberText ); } + const OUString& GetClassificationPath() { return GetPath( SvtPathOptions::Paths::Classification ); } + + // set the paths + void SetPath( SvtPathOptions::Paths, const OUString& rNewPath ); + void SetAddinPath( const OUString& rPath ) { SetPath( SvtPathOptions::Paths::AddIn, rPath ); } + void SetAutoCorrectPath( const OUString& rPath ) { SetPath( SvtPathOptions::Paths::AutoCorrect, rPath ); } + void SetAutoTextPath( const OUString& rPath ) { SetPath( SvtPathOptions::Paths::AutoText, rPath ); } + void SetBackupPath( const OUString& rPath ) { SetPath( SvtPathOptions::Paths::Backup, rPath ); } + void SetBasicPath( const OUString& rPath ) { SetPath( SvtPathOptions::Paths::Basic, rPath ); } + void SetBitmapPath( const OUString& rPath ) { SetPath( SvtPathOptions::Paths::Bitmap, rPath ); } + void SetConfigPath( const OUString& rPath ) { SetPath( SvtPathOptions::Paths::Config, rPath ); } + void SetDictionaryPath( const OUString& rPath ) { SetPath( SvtPathOptions::Paths::Dictionary, rPath ); } + void SetFavoritesPath( const OUString& rPath ) { SetPath( SvtPathOptions::Paths::Favorites, rPath ); } + void SetFilterPath( const OUString& rPath ) { SetPath( SvtPathOptions::Paths::Filter, rPath ); } + void SetGalleryPath( const OUString& rPath ) { SetPath( SvtPathOptions::Paths::Gallery, rPath ); } + void SetGraphicPath( const OUString& rPath ) { SetPath( SvtPathOptions::Paths::Graphic, rPath ); } + void SetHelpPath( const OUString& rPath ) { SetPath( SvtPathOptions::Paths::Help, rPath ); } + void SetLinguisticPath( const OUString& rPath ) { SetPath( SvtPathOptions::Paths::Linguistic, rPath ); } + void SetModulePath( const OUString& rPath ) { SetPath( SvtPathOptions::Paths::Module, rPath ); } + void SetPalettePath( const OUString& rPath ) { SetPath( SvtPathOptions::Paths::Palette, rPath ); } + void SetPluginPath( const OUString& rPath ) { SetPath( SvtPathOptions::Paths::Plugin, rPath ); } + void SetStoragePath( const OUString& rPath ) { SetPath( SvtPathOptions::Paths::Storage, rPath ); } + void SetTempPath( const OUString& rPath ) { SetPath( SvtPathOptions::Paths::Temp, rPath ); } + void SetTemplatePath( const OUString& rPath ) { SetPath( SvtPathOptions::Paths::Template, rPath ); } + void SetUserConfigPath( const OUString& rPath ) { SetPath( SvtPathOptions::Paths::UserConfig, rPath ); } + void SetWorkPath( const OUString& rPath ) { SetPath( SvtPathOptions::Paths::Work, rPath ); } + + OUString SubstVar( const OUString& rVar ) const; + OUString ExpandMacros( const OUString& rPath ) const; + OUString UsePathVariables( const OUString& rPath ) const; +}; + +// global ---------------------------------------------------------------- + +static std::weak_ptr<SvtPathOptions_Impl> g_pOptions; + +namespace { + +// functions ------------------------------------------------------------- +struct PropertyStruct +{ + const char* pPropName; // The ascii name of the Office path + SvtPathOptions::Paths ePath; // The enum value used by SvtPathOptions +}; + +struct VarNameAttribute +{ + const char* pVarName; // The name of the path variable +}; + +} + +const PropertyStruct aPropNames[] = +{ + { "Addin", SvtPathOptions::Paths::AddIn }, + { "AutoCorrect", SvtPathOptions::Paths::AutoCorrect }, + { "AutoText", SvtPathOptions::Paths::AutoText }, + { "Backup", SvtPathOptions::Paths::Backup }, + { "Basic", SvtPathOptions::Paths::Basic }, + { "Bitmap", SvtPathOptions::Paths::Bitmap }, + { "Config", SvtPathOptions::Paths::Config }, + { "Dictionary", SvtPathOptions::Paths::Dictionary }, + { "Favorite", SvtPathOptions::Paths::Favorites }, + { "Filter", SvtPathOptions::Paths::Filter }, + { "Gallery", SvtPathOptions::Paths::Gallery }, + { "Graphic", SvtPathOptions::Paths::Graphic }, + { "Help", SvtPathOptions::Paths::Help }, + { "Iconset", SvtPathOptions::Paths::IconSet }, + { "Linguistic", SvtPathOptions::Paths::Linguistic }, + { "Module", SvtPathOptions::Paths::Module }, + { "Palette", SvtPathOptions::Paths::Palette }, + { "Plugin", SvtPathOptions::Paths::Plugin }, + { "Storage", SvtPathOptions::Paths::Storage }, + { "Temp", SvtPathOptions::Paths::Temp }, + { "Template", SvtPathOptions::Paths::Template }, + { "UserConfig", SvtPathOptions::Paths::UserConfig }, + { "Work", SvtPathOptions::Paths::Work }, + { "UIConfig", SvtPathOptions::Paths::UIConfig }, + { "Fingerprint", SvtPathOptions::Paths::Fingerprint }, + { "Numbertext", SvtPathOptions::Paths::NumberText }, + { "Classification", SvtPathOptions::Paths::Classification } +}; + +const VarNameAttribute aVarNameAttribute[] = +{ + { SUBSTITUTE_INSTPATH }, // $(instpath) + { SUBSTITUTE_PROGPATH }, // $(progpath) + { SUBSTITUTE_USERPATH }, // $(userpath) + { SUBSTITUTE_PATH }, // $(path) +}; + +// class SvtPathOptions_Impl --------------------------------------------- + +const OUString& SvtPathOptions_Impl::GetPath( SvtPathOptions::Paths ePath ) +{ + std::unique_lock aGuard( m_aMutex ); + + try + { + OUString aPathValue; + sal_Int32 nHandle = m_aMapEnumToPropHandle[ePath]; + + // Substitution is done by the service itself using the substitution service + Any a = m_xPathSettings->getFastPropertyValue( nHandle ); + a >>= aPathValue; + if( ePath == SvtPathOptions::Paths::AddIn || + ePath == SvtPathOptions::Paths::Filter || + ePath == SvtPathOptions::Paths::Help || + ePath == SvtPathOptions::Paths::Module || + ePath == SvtPathOptions::Paths::Plugin || + ePath == SvtPathOptions::Paths::Storage + ) + { + // These office paths have to be converted to system pates + OUString aResult; + osl::FileBase::getSystemPathFromFileURL( aPathValue, aResult ); + aPathValue = aResult; + } + else if (ePath == SvtPathOptions::Paths::Palette || + ePath == SvtPathOptions::Paths::IconSet) + { + auto ctx = comphelper::getProcessComponentContext(); + OUStringBuffer buf(aPathValue.getLength()*2); + for (sal_Int32 i = 0;;) + { + buf.append( + comphelper::getExpandedUri( + ctx, aPathValue.getToken(0, ';', i))); + if (i == -1) { + break; + } + buf.append(';'); + } + aPathValue = buf.makeStringAndClear(); + } + + m_aPathArray[ ePath ] = aPathValue; + return m_aPathArray[ ePath ]; + } + catch (UnknownPropertyException &) + { + } + + return m_aEmptyString; +} + +void SvtPathOptions_Impl::SetPath( SvtPathOptions::Paths ePath, const OUString& rNewPath ) +{ + std::unique_lock aGuard( m_aMutex ); + + OUString aResult; + OUString aNewValue; + Any a; + + switch ( ePath ) + { + case SvtPathOptions::Paths::AddIn: + case SvtPathOptions::Paths::Filter: + case SvtPathOptions::Paths::Help: + case SvtPathOptions::Paths::Module: + case SvtPathOptions::Paths::Plugin: + case SvtPathOptions::Paths::Storage: + { + // These office paths have to be convert back to UCB-URL's + osl::FileBase::getFileURLFromSystemPath( rNewPath, aResult ); + aNewValue = aResult; + } + break; + + default: + aNewValue = rNewPath; + } + + // Resubstitution is done by the service itself using the substitution service + a <<= aNewValue; + try + { + m_xPathSettings->setFastPropertyValue( m_aMapEnumToPropHandle[ePath], a ); + } + catch (const Exception&) + { + TOOLS_WARN_EXCEPTION("unotools.config", "SetPath"); + } +} + +OUString SvtPathOptions_Impl::ExpandMacros( const OUString& rPath ) const +{ + OUString sExpanded( rPath ); + + const INetURLObject aParser( rPath ); + if ( aParser.GetProtocol() == INetProtocol::VndSunStarExpand ) + sExpanded = m_xMacroExpander->expandMacros( aParser.GetURLPath( INetURLObject::DecodeMechanism::WithCharset ) ); + + return sExpanded; +} + +OUString SvtPathOptions_Impl::UsePathVariables( const OUString& rPath ) const +{ + return m_xSubstVariables->reSubstituteVariables( rPath ); +} + +OUString SvtPathOptions_Impl::SubstVar( const OUString& rVar ) const +{ + // Don't work at parameter-string directly. Copy it. + OUString aWorkText = rVar; + + // Convert the returned path to system path! + bool bConvertLocal = false; + + // Search for first occurrence of "$(...". + sal_Int32 nPosition = aWorkText.indexOf( SIGN_STARTVARIABLE ); // = first position of "$(" in string + sal_Int32 nLength = 0; // = count of letters from "$(" to ")" in string + + // Have we found any variable like "$(...)"? + if ( nPosition != STRPOS_NOTFOUND ) + { + // Yes; Get length of found variable. + // If no ")" was found - nLength is set to 0 by default! see before. + sal_Int32 nEndPosition = aWorkText.indexOf( SIGN_ENDVARIABLE, nPosition ); + if ( nEndPosition != STRPOS_NOTFOUND ) + nLength = nEndPosition - nPosition + 1; + } + + // Is there another path variable? + while ( ( nPosition != STRPOS_NOTFOUND ) && ( nLength > 0 ) ) + { + // YES; Get the next variable for replace. + OUString aSubString = aWorkText.copy( nPosition, nLength ); + aSubString = aSubString.toAsciiLowerCase(); + + // Look for special variable that needs a system path. + VarNameSet::const_iterator pIter = m_aSystemPathVarNames.find( aSubString ); + if ( pIter != m_aSystemPathVarNames.end() ) + bConvertLocal = true; + + nPosition += nLength; + + // We must control index in string before call something at OUString! + // The OUString-implementation don't do it for us :-( but the result is not defined otherwise. + if ( nPosition + 1 > aWorkText.getLength() ) + { + // Position is out of range. Break loop! + nPosition = STRPOS_NOTFOUND; + nLength = 0; + } + else + { + // Else; Position is valid. Search for next variable. + nPosition = aWorkText.indexOf( SIGN_STARTVARIABLE, nPosition ); + // Have we found any variable like "$(...)"? + if ( nPosition != STRPOS_NOTFOUND ) + { + // Yes; Get length of found variable. If no ")" was found - nLength must set to 0! + nLength = 0; + sal_Int32 nEndPosition = aWorkText.indexOf( SIGN_ENDVARIABLE, nPosition ); + if ( nEndPosition != STRPOS_NOTFOUND ) + nLength = nEndPosition - nPosition + 1; + } + } + } + + aWorkText = m_xSubstVariables->substituteVariables( rVar, false ); + + if ( bConvertLocal ) + { + // Convert the URL to a system path for special path variables + OUString aReturn; + osl::FileBase::getSystemPathFromFileURL( aWorkText, aReturn ); + return aReturn; + } + + return aWorkText; +} + +SvtPathOptions_Impl::SvtPathOptions_Impl() +{ + Reference< XComponentContext > xContext = comphelper::getProcessComponentContext(); + + // Create necessary services + Reference< XPathSettings > xPathSettings = thePathSettings::get(xContext); + m_xPathSettings.set( xPathSettings, UNO_QUERY_THROW ); + m_xSubstVariables.set( PathSubstitution::create(xContext) ); + m_xMacroExpander = theMacroExpander::get(xContext); + + // Create temporary hash map to have a mapping between property names and property handles + Reference< XPropertySetInfo > xPropSetInfo = xPathSettings->getPropertySetInfo(); + const Sequence< Property > aPathPropSeq = xPropSetInfo->getProperties(); + + NameToHandleMap aTempHashMap; + for ( const css::beans::Property& aProperty : aPathPropSeq ) + { + aTempHashMap.emplace(aProperty.Name, aProperty.Handle); + } + + // Create mapping between internal enum (SvtPathOptions::Paths) and property handle + for ( auto const & p : aPropNames ) + { + NameToHandleMap::const_iterator pIter = + aTempHashMap.find( OUString::createFromAscii( p.pPropName )); + + if ( pIter != aTempHashMap.end() ) + { + sal_Int32 nHandle = pIter->second; + SvtPathOptions::Paths nEnum = p.ePath; + m_aMapEnumToPropHandle.emplace( nEnum, nHandle ); + } + } + + // Create hash map for path variables that need a system path as a return value! + for ( auto const & i : aVarNameAttribute ) + { + m_aSystemPathVarNames.insert( OUString::createFromAscii( i.pVarName ) ); + } +} + +// class SvtPathOptions -------------------------------------------------- + +namespace +{ + std::mutex& lclMutex() + { + static std::mutex SINGLETON; + return SINGLETON; + } +} + +SvtPathOptions::SvtPathOptions() +{ + // Global access, must be guarded (multithreading) + std::unique_lock aGuard( lclMutex() ); + pImpl = g_pOptions.lock(); + if ( !pImpl ) + { + pImpl = std::make_shared<SvtPathOptions_Impl>(); + g_pOptions = pImpl; + aGuard.unlock(); // because holdConfigItem will call this constructor + ItemHolder1::holdConfigItem(EItem::PathOptions); + } +} + +SvtPathOptions::~SvtPathOptions() +{ + // Global access, must be guarded (multithreading) + std::unique_lock aGuard( lclMutex() ); + + pImpl.reset(); +} + +const OUString& SvtPathOptions::GetAddinPath() const +{ + return pImpl->GetAddinPath(); +} + +const OUString& SvtPathOptions::GetAutoCorrectPath() const +{ + return pImpl->GetAutoCorrectPath(); +} + +const OUString& SvtPathOptions::GetAutoTextPath() const +{ + return pImpl->GetAutoTextPath(); +} + +const OUString& SvtPathOptions::GetBackupPath() const +{ + return pImpl->GetBackupPath(); +} + +const OUString& SvtPathOptions::GetBasicPath() const +{ + return pImpl->GetBasicPath(); +} + +const OUString& SvtPathOptions::GetBitmapPath() const +{ + return pImpl->GetBitmapPath(); +} + +const OUString& SvtPathOptions::GetConfigPath() const +{ + return pImpl->GetConfigPath(); +} + +const OUString& SvtPathOptions::GetDictionaryPath() const +{ + return pImpl->GetDictionaryPath(); +} + +const OUString& SvtPathOptions::GetFavoritesPath() const +{ + return pImpl->GetFavoritesPath(); +} + +const OUString& SvtPathOptions::GetFilterPath() const +{ + return pImpl->GetFilterPath(); +} + +const OUString& SvtPathOptions::GetGalleryPath() const +{ + return pImpl->GetGalleryPath(); +} + +const OUString& SvtPathOptions::GetGraphicPath() const +{ + return pImpl->GetGraphicPath(); +} + +const OUString& SvtPathOptions::GetHelpPath() const +{ + return pImpl->GetHelpPath(); +} + +const OUString& SvtPathOptions::GetLinguisticPath() const +{ + return pImpl->GetLinguisticPath(); +} + +const OUString& SvtPathOptions::GetFingerprintPath() const +{ + return pImpl->GetFingerprintPath(); +} + +const OUString& SvtPathOptions::GetNumbertextPath() const +{ + return pImpl->GetNumbertextPath(); +} + +const OUString& SvtPathOptions::GetModulePath() const +{ + return pImpl->GetModulePath(); +} + +const OUString& SvtPathOptions::GetPalettePath() const +{ + return pImpl->GetPalettePath(); +} + +const OUString& SvtPathOptions::GetIconsetPath() const +{ + return pImpl->GetIconsetPath(); +} + +const OUString& SvtPathOptions::GetPluginPath() const +{ + return pImpl->GetPluginPath(); +} + +const OUString& SvtPathOptions::GetStoragePath() const +{ + return pImpl->GetStoragePath(); +} + +const OUString& SvtPathOptions::GetTempPath() const +{ + return pImpl->GetTempPath(); +} + +const OUString& SvtPathOptions::GetTemplatePath() const +{ + return pImpl->GetTemplatePath(); +} + +const OUString& SvtPathOptions::GetUserConfigPath() const +{ + return pImpl->GetUserConfigPath(); +} + +const OUString& SvtPathOptions::GetWorkPath() const +{ + return pImpl->GetWorkPath(); +} + +const OUString& SvtPathOptions::GetClassificationPath() const +{ + return pImpl->GetClassificationPath(); +} + +void SvtPathOptions::SetAddinPath( const OUString& rPath ) +{ + pImpl->SetAddinPath( rPath ); +} + +void SvtPathOptions::SetAutoCorrectPath( const OUString& rPath ) +{ + pImpl->SetAutoCorrectPath( rPath ); +} + +void SvtPathOptions::SetAutoTextPath( const OUString& rPath ) +{ + pImpl->SetAutoTextPath( rPath ); +} + +void SvtPathOptions::SetBackupPath( const OUString& rPath ) +{ + pImpl->SetBackupPath( rPath ); +} + +void SvtPathOptions::SetBasicPath( const OUString& rPath ) +{ + pImpl->SetBasicPath( rPath ); +} + +void SvtPathOptions::SetBitmapPath( const OUString& rPath ) +{ + pImpl->SetBitmapPath( rPath ); +} + +void SvtPathOptions::SetConfigPath( const OUString& rPath ) +{ + pImpl->SetConfigPath( rPath ); +} + +void SvtPathOptions::SetDictionaryPath( const OUString& rPath ) +{ + pImpl->SetDictionaryPath( rPath ); +} + +void SvtPathOptions::SetFavoritesPath( const OUString& rPath ) +{ + pImpl->SetFavoritesPath( rPath ); +} + +void SvtPathOptions::SetFilterPath( const OUString& rPath ) +{ + pImpl->SetFilterPath( rPath ); +} + +void SvtPathOptions::SetGalleryPath( const OUString& rPath ) +{ + pImpl->SetGalleryPath( rPath ); +} + +void SvtPathOptions::SetGraphicPath( const OUString& rPath ) +{ + pImpl->SetGraphicPath( rPath ); +} + +void SvtPathOptions::SetHelpPath( const OUString& rPath ) +{ + pImpl->SetHelpPath( rPath ); +} + +void SvtPathOptions::SetLinguisticPath( const OUString& rPath ) +{ + pImpl->SetLinguisticPath( rPath ); +} + +void SvtPathOptions::SetModulePath( const OUString& rPath ) +{ + pImpl->SetModulePath( rPath ); +} + +void SvtPathOptions::SetPalettePath( const OUString& rPath ) +{ + pImpl->SetPalettePath( rPath ); +} + +void SvtPathOptions::SetPluginPath( const OUString& rPath ) +{ + pImpl->SetPluginPath( rPath ); +} + +void SvtPathOptions::SetStoragePath( const OUString& rPath ) +{ + pImpl->SetStoragePath( rPath ); +} + +void SvtPathOptions::SetTempPath( const OUString& rPath ) +{ + pImpl->SetTempPath( rPath ); +} + +void SvtPathOptions::SetTemplatePath( const OUString& rPath ) +{ + pImpl->SetTemplatePath( rPath ); +} + +void SvtPathOptions::SetUserConfigPath( const OUString& rPath ) +{ + pImpl->SetUserConfigPath( rPath ); +} + +void SvtPathOptions::SetWorkPath( const OUString& rPath ) +{ + pImpl->SetWorkPath( rPath ); +} + +OUString SvtPathOptions::SubstituteVariable( const OUString& rVar ) const +{ + return pImpl->SubstVar( rVar ); +} + +OUString SvtPathOptions::ExpandMacros( const OUString& rPath ) const +{ + return pImpl->ExpandMacros( rPath ); +} + +OUString SvtPathOptions::UseVariable( const OUString& rPath ) const +{ + return pImpl->UsePathVariables( rPath ); +} + +bool SvtPathOptions::SearchFile( OUString& rIniFile, SvtPathOptions::Paths ePath ) +{ + // check parameter: empty inifile name? + if ( rIniFile.isEmpty() ) + { + SAL_WARN( "unotools.config", "SvtPathOptions::SearchFile(): invalid parameter" ); + return false; + } + + OUString aIniFile = pImpl->SubstVar( rIniFile ); + bool bRet = false; + + switch ( ePath ) + { + case SvtPathOptions::Paths::UserConfig: + { + // path is a URL + bRet = true; + INetURLObject aObj( GetUserConfigPath() ); + + sal_Int32 nIniIndex = 0; + do + { + std::u16string_view aToken = o3tl::getToken(aIniFile, 0, '/', nIniIndex ); + aObj.insertName(aToken); + } + while ( nIniIndex >= 0 ); + + if ( !::utl::UCBContentHelper::Exists( aObj.GetMainURL( INetURLObject::DecodeMechanism::NONE ) ) ) + { + aObj.SetSmartURL( GetConfigPath() ); + aObj.insertName( aIniFile ); + bRet = ::utl::UCBContentHelper::Exists( aObj.GetMainURL( INetURLObject::DecodeMechanism::NONE ) ); + } + + if ( bRet ) + rIniFile = aObj.GetMainURL( INetURLObject::DecodeMechanism::NONE ); + + break; + } + + default: + { + OUString aPath; + switch ( ePath ) + { + case SvtPathOptions::Paths::AddIn: aPath = GetAddinPath(); break; + case SvtPathOptions::Paths::AutoCorrect: aPath = GetAutoCorrectPath(); break; + case SvtPathOptions::Paths::AutoText: aPath = GetAutoTextPath(); break; + case SvtPathOptions::Paths::Backup: aPath = GetBackupPath(); break; + case SvtPathOptions::Paths::Basic: aPath = GetBasicPath(); break; + case SvtPathOptions::Paths::Bitmap: aPath = GetBitmapPath(); break; + case SvtPathOptions::Paths::Config: aPath = GetConfigPath(); break; + case SvtPathOptions::Paths::Dictionary: aPath = GetDictionaryPath(); break; + case SvtPathOptions::Paths::Favorites: aPath = GetFavoritesPath(); break; + case SvtPathOptions::Paths::Filter: aPath = GetFilterPath(); break; + case SvtPathOptions::Paths::Gallery: aPath = GetGalleryPath(); break; + case SvtPathOptions::Paths::Graphic: aPath = GetGraphicPath(); break; + case SvtPathOptions::Paths::Help: aPath = GetHelpPath(); break; + case SvtPathOptions::Paths::Linguistic: aPath = GetLinguisticPath(); break; + case SvtPathOptions::Paths::Module: aPath = GetModulePath(); break; + case SvtPathOptions::Paths::Palette: aPath = GetPalettePath(); break; + case SvtPathOptions::Paths::IconSet: aPath = GetIconsetPath(); break; + case SvtPathOptions::Paths::Plugin: aPath = GetPluginPath(); break; + case SvtPathOptions::Paths::Storage: aPath = GetStoragePath(); break; + case SvtPathOptions::Paths::Temp: aPath = GetTempPath(); break; + case SvtPathOptions::Paths::Template: aPath = GetTemplatePath(); break; + case SvtPathOptions::Paths::Work: aPath = GetWorkPath(); break; + case SvtPathOptions::Paths::UIConfig: aPath = pImpl->GetUIConfigPath(); break; + case SvtPathOptions::Paths::Fingerprint: aPath = GetFingerprintPath(); break; + case SvtPathOptions::Paths::NumberText: aPath = GetNumbertextPath(); break; + case SvtPathOptions::Paths::Classification: aPath = GetClassificationPath(); break; + // coverity[dead_error_begin] - following conditions exist to avoid compiler warning + case SvtPathOptions::Paths::UserConfig: + case SvtPathOptions::Paths::LAST: + break; + } + + sal_Int32 nPathIndex = 0; + do + { + bool bIsURL = true; + OUString aPathToken( aPath.getToken( 0, SEARCHPATH_DELIMITER, nPathIndex ) ); + INetURLObject aObj( aPathToken ); + if ( aObj.HasError() ) + { + bIsURL = false; + OUString aURL; + if ( osl::FileBase::getFileURLFromSystemPath( aPathToken, aURL ) + == osl::FileBase::E_None ) + aObj.SetURL( aURL ); + } + if ( aObj.GetProtocol() == INetProtocol::VndSunStarExpand ) + { + Reference< XMacroExpander > xMacroExpander = theMacroExpander::get( ::comphelper::getProcessComponentContext() ); + const OUString sExpandedPath = xMacroExpander->expandMacros( aObj.GetURLPath( INetURLObject::DecodeMechanism::WithCharset ) ); + aObj.SetURL( sExpandedPath ); + } + + sal_Int32 nIniIndex = 0; + do + { + std::u16string_view aToken = o3tl::getToken(aIniFile, 0, '/', nIniIndex ); + aObj.insertName(aToken); + } + while ( nIniIndex >= 0 ); + + bRet = ::utl::UCBContentHelper::Exists( aObj.GetMainURL( INetURLObject::DecodeMechanism::NONE ) ); + + if ( bRet ) + { + if ( !bIsURL ) + { + OUString sTmp; + osl::FileBase::getSystemPathFromFileURL( + aObj.GetMainURL( INetURLObject::DecodeMechanism::NONE ), sTmp ); + rIniFile = sTmp; + } + else + rIniFile = aObj.GetMainURL( INetURLObject::DecodeMechanism::NONE ); + break; + } + } + while ( nPathIndex >= 0 ); + } + } + + return bRet; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/saveopt.cxx b/unotools/source/config/saveopt.cxx new file mode 100644 index 000000000..b91ba8639 --- /dev/null +++ b/unotools/source/config/saveopt.cxx @@ -0,0 +1,94 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * 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/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <sal/config.h> + +#include <sal/log.hxx> +#include <unotools/saveopt.hxx> +#include <unotools/configmgr.hxx> + +#include <officecfg/Office/Common.hxx> + +using namespace utl; +using namespace com::sun::star::uno; + +void SetODFDefaultVersion( SvtSaveOptions::ODFDefaultVersion eVersion, const std::shared_ptr<comphelper::ConfigurationChanges>& xChanges ) +{ + sal_Int16 nTmp = (eVersion == SvtSaveOptions::ODFVER_LATEST) ? sal_Int16( 3 ) : sal_Int16( eVersion ); + officecfg::Office::Common::Save::ODF::DefaultVersion::set(nTmp, xChanges); +} + +void SetODFDefaultVersion( SvtSaveOptions::ODFDefaultVersion eVersion ) +{ + auto xChanges = comphelper::ConfigurationChanges::create(); + SetODFDefaultVersion(eVersion, xChanges); + xChanges->commit(); +} + +SvtSaveOptions::ODFDefaultVersion GetODFDefaultVersion() +{ + SvtSaveOptions::ODFDefaultVersion nRet; + sal_Int16 nTmp = officecfg::Office::Common::Save::ODF::DefaultVersion::get(); + if( nTmp == 3 ) + nRet = SvtSaveOptions::ODFVER_LATEST; + else + nRet = SvtSaveOptions::ODFDefaultVersion( nTmp ); + SAL_WARN_IF(nRet == SvtSaveOptions::ODFVER_UNKNOWN, "unotools.config", "DefaultVersion is ODFVER_UNKNOWN?"); + return (nRet == SvtSaveOptions::ODFVER_UNKNOWN) ? SvtSaveOptions::ODFVER_LATEST : nRet; +} + +SvtSaveOptions::ODFSaneDefaultVersion GetODFSaneDefaultVersion() +{ + SvtSaveOptions::ODFDefaultVersion nRet; + sal_Int16 nTmp = officecfg::Office::Common::Save::ODF::DefaultVersion::get(); + if( nTmp == 3 ) + nRet = SvtSaveOptions::ODFVER_LATEST; + else + nRet = SvtSaveOptions::ODFDefaultVersion( nTmp ); + + return GetODFSaneDefaultVersion(nRet); +} + +SvtSaveOptions::ODFSaneDefaultVersion GetODFSaneDefaultVersion(SvtSaveOptions::ODFDefaultVersion eODFDefaultVersion) +{ + switch (eODFDefaultVersion) + { + default: + assert(!"map new ODFDefaultVersion to ODFSaneDefaultVersion"); + break; + case SvtSaveOptions::ODFVER_UNKNOWN: + case SvtSaveOptions::ODFVER_LATEST: + return SvtSaveOptions::ODFSVER_LATEST_EXTENDED; + case SvtSaveOptions::ODFVER_010: + return SvtSaveOptions::ODFSVER_010; + case SvtSaveOptions::ODFVER_011: + return SvtSaveOptions::ODFSVER_011; + case SvtSaveOptions::ODFVER_012: + return SvtSaveOptions::ODFSVER_012; + case SvtSaveOptions::ODFVER_012_EXT_COMPAT: + return SvtSaveOptions::ODFSVER_012_EXT_COMPAT; + case SvtSaveOptions::ODFVER_012_EXTENDED: + return SvtSaveOptions::ODFSVER_012_EXTENDED; + case SvtSaveOptions::ODFVER_013: + return SvtSaveOptions::ODFSVER_013; + } + return SvtSaveOptions::ODFSVER_LATEST_EXTENDED; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/searchopt.cxx b/unotools/source/config/searchopt.cxx new file mode 100644 index 000000000..23a2ae933 --- /dev/null +++ b/unotools/source/config/searchopt.cxx @@ -0,0 +1,614 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * 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/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <sal/config.h> + +#include <unotools/searchopt.hxx> +#include <tools/debug.hxx> +#include <unotools/configitem.hxx> +#include <com/sun/star/uno/Sequence.hxx> +#include <com/sun/star/uno/Any.h> +#include <sal/macros.h> +#include <osl/diagnose.h> +#include <i18nutil/transliteration.hxx> + +using namespace utl; +using namespace com::sun::star::uno; + +#define MAX_FLAGS_OFFSET 29 + +class SvtSearchOptions_Impl : public ConfigItem +{ + sal_Int32 nFlags; + bool bModified; + + SvtSearchOptions_Impl(const SvtSearchOptions_Impl&) = delete; + SvtSearchOptions_Impl& operator=(const SvtSearchOptions_Impl&) = delete; + + // ConfigItem + virtual void ImplCommit() override; + +protected: + bool IsModified() const { return bModified; } + using ConfigItem::SetModified; + void SetModified( bool bVal ); + void Load(); + bool Save(); + + static Sequence< OUString > GetPropertyNames(); + +public: + SvtSearchOptions_Impl(); + virtual ~SvtSearchOptions_Impl() override; + + virtual void Notify( const css::uno::Sequence< OUString >& aPropertyNames ) override; + + bool GetFlag( sal_uInt16 nOffset ) const; + void SetFlag( sal_uInt16 nOffset, bool bVal ); + void SetSearchAlgorithm( sal_uInt16 nOffset, bool bVal ); +}; + +SvtSearchOptions_Impl::SvtSearchOptions_Impl() : + ConfigItem( "Office.Common/SearchOptions" ), + nFlags(0x0003FFFF) // set all options values to 'true' + +{ + Load(); + SetModified( false ); +} + +SvtSearchOptions_Impl::~SvtSearchOptions_Impl() +{ + assert(!IsModified()); // should have been committed +} + +void SvtSearchOptions_Impl::ImplCommit() +{ + if (IsModified()) + Save(); +} + +void SvtSearchOptions_Impl::Notify( const Sequence< OUString >& ) +{ +} + +bool SvtSearchOptions_Impl::GetFlag( sal_uInt16 nOffset ) const +{ + DBG_ASSERT( nOffset <= MAX_FLAGS_OFFSET, "offset out of range"); + return ((nFlags >> nOffset) & 0x01) != 0; +} + +void SvtSearchOptions_Impl::SetFlag( sal_uInt16 nOffset, bool bVal ) +{ + DBG_ASSERT( nOffset <= MAX_FLAGS_OFFSET, "offset out of range"); + sal_Int32 nOldFlags = nFlags; + sal_Int32 nMask = (sal_Int32(1)) << nOffset; + if (bVal) + nFlags |= nMask; + else + nFlags &= ~nMask; + if (nFlags != nOldFlags) + SetModified( true ); +} + +void SvtSearchOptions_Impl::SetModified( bool bVal ) +{ + bModified = bVal; + if (bModified) + { + ConfigItem::SetModified(); + } +} + +Sequence< OUString > SvtSearchOptions_Impl::GetPropertyNames() +{ + static const char* aPropNames[ MAX_FLAGS_OFFSET + 1 ] = + { + "IsWholeWordsOnly", // 0 + "IsBackwards", // 1 + "IsUseRegularExpression", // 2 + //"IsCurrentSelectionOnly", // interactively set or not... + "IsSearchForStyles", // 3 + "IsSimilaritySearch", // 4 + "IsUseAsianOptions", // 5 + "IsMatchCase", // 6 + "Japanese/IsMatchFullHalfWidthForms", // 7 + "Japanese/IsMatchHiraganaKatakana", // 8 + "Japanese/IsMatchContractions", // 9 + "Japanese/IsMatchMinusDashCho-on", // 10 + "Japanese/IsMatchRepeatCharMarks", // 11 + "Japanese/IsMatchVariantFormKanji", // 12 + "Japanese/IsMatchOldKanaForms", // 13 + "Japanese/IsMatch_DiZi_DuZu", // 14 + "Japanese/IsMatch_BaVa_HaFa", // 15 + "Japanese/IsMatch_TsiThiChi_DhiZi", // 16 + "Japanese/IsMatch_HyuIyu_ByuVyu", // 17 + "Japanese/IsMatch_SeShe_ZeJe", // 18 + "Japanese/IsMatch_IaIya", // 19 + "Japanese/IsMatch_KiKu", // 20 + "Japanese/IsIgnorePunctuation", // 21 + "Japanese/IsIgnoreWhitespace", // 22 + "Japanese/IsIgnoreProlongedSoundMark", // 23 + "Japanese/IsIgnoreMiddleDot", // 24 + "IsNotes", // 25 + "IsIgnoreDiacritics_CTL", // 26 + "IsIgnoreKashida_CTL", // 27 + "IsSearchFormatted", // 28 + "IsUseWildcard" // 29 + }; + + const int nCount = SAL_N_ELEMENTS( aPropNames ); + Sequence< OUString > aNames( nCount ); + OUString* pNames = aNames.getArray(); + for (sal_Int32 i = 0; i < nCount; ++i) + pNames[i] = OUString::createFromAscii( aPropNames[i] ); + + return aNames; +} + +void SvtSearchOptions_Impl::SetSearchAlgorithm( sal_uInt16 nOffset, bool bVal ) +{ + if (bVal) + { + // Search algorithms are mutually exclusive. + if (nOffset != 2 && GetFlag(2)) + SetFlag( 2, false ); + if (nOffset != 4 && GetFlag(4)) + SetFlag( 4, false ); + if (nOffset != 29 && GetFlag(29)) + SetFlag( 29, false ); + } + SetFlag( nOffset, bVal ); +} + +void SvtSearchOptions_Impl::Load() +{ + bool bSucc = false; + + Sequence< OUString > aNames = GetPropertyNames(); + sal_Int32 nProps = aNames.getLength(); + + const Sequence< Any > aValues = GetProperties( aNames ); + DBG_ASSERT( aValues.getLength() == aNames.getLength(), + "GetProperties failed" ); + //EnableNotification( aNames ); + + if (nProps && aValues.getLength() == nProps) + { + bSucc = true; + + const Any* pValues = aValues.getConstArray(); + for (sal_Int32 i = 0; i < nProps; ++i) + { + const Any &rVal = pValues[i]; + DBG_ASSERT( rVal.hasValue(), "property value missing" ); + if (rVal.hasValue()) + { + bool bVal = bool(); + if (rVal >>= bVal) + { + if (i <= MAX_FLAGS_OFFSET) + { + // use index in sequence as flag index + SetFlag( i, bVal ); + } + else { + OSL_FAIL( "unexpected index" ); + } + } + else + { + OSL_FAIL( "unexpected type" ); + bSucc = false; + } + } + else + { + OSL_FAIL( "value missing" ); + bSucc = false; + } + } + } + DBG_ASSERT( bSucc, "LoadConfig failed" ); +} + +bool SvtSearchOptions_Impl::Save() +{ + bool bSucc = false; + + const Sequence< OUString > aNames = GetPropertyNames(); + sal_Int32 nProps = aNames.getLength(); + + Sequence< Any > aValues( nProps ); + Any *pValue = aValues.getArray(); + + DBG_ASSERT( nProps == MAX_FLAGS_OFFSET + 1, + "unexpected size of index" ); + if (nProps == MAX_FLAGS_OFFSET + 1) + { + for (sal_Int32 i = 0; i < nProps; ++i) + pValue[i] <<= GetFlag(i); + bSucc |= PutProperties( aNames, aValues ); + } + + if (bSucc) + SetModified( false ); + + return bSucc; +} + +SvtSearchOptions::SvtSearchOptions() + : pImpl( new SvtSearchOptions_Impl ) +{ +} + +SvtSearchOptions::~SvtSearchOptions() +{ +} + +void SvtSearchOptions::Commit() +{ + pImpl->Commit(); +} + +TransliterationFlags SvtSearchOptions::GetTransliterationFlags() const +{ + TransliterationFlags nRes = TransliterationFlags::NONE; + + if (!IsMatchCase()) // 'IsMatchCase' means act case sensitive + nRes |= TransliterationFlags::IGNORE_CASE; + if ( IsMatchFullHalfWidthForms()) + nRes |= TransliterationFlags::IGNORE_WIDTH; + if ( IsMatchHiraganaKatakana()) + nRes |= TransliterationFlags::IGNORE_KANA; + if ( IsMatchContractions()) + nRes |= TransliterationFlags::ignoreSize_ja_JP; + if ( IsMatchMinusDashChoon()) + nRes |= TransliterationFlags::ignoreMinusSign_ja_JP; + if ( IsMatchRepeatCharMarks()) + nRes |= TransliterationFlags::ignoreIterationMark_ja_JP; + if ( IsMatchVariantFormKanji()) + nRes |= TransliterationFlags::ignoreTraditionalKanji_ja_JP; + if ( IsMatchOldKanaForms()) + nRes |= TransliterationFlags::ignoreTraditionalKana_ja_JP; + if ( IsMatchDiziDuzu()) + nRes |= TransliterationFlags::ignoreZiZu_ja_JP; + if ( IsMatchBavaHafa()) + nRes |= TransliterationFlags::ignoreBaFa_ja_JP; + if ( IsMatchTsithichiDhizi()) + nRes |= TransliterationFlags::ignoreTiJi_ja_JP; + if ( IsMatchHyuiyuByuvyu()) + nRes |= TransliterationFlags::ignoreHyuByu_ja_JP; + if ( IsMatchSesheZeje()) + nRes |= TransliterationFlags::ignoreSeZe_ja_JP; + if ( IsMatchIaiya()) + nRes |= TransliterationFlags::ignoreIandEfollowedByYa_ja_JP; + if ( IsMatchKiku()) + nRes |= TransliterationFlags::ignoreKiKuFollowedBySa_ja_JP; + if ( IsIgnorePunctuation()) + nRes |= TransliterationFlags::ignoreSeparator_ja_JP; + if ( IsIgnoreWhitespace()) + nRes |= TransliterationFlags::ignoreSpace_ja_JP; + if ( IsIgnoreProlongedSoundMark()) + nRes |= TransliterationFlags::ignoreProlongedSoundMark_ja_JP; + if ( IsIgnoreMiddleDot()) + nRes |= TransliterationFlags::ignoreMiddleDot_ja_JP; + if ( IsIgnoreDiacritics_CTL()) + nRes |= TransliterationFlags::IGNORE_DIACRITICS_CTL; + if ( IsIgnoreKashida_CTL()) + nRes |= TransliterationFlags::IGNORE_KASHIDA_CTL; + return nRes; +} + +bool SvtSearchOptions::IsWholeWordsOnly() const +{ + return pImpl->GetFlag( 0 ); +} + +void SvtSearchOptions::SetWholeWordsOnly( bool bVal ) +{ + pImpl->SetFlag( 0, bVal ); +} + +bool SvtSearchOptions::IsBackwards() const +{ + return pImpl->GetFlag( 1 ); +} + +void SvtSearchOptions::SetBackwards( bool bVal ) +{ + pImpl->SetFlag( 1, bVal ); +} + +bool SvtSearchOptions::IsUseRegularExpression() const +{ + return pImpl->GetFlag( 2 ); +} + +void SvtSearchOptions::SetUseRegularExpression( bool bVal ) +{ + pImpl->SetSearchAlgorithm( 2, bVal ); +} + +void SvtSearchOptions::SetSearchForStyles( bool bVal ) +{ + pImpl->SetFlag( 3, bVal ); +} + +bool SvtSearchOptions::IsSimilaritySearch() const +{ + return pImpl->GetFlag( 4 ); +} + +void SvtSearchOptions::SetSimilaritySearch( bool bVal ) +{ + pImpl->SetSearchAlgorithm( 4, bVal ); +} + +bool SvtSearchOptions::IsUseAsianOptions() const +{ + return pImpl->GetFlag( 5 ); +} + +void SvtSearchOptions::SetUseAsianOptions( bool bVal ) +{ + pImpl->SetFlag( 5, bVal ); +} + +bool SvtSearchOptions::IsMatchCase() const +{ + return pImpl->GetFlag( 6 ); +} + +void SvtSearchOptions::SetMatchCase( bool bVal ) +{ + pImpl->SetFlag( 6, bVal ); +} + +bool SvtSearchOptions::IsMatchFullHalfWidthForms() const +{ + return pImpl->GetFlag( 7 ); +} + +void SvtSearchOptions::SetMatchFullHalfWidthForms( bool bVal ) +{ + pImpl->SetFlag( 7, bVal ); +} + +bool SvtSearchOptions::IsMatchHiraganaKatakana() const +{ + return pImpl->GetFlag( 8 ); +} + +void SvtSearchOptions::SetMatchHiraganaKatakana( bool bVal ) +{ + pImpl->SetFlag( 8, bVal ); +} + +bool SvtSearchOptions::IsMatchContractions() const +{ + return pImpl->GetFlag( 9 ); +} + +void SvtSearchOptions::SetMatchContractions( bool bVal ) +{ + pImpl->SetFlag( 9, bVal ); +} + +bool SvtSearchOptions::IsMatchMinusDashChoon() const +{ + return pImpl->GetFlag( 10 ); +} + +void SvtSearchOptions::SetMatchMinusDashChoon( bool bVal ) +{ + pImpl->SetFlag( 10, bVal ); +} + +bool SvtSearchOptions::IsMatchRepeatCharMarks() const +{ + return pImpl->GetFlag( 11 ); +} + +void SvtSearchOptions::SetMatchRepeatCharMarks( bool bVal ) +{ + pImpl->SetFlag( 11, bVal ); +} + +bool SvtSearchOptions::IsMatchVariantFormKanji() const +{ + return pImpl->GetFlag( 12 ); +} + +void SvtSearchOptions::SetMatchVariantFormKanji( bool bVal ) +{ + pImpl->SetFlag( 12, bVal ); +} + +bool SvtSearchOptions::IsMatchOldKanaForms() const +{ + return pImpl->GetFlag( 13 ); +} + +void SvtSearchOptions::SetMatchOldKanaForms( bool bVal ) +{ + pImpl->SetFlag( 13, bVal ); +} + +bool SvtSearchOptions::IsMatchDiziDuzu() const +{ + return pImpl->GetFlag( 14 ); +} + +void SvtSearchOptions::SetMatchDiziDuzu( bool bVal ) +{ + pImpl->SetFlag( 14, bVal ); +} + +bool SvtSearchOptions::IsMatchBavaHafa() const +{ + return pImpl->GetFlag( 15 ); +} + +void SvtSearchOptions::SetMatchBavaHafa( bool bVal ) +{ + pImpl->SetFlag( 15, bVal ); +} + +bool SvtSearchOptions::IsMatchTsithichiDhizi() const +{ + return pImpl->GetFlag( 16 ); +} + +void SvtSearchOptions::SetMatchTsithichiDhizi( bool bVal ) +{ + pImpl->SetFlag( 16, bVal ); +} + +bool SvtSearchOptions::IsMatchHyuiyuByuvyu() const +{ + return pImpl->GetFlag( 17 ); +} + +void SvtSearchOptions::SetMatchHyuiyuByuvyu( bool bVal ) +{ + pImpl->SetFlag( 17, bVal ); +} + +bool SvtSearchOptions::IsMatchSesheZeje() const +{ + return pImpl->GetFlag( 18 ); +} + +void SvtSearchOptions::SetMatchSesheZeje( bool bVal ) +{ + pImpl->SetFlag( 18, bVal ); +} + +bool SvtSearchOptions::IsMatchIaiya() const +{ + return pImpl->GetFlag( 19 ); +} + +void SvtSearchOptions::SetMatchIaiya( bool bVal ) +{ + pImpl->SetFlag( 19, bVal ); +} + +bool SvtSearchOptions::IsMatchKiku() const +{ + return pImpl->GetFlag( 20 ); +} + +void SvtSearchOptions::SetMatchKiku( bool bVal ) +{ + pImpl->SetFlag( 20, bVal ); +} + +bool SvtSearchOptions::IsIgnorePunctuation() const +{ + return pImpl->GetFlag( 21 ); +} + +void SvtSearchOptions::SetIgnorePunctuation( bool bVal ) +{ + pImpl->SetFlag( 21, bVal ); +} + +bool SvtSearchOptions::IsIgnoreWhitespace() const +{ + return pImpl->GetFlag( 22 ); +} + +void SvtSearchOptions::SetIgnoreWhitespace( bool bVal ) +{ + pImpl->SetFlag( 22, bVal ); +} + +bool SvtSearchOptions::IsIgnoreProlongedSoundMark() const +{ + return pImpl->GetFlag( 23 ); +} + +void SvtSearchOptions::SetIgnoreProlongedSoundMark( bool bVal ) +{ + pImpl->SetFlag( 23, bVal ); +} + +bool SvtSearchOptions::IsIgnoreMiddleDot() const +{ + return pImpl->GetFlag( 24 ); +} + +void SvtSearchOptions::SetIgnoreMiddleDot( bool bVal ) +{ + pImpl->SetFlag( 24, bVal ); +} + +bool SvtSearchOptions::IsNotes() const +{ + return pImpl->GetFlag( 25 ); +} + +void SvtSearchOptions::SetNotes( bool bVal ) +{ + pImpl->SetFlag( 25, bVal ); +} + +bool SvtSearchOptions::IsIgnoreDiacritics_CTL() const +{ + return pImpl->GetFlag( 26 ); +} + +void SvtSearchOptions::SetIgnoreDiacritics_CTL( bool bVal ) +{ + pImpl->SetFlag( 26, bVal ); +} + +bool SvtSearchOptions::IsIgnoreKashida_CTL() const +{ + return pImpl->GetFlag( 27 ); +} + +void SvtSearchOptions::SetIgnoreKashida_CTL( bool bVal ) +{ + pImpl->SetFlag( 27, bVal ); +} + +bool SvtSearchOptions::IsSearchFormatted() const +{ + return pImpl->GetFlag( 28 ); +} + +void SvtSearchOptions::SetSearchFormatted( bool bVal ) +{ + pImpl->SetFlag( 28, bVal ); +} + +bool SvtSearchOptions::IsUseWildcard() const +{ + return pImpl->GetFlag( 29 ); +} + +void SvtSearchOptions::SetUseWildcard( bool bVal ) +{ + pImpl->SetSearchAlgorithm( 29, bVal ); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/securityoptions.cxx b/unotools/source/config/securityoptions.cxx new file mode 100644 index 000000000..4749065fb --- /dev/null +++ b/unotools/source/config/securityoptions.cxx @@ -0,0 +1,357 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * 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/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <unotools/securityoptions.hxx> +#include <unotools/configmgr.hxx> +#include <unotools/configitem.hxx> +#include <unotools/ucbhelper.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> + +#include <com/sun/star/beans/PropertyValue.hpp> +#include <comphelper/propertyvalue.hxx> +#include <comphelper/sequence.hxx> +#include <tools/urlobj.hxx> + +#include <unotools/pathoptions.hxx> +#include <officecfg/Office/Common.hxx> + +// namespaces + +using namespace ::com::sun::star::uno; + +constexpr OUStringLiteral PROPERTYNAME_MACRO_TRUSTEDAUTHORS = u"TrustedAuthors"; +constexpr OUStringLiteral PROPERTYNAME_TRUSTEDAUTHOR_SUBJECTNAME = u"SubjectName"; +constexpr OUStringLiteral PROPERTYNAME_TRUSTEDAUTHOR_SERIALNUMBER = u"SerialNumber"; +constexpr OUStringLiteral PROPERTYNAME_TRUSTEDAUTHOR_RAWDATA = u"RawData"; + + +namespace SvtSecurityOptions +{ + +bool IsReadOnly( EOption eOption ) +{ + bool bReadonly; + switch(eOption) + { + case SvtSecurityOptions::EOption::SecureUrls : + bReadonly = officecfg::Office::Common::Security::Scripting::SecureURL::isReadOnly(); + break; + case SvtSecurityOptions::EOption::DocWarnSaveOrSend: + bReadonly = officecfg::Office::Common::Security::Scripting::WarnSaveOrSendDoc::isReadOnly(); + break; + case SvtSecurityOptions::EOption::DocWarnSigning: + bReadonly = officecfg::Office::Common::Security::Scripting::WarnSignDoc::isReadOnly(); + break; + case SvtSecurityOptions::EOption::DocWarnPrint: + bReadonly = officecfg::Office::Common::Security::Scripting::WarnPrintDoc::isReadOnly(); + break; + case SvtSecurityOptions::EOption::DocWarnCreatePdf: + bReadonly = officecfg::Office::Common::Security::Scripting::WarnCreatePDF::isReadOnly(); + break; + case SvtSecurityOptions::EOption::DocWarnRemovePersonalInfo: + bReadonly = officecfg::Office::Common::Security::Scripting::RemovePersonalInfoOnSaving::isReadOnly(); + break; + case SvtSecurityOptions::EOption::DocWarnRecommendPassword: + bReadonly = officecfg::Office::Common::Security::Scripting::RecommendPasswordProtection::isReadOnly(); + break; + case SvtSecurityOptions::EOption::MacroSecLevel: + bReadonly = officecfg::Office::Common::Security::Scripting::MacroSecurityLevel::isReadOnly(); + break; + case SvtSecurityOptions::EOption::MacroTrustedAuthors: + bReadonly = false; // TODO? officecfg::Office::Common::Security::Scripting::TrustedAuthors::isReadOnly(); + break; + case SvtSecurityOptions::EOption::CtrlClickHyperlink: + bReadonly = officecfg::Office::Common::Security::Scripting::HyperlinksWithCtrlClick::isReadOnly(); + break; + case SvtSecurityOptions::EOption::BlockUntrustedRefererLinks: + bReadonly = officecfg::Office::Common::Security::Scripting::BlockUntrustedRefererLinks::isReadOnly(); + break; + + default: + assert(false); + bReadonly = true; + } + + return bReadonly; +} + +std::vector< OUString > GetSecureURLs() +{ + if (utl::ConfigManager::IsFuzzing()) + return {}; + std::vector<OUString> aRet = comphelper::sequenceToContainer<std::vector<OUString>>( + officecfg::Office::Common::Security::Scripting::SecureURL::get()); + SvtPathOptions aOpt; + std::transform(aRet.begin(), aRet.end(), aRet.begin(), + [&aOpt](const OUString& rUrl) -> OUString { return aOpt.SubstituteVariable( rUrl ); }); + return aRet; +} + +void SetSecureURLs( std::vector< OUString >&& urlList ) +{ +// DBG_ASSERT(!officecfg::SecureURL::isReadOnly(), "SvtSecurityOptions_Impl::SetSecureURLs()\nYou tried to write on a readonly value!\n"); +// if (officecfg::SecureURL::isReadOnly()) +// return; + std::vector< OUString > lURLs( std::move(urlList) ); + SvtPathOptions aOpt; + std::transform(lURLs.begin(), lURLs.end(), lURLs.begin(), + [&aOpt](const OUString& rUrl) -> OUString { return aOpt.UseVariable( rUrl ); }); + std::shared_ptr<comphelper::ConfigurationChanges> xChanges = comphelper::ConfigurationChanges::create(); + officecfg::Office::Common::Security::Scripting::SecureURL::set(comphelper::containerToSequence(lURLs), xChanges); + xChanges->commit(); +} + +bool isSecureMacroUri( + OUString const & uri, OUString const & referer) +{ + switch (INetURLObject(uri).GetProtocol()) { + case INetProtocol::Macro: + if (uri.startsWithIgnoreAsciiCase("macro:///")) { + // Denotes an App-BASIC macro (see SfxMacroLoader::loadMacro), which + // is considered safe: + return true; + } + [[fallthrough]]; + case INetProtocol::Slot: + return referer.equalsIgnoreAsciiCase("private:user") + || isTrustedLocationUri(referer); + default: + return true; + } +} + +bool isUntrustedReferer(OUString const & referer) +{ + return IsOptionSet(EOption::BlockUntrustedRefererLinks) + && !(referer.isEmpty() || referer.startsWithIgnoreAsciiCase("private:") + || isTrustedLocationUri(referer)); +} + +bool isTrustedLocationUri(OUString const & uri) +{ + for (const auto & url : GetSecureURLs()) + { + if (utl::UCBContentHelper::IsSubPath(url, uri)) + { + return true; + } + } + return false; +} + +bool isTrustedLocationUriForUpdatingLinks(OUString const & uri) +{ + return GetMacroSecurityLevel() == 0 || uri.isEmpty() + || uri.startsWithIgnoreAsciiCase("private:") + || isTrustedLocationUri(uri); +} + +sal_Int32 GetMacroSecurityLevel() +{ + return officecfg::Office::Common::Security::Scripting::MacroSecurityLevel::get(); +} + +void SetMacroSecurityLevel( sal_Int32 _nLevel ) +{ + if( officecfg::Office::Common::Security::Scripting::MacroSecurityLevel::isReadOnly() ) + return; + + if( _nLevel > 3 || _nLevel < 0 ) + _nLevel = 3; + + std::shared_ptr<comphelper::ConfigurationChanges> xChanges = comphelper::ConfigurationChanges::create(); + officecfg::Office::Common::Security::Scripting::MacroSecurityLevel::set(_nLevel, xChanges); + xChanges->commit(); +} + +bool IsMacroDisabled() +{ + return officecfg::Office::Common::Security::Scripting::DisableMacrosExecution::get(); +} + +std::vector< SvtSecurityOptions::Certificate > GetTrustedAuthors() +{ + Reference<css::container::XHierarchicalNameAccess> xHierarchyAccess = utl::ConfigManager::acquireTree(u"Office.Common/Security/Scripting"); + const Sequence< OUString > lAuthors = utl::ConfigItem::GetNodeNames( xHierarchyAccess, PROPERTYNAME_MACRO_TRUSTEDAUTHORS, utl::ConfigNameFormat::LocalPath ); + sal_Int32 c1 = lAuthors.getLength(); + if( !c1 ) + return {}; + + sal_Int32 c2 = c1 * 3; // 3 Properties inside Struct TrustedAuthor + Sequence< OUString > lAllAuthors( c2 ); + auto plAllAuthors = lAllAuthors.getArray(); + sal_Int32 i2 = 0; + OUString aSep( "/" ); + for( const auto& rAuthor : lAuthors ) + { + plAllAuthors[ i2 ] = PROPERTYNAME_MACRO_TRUSTEDAUTHORS + aSep + rAuthor + aSep + PROPERTYNAME_TRUSTEDAUTHOR_SUBJECTNAME; + ++i2; + plAllAuthors[ i2 ] = PROPERTYNAME_MACRO_TRUSTEDAUTHORS + aSep + rAuthor + aSep + PROPERTYNAME_TRUSTEDAUTHOR_SERIALNUMBER; + ++i2; + plAllAuthors[ i2 ] = PROPERTYNAME_MACRO_TRUSTEDAUTHORS + aSep + rAuthor + aSep + PROPERTYNAME_TRUSTEDAUTHOR_RAWDATA; + ++i2; + } + + Sequence< Any > lValues = utl::ConfigItem::GetProperties( xHierarchyAccess, lAllAuthors, /*bAllLocales*/false ); + if( lValues.getLength() != c2 ) + return {}; + + std::vector< SvtSecurityOptions::Certificate > aTrustedAuthors; + SvtSecurityOptions::Certificate aCert; + i2 = 0; + for( sal_Int32 i1 = 0; i1 < c1; ++i1 ) + { + lValues[ i2 ] >>= aCert.SubjectName; + ++i2; + lValues[ i2 ] >>= aCert.SerialNumber; + ++i2; + lValues[ i2 ] >>= aCert.RawData; + ++i2; + // Filter out TrustedAuthor entries with empty RawData, which + // would cause an unexpected std::bad_alloc in + // SecurityEnvironment_NssImpl::createCertificateFromAscii and + // have been observed in the wild (fdo#55019): + if( !aCert.RawData.isEmpty() ) + { + aTrustedAuthors.push_back( aCert ); + } + } + return aTrustedAuthors; +} + +void SetTrustedAuthors( const std::vector< Certificate >& rAuthors ) +{ +// DBG_ASSERT(!m_bROTrustedAuthors, "SvtSecurityOptions_Impl::SetTrustedAuthors()\nYou tried to write on a readonly value!\n"); +// if( m_bROTrustedAuthors ) +// return; + + Reference<css::container::XHierarchicalNameAccess> xHierarchyAccess = utl::ConfigManager::acquireTree(u"Office.Common/Security/Scripting"); + sal_Int32 nCnt = rAuthors.size(); + for( sal_Int32 i = 0; i < nCnt; ++i ) + { + OUString aPrefix( + PROPERTYNAME_MACRO_TRUSTEDAUTHORS + "/a" + + OUString::number(i) + "/"); + Sequence< css::beans::PropertyValue > lPropertyValues{ + comphelper::makePropertyValue(aPrefix + PROPERTYNAME_TRUSTEDAUTHOR_SUBJECTNAME, + rAuthors[i].SubjectName), + comphelper::makePropertyValue(aPrefix + PROPERTYNAME_TRUSTEDAUTHOR_SERIALNUMBER, + rAuthors[i].SerialNumber), + comphelper::makePropertyValue(aPrefix + PROPERTYNAME_TRUSTEDAUTHOR_RAWDATA, + rAuthors[i].RawData) + }; + + utl::ConfigItem::SetSetProperties( xHierarchyAccess, PROPERTYNAME_MACRO_TRUSTEDAUTHORS, lPropertyValues ); + } +} + +bool IsOptionSet( EOption eOption ) +{ + if (utl::ConfigManager::IsFuzzing()) + return false; + bool bSet = false; + switch(eOption) + { + case SvtSecurityOptions::EOption::DocWarnSaveOrSend: + bSet = officecfg::Office::Common::Security::Scripting::WarnSaveOrSendDoc::get(); + break; + case SvtSecurityOptions::EOption::DocWarnSigning: + bSet = officecfg::Office::Common::Security::Scripting::WarnSignDoc::get(); + break; + case SvtSecurityOptions::EOption::DocWarnPrint: + bSet = officecfg::Office::Common::Security::Scripting::WarnPrintDoc::get(); + break; + case SvtSecurityOptions::EOption::DocWarnCreatePdf: + bSet = officecfg::Office::Common::Security::Scripting::WarnCreatePDF::get(); + break; + case SvtSecurityOptions::EOption::DocWarnRemovePersonalInfo: + bSet = officecfg::Office::Common::Security::Scripting::RemovePersonalInfoOnSaving::get(); + break; + case SvtSecurityOptions::EOption::DocWarnRecommendPassword: + bSet = officecfg::Office::Common::Security::Scripting::RecommendPasswordProtection::get(); + break; + case SvtSecurityOptions::EOption::CtrlClickHyperlink: + bSet = officecfg::Office::Common::Security::Scripting::HyperlinksWithCtrlClick::get(); + break; + case SvtSecurityOptions::EOption::BlockUntrustedRefererLinks: + bSet = officecfg::Office::Common::Security::Scripting::BlockUntrustedRefererLinks::get(); + break; + + default: + assert(false); + } + + return bSet; +} + +void SetOption( EOption eOption, bool bValue ) +{ + std::shared_ptr<comphelper::ConfigurationChanges> xChanges = comphelper::ConfigurationChanges::create(); + switch(eOption) + { + case SvtSecurityOptions::EOption::DocWarnSaveOrSend: + officecfg::Office::Common::Security::Scripting::WarnSaveOrSendDoc::set(bValue, xChanges); + break; + case SvtSecurityOptions::EOption::DocWarnSigning: + officecfg::Office::Common::Security::Scripting::WarnSignDoc::set(bValue, xChanges); + break; + case SvtSecurityOptions::EOption::DocWarnPrint: + officecfg::Office::Common::Security::Scripting::WarnPrintDoc::set(bValue, xChanges); + break; + case SvtSecurityOptions::EOption::DocWarnCreatePdf: + officecfg::Office::Common::Security::Scripting::WarnCreatePDF::set(bValue, xChanges); + break; + case SvtSecurityOptions::EOption::DocWarnRemovePersonalInfo: + officecfg::Office::Common::Security::Scripting::RemovePersonalInfoOnSaving::set(bValue, xChanges); + break; + case SvtSecurityOptions::EOption::DocWarnRecommendPassword: + officecfg::Office::Common::Security::Scripting::RecommendPasswordProtection::set(bValue, xChanges); + break; + case SvtSecurityOptions::EOption::CtrlClickHyperlink: + officecfg::Office::Common::Security::Scripting::HyperlinksWithCtrlClick::set(bValue, xChanges); + break; + case SvtSecurityOptions::EOption::BlockUntrustedRefererLinks: + officecfg::Office::Common::Security::Scripting::BlockUntrustedRefererLinks::set(bValue, xChanges); + break; + + default: + assert(false); + } + xChanges->commit(); +} + +} // namespace SvtSecurityOptions + + +// map personal info strings to 1, 2, ... to remove personal info +size_t SvtSecurityMapPersonalInfo::GetInfoID( const OUString sPersonalInfo ) +{ + auto aIter = aInfoIDs.find( sPersonalInfo ); + if ( aIter == aInfoIDs.end() ) + { + size_t nNewID = aInfoIDs.size() + 1; + aInfoIDs[sPersonalInfo] = nNewID; + return nNewID; + } + + return aIter->second; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/syslocaleoptions.cxx b/unotools/source/config/syslocaleoptions.cxx new file mode 100644 index 000000000..8f08202a7 --- /dev/null +++ b/unotools/source/config/syslocaleoptions.cxx @@ -0,0 +1,708 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * 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/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <com/sun/star/uno/Sequence.hxx> +#include <sal/log.hxx> +#include <i18nlangtag/mslangid.hxx> +#include <i18nlangtag/languagetag.hxx> +#include <tools/debug.hxx> +#include <tools/link.hxx> +#include <unotools/syslocaleoptions.hxx> +#include <unotools/configmgr.hxx> +#include <unotools/configitem.hxx> +#include <com/sun/star/uno/Any.hxx> + +#include "itemholder1.hxx" + +#define CFG_READONLY_DEFAULT false + +using namespace osl; +using namespace utl; +using namespace com::sun::star::uno; +using namespace com::sun::star::lang; + +namespace +{ + std::weak_ptr<SvtSysLocaleOptions_Impl> g_pSysLocaleOptions; + Link<LinkParamNone*,void> g_CurrencyChangeLink; + +Mutex& GetMutex() +{ + // #i77768# Due to a static reference in the toolkit lib + // we need a mutex that lives longer than the svl library. + // Otherwise the dtor would use a destructed mutex!! + static Mutex* persistentMutex(new Mutex); + + return *persistentMutex; +} + +} + +class SvtSysLocaleOptions_Impl : public utl::ConfigItem +{ + LanguageTag m_aRealLocale; + LanguageTag m_aRealUILocale; + OUString m_aLocaleString; // en-US or de-DE or empty for SYSTEM + OUString m_aUILocaleString; // en-US or de-DE or empty for SYSTEM + OUString m_aCurrencyString; // USD-en-US or EUR-de-DE + OUString m_aDatePatternsString; // "Y-M-D;M-D" + bool m_bDecimalSeparator; //use decimal separator same as locale + bool m_bIgnoreLanguageChange; //OS language change doesn't affect LO document language + + bool m_bROLocale; + bool m_bROUILocale; + bool m_bROCurrency; + bool m_bRODatePatterns; + bool m_bRODecimalSeparator; + bool m_bROIgnoreLanguageChange; + + static Sequence<OUString> GetPropertyNames(); + void MakeRealLocale(); + void MakeRealUILocale(); + + virtual void ImplCommit() override; + +public: + SvtSysLocaleOptions_Impl(); + virtual ~SvtSysLocaleOptions_Impl() override; + + virtual void Notify( const css::uno::Sequence< OUString >& aPropertyNames ) override; + + const OUString& GetLocaleString() const + { return m_aLocaleString; } + void SetLocaleString( const OUString& rStr ); + + void SetUILocaleString( const OUString& rStr ); + + const OUString& GetCurrencyString() const + { return m_aCurrencyString; } + void SetCurrencyString( const OUString& rStr ); + + const OUString& GetDatePatternsString() const + { return m_aDatePatternsString; } + void SetDatePatternsString( const OUString& rStr ); + + bool IsDecimalSeparatorAsLocale() const { return m_bDecimalSeparator;} + void SetDecimalSeparatorAsLocale( bool bSet); + + bool IsIgnoreLanguageChange() const { return m_bIgnoreLanguageChange;} + void SetIgnoreLanguageChange( bool bSet); + + bool IsReadOnly( SvtSysLocaleOptions::EOption eOption ) const; + const LanguageTag& GetRealLocale() const { return m_aRealLocale; } + const LanguageTag& GetRealUILocale() const { return m_aRealUILocale; } +}; + +constexpr OUStringLiteral ROOTNODE_SYSLOCALE = u"Setup/L10N"; + +constexpr OUStringLiteral PROPERTYNAME_LOCALE = u"ooSetupSystemLocale"; +constexpr OUStringLiteral PROPERTYNAME_UILOCALE = u"ooLocale"; +constexpr OUStringLiteral PROPERTYNAME_CURRENCY = u"ooSetupCurrency"; +constexpr OUStringLiteral PROPERTYNAME_DECIMALSEPARATOR = u"DecimalSeparatorAsLocale"; +constexpr OUStringLiteral PROPERTYNAME_DATEPATTERNS = u"DateAcceptancePatterns"; +constexpr OUStringLiteral PROPERTYNAME_IGNORELANGCHANGE = u"IgnoreLanguageChange"; + +#define PROPERTYHANDLE_LOCALE 0 +#define PROPERTYHANDLE_UILOCALE 1 +#define PROPERTYHANDLE_CURRENCY 2 +#define PROPERTYHANDLE_DECIMALSEPARATOR 3 +#define PROPERTYHANDLE_DATEPATTERNS 4 +#define PROPERTYHANDLE_IGNORELANGCHANGE 5 + +Sequence< OUString > SvtSysLocaleOptions_Impl::GetPropertyNames() +{ + return Sequence< OUString > + { + PROPERTYNAME_LOCALE, + PROPERTYNAME_UILOCALE, + PROPERTYNAME_CURRENCY, + PROPERTYNAME_DECIMALSEPARATOR, + PROPERTYNAME_DATEPATTERNS, + PROPERTYNAME_IGNORELANGCHANGE + }; +} + +SvtSysLocaleOptions_Impl::SvtSysLocaleOptions_Impl() + : ConfigItem( ROOTNODE_SYSLOCALE ) + , m_aRealLocale( LANGUAGE_SYSTEM) + , m_aRealUILocale( LANGUAGE_SYSTEM) + , m_bDecimalSeparator( true ) + , m_bIgnoreLanguageChange( false) + , m_bROLocale(CFG_READONLY_DEFAULT) + , m_bROUILocale(CFG_READONLY_DEFAULT) + , m_bROCurrency(CFG_READONLY_DEFAULT) + , m_bRODatePatterns(CFG_READONLY_DEFAULT) + , m_bRODecimalSeparator(false) + , m_bROIgnoreLanguageChange(false) + +{ + const Sequence< OUString > aNames = GetPropertyNames(); + Sequence< Any > aValues = GetProperties( aNames ); + Sequence< sal_Bool > aROStates = GetReadOnlyStates( aNames ); + const Any* pValues = aValues.getConstArray(); + const sal_Bool* pROStates = aROStates.getConstArray(); + DBG_ASSERT( aValues.getLength() == aNames.getLength(), "GetProperties failed" ); + DBG_ASSERT( aROStates.getLength() == aNames.getLength(), "GetReadOnlyStates failed" ); + if ( aValues.getLength() == aNames.getLength() && aROStates.getLength() == aNames.getLength() ) + { + for ( sal_Int32 nProp = 0; nProp < aNames.getLength(); nProp++ ) + { + if ( pValues[nProp].hasValue() ) + { + switch ( nProp ) + { + case PROPERTYHANDLE_LOCALE : + { + OUString aStr; + if ( pValues[nProp] >>= aStr ) + m_aLocaleString = aStr; + else + { + SAL_WARN( "unotools.config", "Wrong property type!" ); + } + m_bROLocale = pROStates[nProp]; + } + break; + case PROPERTYHANDLE_UILOCALE : + { + OUString aStr; + if ( pValues[nProp] >>= aStr ) + m_aUILocaleString = aStr; + else + { + SAL_WARN( "unotools.config", "Wrong property type!" ); + } + m_bROUILocale = pROStates[nProp]; + } + break; + case PROPERTYHANDLE_CURRENCY : + { + OUString aStr; + if ( pValues[nProp] >>= aStr ) + m_aCurrencyString = aStr; + else + { + SAL_WARN( "unotools.config", "Wrong property type!" ); + } + m_bROCurrency = pROStates[nProp]; + } + break; + case PROPERTYHANDLE_DECIMALSEPARATOR: + { + bool bValue = false; + if ( pValues[nProp] >>= bValue ) + m_bDecimalSeparator = bValue; + else + { + SAL_WARN( "unotools.config", "Wrong property type!" ); + } + m_bRODecimalSeparator = pROStates[nProp]; + } + break; + case PROPERTYHANDLE_DATEPATTERNS : + { + OUString aStr; + if ( pValues[nProp] >>= aStr ) + m_aDatePatternsString = aStr; + else + { + SAL_WARN( "unotools.config", "Wrong property type!" ); + } + m_bRODatePatterns = pROStates[nProp]; + } + break; + case PROPERTYHANDLE_IGNORELANGCHANGE : + { + bool bValue = false; + if ( pValues[nProp] >>= bValue ) + m_bIgnoreLanguageChange = bValue; + else + { + SAL_WARN( "unotools.config", "Wrong property type!" ); + } + m_bROIgnoreLanguageChange = pROStates[nProp]; + } + break; + default: + SAL_WARN( "unotools.config", "Wrong property type!" ); + } + } + } + } + EnableNotification( aNames ); + + MakeRealLocale(); + MakeRealUILocale(); +} + +SvtSysLocaleOptions_Impl::~SvtSysLocaleOptions_Impl() +{ + assert(!IsModified()); // should have been committed +} + +void SvtSysLocaleOptions_Impl::MakeRealLocale() +{ + if (m_aLocaleString.isEmpty()) + { + LanguageType nLang = MsLangId::getConfiguredSystemLanguage(); + m_aRealLocale.reset( nLang).makeFallback(); + } + else + { + m_aRealLocale.reset( m_aLocaleString).makeFallback(); + } +} + +void SvtSysLocaleOptions_Impl::MakeRealUILocale() +{ + if (m_aUILocaleString.isEmpty()) + { + LanguageType nLang = MsLangId::getConfiguredSystemUILanguage(); + m_aRealUILocale.reset( nLang).makeFallback(); + } + else + { + m_aRealUILocale.reset( m_aUILocaleString).makeFallback(); + } +} + +bool SvtSysLocaleOptions_Impl::IsReadOnly( SvtSysLocaleOptions::EOption eOption ) const +{ + bool bReadOnly = CFG_READONLY_DEFAULT; + switch(eOption) + { + case SvtSysLocaleOptions::EOption::Locale : + { + bReadOnly = m_bROLocale; + break; + } + case SvtSysLocaleOptions::EOption::Currency : + { + bReadOnly = m_bROCurrency; + break; + } + case SvtSysLocaleOptions::EOption::DatePatterns : + { + bReadOnly = m_bRODatePatterns; + break; + } + } + return bReadOnly; +} + +void SvtSysLocaleOptions_Impl::ImplCommit() +{ + const Sequence< OUString > aOrgNames = GetPropertyNames(); + sal_Int32 nOrgCount = aOrgNames.getLength(); + + Sequence< OUString > aNames( nOrgCount ); + Sequence< Any > aValues( nOrgCount ); + + OUString* pNames = aNames.getArray(); + Any* pValues = aValues.getArray(); + sal_Int32 nRealCount = 0; + + for ( sal_Int32 nProp = 0; nProp < nOrgCount; nProp++ ) + { + switch ( nProp ) + { + case PROPERTYHANDLE_LOCALE : + { + if (!m_bROLocale) + { + pNames[nRealCount] = aOrgNames[nProp]; + pValues[nRealCount] <<= m_aLocaleString; + ++nRealCount; + } + } + break; + case PROPERTYHANDLE_UILOCALE : + { + if (!m_bROUILocale) + { + pNames[nRealCount] = aOrgNames[nProp]; + pValues[nRealCount] <<= m_aUILocaleString; + ++nRealCount; + } + } + break; + case PROPERTYHANDLE_CURRENCY : + { + if (!m_bROCurrency) + { + pNames[nRealCount] = aOrgNames[nProp]; + pValues[nRealCount] <<= m_aCurrencyString; + ++nRealCount; + } + } + break; + case PROPERTYHANDLE_DECIMALSEPARATOR: + if( !m_bRODecimalSeparator ) + { + pNames[nRealCount] = aOrgNames[nProp]; + pValues[nRealCount] <<= m_bDecimalSeparator; + ++nRealCount; + } + break; + case PROPERTYHANDLE_DATEPATTERNS : + if (!m_bRODatePatterns) + { + pNames[nRealCount] = aOrgNames[nProp]; + pValues[nRealCount] <<= m_aDatePatternsString; + ++nRealCount; + } + break; + case PROPERTYHANDLE_IGNORELANGCHANGE : + if (!m_bROIgnoreLanguageChange) + { + pNames[nRealCount] = aOrgNames[nProp]; + pValues[nRealCount] <<= m_bIgnoreLanguageChange; + ++nRealCount; + } + break; + default: + SAL_WARN( "unotools.config", "invalid index to save a path" ); + } + } + aNames.realloc(nRealCount); + aValues.realloc(nRealCount); + PutProperties( aNames, aValues ); +} + +void SvtSysLocaleOptions_Impl::SetLocaleString( const OUString& rStr ) +{ + ConfigurationHints nHint = ConfigurationHints::Locale; + { + MutexGuard aGuard( GetMutex() ); + if (m_bROLocale || rStr == m_aLocaleString ) + { + return; + } + m_aLocaleString = rStr; + MakeRealLocale(); + LanguageTag::setConfiguredSystemLanguage( m_aRealLocale.getLanguageType() ); + SetModified(); + if ( m_aCurrencyString.isEmpty() ) + nHint |= ConfigurationHints::Currency; + } + NotifyListeners( nHint ); +} + +void SvtSysLocaleOptions_Impl::SetUILocaleString( const OUString& rStr ) +{ + { + MutexGuard aGuard( GetMutex() ); + if (m_bROUILocale || rStr == m_aUILocaleString ) + { + return; + } + m_aUILocaleString = rStr; + + // as we can't switch UILocale at runtime, we only store changes in the configuration + MakeRealUILocale(); + SetModified(); + } + NotifyListeners( ConfigurationHints::UiLocale ); +} + +void SvtSysLocaleOptions_Impl::SetCurrencyString( const OUString& rStr ) +{ + { + MutexGuard aGuard( GetMutex() ); + if (m_bROCurrency || rStr == m_aCurrencyString ) + { + return; + } + m_aCurrencyString = rStr; + SetModified(); + } + NotifyListeners( ConfigurationHints::Currency ); +} + +void SvtSysLocaleOptions_Impl::SetDatePatternsString( const OUString& rStr ) +{ + { + MutexGuard aGuard( GetMutex() ); + if (m_bRODatePatterns || rStr == m_aDatePatternsString ) + { + return; + } + m_aDatePatternsString = rStr; + SetModified(); + } + NotifyListeners( ConfigurationHints::DatePatterns ); +} + +void SvtSysLocaleOptions_Impl::SetDecimalSeparatorAsLocale( bool bSet) +{ + { + MutexGuard aGuard( GetMutex() ); + if(bSet == m_bDecimalSeparator) + { + return; + } + m_bDecimalSeparator = bSet; + SetModified(); + } + NotifyListeners( ConfigurationHints::DecSep ); +} + +void SvtSysLocaleOptions_Impl::SetIgnoreLanguageChange( bool bSet) +{ + { + MutexGuard aGuard( GetMutex() ); + if(bSet == m_bIgnoreLanguageChange) + { + return; + } + m_bIgnoreLanguageChange = bSet; + SetModified(); + } + NotifyListeners( ConfigurationHints::IgnoreLang ); +} + +void SvtSysLocaleOptions_Impl::Notify( const Sequence< OUString >& seqPropertyNames ) +{ + ConfigurationHints nHint = ConfigurationHints::NONE; + Sequence< Any > seqValues = GetProperties( seqPropertyNames ); + Sequence< sal_Bool > seqROStates = GetReadOnlyStates( seqPropertyNames ); + sal_Int32 nCount = seqPropertyNames.getLength(); + for( sal_Int32 nProp = 0; nProp < nCount; ++nProp ) + { + if( seqPropertyNames[nProp] == PROPERTYNAME_LOCALE ) + { + DBG_ASSERT( seqValues[nProp].getValueTypeClass() == TypeClass_STRING, "Locale property type" ); + seqValues[nProp] >>= m_aLocaleString; + m_bROLocale = seqROStates[nProp]; + nHint |= ConfigurationHints::Locale; + if ( m_aCurrencyString.isEmpty() ) + nHint |= ConfigurationHints::Currency; + MakeRealLocale(); + } + if( seqPropertyNames[nProp] == PROPERTYNAME_UILOCALE ) + { + DBG_ASSERT( seqValues[nProp].getValueTypeClass() == TypeClass_STRING, "Locale property type" ); + seqValues[nProp] >>= m_aUILocaleString; + m_bROUILocale = seqROStates[nProp]; + nHint |= ConfigurationHints::UiLocale; + MakeRealUILocale(); + } + else if( seqPropertyNames[nProp] == PROPERTYNAME_CURRENCY ) + { + DBG_ASSERT( seqValues[nProp].getValueTypeClass() == TypeClass_STRING, "Currency property type" ); + seqValues[nProp] >>= m_aCurrencyString; + m_bROCurrency = seqROStates[nProp]; + nHint |= ConfigurationHints::Currency; + } + else if( seqPropertyNames[nProp] == PROPERTYNAME_DECIMALSEPARATOR ) + { + seqValues[nProp] >>= m_bDecimalSeparator; + m_bRODecimalSeparator = seqROStates[nProp]; + } + else if( seqPropertyNames[nProp] == PROPERTYNAME_IGNORELANGCHANGE ) + { + seqValues[nProp] >>= m_bIgnoreLanguageChange; + m_bROIgnoreLanguageChange = seqROStates[nProp]; + } + else if( seqPropertyNames[nProp] == PROPERTYNAME_DATEPATTERNS ) + { + DBG_ASSERT( seqValues[nProp].getValueTypeClass() == TypeClass_STRING, "DatePatterns property type" ); + seqValues[nProp] >>= m_aDatePatternsString; + m_bRODatePatterns = seqROStates[nProp]; + nHint |= ConfigurationHints::DatePatterns; + } + } + if ( nHint != ConfigurationHints::NONE ) + NotifyListeners( nHint ); +} + +SvtSysLocaleOptions::SvtSysLocaleOptions() +{ + MutexGuard aGuard( GetMutex() ); + pImpl = g_pSysLocaleOptions.lock(); + if ( !pImpl ) + { + pImpl = std::make_shared<SvtSysLocaleOptions_Impl>(); + g_pSysLocaleOptions = pImpl; + if (!utl::ConfigManager::IsFuzzing()) + ItemHolder1::holdConfigItem(EItem::SysLocaleOptions); + } + pImpl->AddListener(this); +} + +SvtSysLocaleOptions::~SvtSysLocaleOptions() +{ + MutexGuard aGuard( GetMutex() ); + pImpl->RemoveListener(this); + pImpl.reset(); +} + +bool SvtSysLocaleOptions::IsModified() const +{ + MutexGuard aGuard( GetMutex() ); + return pImpl->IsModified(); +} + +void SvtSysLocaleOptions::Commit() +{ + MutexGuard aGuard( GetMutex() ); + pImpl->Commit(); +} + +void SvtSysLocaleOptions::BlockBroadcasts( bool bBlock ) +{ + MutexGuard aGuard( GetMutex() ); + pImpl->BlockBroadcasts( bBlock ); +} + +void SvtSysLocaleOptions::SetLocaleConfigString( const OUString& rStr ) +{ + pImpl->SetLocaleString( rStr ); +} + +void SvtSysLocaleOptions::SetUILocaleConfigString( const OUString& rStr ) +{ + pImpl->SetUILocaleString( rStr ); +} + +const OUString& SvtSysLocaleOptions::GetCurrencyConfigString() const +{ + MutexGuard aGuard( GetMutex() ); + return pImpl->GetCurrencyString(); +} + +void SvtSysLocaleOptions::SetCurrencyConfigString( const OUString& rStr ) +{ + pImpl->SetCurrencyString( rStr ); +} + +const OUString& SvtSysLocaleOptions::GetDatePatternsConfigString() const +{ + MutexGuard aGuard( GetMutex() ); + return pImpl->GetDatePatternsString(); +} + +void SvtSysLocaleOptions::SetDatePatternsConfigString( const OUString& rStr ) +{ + pImpl->SetDatePatternsString( rStr ); +} + +bool SvtSysLocaleOptions::IsDecimalSeparatorAsLocale() const +{ + MutexGuard aGuard( GetMutex() ); + return pImpl->IsDecimalSeparatorAsLocale(); +} + +void SvtSysLocaleOptions::SetDecimalSeparatorAsLocale( bool bSet) +{ + pImpl->SetDecimalSeparatorAsLocale(bSet); +} + +bool SvtSysLocaleOptions::IsIgnoreLanguageChange() const +{ + MutexGuard aGuard( GetMutex() ); + return pImpl->IsIgnoreLanguageChange(); +} + +void SvtSysLocaleOptions::SetIgnoreLanguageChange( bool bSet) +{ + pImpl->SetIgnoreLanguageChange(bSet); +} + +bool SvtSysLocaleOptions::IsReadOnly( EOption eOption ) const +{ + MutexGuard aGuard( GetMutex() ); + return pImpl->IsReadOnly( eOption ); +} + +// static +void SvtSysLocaleOptions::GetCurrencyAbbrevAndLanguage( OUString& rAbbrev, + LanguageType& eLang, + const OUString& rConfigString ) +{ + sal_Int32 nDelim = rConfigString.indexOf( '-' ); + if ( nDelim >= 0 ) + { + rAbbrev = rConfigString.copy( 0, nDelim ); + OUString aIsoStr( rConfigString.copy( nDelim+1 ) ); + eLang = LanguageTag::convertToLanguageTypeWithFallback( aIsoStr ); + } + else + { + rAbbrev = rConfigString; + eLang = (rAbbrev.isEmpty() ? LANGUAGE_SYSTEM : LANGUAGE_NONE); + } +} + +// static +OUString SvtSysLocaleOptions::CreateCurrencyConfigString( + const OUString& rAbbrev, LanguageType eLang ) +{ + OUString aIsoStr( LanguageTag::convertToBcp47( eLang ) ); + if ( !aIsoStr.isEmpty() ) + { + return rAbbrev + "-" + aIsoStr; + } + else + return rAbbrev; +} + +// static +void SvtSysLocaleOptions::SetCurrencyChangeLink( const Link<LinkParamNone*,void>& rLink ) +{ + MutexGuard aGuard( GetMutex() ); + DBG_ASSERT( !g_CurrencyChangeLink.IsSet(), "SvtSysLocaleOptions::SetCurrencyChangeLink: already set" ); + g_CurrencyChangeLink = rLink; +} + +// static +const Link<LinkParamNone*,void>& SvtSysLocaleOptions::GetCurrencyChangeLink() +{ + MutexGuard aGuard( GetMutex() ); + return g_CurrencyChangeLink; +} + +void SvtSysLocaleOptions::ConfigurationChanged( utl::ConfigurationBroadcaster* p, ConfigurationHints nHint ) +{ + if ( nHint & ConfigurationHints::Currency ) + { + const Link<LinkParamNone*,void>& rLink = GetCurrencyChangeLink(); + rLink.Call( nullptr ); + } + + ::utl::detail::Options::ConfigurationChanged( p, nHint ); +} + +LanguageTag SvtSysLocaleOptions::GetLanguageTag() const +{ + MutexGuard aGuard( GetMutex() ); + return LanguageTag( pImpl->GetLocaleString() ); +} + +const LanguageTag & SvtSysLocaleOptions::GetRealLanguageTag() const +{ + return pImpl->GetRealLocale(); +} + +const LanguageTag & SvtSysLocaleOptions::GetRealUILanguageTag() const +{ + return pImpl->GetRealUILocale(); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/useroptions.cxx b/unotools/source/config/useroptions.cxx new file mode 100644 index 000000000..fb8b24d9f --- /dev/null +++ b/unotools/source/config/useroptions.cxx @@ -0,0 +1,346 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * 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/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <sal/config.h> + +#include <unotools/useroptions.hxx> +#include <unotools/syslocale.hxx> +#include <com/sun/star/uno/Any.hxx> +#include "itemholder1.hxx" + +#include <cppuhelper/implbase.hxx> +#include <com/sun/star/beans/Property.hpp> +#include <com/sun/star/beans/XPropertySet.hpp> +#include <com/sun/star/beans/PropertyAttribute.hpp> +#include <com/sun/star/container/XNameAccess.hpp> +#include <com/sun/star/util/XChangesListener.hpp> +#include <com/sun/star/util/XChangesNotifier.hpp> +#include <com/sun/star/util/ChangesEvent.hpp> +#include <comphelper/configurationhelper.hxx> +#include <comphelper/processfactory.hxx> +#include <i18nlangtag/mslangid.hxx> +#include <i18nlangtag/languagetag.hxx> +#include <o3tl/enumarray.hxx> +#include <o3tl/string_view.hxx> +#include <tools/diagnose_ex.h> + +using namespace utl; +using namespace com::sun::star; + +// vOptionNames[] -- names of the user option entries +// The order must correspond to the enum class UserOptToken in useroptions.hxx. +static o3tl::enumarray<UserOptToken, char const *> vOptionNames = { + "l", // UserOptToken::City + "o", // UserOptToken::Company + "c", // UserOptToken::Country + "mail", // UserOptToken::Email + "facsimiletelephonenumber", // UserOptToken::Fax + "givenname", // UserOptToken::FirstName + "sn", // UserOptToken::LastName + "position", // UserOptToken::Position + "st", // UserOptToken::State + "street", // UserOptToken::Street + "homephone", // UserOptToken::TelephoneHome + "telephonenumber", // UserOptToken::TelephoneWork + "title", // UserOptToken::Title + "initials", // UserOptToken::ID + "postalcode", // UserOptToken::Zip + "fathersname", // UserOptToken::FathersName + "apartment", // UserOptToken::Apartment + "signingkey", // UserOptToken::SigningKey + "encryptionkey", // UserOptToken::EncryptionKey + "encrypttoself" // UserOptToken::EncryptToSelf +}; + +std::weak_ptr<SvtUserOptions::Impl> SvtUserOptions::xSharedImpl; + +class SvtUserOptions::ChangeListener : public cppu::WeakImplHelper<util::XChangesListener> +{ +public: + explicit ChangeListener (Impl& rParent): m_rParent(rParent) { } + + // XChangesListener + virtual void SAL_CALL changesOccurred (util::ChangesEvent const& Event) override; + // XEventListener + virtual void SAL_CALL disposing (lang::EventObject const& Source) override; + +private: + Impl& m_rParent; +}; + +class SvtUserOptions::Impl : public utl::ConfigurationBroadcaster +{ +public: + Impl (); + + OUString GetFullName () const; + + bool IsTokenReadonly (UserOptToken nToken) const; + OUString GetToken (UserOptToken nToken) const; + void SetToken (UserOptToken nToken, OUString const& rNewToken); + bool GetBoolValue (UserOptToken nToken) const; + void SetBoolValue (UserOptToken nToken, bool bNewValue); + void Notify (); + +private: + uno::Reference<util::XChangesListener> m_xChangeListener; + uno::Reference<container::XNameAccess> m_xCfg; + uno::Reference<beans::XPropertySet> m_xData; + + template < typename ValueType > + ValueType GetValue_Impl( UserOptToken nToken ) const; + template < typename ValueType > + void SetValue_Impl( UserOptToken nToken, ValueType const& rNewValue ); +}; + +void SvtUserOptions::ChangeListener::changesOccurred (util::ChangesEvent const& rEvent) +{ + if (rEvent.Changes.hasElements()) + m_rParent.Notify(); +} + +void SvtUserOptions::ChangeListener::disposing (lang::EventObject const& rSource) +{ + try + { + uno::Reference<util::XChangesNotifier> xChgNot(rSource.Source, uno::UNO_QUERY_THROW); + xChgNot->removeChangesListener(this); + } + catch (uno::Exception&) + { + } +} + +SvtUserOptions::Impl::Impl() : + m_xChangeListener( new ChangeListener(*this) ) +{ + try + { + m_xCfg.set( + comphelper::ConfigurationHelper::openConfig( + comphelper::getProcessComponentContext(), + "org.openoffice.UserProfile/Data", + comphelper::EConfigurationModes::Standard + ), + uno::UNO_QUERY + ); + + m_xData.set(m_xCfg, uno::UNO_QUERY); + uno::Reference<util::XChangesNotifier> xChgNot(m_xCfg, uno::UNO_QUERY); + try + { + xChgNot->addChangesListener(m_xChangeListener); + } + catch (uno::RuntimeException&) + { + } + } + catch (uno::Exception const&) + { + DBG_UNHANDLED_EXCEPTION("unotools.config"); + m_xCfg.clear(); + } +} + +template < typename ValueType > +ValueType SvtUserOptions::Impl::GetValue_Impl (UserOptToken nToken) const +{ + ValueType sToken = ValueType(); + try + { + if (m_xData.is()) + m_xData->getPropertyValue(OUString::createFromAscii(vOptionNames[nToken])) >>= sToken; + } + catch (uno::Exception const&) + { + DBG_UNHANDLED_EXCEPTION("unotools.config"); + } + return sToken; +} + +template < typename ValueType > +void SvtUserOptions::Impl::SetValue_Impl (UserOptToken nToken, ValueType const& sToken) +{ + try + { + if (m_xData.is()) + m_xData->setPropertyValue(OUString::createFromAscii(vOptionNames[nToken]), uno::Any(sToken)); + comphelper::ConfigurationHelper::flush(m_xCfg); + } + catch (uno::Exception const&) + { + DBG_UNHANDLED_EXCEPTION("unotools.config"); + } +} + +OUString SvtUserOptions::Impl::GetToken (UserOptToken nToken) const +{ + return GetValue_Impl<OUString>( nToken ); +} + +void SvtUserOptions::Impl::SetToken (UserOptToken nToken, OUString const& sToken) +{ + SetValue_Impl<OUString>( nToken, sToken ); +} + +bool SvtUserOptions::Impl::GetBoolValue (UserOptToken nToken) const +{ + return GetValue_Impl<bool>( nToken ); +} + +void SvtUserOptions::Impl::SetBoolValue (UserOptToken nToken, bool bNewValue) +{ + SetValue_Impl<bool>( nToken, bNewValue ); +} + +OUString SvtUserOptions::Impl::GetFullName () const +{ + OUString sFullName; + LanguageType const eLang = SvtSysLocale().GetUILanguageTag().getLanguageType(); + if (eLang == LANGUAGE_RUSSIAN) + { + sFullName = GetToken(UserOptToken::FirstName).trim(); + if (!sFullName.isEmpty()) + sFullName += " "; + sFullName += o3tl::trim(GetToken(UserOptToken::FathersName)); + if (!sFullName.isEmpty()) + sFullName += " "; + sFullName += o3tl::trim(GetToken(UserOptToken::LastName)); + } + else + { + if (MsLangId::isFamilyNameFirst(eLang)) + { + sFullName = GetToken(UserOptToken::LastName).trim(); + if (!sFullName.isEmpty()) + sFullName += " "; + sFullName += o3tl::trim(GetToken(UserOptToken::FirstName)); + } + else + { + sFullName = GetToken(UserOptToken::FirstName).trim(); + if (!sFullName.isEmpty()) + sFullName += " "; + sFullName += o3tl::trim(GetToken(UserOptToken::LastName)); + } + } + sFullName = sFullName.trim(); + + return sFullName; +} + +void SvtUserOptions::Impl::Notify () +{ + NotifyListeners(ConfigurationHints::NONE); +} + +bool SvtUserOptions::Impl::IsTokenReadonly (UserOptToken nToken) const +{ + uno::Reference<beans::XPropertySet> xData(m_xCfg, uno::UNO_QUERY); + uno::Reference<beans::XPropertySetInfo> xInfo = xData->getPropertySetInfo(); + beans::Property aProp = xInfo->getPropertyByName(OUString::createFromAscii(vOptionNames[nToken])); + return ((aProp.Attributes & beans::PropertyAttribute::READONLY) == + beans::PropertyAttribute::READONLY); +} + +static std::recursive_mutex& GetInitMutex() +{ + static std::recursive_mutex gMutex; + return gMutex; +} + + +SvtUserOptions::SvtUserOptions () +{ + // Global access, must be guarded (multithreading) + std::unique_lock aGuard(GetInitMutex()); + + xImpl = xSharedImpl.lock(); + if (!xImpl) + { + xImpl = std::make_shared<Impl>(); + xSharedImpl = xImpl; + aGuard.unlock(); // because holdConfigItem will call this constructor + ItemHolder1::holdConfigItem(EItem::UserOptions); + } + xImpl->AddListener(this); +} + +SvtUserOptions::~SvtUserOptions() +{ + // Global access, must be guarded (multithreading) + std::unique_lock aGuard( GetInitMutex() ); + xImpl->RemoveListener(this); +} + +OUString SvtUserOptions::GetCompany () const { return GetToken(UserOptToken::Company); } +OUString SvtUserOptions::GetFirstName () const { return GetToken(UserOptToken::FirstName); } +OUString SvtUserOptions::GetLastName () const { return GetToken(UserOptToken::LastName); } +OUString SvtUserOptions::GetID () const { return GetToken(UserOptToken::ID); } +OUString SvtUserOptions::GetStreet () const { return GetToken(UserOptToken::Street); } +OUString SvtUserOptions::GetCity () const { return GetToken(UserOptToken::City); } +OUString SvtUserOptions::GetState () const { return GetToken(UserOptToken::State); } +OUString SvtUserOptions::GetZip () const { return GetToken(UserOptToken::Zip); } +OUString SvtUserOptions::GetCountry () const { return GetToken(UserOptToken::Country); } +OUString SvtUserOptions::GetPosition () const { return GetToken(UserOptToken::Position); } +OUString SvtUserOptions::GetTitle () const { return GetToken(UserOptToken::Title); } +OUString SvtUserOptions::GetTelephoneHome () const { return GetToken(UserOptToken::TelephoneHome); } +OUString SvtUserOptions::GetTelephoneWork () const { return GetToken(UserOptToken::TelephoneWork); } +OUString SvtUserOptions::GetFax () const { return GetToken(UserOptToken::Fax); } +OUString SvtUserOptions::GetEmail () const { return GetToken(UserOptToken::Email); } +OUString SvtUserOptions::GetSigningKey () const { return GetToken(UserOptToken::SigningKey); } +OUString SvtUserOptions::GetEncryptionKey () const { return GetToken(UserOptToken::EncryptionKey); } + +bool SvtUserOptions::IsTokenReadonly (UserOptToken nToken) const +{ + std::unique_lock aGuard(GetInitMutex()); + return xImpl->IsTokenReadonly(nToken); +} + +OUString SvtUserOptions::GetToken (UserOptToken nToken) const +{ + std::unique_lock aGuard(GetInitMutex()); + return xImpl->GetToken(nToken); +} + +void SvtUserOptions::SetToken (UserOptToken nToken, OUString const& rNewToken) +{ + std::unique_lock aGuard(GetInitMutex()); + xImpl->SetToken(nToken, rNewToken); +} + +void SvtUserOptions::SetBoolValue (UserOptToken nToken, bool bNewValue) +{ + std::unique_lock aGuard(GetInitMutex()); + xImpl->SetBoolValue(nToken, bNewValue); +} + +bool SvtUserOptions::GetEncryptToSelf() const +{ + std::unique_lock aGuard(GetInitMutex()); + return xImpl->GetBoolValue(UserOptToken::EncryptToSelf); +} + +OUString SvtUserOptions::GetFullName () const +{ + std::unique_lock aGuard(GetInitMutex()); + return xImpl->GetFullName(); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/viewoptions.cxx b/unotools/source/config/viewoptions.cxx new file mode 100644 index 000000000..173ccdc10 --- /dev/null +++ b/unotools/source/config/viewoptions.cxx @@ -0,0 +1,450 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * 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/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <unotools/viewoptions.hxx> +#include <com/sun/star/uno/Any.hxx> + +#include <com/sun/star/beans/NamedValue.hpp> +#include <com/sun/star/container/XNameContainer.hpp> +#include <com/sun/star/container/XNameAccess.hpp> +#include <com/sun/star/beans/XPropertySet.hpp> +#include <unotools/configmgr.hxx> +#include <comphelper/configurationhelper.hxx> +#include <comphelper/processfactory.hxx> +#include <utility> +#include <tools/diagnose_ex.h> + +constexpr OUStringLiteral PACKAGE_VIEWS = u"org.openoffice.Office.Views"; +constexpr OUStringLiteral PROPERTY_WINDOWSTATE = u"WindowState"; +constexpr OUStringLiteral PROPERTY_PAGEID = u"PageID"; +constexpr OUStringLiteral PROPERTY_VISIBLE = u"Visible"; +constexpr OUStringLiteral PROPERTY_USERDATA = u"UserData"; + + +SvtViewOptions::SvtViewOptions( EViewType eType, OUString sViewName ) + : m_eViewType ( eType ) + , m_sViewName (std::move( sViewName )) +{ + (void)m_eViewType; // so the release build does not complain, since we only use it in assert + // we must know, which view type we must support + switch( eType ) + { + case EViewType::Dialog: m_sListName = "Dialogs"; break; + case EViewType::TabDialog: m_sListName = "TabDialogs"; break; + case EViewType::TabPage: m_sListName = "TabPages"; break; + case EViewType::Window: m_sListName = "Windows"; break; + default: assert(false); + } + if (utl::ConfigManager::IsFuzzing()) + return; + + try + { + m_xRoot.set( ::comphelper::ConfigurationHelper::openConfig( + ::comphelper::getProcessComponentContext(), + PACKAGE_VIEWS, + ::comphelper::EConfigurationModes::Standard), + css::uno::UNO_QUERY); + if (m_xRoot.is()) + m_xRoot->getByName(m_sListName) >>= m_xSet; + } + catch(const css::uno::Exception&) + { + TOOLS_WARN_EXCEPTION("unotools", "Unexpected exception"); + m_xRoot.clear(); + m_xSet.clear(); + } +} + +// public method + +/*-************************************************************************************************************ + @short checks for already existing entries + @descr If user don't know, if an entry already exist - he can get this information by calling this method. + + @seealso member m_aList + + @param "sName", name of entry to check exist state + @return true , if item exist + false, otherwise +*//*-*************************************************************************************************************/ +bool SvtViewOptions::Exists() const +{ + bool bExists = false; + + try + { + if (m_xSet.is()) + bExists = m_xSet->hasByName(m_sViewName); + } + catch(const css::uno::Exception&) + { + TOOLS_WARN_EXCEPTION("unotools", "Unexpected exception"); + bExists = false; + } + + return bExists; +} + +// public method + +/*-************************************************************************************************************ + @short delete entry + @descr Use it to delete set entry by given name. + + @seealso member m_aList + + @param "sName", name of entry to delete it +*//*-*************************************************************************************************************/ +void SvtViewOptions::Delete() +{ + try + { + css::uno::Reference< css::container::XNameContainer > xSet(m_xSet, css::uno::UNO_QUERY_THROW); + xSet->removeByName(m_sViewName); + ::comphelper::ConfigurationHelper::flush(m_xRoot); + } + catch(const css::container::NoSuchElementException&) + { } + catch(const css::uno::Exception&) + { + TOOLS_WARN_EXCEPTION("unotools", "Unexpected exception"); + } +} + +// public method + +/*-************************************************************************************************************ + @short read/write access to cache view items and her properties + @descr Follow methods support read/write access to all cache view items. + + @seealso member m_sList +*//*-*************************************************************************************************************/ +OUString SvtViewOptions::GetWindowState() const +{ + OUString sWindowState; + try + { + css::uno::Reference< css::beans::XPropertySet > xNode( + impl_getSetNode(m_sViewName, false), + css::uno::UNO_QUERY); + if (xNode.is()) + xNode->getPropertyValue(PROPERTY_WINDOWSTATE) >>= sWindowState; + } + catch(const css::uno::Exception&) + { + TOOLS_WARN_EXCEPTION("unotools", "Unexpected exception"); + sWindowState.clear(); + } + + return sWindowState; +} + + +// public method + +/*-************************************************************************************************************ + @short ctor + @descr We use it to open right configuration file and let configuration objects fill her caches. + Then we read all existing entries from right list and cached it inside our object too. + Normally we should enable notifications for changes on these values too ... but these feature + isn't full implemented in the moment. + + @seealso baseclass ::utl::ConfigItem + @seealso method Notify() +*//*-*************************************************************************************************************/ +void SvtViewOptions::SetWindowState( const OUString& sState ) +{ + try + { + css::uno::Reference< css::beans::XPropertySet > xNode( + impl_getSetNode(m_sViewName, true), + css::uno::UNO_QUERY_THROW); + xNode->setPropertyValue(PROPERTY_WINDOWSTATE, css::uno::Any(sState)); + ::comphelper::ConfigurationHelper::flush(m_xRoot); + } + catch(const css::uno::Exception&) + { + TOOLS_WARN_EXCEPTION("unotools", "Unexpected exception"); + } +} + +// public method + +OString SvtViewOptions::GetPageID() const +{ + // Safe impossible cases. + // These call isn't allowed for dialogs, tab-pages or windows! + assert( m_eViewType == EViewType::TabDialog && "SvtViewOptions::GetPageID()\nCall not allowed for Dialogs, TabPages or Windows! I do nothing!" ); + + OUString sID; + try + { + css::uno::Reference< css::beans::XPropertySet > xNode( + impl_getSetNode(m_sViewName, false), + css::uno::UNO_QUERY); + if (xNode.is()) + xNode->getPropertyValue(PROPERTY_PAGEID) >>= sID; + } + catch(const css::uno::Exception&) + { + TOOLS_WARN_EXCEPTION("unotools", "Unexpected exception"); + } + + return sID.toUtf8(); +} + + +// public method + +void SvtViewOptions::SetPageID(std::string_view rID) +{ + // Safe impossible cases. + // These call isn't allowed for dialogs, tab-pages or windows! + assert( m_eViewType == EViewType::TabDialog && "SvtViewOptions::SetPageID()\nCall not allowed for Dialogs, TabPages or Windows! I do nothing!" ); + + try + { + css::uno::Reference< css::beans::XPropertySet > xNode( + impl_getSetNode(m_sViewName, true), + css::uno::UNO_QUERY_THROW); + xNode->setPropertyValue(PROPERTY_PAGEID, css::uno::Any(OUString::fromUtf8(rID))); + ::comphelper::ConfigurationHelper::flush(m_xRoot); + } + catch(const css::uno::Exception&) + { + TOOLS_WARN_EXCEPTION("unotools", "Unexpected exception"); + } +} + + +// public method + +bool SvtViewOptions::IsVisible() const +{ + // Safe impossible cases. + // These call isn't allowed for dialogs, tab-dialogs or tab-pages! + assert( m_eViewType == EViewType::Window && "SvtViewOptions::IsVisible()\nCall not allowed for Dialogs, TabDialogs or TabPages! I do nothing!" ); + + return GetVisible() == STATE_TRUE; +} + +SvtViewOptions::State SvtViewOptions::GetVisible() const +{ + State eState = STATE_NONE; + try + { + css::uno::Reference< css::beans::XPropertySet > xNode( + impl_getSetNode(m_sViewName, false), + css::uno::UNO_QUERY); + if (xNode.is()) + { + bool bVisible = false; + if (xNode->getPropertyValue(PROPERTY_VISIBLE) >>= bVisible) + { + eState = bVisible ? STATE_TRUE : STATE_FALSE; + } + } + } + catch(const css::uno::Exception&) + { + TOOLS_WARN_EXCEPTION("unotools", "Unexpected exception"); + } + return eState; +} + +// public method + +void SvtViewOptions::SetVisible( bool bVisible ) +{ + // Safe impossible cases. + // These call isn't allowed for dialogs, tab-dialogs or tab-pages! + assert(m_eViewType == EViewType::Window && "SvtViewOptions::SetVisible()\nCall not allowed for Dialogs, TabDialogs or TabPages! I do nothing!" ); + + try + { + css::uno::Reference< css::beans::XPropertySet > xNode( + impl_getSetNode(m_sViewName, true), + css::uno::UNO_QUERY_THROW); + xNode->setPropertyValue(PROPERTY_VISIBLE, css::uno::Any(bVisible)); + ::comphelper::ConfigurationHelper::flush(m_xRoot); + } + catch(const css::uno::Exception&) + { + TOOLS_WARN_EXCEPTION("unotools", "Unexpected exception"); + } +} + +// public method + +bool SvtViewOptions::HasVisible() const +{ + // Safe impossible cases. + // These call isn't allowed for dialogs, tab-dialogs or tab-pages! + assert( m_eViewType == EViewType::Window && "SvtViewOptions::IsVisible()\nCall not allowed for Dialogs, TabDialogs or TabPages! I do nothing!" ); + + return GetVisible() != STATE_NONE; +} + +css::uno::Sequence< css::beans::NamedValue > SvtViewOptions::GetUserData() const +{ + try + { + css::uno::Reference< css::container::XNameAccess > xNode( + impl_getSetNode(m_sViewName, false), + css::uno::UNO_QUERY); // no _THROW ! because we don't create missing items here. So we have to live with zero references .-) + css::uno::Reference< css::container::XNameAccess > xUserData; + if (xNode.is()) + xNode->getByName(PROPERTY_USERDATA) >>= xUserData; + if (xUserData.is()) + { + const css::uno::Sequence<OUString> lNames = xUserData->getElementNames(); + sal_Int32 c = lNames.getLength(); + css::uno::Sequence< css::beans::NamedValue > lUserData(c); + + std::transform(lNames.begin(), lNames.end(), lUserData.getArray(), + [&xUserData](const OUString& rName) -> css::beans::NamedValue { + return { rName, xUserData->getByName(rName) }; }); + + return lUserData; + } + } + catch(const css::uno::Exception&) + { + TOOLS_WARN_EXCEPTION("unotools", "Unexpected exception"); + } + + return css::uno::Sequence< css::beans::NamedValue >(); +} + +void SvtViewOptions::SetUserData( const css::uno::Sequence< css::beans::NamedValue >& lData ) +{ + try + { + css::uno::Reference< css::container::XNameAccess > xNode( + impl_getSetNode(m_sViewName, true), + css::uno::UNO_QUERY_THROW); + css::uno::Reference< css::container::XNameContainer > xUserData; + xNode->getByName(PROPERTY_USERDATA) >>= xUserData; + if (xUserData.is()) + { + for (const css::beans::NamedValue& rData : lData) + { + if (xUserData->hasByName(rData.Name)) + xUserData->replaceByName(rData.Name, rData.Value); + else + xUserData->insertByName(rData.Name, rData.Value); + } + } + ::comphelper::ConfigurationHelper::flush(m_xRoot); + } + catch(const css::uno::Exception&) + { + TOOLS_WARN_EXCEPTION("unotools", "Unexpected exception"); + } +} + +css::uno::Any SvtViewOptions::GetUserItem( const OUString& sItemName ) const +{ + css::uno::Any aItem; + try + { + css::uno::Reference< css::container::XNameAccess > xNode( + impl_getSetNode(m_sViewName, false), + css::uno::UNO_QUERY); + css::uno::Reference< css::container::XNameAccess > xUserData; + if (xNode.is()) + xNode->getByName(PROPERTY_USERDATA) >>= xUserData; + if (xUserData.is()) + aItem = xUserData->getByName(sItemName); + } + catch(const css::container::NoSuchElementException&) + { aItem.clear(); } + catch(const css::uno::Exception&) + { + TOOLS_WARN_EXCEPTION("unotools", "Unexpected exception"); + aItem.clear(); + } + + return aItem; +} + +void SvtViewOptions::SetUserItem( const OUString& sItemName , + const css::uno::Any& aValue ) +{ + try + { + css::uno::Reference< css::container::XNameAccess > xNode( + impl_getSetNode(m_sViewName, true), + css::uno::UNO_QUERY_THROW); + css::uno::Reference< css::container::XNameContainer > xUserData; + xNode->getByName(PROPERTY_USERDATA) >>= xUserData; + if (xUserData.is()) + { + if (xUserData->hasByName(sItemName)) + xUserData->replaceByName(sItemName, aValue); + else + xUserData->insertByName(sItemName, aValue); + } + ::comphelper::ConfigurationHelper::flush(m_xRoot); + } + catch(const css::uno::Exception&) + { + TOOLS_WARN_EXCEPTION("unotools", "Unexpected exception"); + } +} + + + +/*-************************************************************************************************************ + @short create new set node with default values on disk + @descr To create a new UserData item - the super node of these property must already exist! + You can call this method to create these new entry with default values and change UserData then. + + @seealso method impl_writeDirectProp() + + @param "sNode", name of new entry +*//*-*************************************************************************************************************/ +css::uno::Reference< css::uno::XInterface > SvtViewOptions::impl_getSetNode( const OUString& sNode , + bool bCreateIfMissing) const +{ + css::uno::Reference< css::uno::XInterface > xNode; + + try + { + if (bCreateIfMissing) + xNode = ::comphelper::ConfigurationHelper::makeSureSetNodeExists(m_xRoot, m_sListName, sNode); + else + { + if (m_xSet.is() && m_xSet->hasByName(sNode) ) + m_xSet->getByName(sNode) >>= xNode; + } + } + catch(const css::container::NoSuchElementException&) + { xNode.clear(); } + catch(const css::uno::Exception&) + { + TOOLS_WARN_EXCEPTION("unotools", "Unexpected exception"); + xNode.clear(); + } + + return xNode; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ |