diff options
Diffstat (limited to 'unotools/source/config')
46 files changed, 30031 insertions, 0 deletions
diff --git a/unotools/source/config/accelcfg.cxx b/unotools/source/config/accelcfg.cxx new file mode 100644 index 000000000000..5c96ab7d049f --- /dev/null +++ b/unotools/source/config/accelcfg.cxx @@ -0,0 +1,291 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" + +#include "rtl/instance.hxx" +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> +#include <com/sun/star/io/XActiveDataSource.hpp> +#include <com/sun/star/io/XInputStream.hpp> +#include <com/sun/star/io/XOutputStream.hpp> +#include <com/sun/star/xml/sax/XParser.hpp> +#include <unotools/configmgr.hxx> +#include <unotools/configitem.hxx> +#include <tools/debug.hxx> + +#include <osl/mutex.hxx> +#include <tools/string.hxx> +#include <tools/urlobj.hxx> +#include <unotools/streamwrap.hxx> +#include <unotools/ucbstreamhelper.hxx> +#include <comphelper/processfactory.hxx> + +#include <unotools/accelcfg.hxx> +#include <unotools/xmlaccelcfg.hxx> +#include <unotools/pathoptions.hxx> +#include "itemholder1.hxx" + + +using namespace utl; +using namespace rtl; +using namespace com::sun::star::uno; +using namespace com::sun::star::io; +using namespace com::sun::star::xml::sax; + + +static SvtAcceleratorConfig_Impl* pOptions = NULL; +static sal_Int32 nRefCount = 0; + +class SvtAcceleratorConfig_Impl +{ +public: + + SvtAcceleratorItemList aList; + bool bModified; + + SvtAcceleratorConfig_Impl() + : bModified( FALSE ) + {} + + SvtAcceleratorConfig_Impl( Reference< XInputStream >& xInputStream ); + bool Commit( Reference< XOutputStream >& xOutputStream ); +}; + +// ----------------------------------------------------------------------- + +SvtAcceleratorConfig_Impl::SvtAcceleratorConfig_Impl( Reference< XInputStream >& rInputStream ) + : bModified( false ) +{ + Reference< XParser > xParser( ::comphelper::getProcessServiceFactory()->createInstance( + ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.xml.sax.Parser"))), + UNO_QUERY); + + // connect stream to input stream to the parser + InputSource aInputSource; + aInputSource.aInputStream = rInputStream; + + // get filter + Reference< XDocumentHandler > xFilter( new OReadAccelatorDocumentHandler( aList )); + + // connect parser and filter + xParser->setDocumentHandler( xFilter ); + xParser->parseStream( aInputSource ); +} + +bool SvtAcceleratorConfig_Impl::Commit( Reference< XOutputStream >& rOutputStream ) +{ + Reference< XDocumentHandler > xWriter; + + xWriter = Reference< XDocumentHandler >( ::comphelper::getProcessServiceFactory()->createInstance( + ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.xml.sax.Writer"))), UNO_QUERY) ; + + Reference< ::com::sun::star::io::XActiveDataSource> xDataSource( xWriter , UNO_QUERY ); + xDataSource->setOutputStream( rOutputStream ); + try + { + OWriteAccelatorDocumentHandler aWriteHandler( aList, xWriter ); + aWriteHandler.WriteAcceleratorDocument(); + rOutputStream->flush(); + return true; + } + catch ( RuntimeException& ) + { + } + catch ( SAXException& ) + { + } + catch ( ::com::sun::star::io::IOException& ) + { + } + + return false; +} + +namespace +{ + class LocalSingleton : public rtl::Static< osl::Mutex, LocalSingleton > + { + }; +} + +SvtAcceleratorConfiguration::SvtAcceleratorConfiguration() +{ + // Global access, must be guarded (multithreading) + ::osl::MutexGuard aGuard( LocalSingleton::get() ); + if ( !pOptions ) + { + SvStream* pStream = GetDefaultStream( STREAM_STD_READ ); + ::utl::OInputStreamWrapper aHelper( *pStream ); + com::sun::star::uno::Reference < ::com::sun::star::io::XInputStream > xOut( &aHelper ); + + try + { + pOptions = new SvtAcceleratorConfig_Impl( xOut ); + } + catch ( RuntimeException& ) + { + pOptions = new SvtAcceleratorConfig_Impl(); + } + catch( SAXException& ) + { + pOptions = new SvtAcceleratorConfig_Impl(); + } + catch( ::com::sun::star::io::IOException& ) + { + pOptions = new SvtAcceleratorConfig_Impl(); + } + + if (pOptions) + ItemHolder1::holdConfigItem(E_ACCELCFG); + + delete pStream; + } + + ++nRefCount; + pImp = pOptions; +} + +SvtAcceleratorConfiguration* SvtAcceleratorConfiguration::CreateFromStream( SvStream& rStream ) +{ + SvtAcceleratorConfiguration* pRet = new SvtAcceleratorConfiguration; + ::utl::OInputStreamWrapper aHelper( rStream ); + com::sun::star::uno::Reference < ::com::sun::star::io::XInputStream > xOut( &aHelper ); + try + { + pRet->pImp = new SvtAcceleratorConfig_Impl( xOut ); + } + catch ( RuntimeException& ) + { + DELETEZ( pRet ); + } + catch( SAXException& ) + { + DELETEZ( pRet ); + } + catch( ::com::sun::star::io::IOException& ) + { + DELETEZ( pRet ); + } + + return pRet; +} + +// ----------------------------------------------------------------------- + +SvtAcceleratorConfiguration::~SvtAcceleratorConfiguration() +{ + if ( pImp == pOptions ) + { + // Global access, must be guarded (multithreading) + ::osl::MutexGuard aGuard( LocalSingleton::get() ); + if ( !--nRefCount ) + { + if ( pImp->bModified ) + { + String aUserConfig = SvtPathOptions().GetUserConfigPath(); + INetURLObject aObj( aUserConfig ); + aObj.insertName( String::CreateFromAscii("GlobalKeyBindings.xml") ); + SvStream* pStream = ::utl::UcbStreamHelper::CreateStream( aObj.GetMainURL( INetURLObject::NO_DECODE ), STREAM_STD_READWRITE|STREAM_TRUNC ); + ::utl::OOutputStreamWrapper aHelper( *pStream ); + com::sun::star::uno::Reference < ::com::sun::star::io::XOutputStream > xOut( &aHelper ); + pImp->Commit( xOut ); + delete pStream; + } + + DELETEZ( pOptions ); + } + } + else + { + delete pImp; + } +} + +::rtl::OUString SvtAcceleratorConfiguration::GetCommand( const ::com::sun::star::awt::KeyEvent& rKeyEvent ) +{ + sal_Int16 nCode=rKeyEvent.KeyCode, nModifier=rKeyEvent.Modifiers; + if ( !nCode ) + nCode = rKeyEvent.KeyFunc; + + std::list< SvtAcceleratorConfigItem>::const_iterator p; + for ( p = pImp->aList.begin(); p != pImp->aList.end(); p++ ) + if ( p->nCode == nCode && p->nModifier == nModifier ) + return p->aCommand; + + return ::rtl::OUString(); +} + +const SvtAcceleratorItemList& SvtAcceleratorConfiguration::GetItems() +{ + return pImp->aList; +} + +void SvtAcceleratorConfiguration::SetCommand( const SvtAcceleratorConfigItem& rItem ) +{ + std::list< SvtAcceleratorConfigItem>::iterator p; + for ( p = pImp->aList.begin(); p != pImp->aList.end(); p++ ) + if ( p->nCode == rItem.nCode && p->nModifier == rItem.nModifier ) + { + p->aCommand = rItem.aCommand; + return; + } + + pImp->aList.push_back( rItem ); + +} + +void SvtAcceleratorConfiguration::SetItems( const SvtAcceleratorItemList& rItems, bool bClear ) +{ + if ( bClear ) + { + pImp->aList = rItems; + } + else + { + std::list< SvtAcceleratorConfigItem>::const_iterator p; + for ( p = rItems.begin(); p != rItems.end(); p++ ) + SetCommand( *p ); + } +} + +String SvtAcceleratorConfiguration::GetStreamName() +{ + return String::CreateFromAscii("KeyBindings.xml"); +} + +SvStream* SvtAcceleratorConfiguration::GetDefaultStream( StreamMode nMode ) +{ + String aUserConfig = SvtPathOptions().GetUserConfigPath(); + INetURLObject aObj( aUserConfig ); + aObj.insertName( GetStreamName() ); + return ::utl::UcbStreamHelper::CreateStream( aObj.GetMainURL( INetURLObject::NO_DECODE ), nMode ); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/bootstrap.cxx b/unotools/source/config/bootstrap.cxx new file mode 100644 index 000000000000..b620f40e1034 --- /dev/null +++ b/unotools/source/config/bootstrap.cxx @@ -0,0 +1,914 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" + +#include <stdio.h> + +#include "unotools/bootstrap.hxx" + +// --------------------------------------------------------------------------------------- +#include <rtl/ustring.hxx> +#include <rtl/ustrbuf.hxx> +#include <osl/file.hxx> +#include <osl/mutex.hxx> +#include <osl/diagnose.h> +// --------------------------------------------------------------------------------------- +#include <rtl/bootstrap.hxx> +#include <osl/process.h> // for osl_getExecutableFile +#include "tools/getprocessworkingdir.hxx" + +// --------------------------------------------------------------------------------------- +// #define this to a non-zero value, if remembering defaults is not supported properly +#define RTL_BOOTSTRAP_DEFAULTS_BROKEN 1 + +// --------------------------------------------------------------------------------------- +#define BOOTSTRAP_DATA_NAME SAL_CONFIGFILE("bootstrap") + +#define BOOTSTRAP_ITEM_PRODUCT_KEY "ProductKey" +#define BOOTSTRAP_ITEM_PRODUCT_SOURCE "ProductSource" +#define BOOTSTRAP_ITEM_VERSIONFILE "Location" +#define BOOTSTRAP_ITEM_BUILDID "buildid" + +#define BOOTSTRAP_ITEM_BASEINSTALLATION "BaseInstallation" +#define BOOTSTRAP_ITEM_USERINSTALLATION "UserInstallation" + +#define BOOTSTRAP_ITEM_SHAREDIR "SharedDataDir" +#define BOOTSTRAP_ITEM_USERDIR "UserDataDir" + +#define BOOTSTRAP_DEFAULT_BASEINSTALL "$SYSBINDIR/.." + +#define BOOTSTRAP_DIRNAME_SHAREDIR "share" +#define BOOTSTRAP_DIRNAME_USERDIR "user" + +#define VERSIONFILE_SECTION "Versions" + +#define SETUP_DATA_NAME SAL_CONFIGFILE("setup") +#define SETUP_ITEM_ALLUSERS "ALLUSERS" +// --------------------------------------------------------------------------------------- +typedef char const * AsciiString; +// --------------------------------------------------------------------------------------- + +namespace utl +{ +// --------------------------------------------------------------------------------------- + using ::rtl::OUString; + using ::rtl::OUStringBuffer; + using ::rtl::OString; + +// --------------------------------------------------------------------------------------- +// Implementation class: Bootstrap::Impl +// --------------------------------------------------------------------------------------- + + class Bootstrap::Impl + { + OUString const m_aImplName; + public: // struct to cache the result of a path lookup + struct PathData + { + OUString path; + PathStatus status; + + PathData() + : path() + , 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 + explicit + Impl(OUString const& _aImplName) + : m_aImplName(_aImplName) + { + status_ = initialize(); + } + + Status initialize(); + + // access helper + OUString getBootstrapValue(OUString const& _sName, OUString const& _sDefault) const; + sal_Bool getVersionValue(OUString const& _sName, OUString& _rValue, OUString const& _sDefault) const; + + OUString getImplName() const { return m_aImplName; } + + private: // implementation + bool initBaseInstallationData(rtl::Bootstrap& _rData); + bool initUserInstallationData(rtl::Bootstrap& _rData); + }; +// --------------------------------------------------------------------------------------- + static OUString getExecutableDirectory(); +// --------------------------------------------------------------------------------------- + + static Bootstrap::Impl* s_pData = NULL; + + Bootstrap::Impl const& Bootstrap::data() + { + + if (!s_pData) + { + using namespace osl; + MutexGuard aGuard( Mutex::getGlobalMutex() ); + + // static Impl s_theData(getExecutableDirectory() + OUString(RTL_CONSTASCII_USTRINGPARAM("/"BOOTSTRAP_DATA_NAME))); + // s_pData = &s_theData; + rtl::OUString uri; + rtl::Bootstrap::get( + rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("BRAND_BASE_DIR")), uri); + s_pData = new Impl(uri + OUString(RTL_CONSTASCII_USTRINGPARAM("/program/"BOOTSTRAP_DATA_NAME))); + } + return *s_pData; + } + + void Bootstrap::reloadData() + { + if (s_pData != NULL) { + delete s_pData; + s_pData = NULL; + } + } + +// --------------------------------------------------------------------------------------- +// helper +// --------------------------------------------------------------------------------------- + +typedef Bootstrap::PathStatus PathStatus; + +sal_Unicode const cURLSeparator = '/'; + +// --------------------------------------------------------------------------------------- +static +inline +OUString getURLSeparator() +{ + static OUString theSep(&cURLSeparator,1); + return theSep; +} + +// --------------------------------------------------------------------------------------- +// path status utility function +static +PathStatus implCheckStatusOfURL(OUString const& _sURL, osl::DirectoryItem& aDirItem) +{ + using namespace osl; + + PathStatus eStatus = Bootstrap::DATA_UNKNOWN; + + if (_sURL.getLength() != 0) + { + switch( DirectoryItem::get(_sURL, aDirItem) ) + { + case DirectoryItem::E_None: // Success + eStatus = Bootstrap::PATH_EXISTS; + break; + + case DirectoryItem::E_NOENT: // No such file or directory<br> + eStatus = Bootstrap::PATH_VALID; + break; + + case DirectoryItem::E_INVAL: // the format of the parameters was not valid<br> + case DirectoryItem::E_NAMETOOLONG: // File name too long<br> + case DirectoryItem::E_NOTDIR: // A component of the path prefix of path is not a directory<p> + eStatus = Bootstrap::DATA_INVALID; + break; + + // how to handle these ? + case DirectoryItem::E_LOOP: // Too many symbolic links encountered<br> + case DirectoryItem::E_ACCES: // permission denied<br> + // 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 cFileStatusMask = FileStatusMask_FileURL; + + FileStatus aFileStatus(cFileStatusMask); + + if (aDirItem.getFileStatus(aFileStatus) != DirectoryItem::E_None) + return false; + + OUString aNormalizedURL = aFileStatus.getFileURL(); + + if (aNormalizedURL.getLength() == 0) + return false; + + // #109863# sal/osl returns final slash for file URLs contradicting + // the URL/URI RFCs. + if ( aNormalizedURL.getStr()[aNormalizedURL.getLength()-1] != 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(tools::getProcessWorkingDir(&sBasePath)); + + OUString sAbsolute; + if ( File::E_None == File::getAbsoluteFileURL(sBasePath, _rsURL, sAbsolute)) + { + _rsURL = sAbsolute; + return true; + } + else + { + OSL_ENSURE(false, "Could not get absolute file URL for URL"); + return false; + } +} +/* old code to strip embedded dots + static OUString const sDots(RTL_CONSTASCII_USTRINGPARAM("/..")); + + sal_Int32 nDotsIndex = _rsURL.indexOf(sDots); + while (nDotsIndex >= 0) + { + OSL_ASSERT(_rsURL.indexOf(sDots) == nDotsIndex); + + sal_Int32 nStripIndex = _rsURL.lastIndexOf(cURLSeparator,nDotsIndex); + if (nStripIndex < 0 || nStripIndex+1 == nDotsIndex) + { + OSL_TRACE("Invalid use of dots in bootstrap URL"); + return false; + } + _rsURL = _rsURL.copy(0,nStripIndex) + _rsURL.copy(nDotsIndex + sDots.getLength()); + + nDotsIndex = _rsURL.indexOf(sDots,nStripIndex); + } + return true; +} + +*/ +// --------------------------------------------------------------------------------------- + +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); +} +// --------------------------------------------------------------------------------------- +#if OSL_DEBUG_LEVEL > 0 +static +PathStatus dbgCheckStatusOfURL(OUString const& _sURL) +{ + using namespace osl; + + DirectoryItem aDirItem; + + return implCheckStatusOfURL(_sURL,aDirItem); +} +// --------------------------------------------------------------------------------------- +#endif + +static +PathStatus checkStatusAndNormalizeURL(OUString & _sURL) +{ + using namespace osl; + + PathStatus eStatus = Bootstrap::DATA_UNKNOWN; + + if (_sURL.getLength() == 0) + eStatus = Bootstrap::DATA_MISSING; + + else if ( !implMakeAbsoluteURL(_sURL) ) + eStatus = Bootstrap::DATA_INVALID; + + else + { + DirectoryItem aDirItem; + + eStatus = implCheckStatusOfURL(_sURL,aDirItem); + + if (eStatus == Bootstrap::PATH_EXISTS) + { + if (!implNormalizeURL(_sURL,aDirItem)) + OSL_ENSURE(false,"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, + OUString const& _sRelativeURL, + rtl::Bootstrap& _rData, OUString const& _sBootstrapParameter + ) +{ + OUString sDerivedURL; + + OSL_PRECOND(!_rData.getFrom(_sBootstrapParameter,sDerivedURL),"Setting for derived path is already defined"); + OSL_PRECOND(_sRelativeURL.getLength() != 0 && _sRelativeURL[0] != cURLSeparator,"Invalid Relative URL"); + + PathStatus aStatus = _aBaseStatus; + + // do we have a base path ? + if (_aBaseURL.getLength()) + { + OSL_PRECOND(_aBaseURL[_aBaseURL.getLength()-1] != cURLSeparator,"Unexpected: base URL ends in slash"); + + sDerivedURL = _aBaseURL + getURLSeparator() + _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"); + OSL_POSTCOND(RTL_BOOTSTRAP_DEFAULTS_BROKEN || + (_rData.getFrom(_sBootstrapParameter,sDerivedURL) && sDerivedURL==_rURL),"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 +inline +PathStatus getDerivedPath( + OUString& _rURL, + Bootstrap::Impl::PathData const& _aBaseData, + OUString const& _sRelativeURL, + rtl::Bootstrap& _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 + OSL_TRACE("Cannot get executable name: osl_getExecutableFile failed\n"); + + return sExecutable; +} + +// --------------------------------------------------------------------------------------- +static +OUString getExecutableDirectory() +{ + OUString sFileName; + OSL_VERIFY(osl_Process_E_None == osl_getExecutableFile(&sFileName.pData)); + + sal_Int32 nDirEnd = sFileName.lastIndexOf(cURLSeparator); + + OSL_ENSURE(nDirEnd >= 0, "Cannot locate executable directory"); + + return sFileName.copy(0,nDirEnd); +} + +// ---------------------------------------------------------------------------------- + +static +inline +Bootstrap::PathStatus updateStatus(Bootstrap::Impl::PathData & _rResult) +{ + return _rResult.status = checkStatusAndNormalizeURL(_rResult.path); +} +// --------------------------------------------------------------------------------------- + +static +Bootstrap::PathStatus implGetBootstrapFile(rtl::Bootstrap& _rData, Bootstrap::Impl::PathData & _rBootstrapFile) +{ + _rData.getIniName(_rBootstrapFile.path); + + return updateStatus(_rBootstrapFile); +} +// --------------------------------------------------------------------------------------- + +static +Bootstrap::PathStatus implGetVersionFile(rtl::Bootstrap& _rData, Bootstrap::Impl::PathData & _rVersionFile) +{ + OUString const csVersionFileItem(RTL_CONSTASCII_USTRINGPARAM(BOOTSTRAP_ITEM_VERSIONFILE)); + + _rData.getFrom(csVersionFileItem,_rVersionFile.path); + + return updateStatus(_rVersionFile); +} +// --------------------------------------------------------------------------------------- +// Error reporting + +static char const IS_MISSING[] = "is missing"; +static char const IS_INVALID[] = "is corrupt"; +static char const PERIOD[] = ". "; + +// --------------------------------------------------------------------------------------- +static void addFileError(OUStringBuffer& _rBuf, OUString const& _aPath, AsciiString _sWhat) +{ + OUString sSimpleFileName = _aPath.copy(1 +_aPath.lastIndexOf(cURLSeparator)); + + _rBuf.appendAscii("The configuration file"); + _rBuf.appendAscii(" '").append(sSimpleFileName).appendAscii("' "); + _rBuf.appendAscii(_sWhat).appendAscii(PERIOD); +} +// --------------------------------------------------------------------------------------- + +static void addMissingDirectoryError(OUStringBuffer& _rBuf, OUString const& _aPath) +{ + _rBuf.appendAscii("The configuration directory"); + _rBuf.appendAscii(" '").append(_aPath).appendAscii("' "); + _rBuf.appendAscii(IS_MISSING).appendAscii(PERIOD); +} +// --------------------------------------------------------------------------------------- + +static void addUnexpectedError(OUStringBuffer& _rBuf, AsciiString _sExtraInfo = NULL) +{ + if (NULL == _sExtraInfo) + _sExtraInfo = "An internal failure occurred"; + + _rBuf.appendAscii(_sExtraInfo).appendAscii(PERIOD); +} +// --------------------------------------------------------------------------------------- + +static Bootstrap::FailureCode describeError(OUStringBuffer& _rBuf, Bootstrap::Impl const& _rData) +{ + Bootstrap::FailureCode eErrCode = Bootstrap::INVALID_BOOTSTRAP_DATA; + + _rBuf.appendAscii("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; + } + // else fall through + + 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); + 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; +} +// --------------------------------------------------------------------------------------- +// --------------------------------------------------------------------------------------- +// class Bootstrap +// --------------------------------------------------------------------------------------- + +OUString Bootstrap::getProductKey() +{ + OUString const csProductKeyItem(RTL_CONSTASCII_USTRINGPARAM(BOOTSTRAP_ITEM_PRODUCT_KEY)); + + OUString const sDefaultProductKey = getExecutableBaseName(); + + return data().getBootstrapValue( csProductKeyItem, sDefaultProductKey ); +} +// --------------------------------------------------------------------------------------- + +OUString Bootstrap::getProductKey(OUString const& _sDefault) +{ + OUString const csProductKeyItem(RTL_CONSTASCII_USTRINGPARAM(BOOTSTRAP_ITEM_PRODUCT_KEY)); + + return data().getBootstrapValue( csProductKeyItem, _sDefault ); +} +// --------------------------------------------------------------------------------------- + +OUString Bootstrap::getProductSource(OUString const& _sDefault) +{ + OUString const csProductSourceItem(RTL_CONSTASCII_USTRINGPARAM(BOOTSTRAP_ITEM_PRODUCT_SOURCE)); + + OUString sProductSource; + // read ProductSource from version.ini (versionrc) + data().getVersionValue( csProductSourceItem, sProductSource, _sDefault ); + return sProductSource; +} +// --------------------------------------------------------------------------------------- + +OUString Bootstrap::getBuildIdData(OUString const& _sDefault) +{ + OUString const csBuildIdItem(RTL_CONSTASCII_USTRINGPARAM(BOOTSTRAP_ITEM_BUILDID)); + + OUString sBuildId; + // read buildid from version.ini (versionrc), if it doesn't exist or buildid is empty + if ( data().getVersionValue( csBuildIdItem, sBuildId, _sDefault ) != sal_True || + sBuildId.getLength() == 0 ) + // read buildid from bootstrap.ini (bootstraprc) + sBuildId = data().getBootstrapValue( csBuildIdItem, _sDefault ); + return sBuildId; +} +// --------------------------------------------------------------------------------------- + +OUString Bootstrap::getAllUsersValue(OUString const& _sDefault) +{ + OUString const csAllUsersItem(RTL_CONSTASCII_USTRINGPARAM(SETUP_ITEM_ALLUSERS)); + + rtl::Bootstrap aData( getExecutableDirectory() + OUString( RTL_CONSTASCII_USTRINGPARAM( "/"SETUP_DATA_NAME ) ) ); + OUString sResult; + aData.getFrom( csAllUsersItem, sResult, _sDefault ); + return sResult; +} +// --------------------------------------------------------------------------------------- + +Bootstrap::PathStatus Bootstrap::locateBaseInstallation(OUString& _rURL) +{ + Impl::PathData const& aPathData = data().aBaseInstall_; + + _rURL = aPathData.path; + return aPathData.status; +} +// --------------------------------------------------------------------------------------- + +PathStatus Bootstrap::locateUserInstallation(OUString& _rURL) +{ + Impl::PathData const& aPathData = data().aUserInstall_; + + _rURL = aPathData.path; + return aPathData.status; +} +// --------------------------------------------------------------------------------------- + +PathStatus Bootstrap::locateSharedData(OUString& _rURL) +{ + OUString const csShareDirItem(RTL_CONSTASCII_USTRINGPARAM(BOOTSTRAP_ITEM_SHAREDIR)); + + rtl::Bootstrap aData( data().getImplName() ); + + if ( aData.getFrom(csShareDirItem, _rURL) ) + { + return checkStatusAndNormalizeURL(_rURL); + } + else + { + OUString const csShareDir(RTL_CONSTASCII_USTRINGPARAM(BOOTSTRAP_DIRNAME_SHAREDIR)); + return getDerivedPath(_rURL, data().aBaseInstall_, csShareDir, aData, csShareDirItem); + } +} +// --------------------------------------------------------------------------------------- + +PathStatus Bootstrap::locateUserData(OUString& _rURL) +{ + OUString const csUserDirItem(RTL_CONSTASCII_USTRINGPARAM(BOOTSTRAP_ITEM_USERDIR)); + + rtl::Bootstrap aData( data().getImplName() ); + + if ( aData.getFrom(csUserDirItem, _rURL) ) + { + return checkStatusAndNormalizeURL(_rURL); + } + else + { + OUString const csUserDir(RTL_CONSTASCII_USTRINGPARAM(BOOTSTRAP_DIRNAME_USERDIR)); + return getDerivedPath(_rURL, data().aUserInstall_ ,csUserDir, aData, csUserDirItem); + } +} +// --------------------------------------------------------------------------------------- + +PathStatus Bootstrap::locateBootstrapFile(OUString& _rURL) +{ + Impl::PathData const& aPathData = data().aBootstrapINI_; + + _rURL = aPathData.path; + return aPathData.status; +} +// --------------------------------------------------------------------------------------- + +PathStatus Bootstrap::locateVersionFile(OUString& _rURL) +{ + Impl::PathData const& aPathData = data().aVersionINI_; + + _rURL = aPathData.path; + return aPathData.status; +} +// --------------------------------------------------------------------------------------- + +Bootstrap::Status Bootstrap::checkBootstrapStatus(OUString& _rDiagnosticMessage) +{ + FailureCode eDummyCode(NO_FAILURE); + + return checkBootstrapStatus(_rDiagnosticMessage,eDummyCode); +} +// --------------------------------------------------------------------------------------- + +Bootstrap::Status Bootstrap::checkBootstrapStatus(rtl::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; +} + +// --------------------------------------------------------------------------------------- +// class Bootstrap::Impl +// --------------------------------------------------------------------------------------- + +bool Bootstrap::Impl::initBaseInstallationData(rtl::Bootstrap& _rData) +{ + OUString const csBaseInstallItem( RTL_CONSTASCII_USTRINGPARAM(BOOTSTRAP_ITEM_BASEINSTALLATION) ); + OUString const csBaseInstallDefault( RTL_CONSTASCII_USTRINGPARAM(BOOTSTRAP_DEFAULT_BASEINSTALL) ); + + _rData.getFrom(csBaseInstallItem, aBaseInstall_.path, csBaseInstallDefault); + + bool bResult = (PATH_EXISTS == updateStatus(aBaseInstall_)); + + implGetBootstrapFile(_rData, aBootstrapINI_); + + return bResult; +} +// --------------------------------------------------------------------------------------- + +bool Bootstrap::Impl::initUserInstallationData(rtl::Bootstrap& _rData) +{ + OUString const csUserInstallItem( RTL_CONSTASCII_USTRINGPARAM(BOOTSTRAP_ITEM_USERINSTALLATION) ); + + if (_rData.getFrom(csUserInstallItem, 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(RTL_CONSTASCII_USTRINGPARAM(BOOTSTRAP_ITEM_USERDIR)); + OUString sDummy; + // look for $BASEINSTALLATION/user only if default UserDir setting is used + if (! _rData.getFrom(csUserDirItem, sDummy)) + { + OUString const csUserDir(RTL_CONSTASCII_USTRINGPARAM(BOOTSTRAP_DIRNAME_USERDIR)); + + if ( PATH_EXISTS == getDerivedPath(sDummy, aBaseInstall_, csUserDir, _rData, csUserDirItem) ) + aUserInstall_ = aBaseInstall_; + } + } + + bool bResult = (PATH_EXISTS == aUserInstall_.status); + + implGetVersionFile(_rData, aVersionINI_); + + return bResult; +} +// --------------------------------------------------------------------------------------- + +Bootstrap::Status Bootstrap::Impl::initialize() +{ + Bootstrap::Status result; + + rtl::Bootstrap aData( m_aImplName ); + + if (!initBaseInstallationData(aData)) + { + result = INVALID_BASE_INSTALL; + } + else if (!initUserInstallationData(aData)) + { + result = INVALID_USER_INSTALL; + + if (aUserInstall_.status >= DATA_MISSING) + { + switch (aVersionINI_.status) + { + case PATH_EXISTS: + case PATH_VALID: + result = MISSING_USER_INSTALL; + break; + + case DATA_INVALID: + case DATA_MISSING: + result = INVALID_BASE_INSTALL; + break; + default: + break; + } + } + } + else + { + result = DATA_OK; + } + return result; +} +// --------------------------------------------------------------------------------------- + +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; +} +// --------------------------------------------------------------------------------------- + +sal_Bool Bootstrap::Impl::getVersionValue(OUString const& _sName, OUString& _rValue, OUString const& _sDefault) const +{ + // try to open version.ini (versionrc) + rtl::OUString uri; + rtl::Bootstrap::get( + rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("BRAND_BASE_DIR")), uri); + rtl::Bootstrap aData( uri + + OUString(RTL_CONSTASCII_USTRINGPARAM("/program/"SAL_CONFIGFILE("version"))) ); + if ( aData.getHandle() == NULL ) + // version.ini (versionrc) doesn't exist + return sal_False; + + // read value + aData.getFrom(_sName,_rValue,_sDefault); + return sal_True; +} +// --------------------------------------------------------------------------------------- + +} // namespace utl + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/cacheoptions.cxx b/unotools/source/config/cacheoptions.cxx new file mode 100644 index 000000000000..45f0850e8969 --- /dev/null +++ b/unotools/source/config/cacheoptions.cxx @@ -0,0 +1,509 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" + +#include <unotools/cacheoptions.hxx> +#include <unotools/configmgr.hxx> +#include <unotools/configitem.hxx> +#include <tools/debug.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> + +//_________________________________________________________________________________________________________________ +// namespaces +//_________________________________________________________________________________________________________________ + +using namespace ::utl; +using namespace ::rtl; +using namespace ::osl; +using namespace ::com::sun::star::uno; + +//_________________________________________________________________________________________________________________ +// const +//_________________________________________________________________________________________________________________ + +#define ROOTNODE_START OUString(RTL_CONSTASCII_USTRINGPARAM("Office.Common/Cache" )) +#define DEFAULT_WRITEROLE 20 +#define DEFAULT_DRAWINGOLE 20 +#define DEFAULT_GRFMGR_TOTALSIZE 10000000 +#define DEFAULT_GRFMGR_OBJECTSIZE 2400000 +#define DEFAULT_GRFMGR_OBJECTRELEASE 600 + +#define PROPERTYNAME_WRITEROLE OUString(RTL_CONSTASCII_USTRINGPARAM("Writer/OLE_Objects")) +#define PROPERTYNAME_DRAWINGOLE OUString(RTL_CONSTASCII_USTRINGPARAM("DrawingEngine/OLE_Objects")) +#define PROPERTYNAME_GRFMGR_TOTALSIZE OUString(RTL_CONSTASCII_USTRINGPARAM("GraphicManager/TotalCacheSize")) +#define PROPERTYNAME_GRFMGR_OBJECTSIZE OUString(RTL_CONSTASCII_USTRINGPARAM("GraphicManager/ObjectCacheSize")) +#define PROPERTYNAME_GRFMGR_OBJECTRELEASE OUString(RTL_CONSTASCII_USTRINGPARAM("GraphicManager/ObjectReleaseTime")) + +#define PROPERTYHANDLE_WRITEROLE 0 +#define PROPERTYHANDLE_DRAWINGOLE 1 +#define PROPERTYHANDLE_GRFMGR_TOTALSIZE 2 +#define PROPERTYHANDLE_GRFMGR_OBJECTSIZE 3 +#define PROPERTYHANDLE_GRFMGR_OBJECTRELEASE 4 + +#define PROPERTYCOUNT 5 + +class SvtCacheOptions_Impl : public ConfigItem +{ +public: + +//--------------------------------------------------------------------------------------------------------- +// constructor / destructor +//--------------------------------------------------------------------------------------------------------- + + SvtCacheOptions_Impl(); + ~SvtCacheOptions_Impl(); + +//--------------------------------------------------------------------------------------------------------- +// overloaded methods of baseclass +//--------------------------------------------------------------------------------------------------------- + + virtual void Commit(); + virtual void Notify( const com::sun::star::uno::Sequence< rtl::OUString >& aPropertyNames ); + +//--------------------------------------------------------------------------------------------------------- +// public interface +//--------------------------------------------------------------------------------------------------------- + + sal_Int32 GetWriterOLE_Objects() const; + sal_Int32 GetDrawingEngineOLE_Objects() const; + sal_Int32 GetGraphicManagerTotalCacheSize() const; + sal_Int32 GetGraphicManagerObjectCacheSize() const; + sal_Int32 GetGraphicManagerObjectReleaseTime() const; + + void SetWriterOLE_Objects( sal_Int32 nObjects ); + void SetDrawingEngineOLE_Objects( sal_Int32 nObjects ); + void SetGraphicManagerTotalCacheSize( sal_Int32 nTotalCacheSize ); + void SetGraphicManagerObjectCacheSize( sal_Int32 nObjectCacheSize ); + void SetGraphicManagerObjectReleaseTime( sal_Int32 nReleaseTimeSeconds ); + +//------------------------------------------------------------------------------------------------------------- +// private methods +//------------------------------------------------------------------------------------------------------------- + +private: + + static Sequence< OUString > impl_GetPropertyNames(); + +//------------------------------------------------------------------------------------------------------------- +// private member +//------------------------------------------------------------------------------------------------------------- + +private: + + sal_Int32 mnWriterOLE; + sal_Int32 mnDrawingOLE; + sal_Int32 mnGrfMgrTotalSize; + sal_Int32 mnGrfMgrObjectSize; + sal_Int32 mnGrfMgrObjectRelease; +}; + +//_________________________________________________________________________________________________________________ +// definitions +//_________________________________________________________________________________________________________________ + +//***************************************************************************************************************** +// constructor +//***************************************************************************************************************** +SvtCacheOptions_Impl::SvtCacheOptions_Impl() : + ConfigItem( ROOTNODE_START ), + mnWriterOLE( DEFAULT_WRITEROLE ), + mnDrawingOLE( DEFAULT_DRAWINGOLE ), + mnGrfMgrTotalSize( DEFAULT_GRFMGR_TOTALSIZE ), + mnGrfMgrObjectSize( DEFAULT_GRFMGR_OBJECTSIZE ), + mnGrfMgrObjectRelease( DEFAULT_GRFMGR_OBJECTRELEASE ) +{ + Sequence< OUString > seqNames( impl_GetPropertyNames() ); + Sequence< Any > seqValues = GetProperties( seqNames ) ; + + DBG_ASSERT( !(seqNames.getLength()!=seqValues.getLength()), "SvtCacheOptions_Impl::SvtCacheOptions_Impl()\nI miss some values of configuration keys!\n" ); + + // Copy values from list in right order to ouer internal member. + sal_Int32 nPropertyCount = seqValues.getLength(); + sal_Int32 nProperty = 0; + + for( nProperty=0; nProperty<nPropertyCount; ++nProperty ) + { + if( seqValues[ nProperty ].hasValue() ) + { + switch( nProperty ) + { + case PROPERTYHANDLE_WRITEROLE: + { + if( seqValues[ nProperty ].getValueTypeClass() == TypeClass_LONG ) + seqValues[nProperty] >>= mnWriterOLE; + } + break; + + case PROPERTYHANDLE_DRAWINGOLE: + { + if( seqValues[ nProperty ].getValueTypeClass() == TypeClass_LONG ) + seqValues[nProperty] >>= mnDrawingOLE; + } + break; + + case PROPERTYHANDLE_GRFMGR_TOTALSIZE: + { + if( seqValues[ nProperty ].getValueTypeClass() == TypeClass_LONG ) + seqValues[nProperty] >>= mnGrfMgrTotalSize; + } + break; + + case PROPERTYHANDLE_GRFMGR_OBJECTSIZE: + { + if( seqValues[ nProperty ].getValueTypeClass() == TypeClass_LONG ) + seqValues[nProperty] >>= mnGrfMgrObjectSize; + } + break; + + case PROPERTYHANDLE_GRFMGR_OBJECTRELEASE: + { + if( seqValues[ nProperty ].getValueTypeClass() == TypeClass_LONG ) + seqValues[nProperty] >>= mnGrfMgrObjectRelease; + } + break; + } + } + } +} + +//***************************************************************************************************************** +// destructor +//***************************************************************************************************************** +SvtCacheOptions_Impl::~SvtCacheOptions_Impl() +{ + if( IsModified() ) + Commit(); +} + +//***************************************************************************************************************** +// Commit +//***************************************************************************************************************** +void SvtCacheOptions_Impl::Commit() +{ + Sequence< OUString > aSeqNames( impl_GetPropertyNames() ); + Sequence< Any > aSeqValues( aSeqNames.getLength() ); + + for( sal_Int32 nProperty = 0, nCount = aSeqNames.getLength(); nProperty < nCount; ++nProperty ) + { + switch( nProperty ) + { + case PROPERTYHANDLE_WRITEROLE: + aSeqValues[nProperty] <<= mnWriterOLE; + break; + + case PROPERTYHANDLE_DRAWINGOLE: + aSeqValues[nProperty] <<= mnDrawingOLE; + break; + + case PROPERTYHANDLE_GRFMGR_TOTALSIZE: + aSeqValues[nProperty] <<= mnGrfMgrTotalSize; + break; + + case PROPERTYHANDLE_GRFMGR_OBJECTSIZE: + aSeqValues[nProperty] <<= mnGrfMgrObjectSize; + break; + + case PROPERTYHANDLE_GRFMGR_OBJECTRELEASE: + aSeqValues[nProperty] <<= mnGrfMgrObjectRelease; + break; + } + } + + PutProperties( aSeqNames, aSeqValues ); +} + +void SvtCacheOptions_Impl::Notify( const Sequence< rtl::OUString >& ) +{ +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Int32 SvtCacheOptions_Impl::GetWriterOLE_Objects() const +{ + return mnWriterOLE; +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Int32 SvtCacheOptions_Impl::GetDrawingEngineOLE_Objects() const +{ + return mnDrawingOLE; +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Int32 SvtCacheOptions_Impl::GetGraphicManagerTotalCacheSize() const +{ + return mnGrfMgrTotalSize; +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Int32 SvtCacheOptions_Impl::GetGraphicManagerObjectCacheSize() const +{ + return mnGrfMgrObjectSize; +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Int32 SvtCacheOptions_Impl::GetGraphicManagerObjectReleaseTime() const +{ + return mnGrfMgrObjectRelease; +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtCacheOptions_Impl::SetWriterOLE_Objects( sal_Int32 nWriterOLE ) +{ + mnWriterOLE = nWriterOLE; + SetModified(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtCacheOptions_Impl::SetDrawingEngineOLE_Objects( sal_Int32 nDrawingOLE ) +{ + mnDrawingOLE = nDrawingOLE; + SetModified(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtCacheOptions_Impl::SetGraphicManagerTotalCacheSize( sal_Int32 nGrfMgrTotalSize ) +{ + mnGrfMgrTotalSize = nGrfMgrTotalSize; + SetModified(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtCacheOptions_Impl::SetGraphicManagerObjectCacheSize( sal_Int32 nGrfMgrObjectSize ) +{ + mnGrfMgrObjectSize = nGrfMgrObjectSize; + SetModified(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtCacheOptions_Impl::SetGraphicManagerObjectReleaseTime( sal_Int32 nGrfMgrObjectReleaseTime ) +{ + mnGrfMgrObjectRelease = nGrfMgrObjectReleaseTime; + SetModified(); +} + +//***************************************************************************************************************** +// private method +//***************************************************************************************************************** +Sequence< OUString > SvtCacheOptions_Impl::impl_GetPropertyNames() +{ + // Build static list of configuration key names. + static const OUString pProperties[] = + { + PROPERTYNAME_WRITEROLE, + PROPERTYNAME_DRAWINGOLE, + PROPERTYNAME_GRFMGR_TOTALSIZE, + PROPERTYNAME_GRFMGR_OBJECTSIZE, + PROPERTYNAME_GRFMGR_OBJECTRELEASE + }; + // Initialize return sequence with these list ... + static const Sequence< OUString > seqPropertyNames( pProperties, PROPERTYCOUNT ); + // ... and return it. + return seqPropertyNames; +} + +//***************************************************************************************************************** +// initialize static member +// DON'T DO IT IN YOUR HEADER! +// see definition for further informations +//***************************************************************************************************************** +SvtCacheOptions_Impl* SvtCacheOptions::m_pDataContainer = NULL; +sal_Int32 SvtCacheOptions::m_nRefCount = 0; + +//***************************************************************************************************************** +// constructor +//***************************************************************************************************************** +SvtCacheOptions::SvtCacheOptions() +{ + // Global access, must be guarded (multithreading!). + MutexGuard aGuard( GetOwnStaticMutex() ); + // Increase ouer refcount ... + ++m_nRefCount; + // ... and initialize ouer data container only if it not already! + if( m_pDataContainer == NULL ) + { + m_pDataContainer = new SvtCacheOptions_Impl(); + } +} + +//***************************************************************************************************************** +// destructor +//***************************************************************************************************************** +SvtCacheOptions::~SvtCacheOptions() +{ + // Global access, must be guarded (multithreading!) + MutexGuard aGuard( GetOwnStaticMutex() ); + // Decrease ouer refcount. + --m_nRefCount; + // If last instance was deleted ... + // we must destroy ouer static data container! + if( m_nRefCount <= 0 ) + { + delete m_pDataContainer; + m_pDataContainer = NULL; + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Int32 SvtCacheOptions::GetWriterOLE_Objects() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->GetWriterOLE_Objects(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Int32 SvtCacheOptions::GetDrawingEngineOLE_Objects() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->GetDrawingEngineOLE_Objects(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Int32 SvtCacheOptions::GetGraphicManagerTotalCacheSize() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->GetGraphicManagerTotalCacheSize(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Int32 SvtCacheOptions::GetGraphicManagerObjectCacheSize() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->GetGraphicManagerObjectCacheSize(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Int32 SvtCacheOptions::GetGraphicManagerObjectReleaseTime() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->GetGraphicManagerObjectReleaseTime(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtCacheOptions::SetWriterOLE_Objects( sal_Int32 nWriterOLE ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetWriterOLE_Objects( nWriterOLE ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtCacheOptions::SetDrawingEngineOLE_Objects( sal_Int32 nDrawingOLE ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetDrawingEngineOLE_Objects( nDrawingOLE ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtCacheOptions::SetGraphicManagerTotalCacheSize( sal_Int32 nGrfMgrTotalSize ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetGraphicManagerTotalCacheSize( nGrfMgrTotalSize ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtCacheOptions::SetGraphicManagerObjectCacheSize( sal_Int32 nGrfMgrObjectSize ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetGraphicManagerObjectCacheSize( nGrfMgrObjectSize ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtCacheOptions::SetGraphicManagerObjectReleaseTime( sal_Int32 nGrfMgrObjectReleaseTime ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetGraphicManagerObjectReleaseTime( nGrfMgrObjectReleaseTime ); +} + +//***************************************************************************************************************** +// private method +//***************************************************************************************************************** +Mutex& SvtCacheOptions::GetOwnStaticMutex() +{ + // Initialize static mutex only for one time! + static Mutex* pMutex = NULL; + // If these method first called (Mutex not already exist!) ... + if( pMutex == NULL ) + { + // ... we must create a new one. Protect follow code with the global mutex - + // It must be - we create a static variable! + MutexGuard aGuard( Mutex::getGlobalMutex() ); + // We must check our pointer again - because it can be that another instance of ouer class will be fastr then these! + if( pMutex == NULL ) + { + // Create the new mutex and set it for return on static variable. + static Mutex aMutex; + pMutex = &aMutex; + } + } + // Return new created or already existing mutex object. + return *pMutex; +} + +/* 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 000000000000..3d8fea23c175 --- /dev/null +++ b/unotools/source/config/cmdoptions.cxx @@ -0,0 +1,631 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" + +//_________________________________________________________________________________________________________________ +// includes +//_________________________________________________________________________________________________________________ + +#include <unotools/cmdoptions.hxx> +#include <unotools/configmgr.hxx> +#include <unotools/configitem.hxx> +#include <tools/debug.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> +#include <cppuhelper/weakref.hxx> +#include <tools/urlobj.hxx> +#include <rtl/ustrbuf.hxx> + +#include <itemholder1.hxx> + +#include <algorithm> +#include <hash_map> + +//_________________________________________________________________________________________________________________ +// namespaces +//_________________________________________________________________________________________________________________ + +using namespace ::std ; +using namespace ::utl ; +using namespace ::rtl ; +using namespace ::osl ; +using namespace ::com::sun::star::uno ; +using namespace ::com::sun::star::beans ; + +//_________________________________________________________________________________________________________________ +// const +//_________________________________________________________________________________________________________________ + +#define ROOTNODE_CMDOPTIONS OUString(RTL_CONSTASCII_USTRINGPARAM("Office.Commands/Execute" )) +#define PATHDELIMITER OUString(RTL_CONSTASCII_USTRINGPARAM("/" )) + +#define SETNODE_DISABLED OUString(RTL_CONSTASCII_USTRINGPARAM("Disabled" )) + +#define PROPERTYNAME_CMD OUString(RTL_CONSTASCII_USTRINGPARAM("Command" )) + +#define PROPERTYCOUNT 1 + +#define OFFSET_CMD 0 + +//_________________________________________________________________________________________________________________ +// private declarations! +//_________________________________________________________________________________________________________________ + +// Method to retrieve a hash code from a string. May be we have to change it to decrease collisions in the hash map +struct OUStringHashCode +{ + size_t operator()( const ::rtl::OUString& sString ) const + { + return sString.hashCode(); + } +}; + +/*-**************************************************************************************************************** + @descr support simple command option structures and operations on it +****************************************************************************************************************-*/ +class SvtCmdOptions +{ + public: + //--------------------------------------------------------------------------------------------------------- + // the only way to free memory! + void Clear() + { + m_aCommandHashMap.clear(); + } + + sal_Bool HasEntries() const + { + return ( m_aCommandHashMap.size() > 0 ); + } + + void SetContainerSize( sal_Int32 nSize ) + { + m_aCommandHashMap.resize( nSize ); + } + + sal_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.insert( CommandHashMap::value_type( aCmd, 0 ) ); + } + + //--------------------------------------------------------------------------------------------------------- + // convert internal list to external format + // for using it on right menus realy + // Notice: We build a property list with 4 entries and set it on result list then. + // The while-loop starts with pointer on internal member list lSetupEntries, change to + // lUserEntries then and stop after that with NULL! + // Separator entries will be packed in another way then normal entries! We define + // special strings "sEmpty" and "sSeperator" to perform too ... + Sequence< OUString > GetList() const + { + sal_Int32 nCount = (sal_Int32)m_aCommandHashMap.size(); + sal_Int32 nIndex = 0; + Sequence< OUString > aList( nCount ); + + CommandHashMap::const_iterator pEntry = m_aCommandHashMap.begin(); + while ( pEntry != m_aCommandHashMap.end() ) + aList[nIndex++] = pEntry->first; + + return aList; + } + + private: + class CommandHashMap : public ::std::hash_map< ::rtl::OUString , + sal_Int32 , + OUStringHashCode , + ::std::equal_to< ::rtl::OUString > > + { + public: + inline void free() + { + CommandHashMap().swap( *this ); + } + }; + + CommandHashMap m_aCommandHashMap; +}; + +typedef ::std::vector< ::com::sun::star::uno::WeakReference< ::com::sun::star::frame::XFrame > > SvtFrameVector; + +class SvtCommandOptions_Impl : public ConfigItem +{ + //------------------------------------------------------------------------------------------------------------- + // public methods + //------------------------------------------------------------------------------------------------------------- + + public: + + //--------------------------------------------------------------------------------------------------------- + // constructor / destructor + //--------------------------------------------------------------------------------------------------------- + + SvtCommandOptions_Impl(); + ~SvtCommandOptions_Impl(); + + //--------------------------------------------------------------------------------------------------------- + // overloaded methods of baseclass + //--------------------------------------------------------------------------------------------------------- + + /*-****************************************************************************************************//** + @short called for notify of configmanager + @descr These method is called from the ConfigManager before 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. + @return - + + @onerror - + *//*-*****************************************************************************************************/ + + virtual void Notify( const Sequence< OUString >& lPropertyNames ); + + /*-****************************************************************************************************//** + @short write changes to configuration + @descr These method writes the changed values into the sub tree + and should always called in our destructor to guarantee consistency of config data. + + @seealso baseclass ConfigItem + + @param - + @return - + + @onerror - + *//*-*****************************************************************************************************/ + + virtual void Commit(); + + //--------------------------------------------------------------------------------------------------------- + // public interface + //--------------------------------------------------------------------------------------------------------- + + /*-****************************************************************************************************//** + @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! + + @seealso - + + @param - + @return - + + @onerror - + *//*-*****************************************************************************************************/ + + void Clear ( SvtCommandOptions::CmdOption eCmdOption ); + sal_Bool HasEntries ( SvtCommandOptions::CmdOption eOption ) const; + sal_Bool Lookup ( SvtCommandOptions::CmdOption eCmdOption, const OUString& ) const; + Sequence< OUString > GetList ( SvtCommandOptions::CmdOption eCmdOption ) const ; + void AddCommand ( SvtCommandOptions::CmdOption eCmdOption, + const OUString& sURL ); + void EstablisFrameCallback(const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame); + + //------------------------------------------------------------------------------------------------------------- + // private methods + //------------------------------------------------------------------------------------------------------------- + + private: + + /*-****************************************************************************************************//** + @short return list of key names of our configuration management which represent oue 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! + + @seealso - + + @param "nDisabledCount" , returns count of menu entries for "new" + @return A list of configuration key names is returned. + + @onerror - + *//*-*****************************************************************************************************/ + + Sequence< OUString > impl_GetPropertyNames(); + + //------------------------------------------------------------------------------------------------------------- + // private member + //------------------------------------------------------------------------------------------------------------- + + private: + SvtCmdOptions m_aDisabledCommands; + SvtFrameVector m_lFrames; +}; + +//_________________________________________________________________________________________________________________ +// definitions +//_________________________________________________________________________________________________________________ + +//***************************************************************************************************************** +// constructor +//***************************************************************************************************************** +SvtCommandOptions_Impl::SvtCommandOptions_Impl() + // Init baseclasses first + : ConfigItem( ROOTNODE_CMDOPTIONS ) + // Init member then... +{ + // Get names and values of all accessable menu entries and fill internal structures. + // See impl_GetPropertyNames() for further informations. + 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 ouer internal member. + // Attention: List for names and values have an internal construction pattern! + sal_Int32 nItem = 0 ; + OUString sCmd ; + + // Set size of hash_map reach a used size of approx. 60% + m_aDisabledCommands.SetContainerSize( lNames.getLength() * 10 / 6 ); + + // 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 ouer baseclass. + // We need it to get information about changes outside these class on ouer used configuration keys! */ + Sequence< OUString > aNotifySeq( 1 ); + aNotifySeq[0] = OUString( RTL_CONSTASCII_USTRINGPARAM( "Disabled" )); + EnableNotification( aNotifySeq, sal_True ); +} + +//***************************************************************************************************************** +// destructor +//***************************************************************************************************************** +SvtCommandOptions_Impl::~SvtCommandOptions_Impl() +{ + // We must save our current values .. if user forget it! + if( IsModified() == sal_True ) + { + Commit(); + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtCommandOptions_Impl::Notify( const Sequence< OUString >& ) +{ + MutexGuard aGuard( SvtCommandOptions::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::SvtCommandOptions_Impl()\nI miss some values of configuration keys!\n" ); + + // Copy values from list in right order to ouer internal member. + // Attention: List for names and values have an internal construction pattern! + sal_Int32 nItem = 0 ; + OUString sCmd ; + + // Set size of hash_map reach a used size of approx. 60% + m_aDisabledCommands.Clear(); + m_aDisabledCommands.SetContainerSize( lNames.getLength() * 10 / 6 ); + + // Get names/values for disabled commands. + for( nItem=0; nItem < lNames.getLength(); ++nItem ) + { + // Currently only one value + lValues[nItem] >>= sCmd; + m_aDisabledCommands.AddCommand( sCmd ); + } + + // dont 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::const_iterator pIt = m_lFrames.begin(); + pIt != m_lFrames.end() ; + ++pIt ) + { + ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame(pIt->get(), ::com::sun::star::uno::UNO_QUERY); + if (xFrame.is()) + xFrame->contextChanged(); + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtCommandOptions_Impl::Commit() +{ + DBG_ERROR( "SvtCommandOptions_Impl::Commit()\nNot implemented yet!\n" ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtCommandOptions_Impl::Clear( SvtCommandOptions::CmdOption eCmdOption ) +{ + switch( eCmdOption ) + { + case SvtCommandOptions::CMDOPTION_DISABLED: + { + m_aDisabledCommands.Clear(); + SetModified(); + } + break; + + default: + DBG_ASSERT( sal_False, "SvtCommandOptions_Impl::Clear()\nUnknown option type given!\n" ); + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Bool SvtCommandOptions_Impl::HasEntries( SvtCommandOptions::CmdOption eOption ) const +{ + if ( eOption == SvtCommandOptions::CMDOPTION_DISABLED ) + return ( m_aDisabledCommands.HasEntries() > 0 ); + else + return sal_False; +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +Sequence< OUString > SvtCommandOptions_Impl::GetList( SvtCommandOptions::CmdOption eCmdOption ) const +{ + Sequence< OUString > lReturn; + + switch( eCmdOption ) + { + case SvtCommandOptions::CMDOPTION_DISABLED: + { + lReturn = m_aDisabledCommands.GetList(); + } + break; + + default: + DBG_ASSERT( sal_False, "SvtCommandOptions_Impl::GetList()\nUnknown option type given!\n" ); + } + + return lReturn; +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Bool SvtCommandOptions_Impl::Lookup( SvtCommandOptions::CmdOption eCmdOption, const OUString& aCommand ) const +{ + switch( eCmdOption ) + { + case SvtCommandOptions::CMDOPTION_DISABLED: + { + return m_aDisabledCommands.Lookup( aCommand ); + } + default: + DBG_ASSERT( sal_False, "SvtCommandOptions_Impl::GetList()\nUnknown option type given!\n" ); + } + + return sal_False; +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtCommandOptions_Impl::AddCommand( SvtCommandOptions::CmdOption eCmdOption, const OUString& sCmd ) +{ + switch( eCmdOption ) + { + case SvtCommandOptions::CMDOPTION_DISABLED: + { + m_aDisabledCommands.AddCommand( sCmd ); + SetModified(); + } + break; + + default: + DBG_ASSERT( sal_False, "SvtCommandOptions_Impl::GetList()\nUnknown option type given!\n" ); + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtCommandOptions_Impl::EstablisFrameCallback(const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame) +{ + // check if frame already exists inside list + // ignore double registrations + // every frame must be notified one times only! + ::com::sun::star::uno::WeakReference< ::com::sun::star::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::CONFIG_NAME_LOCAL_PATH ); + + OUString aSetNode( SETNODE_DISABLED ); + aSetNode += PATHDELIMITER; + + OUString aCommandKey( PATHDELIMITER ); + aCommandKey += PROPERTYNAME_CMD; + + // Expand all keys + for (sal_Int32 i=0; i<lDisabledItems.getLength(); ++i ) + { + OUStringBuffer aBuffer( 32 ); + aBuffer.append( aSetNode ); + aBuffer.append( lDisabledItems[i] ); + aBuffer.append( aCommandKey ); + lDisabledItems[i] = aBuffer.makeStringAndClear(); + } + + // Return result. + return lDisabledItems; +} + +//***************************************************************************************************************** +// initialize static member +// DON'T DO IT IN YOUR HEADER! +// see definition for further informations +//***************************************************************************************************************** +SvtCommandOptions_Impl* SvtCommandOptions::m_pDataContainer = NULL ; +sal_Int32 SvtCommandOptions::m_nRefCount = 0 ; + +//***************************************************************************************************************** +// constructor +//***************************************************************************************************************** +SvtCommandOptions::SvtCommandOptions() +{ + // Global access, must be guarded (multithreading!). + MutexGuard aGuard( GetOwnStaticMutex() ); + // Increase ouer refcount ... + ++m_nRefCount; + // ... and initialize ouer data container only if it not already exist! + if( m_pDataContainer == NULL ) + { + m_pDataContainer = new SvtCommandOptions_Impl; + ItemHolder1::holdConfigItem(E_CMDOPTIONS); + } +} + +//***************************************************************************************************************** +// destructor +//***************************************************************************************************************** +SvtCommandOptions::~SvtCommandOptions() +{ + // Global access, must be guarded (multithreading!) + MutexGuard aGuard( GetOwnStaticMutex() ); + // Decrease ouer refcount. + --m_nRefCount; + // If last instance was deleted ... + // we must destroy ouer static data container! + if( m_nRefCount <= 0 ) + { + delete m_pDataContainer; + m_pDataContainer = NULL; + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtCommandOptions::Clear( CmdOption eCmdOption ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->Clear( eCmdOption ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Bool SvtCommandOptions::HasEntries( CmdOption eOption ) const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->HasEntries( eOption ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Bool SvtCommandOptions::Lookup( CmdOption eCmdOption, const OUString& aCommandURL ) const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->Lookup( eCmdOption, aCommandURL ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +Sequence< OUString > SvtCommandOptions::GetList( CmdOption eCmdOption ) const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->GetList( eCmdOption ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtCommandOptions::AddCommand( CmdOption eCmdOption, const OUString& sURL ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->AddCommand( eCmdOption, sURL ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtCommandOptions::EstablisFrameCallback(const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->EstablisFrameCallback(xFrame); +} + +//***************************************************************************************************************** +// private method +//***************************************************************************************************************** +Mutex& SvtCommandOptions::GetOwnStaticMutex() +{ + // Initialize static mutex only for one time! + static Mutex* pMutex = NULL; + // If these method first called (Mutex not already exist!) ... + if( pMutex == NULL ) + { + // ... we must create a new one. Protect follow code with the global mutex - + // It must be - we create a static variable! + MutexGuard aGuard( Mutex::getGlobalMutex() ); + // We must check our pointer again - because it can be that another instance of ouer class will be fastr then these! + if( pMutex == NULL ) + { + // Create the new mutex and set it for return on static variable. + static Mutex aMutex; + pMutex = &aMutex; + } + } + // Return new created or already existing mutex object. + return *pMutex; +} + +/* 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 000000000000..6d426095eed2 --- /dev/null +++ b/unotools/source/config/compatibility.cxx @@ -0,0 +1,844 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" + +//_________________________________________________________________________________________________________________ +// includes +//_________________________________________________________________________________________________________________ + +#include <unotools/compatibility.hxx> +#include <unotools/configmgr.hxx> +#include <unotools/configitem.hxx> +#include <unotools/syslocale.hxx> +#include <tools/debug.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> + +#include <vector> + +#include <itemholder1.hxx> + +#include <algorithm> + +//_________________________________________________________________________________________________________________ +// namespaces +//_________________________________________________________________________________________________________________ + +using namespace ::std; +using namespace ::utl; +using namespace ::rtl; +using namespace ::osl; +using namespace ::com::sun::star::uno; +using namespace ::com::sun::star::beans; + +//_________________________________________________________________________________________________________________ +// const +//_________________________________________________________________________________________________________________ + +#define ROOTNODE_OPTIONS OUString( RTL_CONSTASCII_USTRINGPARAM( "Office.Compatibility/" ) ) +#define PATHDELIMITER OUString( RTL_CONSTASCII_USTRINGPARAM( "/" ) ) +#define SETNODE_ALLFILEFORMATS OUString( RTL_CONSTASCII_USTRINGPARAM( "AllFileFormats" ) ) + +#define PROPERTYNAME_NAME COMPATIBILITY_PROPERTYNAME_NAME +#define PROPERTYNAME_MODULE COMPATIBILITY_PROPERTYNAME_MODULE +#define PROPERTYNAME_USEPRTMETRICS COMPATIBILITY_PROPERTYNAME_USEPRTMETRICS +#define PROPERTYNAME_ADDSPACING COMPATIBILITY_PROPERTYNAME_ADDSPACING +#define PROPERTYNAME_ADDSPACINGATPAGES COMPATIBILITY_PROPERTYNAME_ADDSPACINGATPAGES +#define PROPERTYNAME_USEOURTABSTOPS COMPATIBILITY_PROPERTYNAME_USEOURTABSTOPS +#define PROPERTYNAME_NOEXTLEADING COMPATIBILITY_PROPERTYNAME_NOEXTLEADING +#define PROPERTYNAME_USELINESPACING COMPATIBILITY_PROPERTYNAME_USELINESPACING +#define PROPERTYNAME_ADDTABLESPACING COMPATIBILITY_PROPERTYNAME_ADDTABLESPACING +#define PROPERTYNAME_USEOBJPOS COMPATIBILITY_PROPERTYNAME_USEOBJECTPOSITIONING +#define PROPERTYNAME_USEOURTEXTWRAP COMPATIBILITY_PROPERTYNAME_USEOURTEXTWRAPPING +#define PROPERTYNAME_CONSIDERWRAPSTYLE COMPATIBILITY_PROPERTYNAME_CONSIDERWRAPPINGSTYLE +#define PROPERTYNAME_EXPANDWORDSPACE COMPATIBILITY_PROPERTYNAME_EXPANDWORDSPACE + +#define PROPERTYCOUNT 13 + +#define OFFSET_NAME 0 +#define OFFSET_MODULE 1 +#define OFFSET_USEPRTMETRICS 2 +#define OFFSET_ADDSPACING 3 +#define OFFSET_ADDSPACINGATPAGES 4 +#define OFFSET_USEOURTABSTOPS 5 +#define OFFSET_NOEXTLEADING 6 +#define OFFSET_USELINESPACING 7 +#define OFFSET_ADDTABLESPACING 8 +#define OFFSET_USEOBJPOS 9 +#define OFFSET_USEOURTEXTWRAPPING 10 +#define OFFSET_CONSIDERWRAPPINGSTYLE 11 +#define OFFSET_EXPANDWORDSPACE 12 + +//_________________________________________________________________________________________________________________ +// private declarations! +//_________________________________________________________________________________________________________________ + +/*-**************************************************************************************************************** + @descr struct to hold information about one compatibility entry +****************************************************************************************************************-*/ +struct SvtCompatibilityEntry +{ + public: + SvtCompatibilityEntry() : + bUsePrtMetrics( false ), bAddSpacing( false ), + bAddSpacingAtPages( false ), bUseOurTabStops( false ), + bNoExtLeading( false ), bUseLineSpacing( false ), + bAddTableSpacing( false ), bUseObjPos( false ), + bUseOurTextWrapping( false ), bConsiderWrappingStyle( false ), + bExpandWordSpace( true ) {} + SvtCompatibilityEntry( + const OUString& _rName, const OUString& _rNewModule ) : + sName( _rName ), sModule( _rNewModule ), + bUsePrtMetrics( false ), bAddSpacing( false ), + bAddSpacingAtPages( false ), bUseOurTabStops( false ), + bNoExtLeading( false ), bUseLineSpacing( false ), + bAddTableSpacing( false ), bUseObjPos( false ), + bUseOurTextWrapping( false ), bConsiderWrappingStyle( false ), + bExpandWordSpace( true ) {} + + inline void SetUsePrtMetrics( bool _bSet ) { bUsePrtMetrics = _bSet; } + inline void SetAddSpacing( bool _bSet ) { bAddSpacing = _bSet; } + inline void SetAddSpacingAtPages( bool _bSet ) { bAddSpacingAtPages = _bSet; } + inline void SetUseOurTabStops( bool _bSet ) { bUseOurTabStops = _bSet; } + inline void SetNoExtLeading( bool _bSet ) { bNoExtLeading = _bSet; } + inline void SetUseLineSpacing( bool _bSet ) { bUseLineSpacing = _bSet; } + inline void SetAddTableSpacing( bool _bSet ) { bAddTableSpacing = _bSet; } + inline void SetUseObjPos( bool _bSet ) { bUseObjPos = _bSet; } + inline void SetUseOurTextWrapping( bool _bSet ) { bUseOurTextWrapping = _bSet; } + inline void SetConsiderWrappingStyle( bool _bSet ) { bConsiderWrappingStyle = _bSet; } + inline void SetExpandWordSpace( bool _bSet ) { bExpandWordSpace = _bSet; } + + public: + OUString sName; + OUString sModule; + bool bUsePrtMetrics; + bool bAddSpacing; + bool bAddSpacingAtPages; + bool bUseOurTabStops; + bool bNoExtLeading; + bool bUseLineSpacing; + bool bAddTableSpacing; + bool bUseObjPos; + bool bUseOurTextWrapping; + bool bConsiderWrappingStyle; + bool bExpandWordSpace; +}; + +/*-**************************************************************************************************************** + @descr support simple menu structures and operations on it +****************************************************************************************************************-*/ +class SvtCompatibility +{ + public: + //--------------------------------------------------------------------------------------------------------- + // append one entry + void AppendEntry( const SvtCompatibilityEntry& rEntry ) + { + lEntries.push_back( rEntry ); + } + + //--------------------------------------------------------------------------------------------------------- + // the only way to free memory! + void Clear() + { + lEntries.clear(); + } + + //--------------------------------------------------------------------------------------------------------- + // convert internal list to external format + Sequence< Sequence< PropertyValue > > GetList() const + { + sal_Int32 nCount = (sal_Int32)lEntries.size(); + sal_Int32 nStep = 0; + Sequence< PropertyValue > lProperties( PROPERTYCOUNT ); + Sequence< Sequence< PropertyValue > > lResult( nCount ); + const vector< SvtCompatibilityEntry >* pList = &lEntries; + + lProperties[ OFFSET_NAME ].Name = PROPERTYNAME_NAME; + lProperties[ OFFSET_MODULE ].Name = PROPERTYNAME_MODULE; + lProperties[ OFFSET_USEPRTMETRICS ].Name = PROPERTYNAME_USEPRTMETRICS; + lProperties[ OFFSET_ADDSPACING ].Name = PROPERTYNAME_ADDSPACING; + lProperties[ OFFSET_ADDSPACINGATPAGES ].Name = PROPERTYNAME_ADDSPACINGATPAGES; + lProperties[ OFFSET_USEOURTABSTOPS ].Name = PROPERTYNAME_USEOURTABSTOPS; + lProperties[ OFFSET_NOEXTLEADING ].Name = PROPERTYNAME_NOEXTLEADING; + lProperties[ OFFSET_USELINESPACING ].Name = PROPERTYNAME_USELINESPACING; + lProperties[ OFFSET_ADDTABLESPACING ].Name = PROPERTYNAME_ADDTABLESPACING; + lProperties[ OFFSET_USEOBJPOS ].Name = PROPERTYNAME_USEOBJPOS; + lProperties[ OFFSET_USEOURTEXTWRAPPING ].Name = PROPERTYNAME_USEOURTEXTWRAP; + lProperties[ OFFSET_CONSIDERWRAPPINGSTYLE ].Name = PROPERTYNAME_CONSIDERWRAPSTYLE; + lProperties[ OFFSET_EXPANDWORDSPACE ].Name = PROPERTYNAME_EXPANDWORDSPACE; + + for ( vector< SvtCompatibilityEntry >::const_iterator pItem = pList->begin(); + pItem != pList->end(); ++pItem ) + { + lProperties[ OFFSET_NAME ].Value <<= pItem->sName; + lProperties[ OFFSET_MODULE ].Value <<= pItem->sModule; + lProperties[ OFFSET_USEPRTMETRICS ].Value <<= pItem->bUsePrtMetrics; + lProperties[ OFFSET_ADDSPACING ].Value <<= pItem->bAddSpacing; + lProperties[ OFFSET_ADDSPACINGATPAGES ].Value <<= pItem->bAddSpacingAtPages; + lProperties[ OFFSET_USEOURTABSTOPS ].Value <<= pItem->bUseOurTabStops; + lProperties[ OFFSET_NOEXTLEADING ].Value <<= pItem->bNoExtLeading; + lProperties[ OFFSET_USELINESPACING ].Value <<= pItem->bUseLineSpacing; + lProperties[ OFFSET_ADDTABLESPACING ].Value <<= pItem->bAddTableSpacing; + lProperties[ OFFSET_USEOBJPOS ].Value <<= pItem->bUseObjPos; + lProperties[ OFFSET_USEOURTEXTWRAPPING ].Value <<= pItem->bUseOurTextWrapping; + lProperties[ OFFSET_CONSIDERWRAPPINGSTYLE ].Value <<= pItem->bConsiderWrappingStyle; + lProperties[ OFFSET_EXPANDWORDSPACE ].Value <<= pItem->bExpandWordSpace; + lResult[ nStep ] = lProperties; + ++nStep; + } + + return lResult; + } + + int size() const + { + return lEntries.size(); + } + + const SvtCompatibilityEntry& operator[]( int i ) const + { + return lEntries[i]; + } + + private: + vector< SvtCompatibilityEntry > lEntries; +}; + +class SvtCompatibilityOptions_Impl : public ConfigItem +{ + //------------------------------------------------------------------------------------------------------------- + // public methods + //------------------------------------------------------------------------------------------------------------- + + public: + + //--------------------------------------------------------------------------------------------------------- + // constructor / destructor + //--------------------------------------------------------------------------------------------------------- + + SvtCompatibilityOptions_Impl(); + ~SvtCompatibilityOptions_Impl(); + + void SetDefault( OUString sName, bool bValue ); + + //--------------------------------------------------------------------------------------------------------- + // overloaded methods of baseclass + //--------------------------------------------------------------------------------------------------------- + + /*-****************************************************************************************************//** + @short called for notify of configmanager + @descr These method is called from the ConfigManager before 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. + @return - + + @onerror - + *//*-*****************************************************************************************************/ + + virtual void Notify( const Sequence< OUString >& lPropertyNames ); + + /*-****************************************************************************************************//** + @short write changes to configuration + @descr These method writes the changed values into the sub tree + and should always called in our destructor to guarantee consistency of config data. + + @seealso baseclass ConfigItem + + @param - + @return - + + @onerror - + *//*-*****************************************************************************************************/ + + virtual void Commit(); + + //--------------------------------------------------------------------------------------------------------- + // public interface + //--------------------------------------------------------------------------------------------------------- + + /*-****************************************************************************************************//** + @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! + + @seealso - + + @param - + @return - + + @onerror - + *//*-*****************************************************************************************************/ + + void Clear(); + Sequence< Sequence< PropertyValue > > GetList() const; + void AppendItem( const ::rtl::OUString& _sName, + const ::rtl::OUString& _sModule, + bool _bUsePrtMetrics, + bool _bAddSpacing, + bool _bAddSpacingAtPages, + bool _bUseOurTabStops, + bool _bNoExtLeading, + bool _bUseLineSpacing, + bool _bAddTableSpacing, + bool _bUseObjPos, + bool _bUseOurTextWrapping, + bool _bConsiderWrappingStyle, + bool _bExpandWordSpace ); + + inline bool IsUsePrtDevice() const { return m_aDefOptions.bUsePrtMetrics; } + inline bool IsAddSpacing() const { return m_aDefOptions.bAddSpacing; } + inline bool IsAddSpacingAtPages() const { return m_aDefOptions.bAddSpacingAtPages; } + inline bool IsUseOurTabStops() const { return m_aDefOptions.bUseOurTabStops; } + inline bool IsNoExtLeading() const { return m_aDefOptions.bNoExtLeading; } + inline bool IsUseLineSpacing() const { return m_aDefOptions.bUseLineSpacing; } + inline bool IsAddTableSpacing() const { return m_aDefOptions.bAddTableSpacing; } + inline bool IsUseObjPos() const { return m_aDefOptions.bUseObjPos; } + inline bool IsUseOurTextWrapping() const { return m_aDefOptions.bUseOurTextWrapping; } + inline bool IsConsiderWrappingStyle() const { return m_aDefOptions.bConsiderWrappingStyle; } + inline bool IsExpandWordSpace() const { return m_aDefOptions.bExpandWordSpace; } + + //------------------------------------------------------------------------------------------------------------- + // private methods + //------------------------------------------------------------------------------------------------------------- + + private: + + /*-****************************************************************************************************//** + @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! + + @seealso - + + @param - + @return A list of configuration key names is returned. + + @onerror - + *//*-*****************************************************************************************************/ + + Sequence< OUString > impl_GetPropertyNames( Sequence< OUString >& rItems ); + + /*-****************************************************************************************************//** + @short expand the list for all well known properties to destination + @descr - + @attention - + + @seealso method impl_GetPropertyNames() + + @param "lSource" , original list + @param "lDestination" , destination of operation + @return A list of configuration key names is returned. + + @onerror - + *//*-*****************************************************************************************************/ + + void impl_ExpandPropertyNames( const Sequence< OUString >& lSource, + Sequence< OUString >& lDestination ); + + //------------------------------------------------------------------------------------------------------------- + // private member + //------------------------------------------------------------------------------------------------------------- + + private: + + SvtCompatibility m_aOptions; + SvtCompatibilityEntry m_aDefOptions; +}; + +//_________________________________________________________________________________________________________________ +// definitions +//_________________________________________________________________________________________________________________ + +//***************************************************************************************************************** +// constructor +//***************************************************************************************************************** +SvtCompatibilityOptions_Impl::SvtCompatibilityOptions_Impl() + // Init baseclasses first + : ConfigItem( ROOTNODE_OPTIONS ) + // Init member then... +{ + // Get names and values of all accessable menu entries and fill internal structures. + // See impl_GetPropertyNames() for further informations. + Sequence< OUString > lNodes; + Sequence< OUString > lNames = impl_GetPropertyNames( lNodes ); + sal_uInt32 nCount = lNodes.getLength(); + 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" ); + + SvtCompatibilityEntry aItem; + sal_uInt32 nItem = 0; + sal_uInt32 nPosition = 0; + + // Get names/values for new menu. + // 4 subkeys for every item! + bool bDefaultFound = false; + for( nItem = 0; nItem < nCount; ++nItem ) + { + aItem.sName = lNodes[ nItem ]; + lValues[ nPosition++ ] >>= aItem.sModule; + lValues[ nPosition++ ] >>= aItem.bUsePrtMetrics; + lValues[ nPosition++ ] >>= aItem.bAddSpacing; + lValues[ nPosition++ ] >>= aItem.bAddSpacingAtPages; + lValues[ nPosition++ ] >>= aItem.bUseOurTabStops; + lValues[ nPosition++ ] >>= aItem.bNoExtLeading; + lValues[ nPosition++ ] >>= aItem.bUseLineSpacing; + lValues[ nPosition++ ] >>= aItem.bAddTableSpacing; + lValues[ nPosition++ ] >>= aItem.bUseObjPos; + lValues[ nPosition++ ] >>= aItem.bUseOurTextWrapping; + lValues[ nPosition++ ] >>= aItem.bConsiderWrappingStyle; + lValues[ nPosition++ ] >>= aItem.bExpandWordSpace; + m_aOptions.AppendEntry( aItem ); + + if ( !bDefaultFound && aItem.sName.equals( COMPATIBILITY_DEFAULT_NAME ) != sal_False ) + { + SvtSysLocale aSysLocale; + com::sun::star::lang::Locale aLocale = aSysLocale.GetLocale(); + if ( aLocale.Language.equalsAscii( "zh" ) || aLocale.Language.equalsAscii( "ja" ) || + aLocale.Language.equalsAscii( "ko" ) ) + aItem.bExpandWordSpace = false; + + m_aDefOptions = aItem; + bDefaultFound = true; + } + } +} + +//***************************************************************************************************************** +// destructor +//***************************************************************************************************************** +SvtCompatibilityOptions_Impl::~SvtCompatibilityOptions_Impl() +{ + // We must save our current values .. if user forget it! + if( IsModified() == sal_True ) + { + Commit(); + } +} + +void SvtCompatibilityOptions_Impl::SetDefault( OUString sName, bool bValue ) +{ + if ( COMPATIBILITY_PROPERTYNAME_USEPRTMETRICS.equals( sName ) ) + m_aDefOptions.SetUsePrtMetrics( bValue ); + else if ( COMPATIBILITY_PROPERTYNAME_ADDSPACING.equals( sName ) ) + m_aDefOptions.SetAddSpacing( bValue ); + else if ( COMPATIBILITY_PROPERTYNAME_ADDSPACINGATPAGES.equals( sName ) ) + m_aDefOptions.SetAddSpacingAtPages( bValue ); + else if ( COMPATIBILITY_PROPERTYNAME_USEOURTABSTOPS.equals( sName ) ) + m_aDefOptions.SetUseOurTabStops( bValue ); + else if ( COMPATIBILITY_PROPERTYNAME_NOEXTLEADING.equals( sName ) ) + m_aDefOptions.SetNoExtLeading( bValue ); + else if ( COMPATIBILITY_PROPERTYNAME_USELINESPACING.equals( sName ) ) + m_aDefOptions.SetUseLineSpacing( bValue ); + else if ( COMPATIBILITY_PROPERTYNAME_ADDTABLESPACING.equals( sName ) ) + m_aDefOptions.SetAddTableSpacing( bValue ); + else if ( COMPATIBILITY_PROPERTYNAME_USEOBJECTPOSITIONING.equals( sName ) ) + m_aDefOptions.SetUseObjPos( bValue ); + else if ( COMPATIBILITY_PROPERTYNAME_USEOURTEXTWRAPPING.equals( sName ) ) + m_aDefOptions.SetUseOurTextWrapping( bValue ); + else if ( COMPATIBILITY_PROPERTYNAME_CONSIDERWRAPPINGSTYLE.equals( sName ) ) + m_aDefOptions.SetConsiderWrappingStyle( bValue ); + else if ( COMPATIBILITY_PROPERTYNAME_EXPANDWORDSPACE.equals( sName ) ) + m_aDefOptions.SetExpandWordSpace( bValue ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtCompatibilityOptions_Impl::Notify( const Sequence< OUString >& ) +{ + DBG_ASSERT( sal_False, "SvtCompatibilityOptions_Impl::Notify()\nNot implemented yet! I don't know how I can handle a dynamical list of unknown properties ...\n" ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtCompatibilityOptions_Impl::Commit() +{ + // Write all properties! + // Delete complete set first. + ClearNodeSet( SETNODE_ALLFILEFORMATS ); + + SvtCompatibilityEntry aItem; + OUString sNode; + Sequence< PropertyValue > lPropertyValues( PROPERTYCOUNT - 1 ); + sal_uInt32 nItem = 0; + sal_uInt32 nNewCount = m_aOptions.size(); + for( nItem = 0; nItem < nNewCount; ++nItem ) + { + aItem = m_aOptions[ nItem ]; + sNode = SETNODE_ALLFILEFORMATS + PATHDELIMITER + aItem.sName + PATHDELIMITER; + + lPropertyValues[ OFFSET_MODULE - 1 ].Name = sNode + PROPERTYNAME_MODULE; + lPropertyValues[ OFFSET_USEPRTMETRICS - 1 ].Name = sNode + PROPERTYNAME_USEPRTMETRICS; + lPropertyValues[ OFFSET_ADDSPACING - 1 ].Name = sNode + PROPERTYNAME_ADDSPACING; + lPropertyValues[ OFFSET_ADDSPACINGATPAGES - 1 ].Name = sNode + PROPERTYNAME_ADDSPACINGATPAGES; + lPropertyValues[ OFFSET_USEOURTABSTOPS - 1 ].Name = sNode + PROPERTYNAME_USEOURTABSTOPS; + lPropertyValues[ OFFSET_NOEXTLEADING - 1 ].Name = sNode + PROPERTYNAME_NOEXTLEADING; + lPropertyValues[ OFFSET_USELINESPACING - 1 ].Name = sNode + PROPERTYNAME_USELINESPACING; + lPropertyValues[ OFFSET_ADDTABLESPACING - 1 ].Name = sNode + PROPERTYNAME_ADDTABLESPACING; + lPropertyValues[ OFFSET_USEOBJPOS - 1 ].Name = sNode + PROPERTYNAME_USEOBJPOS; + lPropertyValues[ OFFSET_USEOURTEXTWRAPPING - 1 ].Name = sNode + PROPERTYNAME_USEOURTEXTWRAP; + lPropertyValues[ OFFSET_CONSIDERWRAPPINGSTYLE - 1 ].Name = sNode + PROPERTYNAME_CONSIDERWRAPSTYLE; + lPropertyValues[ OFFSET_EXPANDWORDSPACE - 1 ].Name = sNode + PROPERTYNAME_EXPANDWORDSPACE; + + lPropertyValues[ OFFSET_MODULE - 1 ].Value <<= aItem.sModule; + lPropertyValues[ OFFSET_USEPRTMETRICS - 1 ].Value <<= aItem.bUsePrtMetrics; + lPropertyValues[ OFFSET_ADDSPACING - 1 ].Value <<= aItem.bAddSpacing; + lPropertyValues[ OFFSET_ADDSPACINGATPAGES - 1 ].Value <<= aItem.bAddSpacingAtPages; + lPropertyValues[ OFFSET_USEOURTABSTOPS - 1 ].Value <<= aItem.bUseOurTabStops; + lPropertyValues[ OFFSET_NOEXTLEADING - 1 ].Value <<= aItem.bNoExtLeading; + lPropertyValues[ OFFSET_USELINESPACING - 1 ].Value <<= aItem.bUseLineSpacing; + lPropertyValues[ OFFSET_ADDTABLESPACING - 1 ].Value <<= aItem.bAddTableSpacing; + lPropertyValues[ OFFSET_USEOBJPOS - 1 ].Value <<= aItem.bUseObjPos; + lPropertyValues[ OFFSET_USEOURTEXTWRAPPING - 1 ].Value <<= aItem.bUseOurTextWrapping; + lPropertyValues[ OFFSET_CONSIDERWRAPPINGSTYLE - 1 ].Value <<= aItem.bConsiderWrappingStyle; + lPropertyValues[ OFFSET_EXPANDWORDSPACE - 1 ].Value <<= aItem.bExpandWordSpace; + + SetSetProperties( SETNODE_ALLFILEFORMATS, lPropertyValues ); + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtCompatibilityOptions_Impl::Clear() +{ + m_aOptions.Clear(); + SetModified(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +Sequence< Sequence< PropertyValue > > SvtCompatibilityOptions_Impl::GetList() const +{ + Sequence< Sequence< PropertyValue > > lReturn; + lReturn = m_aOptions.GetList(); + return lReturn; +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** + +void SvtCompatibilityOptions_Impl::AppendItem( const ::rtl::OUString& _sName, + const ::rtl::OUString& _sModule, + bool _bUsePrtMetrics, + bool _bAddSpacing, + bool _bAddSpacingAtPages, + bool _bUseOurTabStops, + bool _bNoExtLeading, + bool _bUseLineSpacing, + bool _bAddTableSpacing, + bool _bUseObjPos, + bool _bUseOurTextWrapping, + bool _bConsiderWrappingStyle, + bool _bExpandWordSpace ) +{ + SvtCompatibilityEntry aItem( _sName, _sModule ); + aItem.SetUsePrtMetrics( _bUsePrtMetrics ); + aItem.SetAddSpacing( _bAddSpacing ); + aItem.SetAddSpacingAtPages( _bAddSpacingAtPages ); + aItem.SetUseOurTabStops( _bUseOurTabStops ); + aItem.SetNoExtLeading( _bNoExtLeading ); + aItem.SetUseLineSpacing( _bUseLineSpacing ); + aItem.SetAddTableSpacing( _bAddTableSpacing ); + aItem.SetUseObjPos( _bUseObjPos ); + aItem.SetUseOurTextWrapping( _bUseOurTextWrapping ); + aItem.SetConsiderWrappingStyle( _bConsiderWrappingStyle ); + aItem.SetExpandWordSpace( _bExpandWordSpace ); + m_aOptions.AppendEntry( aItem ); + + // default item reset? + if ( _sName.equals( COMPATIBILITY_DEFAULT_NAME ) != sal_False ) + m_aDefOptions = aItem; + + SetModified(); +} + +//***************************************************************************************************************** +// private method +//***************************************************************************************************************** +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() * ( PROPERTYCOUNT - 1 ) ); + impl_ExpandPropertyNames( rItems, lProperties ); + // Return result. + return lProperties; +} + +//***************************************************************************************************************** +// private method +//***************************************************************************************************************** +void SvtCompatibilityOptions_Impl::impl_ExpandPropertyNames( + const Sequence< OUString >& lSource, Sequence< OUString >& lDestination ) +{ + OUString sFixPath; + sal_Int32 nDestStep = 0; + sal_Int32 nSourceCount = lSource.getLength(); + // Copy entries to destination and expand every item with 2 supported sub properties. + for( sal_Int32 nSourceStep = 0; nSourceStep < nSourceCount; ++nSourceStep ) + { + sFixPath = SETNODE_ALLFILEFORMATS; + sFixPath += PATHDELIMITER; + sFixPath += lSource[ nSourceStep ]; + sFixPath += PATHDELIMITER; + + lDestination[nDestStep] = sFixPath; + lDestination[nDestStep] += PROPERTYNAME_MODULE; + ++nDestStep; + lDestination[nDestStep] = sFixPath; + lDestination[nDestStep] += PROPERTYNAME_USEPRTMETRICS; + ++nDestStep; + lDestination[nDestStep] = sFixPath; + lDestination[nDestStep] += PROPERTYNAME_ADDSPACING; + ++nDestStep; + lDestination[nDestStep] = sFixPath; + lDestination[nDestStep] += PROPERTYNAME_ADDSPACINGATPAGES; + ++nDestStep; + lDestination[nDestStep] = sFixPath; + lDestination[nDestStep] += PROPERTYNAME_USEOURTABSTOPS; + ++nDestStep; + lDestination[nDestStep] = sFixPath; + lDestination[nDestStep] += PROPERTYNAME_NOEXTLEADING; + ++nDestStep; + lDestination[nDestStep] = sFixPath; + lDestination[nDestStep] += PROPERTYNAME_USELINESPACING; + ++nDestStep; + lDestination[nDestStep] = sFixPath; + lDestination[nDestStep] += PROPERTYNAME_ADDTABLESPACING; + ++nDestStep; + lDestination[nDestStep] = sFixPath; + lDestination[nDestStep] += PROPERTYNAME_USEOBJPOS; + ++nDestStep; + lDestination[nDestStep] = sFixPath; + lDestination[nDestStep] += PROPERTYNAME_USEOURTEXTWRAP; + ++nDestStep; + lDestination[nDestStep] = sFixPath; + lDestination[nDestStep] += PROPERTYNAME_CONSIDERWRAPSTYLE; + ++nDestStep; + lDestination[nDestStep] = sFixPath; + lDestination[nDestStep] += PROPERTYNAME_EXPANDWORDSPACE; + ++nDestStep; + } +} + +//***************************************************************************************************************** +// initialize static member +// DON'T DO IT IN YOUR HEADER! +// see definition for further informations +//***************************************************************************************************************** +SvtCompatibilityOptions_Impl* SvtCompatibilityOptions::m_pDataContainer = NULL; +sal_Int32 SvtCompatibilityOptions::m_nRefCount = 0; + +//***************************************************************************************************************** +// constructor +//***************************************************************************************************************** +SvtCompatibilityOptions::SvtCompatibilityOptions() +{ + // Global access, must be guarded (multithreading!). + MutexGuard aGuard( GetOwnStaticMutex() ); + // Increase ouer refcount ... + ++m_nRefCount; + // ... and initialize ouer data container only if it not already exist! + if( m_pDataContainer == NULL ) + { + m_pDataContainer = new SvtCompatibilityOptions_Impl; + ItemHolder1::holdConfigItem(E_COMPATIBILITY); + } +} + +//***************************************************************************************************************** +// destructor +//***************************************************************************************************************** +SvtCompatibilityOptions::~SvtCompatibilityOptions() +{ + // Global access, must be guarded (multithreading!) + MutexGuard aGuard( GetOwnStaticMutex() ); + // Decrease ouer refcount. + --m_nRefCount; + // If last instance was deleted ... + // we must destroy ouer static data container! + if( m_nRefCount <= 0 ) + { + delete m_pDataContainer; + m_pDataContainer = NULL; + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtCompatibilityOptions::Clear() +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->Clear(); +} + +void SvtCompatibilityOptions::SetDefault( ::rtl::OUString sName, bool bValue ) +{ + m_pDataContainer->SetDefault( sName, bValue ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtCompatibilityOptions::AppendItem( const ::rtl::OUString& sName, + const ::rtl::OUString& sModule, + bool bUsePrtMetrics, + bool bAddSpacing, + bool bAddSpacingAtPages, + bool bUseOurTabStops, + bool bNoExtLeading, + bool bUseLineSpacing, + bool bAddTableSpacing, + bool bUseObjPos, + bool bUseOurTextWrapping, + bool bConsiderWrappingStyle, + bool bExpandWordSpace ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->AppendItem( + sName, sModule, bUsePrtMetrics, bAddSpacing, + bAddSpacingAtPages, bUseOurTabStops, bNoExtLeading, + bUseLineSpacing, bAddTableSpacing, bUseObjPos, + bUseOurTextWrapping, bConsiderWrappingStyle, bExpandWordSpace ); +} + +bool SvtCompatibilityOptions::IsUsePrtDevice() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsUsePrtDevice(); +} + +bool SvtCompatibilityOptions::IsAddSpacing() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsAddSpacing(); +} + +bool SvtCompatibilityOptions::IsAddSpacingAtPages() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsAddSpacingAtPages(); +} + +bool SvtCompatibilityOptions::IsUseOurTabStops() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsUseOurTabStops(); +} + +bool SvtCompatibilityOptions::IsNoExtLeading() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsNoExtLeading(); +} + +bool SvtCompatibilityOptions::IsUseLineSpacing() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsUseLineSpacing(); +} + +bool SvtCompatibilityOptions::IsAddTableSpacing() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsAddTableSpacing(); +} + +bool SvtCompatibilityOptions::IsUseObjectPositioning() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsUseObjPos(); +} + +bool SvtCompatibilityOptions::IsUseOurTextWrapping() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsUseOurTextWrapping(); +} + +bool SvtCompatibilityOptions::IsConsiderWrappingStyle() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsConsiderWrappingStyle(); +} + +bool SvtCompatibilityOptions::IsExpandWordSpace() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsExpandWordSpace(); +} + +Sequence< Sequence< PropertyValue > > SvtCompatibilityOptions::GetList() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->GetList(); +} + +//***************************************************************************************************************** +// private method +//***************************************************************************************************************** +Mutex& SvtCompatibilityOptions::GetOwnStaticMutex() +{ + // Initialize static mutex only for one time! + static Mutex* pMutex = NULL; + // If these method first called (Mutex not already exist!) ... + if( pMutex == NULL ) + { + // ... we must create a new one. Protect follow code with the global mutex - + // It must be - we create a static variable! + MutexGuard aGuard( Mutex::getGlobalMutex() ); + // We must check our pointer again - because it can be that another instance of ouer class will be fastr then these! + if( pMutex == NULL ) + { + // Create the new mutex and set it for return on static variable. + static Mutex aMutex; + pMutex = &aMutex; + } + } + // Return new created or already existing mutex object. + return *pMutex; +} + +/* 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 000000000000..e836c3b80a86 --- /dev/null +++ b/unotools/source/config/configitem.cxx @@ -0,0 +1,1345 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" +#include "unotools/configitem.hxx" +#include "unotools/configmgr.hxx" +#include "unotools/configpathes.hxx" +#include <comphelper/processfactory.hxx> +#include <com/sun/star/beans/XMultiPropertySet.hpp> +#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/container/XHierarchicalName.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/awt/XRequestCallback.hpp> +#include <com/sun/star/beans/PropertyValue.hpp> +#include <com/sun/star/beans/PropertyAttribute.hpp> +#include <com/sun/star/util/XStringEscape.hpp> +#include <com/sun/star/util/XChangesBatch.hpp> +#include <osl/diagnose.h> +#include <tools/solarmutex.hxx> +#include <rtl/ustrbuf.hxx> + +using namespace utl; +using rtl::OUString; +using rtl::OString; +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; + +#define C2U(cChar) OUString::createFromAscii(cChar) +#include <cppuhelper/implbase1.hxx> // helper for implementations + +#ifdef DBG_UTIL +inline void lcl_CFG_DBG_EXCEPTION(const sal_Char* cText, const Exception& rEx) +{ + OString sMsg(cText); + sMsg += OString(rEx.Message.getStr(), rEx.Message.getLength(), RTL_TEXTENCODING_ASCII_US); + OSL_ENSURE(sal_False, sMsg.getStr()); +} +#define CATCH_INFO(a) \ +catch(Exception& rEx) \ +{ \ + lcl_CFG_DBG_EXCEPTION(a, rEx);\ +} +#else + #define lcl_CFG_DBG_EXCEPTION( a, b) + #define CATCH_INFO(a) catch(Exception& ){} +#endif + +/* + 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::WeakImplHelper1 + < + com::sun::star::util::XChangesListener + > + { + public: + ConfigItem* pParent; + const Sequence< OUString > aPropertyNames; + ConfigChangeListener_Impl(ConfigItem& rItem, const Sequence< OUString >& rNames); + ~ConfigChangeListener_Impl(); + + //XChangesListener + virtual void SAL_CALL changesOccurred( const ChangesEvent& Event ) throw(RuntimeException); + + //XEventListener + virtual void SAL_CALL disposing( const EventObject& Source ) throw(RuntimeException); + }; + +struct ConfigItem_Impl +{ + utl::ConfigManager* pManager; + sal_Int16 nMode; + sal_Bool bIsModified; + sal_Bool bEnableInternalNotification; + + sal_Int16 nInValueChange; + ConfigItem_Impl() : + pManager(0), + nMode(0), + bIsModified(sal_False), + bEnableInternalNotification(sal_False), + nInValueChange(0) + {} +}; +} + +class ValueCounter_Impl +{ + sal_Int16& rCnt; +public: + ValueCounter_Impl(sal_Int16& rCounter): + rCnt(rCounter) + {rCnt++;} + ~ValueCounter_Impl() + { + OSL_ENSURE(rCnt>0, "RefCount < 0 ??"); + rCnt--; + } +}; + +namespace +{ + // helper to achieve exception - safe handling of an Item under construction + template <class TYP> + class AutoDeleter // : Noncopyable + { + TYP* m_pItem; + public: + AutoDeleter(TYP * pItem) + : m_pItem(pItem) + { + } + + ~AutoDeleter() + { + delete m_pItem; + } + + void keep() { m_pItem = 0; } + }; +} + +ConfigChangeListener_Impl::ConfigChangeListener_Impl( + ConfigItem& rItem, const Sequence< OUString >& rNames) : + pParent(&rItem), + aPropertyNames(rNames) +{ +} + +ConfigChangeListener_Impl::~ConfigChangeListener_Impl() +{ +} + +sal_Bool lcl_Find( + const rtl::OUString& rTemp, + const OUString* pCheckPropertyNames, + sal_Int32 nLength) +{ + //return true if the path is completely correct or if it is longer + //i.e ...Print/Content/Graphic and .../Print + for(sal_Int32 nIndex = 0; nIndex < nLength; nIndex++) + if( isPrefixOfConfigurationPath(rTemp, pCheckPropertyNames[nIndex]) ) + return sal_True; + return sal_False; +} +//----------------------------------------------------------------------------- +void ConfigChangeListener_Impl::changesOccurred( const ChangesEvent& rEvent ) throw(RuntimeException) +{ + const ElementChange* pElementChanges = rEvent.Changes.getConstArray(); + + Sequence<OUString> aChangedNames(rEvent.Changes.getLength()); + OUString* pNames = aChangedNames.getArray(); + + const OUString* pCheckPropertyNames = aPropertyNames.getConstArray(); + + sal_Int32 nNotify = 0; + for(int i = 0; i < aChangedNames.getLength(); i++) + { + OUString sTemp; + pElementChanges[i].Accessor >>= sTemp; + if(lcl_Find(sTemp, pCheckPropertyNames, aPropertyNames.getLength())) + pNames[nNotify++] = sTemp; + } + if( nNotify ) + { + if ( ::tools::SolarMutex::Acquire() ) + { + aChangedNames.realloc(nNotify); + pParent->CallNotify(aChangedNames); + ::tools::SolarMutex::Release(); + } + } +} + + +void ConfigChangeListener_Impl::disposing( const EventObject& /*rSource*/ ) throw(RuntimeException) +{ + pParent->RemoveChangesListener(); +} + +ConfigItem::ConfigItem(const OUString rSubTree, sal_Int16 nSetMode ) : + sSubTree(rSubTree), + pImpl(new ConfigItem_Impl) +{ + AutoDeleter<ConfigItem_Impl> aNewImpl(pImpl); + + pImpl->pManager = &ConfigManager::GetConfigManager(); + pImpl->nMode = nSetMode; + if(0 != (nSetMode&CONFIG_MODE_RELEASE_TREE)) + pImpl->pManager->AddConfigItem(*this); + else + m_xHierarchyAccess = pImpl->pManager->AddConfigItem(*this); + + // no more exceptions after c'tor has finished + aNewImpl.keep(); + pImpl->nMode &= ~CONFIG_MODE_PROPAGATE_ERRORS; +} + +ConfigItem::ConfigItem(utl::ConfigManager& rManager, const rtl::OUString rSubTree) : + sSubTree(rSubTree), + pImpl(new ConfigItem_Impl) +{ + pImpl->pManager = &rManager; + pImpl->nMode = CONFIG_MODE_IMMEDIATE_UPDATE; // does not allow exceptions + m_xHierarchyAccess = pImpl->pManager->AddConfigItem(*this); +} + +sal_Bool ConfigItem::IsValidConfigMgr() const +{ + return ( pImpl->pManager && pImpl->pManager->GetConfigurationProvider().is() ); +} + +ConfigItem::~ConfigItem() +{ + if(pImpl->pManager) + { + RemoveChangesListener(); + pImpl->pManager->RemoveConfigItem(*this); + } + delete pImpl; +} + +void ConfigItem::ReleaseConfigMgr() +{ + Reference<XHierarchicalNameAccess> xHierarchyAccess = GetTree(); + if(xHierarchyAccess.is()) + { + try + { + Reference<XChangesBatch> xBatch(xHierarchyAccess, UNO_QUERY); + xBatch->commitChanges(); + } + CATCH_INFO("Exception from commitChanges(): ") + } + RemoveChangesListener(); + OSL_ENSURE(pImpl->pManager, "ConfigManager already released"); + pImpl->pManager = 0; +} + +void ConfigItem::CallNotify( const com::sun::star::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(!IsInValueChange() || pImpl->bEnableInternalNotification) + Notify(rPropertyNames); +} + +sal_Bool lcl_IsLocalProperty(const OUString& rSubTree, const OUString& rProperty) +{ + static const sal_Char* aLocalProperties[] = + { + "Office.Common/Path/Current/Storage", + "Office.Common/Path/Current/Temp" + }; + static const int aLocalPropLen[] = + { + 34, + 31 + }; + OUString sProperty(rSubTree); + sProperty += C2U("/"); + sProperty += rProperty; + + if(sProperty.equalsAsciiL( aLocalProperties[0], aLocalPropLen[0]) || + sProperty.equalsAsciiL( aLocalProperties[1], aLocalPropLen[1])) + return sal_True; + + return sal_False; +} + +void ConfigItem::impl_packLocalizedProperties( const Sequence< OUString >& lInNames , + const Sequence< Any >& lInValues , + Sequence< Any >& lOutValues ) +{ + // Safe impossible cases. + // This method should be called for special ConfigItem-mode only! + OSL_ENSURE( ((pImpl->nMode & CONFIG_MODE_ALL_LOCALES ) == CONFIG_MODE_ALL_LOCALES), "ConfigItem::impl_packLocalizedProperties()\nWrong call of this method detected!\n" ); + + 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 an 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 ); + + // 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() == C2U("com.sun.star.uno.XInterface") ) + { + lInValues[nSourceCounter] >>= xLocalizedNode; + Reference< XNameContainer > xSetAccess( xLocalizedNode, UNO_QUERY ); + if( xSetAccess.is() == sal_True ) + { + lPropertyNames = xSetAccess->getElementNames() ; + nPropertiesSize = lPropertyNames.getLength() ; + lProperties.realloc( nPropertiesSize ) ; + + for( nPropertyCounter=0; nPropertyCounter<nPropertiesSize; ++nPropertyCounter ) + { + #if OSL_DEBUG_LEVEL > 1 + // Sometimes it's better to see what's going on :-) + OUString sPropName = lInNames[nSourceCounter]; + OUString sLocaleName = lPropertyNames[nPropertyCounter]; + #endif + lProperties[nPropertyCounter].Name = lPropertyNames[nPropertyCounter] ; + OUString sLocaleValue; + xSetAccess->getByName( lPropertyNames[nPropertyCounter] ) >>= sLocaleValue ; + lProperties[nPropertyCounter].Value <<= sLocaleValue; + } + + lOutValues[nDestinationCounter] <<= lProperties; + } + } + // ... or copy normal items to return lists directly. + else + { + lOutValues[nDestinationCounter] = lInValues[nSourceCounter]; + } + ++nDestinationCounter; + } +} + +void ConfigItem::impl_unpackLocalizedProperties( const Sequence< OUString >& lInNames , + const Sequence< Any >& lInValues , + Sequence< OUString >& lOutNames , + Sequence< Any >& lOutValues ) +{ + // Safe impossible cases. + // This method should be called for special ConfigItem-mode only! + OSL_ENSURE( ((pImpl->nMode & CONFIG_MODE_ALL_LOCALES ) == CONFIG_MODE_ALL_LOCALES), "ConfigItem::impl_unpackLocalizedProperties()\nWrong call of this method detected!\n" ); + + 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 + OUString sNodeName ; // base name of node ( e.g. "UIName/" ) ... expand to locale ( e.g. "UIName/de" ) + Sequence< PropertyValue > lProperties ; // localized values of an configuration entry getted 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 ); + lOutValues.realloc ( nSourceSize ); + + // 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( nSourceCounter=0; nSourceCounter<nSourceSize; ++nSourceCounter ) + { + // If item a special localized one ... split it and insert his parts to output lists ... + if( lInValues[nSourceCounter].getValueType() == ::getCppuType( (const Sequence< PropertyValue >*)NULL ) ) + { + lInValues[nSourceCounter] >>= lProperties ; + sNodeName = lInNames[nSourceCounter] ; + sNodeName += C2U("/") ; + nPropertiesSize = lProperties.getLength() ; + + if( (nDestinationCounter+nPropertiesSize) > lOutNames.getLength() ) + { + lOutNames.realloc ( nDestinationCounter+nPropertiesSize ); + lOutValues.realloc ( nDestinationCounter+nPropertiesSize ); + } + + for( nPropertyCounter=0; nPropertyCounter<nPropertiesSize; ++nPropertyCounter ) + { + lOutNames [nDestinationCounter] = sNodeName + lProperties[nPropertyCounter].Name ; + lOutValues[nDestinationCounter] = lProperties[nPropertyCounter].Value ; + ++nDestinationCounter; + } + } + // ... or copy normal items to return lists directly. + else + { + if( (nDestinationCounter+1) > lOutNames.getLength() ) + { + lOutNames.realloc ( nDestinationCounter+1 ); + lOutValues.realloc ( nDestinationCounter+1 ); + } + + lOutNames [nDestinationCounter] = lInNames [nSourceCounter]; + lOutValues[nDestinationCounter] = lInValues[nSourceCounter]; + ++nDestinationCounter; + } + } +} + +Sequence< sal_Bool > ConfigItem::GetReadOnlyStates(const com::sun::star::uno::Sequence< rtl::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); + + // We must be shure to return a valid information everytime! + // Set default to non readonly ... similar to the configuration handling of this property. + for ( i=0; i<nCount; ++i) + lStates[i] = sal_False; + + // no access - no informations ... + Reference< XHierarchicalNameAccess > xHierarchyAccess = GetTree(); + if (!xHierarchyAccess.is()) + return lStates; + + for (i=0; i<nCount; ++i) + { + try + { + if(pImpl->pManager->IsLocalConfigProvider() && lcl_IsLocalProperty(sSubTree, rNames[i])) + { + OSL_ENSURE(sal_False, "ConfigItem::IsReadonly()\nlocal mode seams to be used!?\n"); + continue; + } + + OUString sName = rNames[i]; + OUString sPath; + OUString sProperty; + + ::utl::splitLastFromConfigurationPath(sName,sPath,sProperty); + if (!sPath.getLength() && !sProperty.getLength()) + { + OSL_ENSURE(sal_False, "ConfigItem::IsReadonly()\nsplitt failed\n"); + continue; + } + + Reference< XInterface > xNode; + Reference< XPropertySet > xSet ; + Reference< XPropertySetInfo > xInfo; + if (sPath.getLength()) + { + Any aNode = xHierarchyAccess->getByHierarchicalName(sPath); + if (!(aNode >>= xNode) || !xNode.is()) + { + OSL_ENSURE(sal_False, "ConfigItem::IsReadonly()\nno set available\n"); + continue; + } + } + else + { + xNode = Reference< XInterface >(xHierarchyAccess, UNO_QUERY); + } + + xSet = Reference< XPropertySet >(xNode, UNO_QUERY); + if (xSet.is()) + { + xInfo = xSet->getPropertySetInfo(); + OSL_ENSURE(xInfo.is(), "ConfigItem::IsReadonly()\ngetPropertySetInfo failed ...\n"); + } + else + { + xInfo = Reference< XPropertySetInfo >(xNode, UNO_QUERY); + OSL_ENSURE(xInfo.is(), "ConfigItem::IsReadonly()\nUNO_QUERY failed ...\n"); + } + + if (!xInfo.is()) + { + OSL_ENSURE(sal_False, "ConfigItem::IsReadonly()\nno prop info available\n"); + continue; + } + + Property aProp = xInfo->getPropertyByName(sProperty); + lStates[i] = ((aProp.Attributes & PropertyAttribute::READONLY) == PropertyAttribute::READONLY); + } + catch(Exception&){} + } + + return lStates; +} + +Sequence< Any > ConfigItem::GetProperties(const Sequence< OUString >& rNames) +{ + Sequence< Any > aRet(rNames.getLength()); + const OUString* pNames = rNames.getConstArray(); + Any* pRet = aRet.getArray(); + Reference<XHierarchicalNameAccess> xHierarchyAccess = GetTree(); + if(xHierarchyAccess.is()) + { + for(int i = 0; i < rNames.getLength(); i++) + { + try + { + if(pImpl->pManager->IsLocalConfigProvider() && lcl_IsLocalProperty(sSubTree, pNames[i])) + { + OUString sProperty(sSubTree); + sProperty += C2U("/"); + sProperty += pNames[i]; + pRet[i] = pImpl->pManager->GetLocalProperty(sProperty); + } + else + pRet[i] = xHierarchyAccess->getByHierarchicalName(pNames[i]); + } + catch(Exception& rEx) + { +#if OSL_DEBUG_LEVEL > 0 + OString sMsg("XHierarchicalNameAccess: "); + sMsg += OString(rEx.Message.getStr(), + rEx.Message.getLength(), + RTL_TEXTENCODING_ASCII_US); + sMsg += OString("\n"); + sMsg += OString(ConfigManager::GetConfigBaseURL().getStr(), + ConfigManager::GetConfigBaseURL().getLength(), + RTL_TEXTENCODING_ASCII_US); + sMsg += OString(sSubTree.getStr(), + sSubTree.getLength(), + RTL_TEXTENCODING_ASCII_US); + sMsg += OString("/"); + sMsg += OString(pNames[i].getStr(), + pNames[i].getLength(), + RTL_TEXTENCODING_ASCII_US); + OSL_ENSURE(sal_False, sMsg.getStr()); +#else + (void) rEx; // avoid warning +#endif + } + } + + // In special mode "ALL_LOCALES" we must convert localized values to Sequence< PropertyValue >. + if((pImpl->nMode & CONFIG_MODE_ALL_LOCALES ) == CONFIG_MODE_ALL_LOCALES) + { + Sequence< Any > lValues; + impl_packLocalizedProperties( rNames, aRet, lValues ); + aRet = lValues; + } + } + return aRet; +} + +sal_Bool ConfigItem::PutProperties( const Sequence< OUString >& rNames, + const Sequence< Any>& rValues) +{ + ValueCounter_Impl aCounter(pImpl->nInValueChange); + Reference<XHierarchicalNameAccess> xHierarchyAccess = GetTree(); + Reference<XNameReplace> xTopNodeReplace(xHierarchyAccess, UNO_QUERY); + sal_Bool bRet = xHierarchyAccess.is() && xTopNodeReplace.is(); + if(bRet) + { + Sequence< OUString > lNames ; + Sequence< Any > lValues ; + const OUString* pNames = NULL ; + const Any* pValues = NULL ; + sal_Int32 nNameCount ; + if(( pImpl->nMode & CONFIG_MODE_ALL_LOCALES ) == CONFIG_MODE_ALL_LOCALES ) + { + // If ConfigItem works in "ALL_LOCALES"-mode ... we must support a Sequence< PropertyValue > + // as value of an 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++) + { + if(pImpl->pManager->IsLocalConfigProvider() && lcl_IsLocalProperty(sSubTree, pNames[i])) + { + OUString sProperty(sSubTree); + sProperty += C2U("/"); + sProperty += pNames[i]; + pImpl->pManager->PutLocalProperty(sProperty, pValues[i]); + } + else + { + 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); + + sal_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 = sal_False; + } + else //direct value + { + xTopNodeReplace->replaceByName(sProperty, pValues[i]); + } + } + CATCH_INFO("Exception from PutProperties: "); + } + } + try + { + Reference<XChangesBatch> xBatch(xHierarchyAccess, UNO_QUERY); + xBatch->commitChanges(); + } + CATCH_INFO("Exception from commitChanges(): ") + } + + return bRet; +} + +void ConfigItem::DisableNotification() +{ + OSL_ENSURE( xChangeLstnr.is(), "ConfigItem::DisableNotification: notifications not enabled currently!" ); + RemoveChangesListener(); +} + +sal_Bool ConfigItem::EnableNotification(const Sequence< OUString >& rNames, + sal_Bool bEnableInternalNotification ) + +{ + OSL_ENSURE(0 == (pImpl->nMode&CONFIG_MODE_RELEASE_TREE), "notification in CONFIG_MODE_RELEASE_TREE mode not possible"); + pImpl->bEnableInternalNotification = bEnableInternalNotification; + Reference<XHierarchicalNameAccess> xHierarchyAccess = GetTree(); + Reference<XChangesNotifier> xChgNot(xHierarchyAccess, UNO_QUERY); + if(!xChgNot.is()) + return sal_False; + + OSL_ENSURE(!xChangeLstnr.is(), "EnableNotification already called"); + if(xChangeLstnr.is()) + xChgNot->removeChangesListener( xChangeLstnr ); + sal_Bool bRet = sal_True; + + try + { + xChangeLstnr = new ConfigChangeListener_Impl(*this, rNames); + xChgNot->addChangesListener( xChangeLstnr ); + } + catch(RuntimeException& ) + { + bRet = sal_False; + } + return bRet; +} + +void ConfigItem::RemoveChangesListener() +{ + Reference<XChangesNotifier> xChgNot(m_xHierarchyAccess, UNO_QUERY); + if(xChgNot.is() && xChangeLstnr.is()) + { + try + { + xChgNot->removeChangesListener( xChangeLstnr ); + xChangeLstnr = 0; + } + catch(Exception & ) + { + } + } +} + +void lcl_normalizeLocalNames(Sequence< OUString >& _rNames, ConfigNameFormat _eFormat, Reference<XInterface> const& _xParentNode) +{ + switch (_eFormat) + { + case CONFIG_NAME_LOCAL_NAME: + // unaltered - this is our input format + break; + + case CONFIG_NAME_FULL_PATH: + { + Reference<XHierarchicalName> xFormatter(_xParentNode, UNO_QUERY); + if (xFormatter.is()) + { + OUString * pNames = _rNames.getArray(); + for(int i = 0; i<_rNames.getLength(); ++i) + try + { + pNames[i] = xFormatter->composeHierarchicalName(pNames[i]); + } + CATCH_INFO("Exception from composeHierarchicalName(): ") + break; + } + } + OSL_ENSURE(false, "Cannot create absolute pathes: missing interface"); + // make local pathes instaed + + case CONFIG_NAME_LOCAL_PATH: + { + Reference<XTemplateContainer> xTypeContainer(_xParentNode, UNO_QUERY); + if (xTypeContainer.is()) + { + OUString sTypeName = xTypeContainer->getElementTemplateName(); + sTypeName = sTypeName.copy(sTypeName.lastIndexOf('/')+1); + + OUString * pNames = _rNames.getArray(); + for(int i = 0; i<_rNames.getLength(); ++i) + { + pNames[i] = wrapConfigurationElementName(pNames[i],sTypeName); + } + } + else + { + static const OUString sSetService(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.configuration.SetAccess")); + Reference<XServiceInfo> xSVI(_xParentNode, UNO_QUERY); + if (xSVI.is() && xSVI->supportsService(sSetService)) + { + OUString * pNames = _rNames.getArray(); + for(int i = 0; i<_rNames.getLength(); ++i) + { + pNames[i] = wrapConfigurationElementName(pNames[i]); + } + } + } + } + break; + + case CONFIG_NAME_PLAINTEXT_NAME: + { + Reference<XStringEscape> xEscaper(_xParentNode, UNO_QUERY); + if (xEscaper.is()) + { + OUString * pNames = _rNames.getArray(); + for(int i = 0; i<_rNames.getLength(); ++i) + try + { + pNames[i] = xEscaper->unescapeString(pNames[i]); + } + CATCH_INFO("Exception from unescapeString(): ") + } + } + break; + + } +} + +Sequence< OUString > ConfigItem::GetNodeNames(const OUString& rNode) +{ + ConfigNameFormat const eDefaultFormat = CONFIG_NAME_LOCAL_NAME; // CONFIG_NAME_DEFAULT; + + return GetNodeNames(rNode, eDefaultFormat); +} + +Sequence< OUString > ConfigItem::GetNodeNames(const OUString& rNode, ConfigNameFormat eFormat) +{ + Sequence< OUString > aRet; + Reference<XHierarchicalNameAccess> xHierarchyAccess = GetTree(); + if(xHierarchyAccess.is()) + { + try + { + Reference<XNameAccess> xCont; + if(rNode.getLength()) + { + Any aNode = xHierarchyAccess->getByHierarchicalName(rNode); + aNode >>= xCont; + } + else + xCont = Reference<XNameAccess> (xHierarchyAccess, UNO_QUERY); + if(xCont.is()) + { + aRet = xCont->getElementNames(); + lcl_normalizeLocalNames(aRet,eFormat,xCont); + } + + } + CATCH_INFO("Exception from GetNodeNames: "); + } + return aRet; +} + +sal_Bool ConfigItem::ClearNodeSet(const OUString& rNode) +{ + ValueCounter_Impl aCounter(pImpl->nInValueChange); + sal_Bool bRet = sal_False; + Reference<XHierarchicalNameAccess> xHierarchyAccess = GetTree(); + if(xHierarchyAccess.is()) + { + try + { + Reference<XNameContainer> xCont; + if(rNode.getLength()) + { + Any aNode = xHierarchyAccess->getByHierarchicalName(rNode); + aNode >>= xCont; + } + else + xCont = Reference<XNameContainer> (xHierarchyAccess, UNO_QUERY); + if(!xCont.is()) + return sal_False; + Sequence< OUString > aNames = xCont->getElementNames(); + const OUString* pNames = aNames.getConstArray(); + Reference<XChangesBatch> xBatch(xHierarchyAccess, UNO_QUERY); + for(sal_Int32 i = 0; i < aNames.getLength(); i++) + { + try + { + xCont->removeByName(pNames[i]); + } + CATCH_INFO("Exception from removeByName(): ") + } + xBatch->commitChanges(); + bRet = sal_True; + } + CATCH_INFO("Exception from ClearNodeSet") + } + return bRet; +} + +sal_Bool ConfigItem::ClearNodeElements(const OUString& rNode, Sequence< OUString >& rElements) +{ + ValueCounter_Impl aCounter(pImpl->nInValueChange); + sal_Bool bRet = sal_False; + Reference<XHierarchicalNameAccess> xHierarchyAccess = GetTree(); + if(xHierarchyAccess.is()) + { + const OUString* pElements = rElements.getConstArray(); + try + { + Reference<XNameContainer> xCont; + if(rNode.getLength()) + { + Any aNode = xHierarchyAccess->getByHierarchicalName(rNode); + aNode >>= xCont; + } + else + xCont = Reference<XNameContainer> (xHierarchyAccess, UNO_QUERY); + if(!xCont.is()) + return sal_False; + try + { + for(sal_Int32 nElement = 0; nElement < rElements.getLength(); nElement++) + { + xCont->removeByName(pElements[nElement]); + } + Reference<XChangesBatch> xBatch(xHierarchyAccess, UNO_QUERY); + xBatch->commitChanges(); + } + CATCH_INFO("Exception from commitChanges(): ") + bRet = sal_True; + } + CATCH_INFO("Exception from GetNodeNames: ") + } + return bRet; +} +//---------------------------------------------------------------------------- +static inline +OUString lcl_extractSetPropertyName( const OUString& rInPath, const OUString& rPrefix ) +{ + OUString const sSubPath = dropPrefixFromConfigurationPath( rInPath, rPrefix); + return extractFirstFromConfigurationPath( sSubPath ); +} +//---------------------------------------------------------------------------- +static +Sequence< OUString > lcl_extractSetPropertyNames( const Sequence< PropertyValue >& rValues, const OUString& rPrefix ) +{ + const PropertyValue* pProperties = rValues.getConstArray(); + + Sequence< OUString > aSubNodeNames(rValues.getLength()); + OUString* pSubNodeNames = aSubNodeNames.getArray(); + + OUString sLastSubNode; + sal_Int32 nSubIndex = 0; + + for(sal_Int32 i = 0; i < rValues.getLength(); i++) + { + OUString const sSubPath = dropPrefixFromConfigurationPath( pProperties[i].Name, rPrefix); + OUString const sSubNode = extractFirstFromConfigurationPath( sSubPath ); + + if(sLastSubNode != sSubNode) + { + pSubNodeNames[nSubIndex++] = sSubNode; + } + + sLastSubNode = sSubNode; + } + aSubNodeNames.realloc(nSubIndex); + + return aSubNodeNames; +} + +// Add or change properties +sal_Bool ConfigItem::SetSetProperties( + const OUString& rNode, Sequence< PropertyValue > rValues) +{ + ValueCounter_Impl aCounter(pImpl->nInValueChange); + sal_Bool bRet = sal_True; + Reference<XHierarchicalNameAccess> xHierarchyAccess = GetTree(); + if(xHierarchyAccess.is()) + { + Reference<XChangesBatch> xBatch(xHierarchyAccess, UNO_QUERY); + try + { + Reference<XNameContainer> xCont; + if(rNode.getLength()) + { + Any aNode = xHierarchyAccess->getByHierarchicalName(rNode); + aNode >>= xCont; + } + else + xCont = Reference<XNameContainer> (xHierarchyAccess, UNO_QUERY); + if(!xCont.is()) + return sal_False; + + Reference<XSingleServiceFactory> xFac(xCont, UNO_QUERY); + + if(xFac.is()) + { + const Sequence< OUString > aSubNodeNames = lcl_extractSetPropertyNames(rValues, rNode); + + const sal_Int32 nSubNodeCount = aSubNodeNames.getLength(); + + for(sal_Int32 j = 0; j <nSubNodeCount ; j++) + { + if(!xCont->hasByName(aSubNodeNames[j])) + { + Reference<XInterface> xInst = xFac->createInstance(); + Any aVal; aVal <<= xInst; + xCont->insertByName(aSubNodeNames[j], aVal); + } + //set values + } + try + { + xBatch->commitChanges(); + } + CATCH_INFO("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(); + + sal_Bool bEmptyNode = rNode.getLength() == 0; + 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(aSetNames, aSetValues); + } + else + { + //if no factory is available then the node contains basic data elements + const PropertyValue* pValues = rValues.getConstArray(); + for(int nValue = 0; nValue < rValues.getLength();nValue++) + { + try + { + OUString sSubNode = lcl_extractSetPropertyName( pValues[nValue].Name, rNode ); + + if(xCont->hasByName(sSubNode)) + xCont->replaceByName(sSubNode, pValues[nValue].Value); + else + xCont->insertByName(sSubNode, pValues[nValue].Value); + + OSL_ENSURE( xHierarchyAccess->hasByHierarchicalName(pValues[nValue].Name), + "Invalid config path" ); + } + CATCH_INFO("Exception form insert/replaceByName(): ") + } + xBatch->commitChanges(); + } + } +#ifdef DBG_UTIL + catch(Exception& rEx) + { + lcl_CFG_DBG_EXCEPTION("Exception from SetSetProperties: ", rEx); +#else + catch(Exception&) + { +#endif + bRet = sal_False; + } + } + return bRet; +} + +sal_Bool ConfigItem::ReplaceSetProperties( + const OUString& rNode, Sequence< PropertyValue > rValues) +{ + ValueCounter_Impl aCounter(pImpl->nInValueChange); + sal_Bool bRet = sal_True; + Reference<XHierarchicalNameAccess> xHierarchyAccess = GetTree(); + if(xHierarchyAccess.is()) + { + Reference<XChangesBatch> xBatch(xHierarchyAccess, UNO_QUERY); + try + { + Reference<XNameContainer> xCont; + if(rNode.getLength()) + { + Any aNode = xHierarchyAccess->getByHierarchicalName(rNode); + aNode >>= xCont; + } + else + xCont = Reference<XNameContainer> (xHierarchyAccess, UNO_QUERY); + if(!xCont.is()) + return sal_False; + + // JB: Change: now the same name handling for sets of simple values + const Sequence< OUString > aSubNodeNames = lcl_extractSetPropertyNames(rValues, rNode); + const OUString* pSubNodeNames = aSubNodeNames.getConstArray(); + const sal_Int32 nSubNodeCount = aSubNodeNames.getLength(); + + Reference<XSingleServiceFactory> xFac(xCont, UNO_QUERY); + const bool isSimpleValueSet = !xFac.is(); + + //remove unknown members first + { + const Sequence<OUString> aContainerSubNodes = xCont->getElementNames(); + const OUString* pContainerSubNodes = aContainerSubNodes.getConstArray(); + + for(sal_Int32 nContSub = 0; nContSub < aContainerSubNodes.getLength(); nContSub++) + { + sal_Bool bFound = sal_False; + for(sal_Int32 j = 0; j < nSubNodeCount; j++) + { + if(pSubNodeNames[j] == pContainerSubNodes[nContSub]) + { + bFound = sal_True; + break; + } + } + if(!bFound) + try + { + xCont->removeByName(pContainerSubNodes[nContSub]); + } + catch (Exception & ) + { + if (isSimpleValueSet) + try + { + // #i37322#: fallback action: replace with <void/> + xCont->replaceByName(pContainerSubNodes[nContSub], Any()); + // fallback successfull: continue looping + continue; + } + catch (Exception &) + {} // propagate original exception, if fallback fails + + throw; + } + } + try { xBatch->commitChanges(); } + CATCH_INFO("Exception from commitChanges(): ") + } + + if(xFac.is()) // !isSimpleValueSet + { + for(sal_Int32 j = 0; j < nSubNodeCount; j++) + { + if(!xCont->hasByName(pSubNodeNames[j])) + { + //create if not available + Reference<XInterface> xInst = xFac->createInstance(); + Any aVal; aVal <<= xInst; + xCont->insertByName(pSubNodeNames[j], aVal); + } + } + try { xBatch->commitChanges(); } + CATCH_INFO("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(); + + sal_Bool bEmptyNode = rNode.getLength() == 0; + 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(aSetNames, aSetValues); + } + else + { + const PropertyValue* pValues = rValues.getConstArray(); + + //if no factory is available then the node contains basic data elements + for(int nValue = 0; nValue < rValues.getLength();nValue++) + { + try + { + OUString sSubNode = lcl_extractSetPropertyName( pValues[nValue].Name, rNode ); + + if(xCont->hasByName(sSubNode)) + xCont->replaceByName(sSubNode, pValues[nValue].Value); + else + xCont->insertByName(sSubNode, pValues[nValue].Value); + } + CATCH_INFO("Exception from insert/replaceByName(): "); + } + xBatch->commitChanges(); + } + } +#ifdef DBG_UTIL + catch(Exception& rEx) + { + lcl_CFG_DBG_EXCEPTION("Exception from ReplaceSetProperties: ", rEx); +#else + catch(Exception&) + { +#endif + bRet = sal_False; + } + } + return bRet; +} + +sal_Bool ConfigItem::getUniqueSetElementName( const ::rtl::OUString& _rSetNode, ::rtl::OUString& _rName) +{ + ::rtl::OUString sNewElementName; + Reference<XHierarchicalNameAccess> xHierarchyAccess = GetTree(); + sal_Bool bRet = sal_False; + if(xHierarchyAccess.is()) + { + try + { + Reference< XNameAccess > xSetNode; + xHierarchyAccess->getByHierarchicalName(_rSetNode) >>= xSetNode; + if (xSetNode.is()) + { + const sal_uInt32 nPrime = 65521; // a prime number + const sal_uInt32 nPrimeLess2 = nPrime - 2; + sal_uInt32 nEngendering = (rand() % nPrimeLess2) + 2; // the engendering of the field + + // the element which will loop through the field + sal_uInt32 nFieldElement = nEngendering; + + for (; 1 != nFieldElement; nFieldElement = (nFieldElement * nEngendering) % nPrime) + { + ::rtl::OUString sThisRoundTrial = _rName; + sThisRoundTrial += ::rtl::OUString::valueOf((sal_Int32)nFieldElement); + + if (!xSetNode->hasByName(sThisRoundTrial)) + { + _rName = sThisRoundTrial; + bRet = sal_True; + break; + } + } + } + } + CATCH_INFO("Exception from getUniqueSetElementName(): ") + } + return bRet; +} + +sal_Bool ConfigItem::AddNode(const rtl::OUString& rNode, const rtl::OUString& rNewNode) +{ + ValueCounter_Impl aCounter(pImpl->nInValueChange); + sal_Bool bRet = sal_True; + Reference<XHierarchicalNameAccess> xHierarchyAccess = GetTree(); + if(xHierarchyAccess.is()) + { + Reference<XChangesBatch> xBatch(xHierarchyAccess, UNO_QUERY); + try + { + Reference<XNameContainer> xCont; + if(rNode.getLength()) + { + Any aNode = xHierarchyAccess->getByHierarchicalName(rNode); + aNode >>= xCont; + } + else + xCont = Reference<XNameContainer> (xHierarchyAccess, UNO_QUERY); + if(!xCont.is()) + return sal_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_INFO("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_INFO("Exception from AddNode(): ") + } + xBatch->commitChanges(); + } +#ifdef DBG_UTIL + catch(Exception& rEx) + { + lcl_CFG_DBG_EXCEPTION("Exception from AddNode(): ", rEx); +#else + catch(Exception&) + { +#endif + bRet = sal_False; + } + } + return bRet; +} + +sal_Int16 ConfigItem::GetMode() const +{ + return pImpl->nMode; +} + +void ConfigItem::SetModified() +{ + pImpl->bIsModified = sal_True; +} + +void ConfigItem::ClearModified() +{ + pImpl->bIsModified = sal_False; +} + +sal_Bool ConfigItem::IsModified() const +{ + return pImpl->bIsModified; +} + +sal_Bool ConfigItem::IsInValueChange() const +{ + return pImpl->nInValueChange > 0; +} + +Reference< XHierarchicalNameAccess> ConfigItem::GetTree() +{ + Reference< XHierarchicalNameAccess> xRet; + if(!m_xHierarchyAccess.is()) + xRet = pImpl->pManager->AcquireTree(*this); + else + xRet = m_xHierarchyAccess; + OSL_ENSURE(xRet.is(), "AcquireTree failed"); + return xRet; +} + +void ConfigItem::LockTree() +{ + OSL_ENSURE(0 != (pImpl->nMode&CONFIG_MODE_RELEASE_TREE), "call LockTree in CONFIG_MODE_RELEASE_TREE mode, only"); + m_xHierarchyAccess = GetTree(); +} + +void ConfigItem::UnlockTree() +{ + OSL_ENSURE(0 != (pImpl->nMode&CONFIG_MODE_RELEASE_TREE), "call UnlockTree in CONFIG_MODE_RELEASE_TREE mode, only"); + if(0 != (pImpl->nMode&CONFIG_MODE_RELEASE_TREE)) + m_xHierarchyAccess = 0; +} + + +/* 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 000000000000..a9584217a590 --- /dev/null +++ b/unotools/source/config/configmgr.cxx @@ -0,0 +1,695 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" +#include "unotools/configmgr.hxx" +#include "unotools/configitem.hxx" +#include "unotools/configpathes.hxx" +#include <unotools/processfactory.hxx> +#include <com/sun/star/lang/XMultiServiceFactory.hpp> +#include <com/sun/star/container/XNameAccess.hpp> +#include <com/sun/star/container/XHierarchicalNameAccess.hpp> +#include <com/sun/star/container/XNameContainer.hpp> +#include <com/sun/star/beans/PropertyValue.hpp> +#include <osl/diagnose.h> +#include <rtl/bootstrap.hxx> +#include <rtl/instance.hxx> +#if OSL_DEBUG_LEVEL > 0 +#include <rtl/strbuf.hxx> +#endif + +#include <list> + +//----------------------------------------------------------------------------- + +using namespace utl; +using namespace rtl; +using namespace com::sun::star::uno; +using namespace com::sun::star::lang; +using namespace com::sun::star::beans; +using namespace com::sun::star::container; + +#define UNISTRING(s) rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(s)) + +//----------------------------------------------------------------------------- +const char* pConfigBaseURL = "/org.openoffice."; +const char* pAccessSrvc = "com.sun.star.configuration.ConfigurationUpdateAccess"; + +namespace +{ + struct BrandName + : public rtl::Static< ::rtl::OUString, BrandName > {}; + struct ProductVersion + : public rtl::Static< ::rtl::OUString, ProductVersion > {}; + struct AboutBoxProductVersion + : public rtl::Static< ::rtl::OUString, AboutBoxProductVersion > {}; + struct OOOVendor + : public rtl::Static< ::rtl::OUString, OOOVendor > {}; + struct ProductExtension + : public rtl::Static< ::rtl::OUString, ProductExtension > {}; + struct XMLFileFormatName + : public rtl::Static< ::rtl::OUString, XMLFileFormatName > {}; + struct XMLFileFormatVersion + : public rtl::Static< ::rtl::OUString, XMLFileFormatVersion > {}; + struct WriterCompatibilityVersionOOo11 + : public rtl::Static< ::rtl::OUString, WriterCompatibilityVersionOOo11 > {}; + struct OpenSourceContext : public rtl::StaticWithInit< sal_Int32, OpenSourceContext > + { + sal_Int32 operator() () { return sal_Int32( -1 ); } + }; + +} + +//----------------------------------------------------------------------------- +struct ConfigItemListEntry_Impl +{ + ConfigItem* pConfigItem; + + ConfigItemListEntry_Impl(ConfigItem* pItem ) : + pConfigItem(pItem){} +}; +typedef std::list<ConfigItemListEntry_Impl> ConfigItemList; +struct utl::ConfigMgr_Impl +{ + ConfigItemList aItemList; +}; + +ConfigManager::ConfigManager() : + pMgrImpl(new utl::ConfigMgr_Impl) +{ + GetConfigurationProvider(); // attempt to create the provider early +} + +ConfigManager::ConfigManager(Reference< XMultiServiceFactory > xConfigProv) : + xConfigurationProvider(xConfigProv), + pMgrImpl(new utl::ConfigMgr_Impl) +{ +} + +ConfigManager::~ConfigManager() +{ + //check list content -> should be empty! + OSL_ENSURE(pMgrImpl->aItemList.empty(), "some ConfigItems are still alive"); + if(!pMgrImpl->aItemList.empty()) + { + ConfigItemList::iterator aListIter; + for(aListIter = pMgrImpl->aItemList.begin(); aListIter != pMgrImpl->aItemList.end(); ++aListIter) + { + ConfigItemListEntry_Impl& rEntry = *aListIter; + rEntry.pConfigItem->ReleaseConfigMgr(); + } + pMgrImpl->aItemList.erase(pMgrImpl->aItemList.begin(), pMgrImpl->aItemList.end()); + } + delete pMgrImpl; + +} + +Reference< XMultiServiceFactory > ConfigManager::GetConfigurationProvider() +{ + if(!xConfigurationProvider.is()) + { + Reference< XMultiServiceFactory > xMSF = ::utl::getProcessServiceFactory(); + if ( xMSF.is() ) + { + try + { + xConfigurationProvider = Reference< XMultiServiceFactory > + (xMSF->createInstance( + UNISTRING("com.sun.star.configuration.ConfigurationProvider")), + UNO_QUERY); + } +#ifdef DBG_UTIL + catch(Exception& rEx) + { + static sal_Bool bMessage = sal_True; + if(bMessage) + { + bMessage = sal_False; + OString sMsg("CreateInstance with arguments exception: "); + sMsg += OString(rEx.Message.getStr(), + rEx.Message.getLength(), + RTL_TEXTENCODING_ASCII_US); + OSL_ENSURE(sal_False, sMsg.getStr()); + } + } +#else + catch(Exception&){} +#endif + } + } + return xConfigurationProvider; +} + +namespace +{ + // helper to achieve exception - safe registration of a ConfigItem under construction + class RegisterConfigItemHelper // : Noncopyable + { + utl::ConfigManager & rCfgMgr; + utl::ConfigItem* pCfgItem; + public: + RegisterConfigItemHelper(utl::ConfigManager & rMgr, utl::ConfigItem& rCfgItem) + : rCfgMgr(rMgr) + , pCfgItem(&rCfgItem) + { + rCfgMgr.RegisterConfigItem(rCfgItem); + } + + ~RegisterConfigItemHelper() + { + if (pCfgItem) rCfgMgr.RemoveConfigItem(*pCfgItem); + } + + void keep() { pCfgItem = 0; } + }; +} + +Reference< XMultiServiceFactory > ConfigManager::GetLocalConfigurationProvider() +{ + return GetConfigurationProvider(); +} + +Reference< XHierarchicalNameAccess > ConfigManager::AddConfigItem(utl::ConfigItem& rCfgItem) +{ + RegisterConfigItemHelper registeredItem(*this,rCfgItem); + Reference< XHierarchicalNameAccess > xTree = AcquireTree(rCfgItem); + registeredItem.keep(); + return xTree; +} + +void ConfigManager::RegisterConfigItem(utl::ConfigItem& rCfgItem) +{ + ConfigItemList::iterator aListIter = pMgrImpl->aItemList.begin(); +#ifdef DBG_UTIL + for(aListIter = pMgrImpl->aItemList.begin(); aListIter != pMgrImpl->aItemList.end(); ++aListIter) + { + ConfigItemListEntry_Impl& rEntry = *aListIter; + if(rEntry.pConfigItem == &rCfgItem) + OSL_ENSURE(sal_False, "RegisterConfigItem: already inserted!"); + } +#endif + pMgrImpl->aItemList.insert(aListIter, ConfigItemListEntry_Impl(&rCfgItem)); +} + +Reference< XHierarchicalNameAccess> ConfigManager::AcquireTree(utl::ConfigItem& rCfgItem) +{ + ConfigItemList::iterator aListIter = pMgrImpl->aItemList.begin(); +#ifdef DBG_UTIL + sal_Bool bFound = sal_False; + for(aListIter = pMgrImpl->aItemList.begin(); aListIter != pMgrImpl->aItemList.end(); ++aListIter) + { + ConfigItemListEntry_Impl& rEntry = *aListIter; + if(rEntry.pConfigItem == &rCfgItem) + { + bFound = sal_True; + break; + } + } + OSL_ENSURE(bFound, "AcquireTree: ConfigItem unknown!"); +#endif + OUString sPath(OUString::createFromAscii(pConfigBaseURL)); + sPath += rCfgItem.GetSubTreeName(); + Sequence< Any > aArgs(2); + Any* pArgs = aArgs.getArray(); + PropertyValue aPath; + aPath.Name = UNISTRING("nodepath"); + aPath.Value <<= sPath; + pArgs[0] <<= aPath; + sal_Bool bLazy = 0 != (rCfgItem.GetMode()&CONFIG_MODE_DELAYED_UPDATE); + PropertyValue aUpdate; + aUpdate.Name = UNISTRING("lazywrite"); + aUpdate.Value.setValue(&bLazy, ::getBooleanCppuType()); + pArgs[1] <<= aUpdate; + + // Initialize item with support for reading/writing more then one locales at same time! + // It's neccessary for creation of a complete configuration entry without changing office locale + // at runtime. + if((rCfgItem.GetMode() & CONFIG_MODE_ALL_LOCALES) == CONFIG_MODE_ALL_LOCALES) + { + sal_Int32 nCount = aArgs.getLength(); + aArgs.realloc(nCount+1); + + PropertyValue aAllLocale; + aAllLocale.Name = UNISTRING("locale"); + aAllLocale.Value <<= UNISTRING("*" ); + aArgs[nCount] <<= aAllLocale; + } + + Reference< XMultiServiceFactory > xCfgProvider = GetConfigurationProvider(); + Reference< XInterface > xIFace; + if(xCfgProvider.is()) + { + try + { + xIFace = xCfgProvider->createInstanceWithArguments( + OUString::createFromAscii(pAccessSrvc), + aArgs); + } + catch(Exception& rEx) + { + if (CONFIG_MODE_PROPAGATE_ERRORS & rCfgItem.GetMode()) + { + OSL_TRACE("ConfigItem: Propagating creation error: %s\n", + OUStringToOString(rEx.Message,RTL_TEXTENCODING_ASCII_US).getStr()); + + throw; + } +#ifdef DBG_UTIL + if(0 == (CONFIG_MODE_IGNORE_ERRORS & rCfgItem.GetMode())) + { + OString sMsg("CreateInstance exception: "); + sMsg += OString(rEx.Message.getStr(), + rEx.Message.getLength(), + RTL_TEXTENCODING_ASCII_US); + OSL_ENSURE(sal_False, sMsg.getStr()); + } +#endif + } + } + return Reference<XHierarchicalNameAccess>(xIFace, UNO_QUERY); +} + +void ConfigManager::RemoveConfigItem(utl::ConfigItem& rCfgItem) +{ + if( !pMgrImpl->aItemList.empty() ) + { + ConfigItemList::iterator aListIter = pMgrImpl->aItemList.begin(); + for(aListIter = pMgrImpl->aItemList.begin(); aListIter != pMgrImpl->aItemList.end(); ++aListIter) + { + ConfigItemListEntry_Impl& rEntry = *aListIter; + if(rEntry.pConfigItem == &rCfgItem) + { + pMgrImpl->aItemList.erase(aListIter); + break; + } + } + } +} + +void ConfigManager::StoreConfigItems() +{ + if(!pMgrImpl->aItemList.empty()) + { + ConfigItemList::iterator aListIter = pMgrImpl->aItemList.begin(); + for(aListIter = pMgrImpl->aItemList.begin(); aListIter != pMgrImpl->aItemList.end(); ++aListIter) + { + ConfigItemListEntry_Impl& rEntry = *aListIter; + if(rEntry.pConfigItem->IsModified()) + { + rEntry.pConfigItem->Commit(); + rEntry.pConfigItem->ClearModified(); + } + } + } +} + +struct theConfigManager : public rtl::Static<ConfigManager, theConfigManager> {}; + +ConfigManager& ConfigManager::GetConfigManager() +{ + return theConfigManager::get(); +} + +rtl::OUString ConfigManager::GetConfigBaseURL() +{ + return OUString::createFromAscii(pConfigBaseURL); +} + +Any ConfigManager::GetDirectConfigProperty(ConfigProperty eProp) +{ + switch(eProp) + { + case INSTALLPATH: + OSL_ENSURE( false, + "ConfigManager::GetDirectConfigProperty: " + "INSTALLPATH no longer supported." ); + return Any(); + case USERINSTALLURL: + OSL_ENSURE( false, + "ConfigManager::GetDirectConfigProperty: " + "USERINSTALLURL no longer supported." ); + return Any(); + case OFFICEINSTALL: + OSL_ENSURE( false, + "ConfigManager::GetDirectConfigProperty: " + "OFFICEINSTALL no longer supported." ); + return Any(); + case OFFICEINSTALLURL: + OSL_ENSURE( false, + "ConfigManager::GetDirectConfigProperty: " + "OFFICEINSTALLURL no longer supported." ); + return Any(); + default: + break; + } + + Any aRet; + ::rtl::OUString &rBrandName = BrandName::get(); + if ( eProp == PRODUCTNAME && rBrandName.getLength() ) + { + aRet <<= rBrandName; + return aRet; + } + + rtl::OUString &rProductVersion = ProductVersion::get(); + if ( eProp == PRODUCTVERSION && rProductVersion.getLength() ) + { + aRet <<= rProductVersion; + return aRet; + } + + rtl::OUString &rAboutBoxProductVersion = AboutBoxProductVersion::get(); + if ( eProp == ABOUTBOXPRODUCTVERSION && rAboutBoxProductVersion.getLength() ) + { + aRet <<= rAboutBoxProductVersion; + return aRet; + } + + rtl::OUString &rOOOVendor = OOOVendor::get(); + if ( eProp == OOOVENDOR && rOOOVendor.getLength() ) + { + aRet <<= rOOOVendor; + return aRet; + } + + + rtl::OUString &rProductExtension = ProductExtension::get(); + if ( eProp == PRODUCTEXTENSION && rProductExtension.getLength() ) + { + aRet <<= rProductExtension; + return aRet; + } + + rtl::OUString &rXMLFileFormatName = XMLFileFormatName::get(); + if ( eProp == PRODUCTXMLFILEFORMATNAME && rXMLFileFormatName.getLength() ) + { + aRet <<= rXMLFileFormatName; + return aRet; + } + + rtl::OUString &rXMLFileFormatVersion = XMLFileFormatVersion::get(); + if ( eProp == PRODUCTXMLFILEFORMATVERSION && rXMLFileFormatVersion.getLength() ) + { + aRet <<= rXMLFileFormatVersion; + return aRet; + } + + sal_Int32 &rOpenSourceContext = OpenSourceContext::get(); + if ( eProp == OPENSOURCECONTEXT && ( rOpenSourceContext >= 0 ) ) + { + aRet <<= rOpenSourceContext; + return aRet; + } + + rtl::OUString &rWriterCompatibilityVersionOOo11 = WriterCompatibilityVersionOOo11::get(); + if ( eProp == WRITERCOMPATIBILITYVERSIONOOO11 && rWriterCompatibilityVersionOOo11.getLength() ) + { + aRet <<= rWriterCompatibilityVersionOOo11; + return aRet; + } + + if (eProp == PRODUCTEXTENSION) { + rtl::OUString name( + rtl::OUString( + RTL_CONSTASCII_USTRINGPARAM( + "${BRAND_BASE_DIR}/program/edition/edition.ini"))); + rtl::Bootstrap::expandMacros(name); + if (rtl::Bootstrap(name).getFrom( + rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("EDITIONNAME")), + rProductExtension)) + { + return com::sun::star::uno::Any(rProductExtension); + } + } + + OUString sPath = OUString::createFromAscii(pConfigBaseURL); + switch(eProp) + { + case LOCALE: sPath += UNISTRING("Setup/L10N"); break; + + case PRODUCTNAME: + case PRODUCTVERSION: + case PRODUCTEXTENSION: + case PRODUCTXMLFILEFORMATNAME : + case PRODUCTXMLFILEFORMATVERSION: + case OPENSOURCECONTEXT: + case OOOVENDOR: + case ABOUTBOXPRODUCTVERSION: sPath += UNISTRING("Setup/Product"); break; + + case DEFAULTCURRENCY: sPath += UNISTRING("Setup/L10N"); break; + + case WRITERCOMPATIBILITYVERSIONOOO11: + sPath += UNISTRING("Office.Compatibility/WriterCompatibilityVersion"); break; + default: + break; + } + Sequence< Any > aArgs(1); + aArgs[0] <<= sPath; + Reference< XMultiServiceFactory > xCfgProvider = GetConfigManager().GetConfigurationProvider(); + if(!xCfgProvider.is()) + return aRet; + Reference< XInterface > xIFace; + try + { + xIFace = xCfgProvider->createInstanceWithArguments( + OUString::createFromAscii(pAccessSrvc), + aArgs); + + } + catch(Exception&){} + Reference<XNameAccess> xDirectAccess(xIFace, UNO_QUERY); + if(xDirectAccess.is()) + { + OUString sProperty; + switch(eProp) + { + case LOCALE: sProperty = UNISTRING("ooLocale"); break; + case PRODUCTNAME: sProperty = UNISTRING("ooName"); break; + case PRODUCTVERSION: sProperty = UNISTRING("ooSetupVersion"); break; + case ABOUTBOXPRODUCTVERSION: sProperty = UNISTRING("ooSetupVersionAboutBox"); break; + case OOOVENDOR: sProperty = UNISTRING("ooVendor"); break; + case PRODUCTEXTENSION: sProperty = UNISTRING("ooSetupExtension"); break; + case PRODUCTXMLFILEFORMATNAME: sProperty = UNISTRING("ooXMLFileFormatName"); break; + case PRODUCTXMLFILEFORMATVERSION: sProperty = UNISTRING("ooXMLFileFormatVersion"); break; + case OPENSOURCECONTEXT: sProperty = UNISTRING("ooOpenSourceContext"); break; + case DEFAULTCURRENCY: sProperty = UNISTRING("ooSetupCurrency"); break; + case WRITERCOMPATIBILITYVERSIONOOO11: sProperty = UNISTRING("OOo11"); break; + default: + break; + } + try + { + aRet = xDirectAccess->getByName(sProperty); + } + catch(Exception&) + { + #if OSL_DEBUG_LEVEL > 0 + rtl::OStringBuffer aBuf(256); + aBuf.append( "ConfigManager::GetDirectConfigProperty: could not retrieve the property \"" ); + aBuf.append( rtl::OUStringToOString( sProperty, RTL_TEXTENCODING_ASCII_US ) ); + aBuf.append( "\" under \"" ); + aBuf.append( rtl::OUStringToOString( sPath, RTL_TEXTENCODING_ASCII_US ) ); + aBuf.append( "\" (caught an exception)!" ); + OSL_ENSURE( sal_False, aBuf.getStr() ); + #endif + } + } + + if ( eProp == PRODUCTNAME ) + aRet >>= rBrandName; + + if ( eProp == PRODUCTXMLFILEFORMATNAME ) + aRet >>= rXMLFileFormatName; + + if ( eProp == PRODUCTXMLFILEFORMATVERSION ) + aRet >>= rXMLFileFormatVersion; + + if ( eProp == PRODUCTVERSION ) + aRet >>= rProductVersion; + + if( eProp == OOOVENDOR ) + aRet >>= rOOOVendor; + + if ( eProp == ABOUTBOXPRODUCTVERSION ) + { + aRet >>= rAboutBoxProductVersion; + getBasisAboutBoxProductVersion( rAboutBoxProductVersion ); + aRet <<= rAboutBoxProductVersion; + } + + if ( eProp == PRODUCTEXTENSION ) + aRet >>= rProductExtension; + + if ( eProp == WRITERCOMPATIBILITYVERSIONOOO11 ) + aRet >>= rWriterCompatibilityVersionOOo11; + + if ( eProp == OPENSOURCECONTEXT ) + aRet >>= rOpenSourceContext; + + return aRet; +} + +/*---------------------------------------------------------------------------*/ +void ConfigManager::getBasisAboutBoxProductVersion( OUString& rVersion ) +{ + rtl::OUString aPackageVersion = UNISTRING( "${$OOO_BASE_DIR/program/" SAL_CONFIGFILE("version") ":OOOPackageVersion}" ); + rtl::Bootstrap::expandMacros( aPackageVersion ); + + if ( aPackageVersion.getLength() ) + { + sal_Int32 nTokIndex = 0; + rtl::OUString aVersionMinor = aPackageVersion.getToken( 1, '.', nTokIndex ); + rtl::OUString aVersionMicro; + + if ( nTokIndex > 0 ) + aVersionMicro = aPackageVersion.getToken( 0, '.', nTokIndex ); + + if ( aVersionMinor.getLength() == 0 ) + aVersionMinor = UNISTRING( "0" ); + if ( aVersionMicro.getLength() == 0 ) + aVersionMicro = UNISTRING( "0" ); + + sal_Int32 nIndex = rVersion.indexOf( '.' ); + if ( nIndex == -1 ) + { + rVersion += UNISTRING( "." ); + rVersion += aVersionMinor; + } + else + { + nIndex = rVersion.indexOf( '.', nIndex+1 ); + } + if ( nIndex == -1 ) + { + rVersion += UNISTRING( "." ); + rVersion += aVersionMicro; + } + else + { + rVersion = rVersion.replaceAt( nIndex+1, rVersion.getLength()-nIndex-1, aVersionMicro ); + } + } +} + +Reference< XHierarchicalNameAccess> ConfigManager::GetHierarchyAccess(const OUString& rFullPath) +{ + Sequence< Any > aArgs(1); + aArgs[0] <<= rFullPath; + Reference< XMultiServiceFactory > xCfgProvider = GetLocalConfigurationProvider(); + Reference< XInterface > xIFace; + if(xCfgProvider.is()) + { + try + { + xIFace = xCfgProvider->createInstanceWithArguments( + OUString::createFromAscii(pAccessSrvc), + aArgs); + } +#ifdef DBG_UTIL + catch(Exception& rEx) + { + OString sMsg("CreateInstance exception: "); + sMsg += OString(rEx.Message.getStr(), + rEx.Message.getLength(), + RTL_TEXTENCODING_ASCII_US); + OSL_ENSURE(sal_False, sMsg.getStr()); + } +#else + catch(Exception&){} +#endif + } + return Reference<XHierarchicalNameAccess>(xIFace, UNO_QUERY); +} + +Any ConfigManager::GetLocalProperty(const OUString& rProperty) +{ + OUString sPath(OUString::createFromAscii(pConfigBaseURL)); + sPath += rProperty; + + OUString sNode, sProperty; + OSL_VERIFY( splitLastFromConfigurationPath(sPath, sNode, sProperty) ); + + Reference< XNameAccess> xAccess( GetHierarchyAccess(sNode), UNO_QUERY ); + Any aRet; + try + { + if(xAccess.is()) + aRet = xAccess->getByName(sProperty); + } +#ifdef DBG_UTIL + catch(Exception& rEx) + { + OString sMsg("GetLocalProperty: "); + sMsg += OString(rEx.Message.getStr(), + rEx.Message.getLength(), + RTL_TEXTENCODING_ASCII_US); + OSL_ENSURE(sal_False, sMsg.getStr()); + } +#else + catch(Exception&){} +#endif + return aRet; +} + +void ConfigManager::PutLocalProperty(const OUString& rProperty, const Any& rValue) +{ + OUString sPath(OUString::createFromAscii(pConfigBaseURL)); + sPath += rProperty; + + OUString sNode, sProperty; + OSL_VERIFY( splitLastFromConfigurationPath(sPath, sNode, sProperty) ); + + Reference<XNameReplace> xNodeReplace(GetHierarchyAccess(sNode), UNO_QUERY); + if(xNodeReplace.is()) + { + try + { + xNodeReplace->replaceByName(sProperty, rValue); + } +#ifdef DBG_UTIL + catch(Exception& rEx) + { + OString sMsg("PutLocalProperty: "); + sMsg += OString(rEx.Message.getStr(), + rEx.Message.getLength(), + RTL_TEXTENCODING_ASCII_US); + OSL_ENSURE(sal_False, sMsg.getStr()); + } +#else + catch(Exception& ){} +#endif + } +} + +sal_Bool ConfigManager::IsLocalConfigProvider() +{ + return false; +} + +/* 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 000000000000..65f7b2b631c9 --- /dev/null +++ b/unotools/source/config/confignode.cxx @@ -0,0 +1,663 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" + +#include <unotools/confignode.hxx> +#include <unotools/configpathes.hxx> +#include <tools/diagnose_ex.h> +#include <osl/diagnose.h> +#include <com/sun/star/container/XHierarchicalName.hpp> +#include <com/sun/star/beans/PropertyValue.hpp> +#include <com/sun/star/lang/XSingleServiceFactory.hpp> +#include <com/sun/star/lang/XComponent.hpp> +#include <com/sun/star/util/XStringEscape.hpp> +#include <com/sun/star/lang/XServiceInfo.hpp> +#include <com/sun/star/container/XNamed.hpp> +#include <comphelper/extract.hxx> +#include <comphelper/componentcontext.hxx> +#include <comphelper/namedvaluecollection.hxx> +#include <rtl/string.hxx> +#if OSL_DEBUG_LEVEL > 0 +#include <rtl/strbuf.hxx> +#endif + +//........................................................................ +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; + + //======================================================================== + //= OConfigurationNode + //======================================================================== + //------------------------------------------------------------------------ + OConfigurationNode::OConfigurationNode(const Reference< XInterface >& _rxNode ) + :m_bEscapeNames(sal_False) + { + OSL_ENSURE(_rxNode.is(), "OConfigurationNode::OConfigurationNode: invalid node interface!"); + if (_rxNode.is()) + { + // collect all interfaces necessary + m_xHierarchyAccess = Reference< XHierarchicalNameAccess >(_rxNode, UNO_QUERY); + m_xDirectAccess = Reference< XNameAccess >(_rxNode, UNO_QUERY); + + // reset _all_ interfaces if _one_ of them is not supported + if (!m_xHierarchyAccess.is() || !m_xDirectAccess.is()) + { + m_xHierarchyAccess = NULL; + m_xDirectAccess = NULL; + } + + // now for the non-critical interfaces + m_xReplaceAccess = Reference< XNameReplace >(_rxNode, UNO_QUERY); + m_xContainerAccess = Reference< XNameContainer >(_rxNode, UNO_QUERY); + } + + Reference< XComponent > xConfigNodeComp(m_xDirectAccess, UNO_QUERY); + if (xConfigNodeComp.is()) + startComponentListening(xConfigNodeComp); + + if (isValid()) + setEscape(isSetNode()); + } + + //------------------------------------------------------------------------ + 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) + ,m_sCompletePath(_rSource.m_sCompletePath) + { + Reference< XComponent > xConfigNodeComp(m_xDirectAccess, UNO_QUERY); + if (xConfigNodeComp.is()) + startComponentListening(xConfigNodeComp); + } + + //------------------------------------------------------------------------ + const 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; + m_sCompletePath = _rSource.m_sCompletePath; + + 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(); + } + + //------------------------------------------------------------------------ + ::rtl::OUString OConfigurationNode::getLocalName() const + { + ::rtl::OUString sLocalName; + try + { + Reference< XNamed > xNamed( m_xDirectAccess, UNO_QUERY_THROW ); + sLocalName = xNamed->getName(); + } + catch( const Exception& ) + { + DBG_UNHANDLED_EXCEPTION(); + } + return sLocalName; + } + + //------------------------------------------------------------------------ + ::rtl::OUString OConfigurationNode::getNodePath() const + { + ::rtl::OUString sNodePath; + try + { + Reference< XHierarchicalName > xNamed( m_xDirectAccess, UNO_QUERY_THROW ); + sNodePath = xNamed->getHierarchicalName(); + } + catch( const Exception& ) + { + DBG_UNHANDLED_EXCEPTION(); + } + return sNodePath; + } + + //------------------------------------------------------------------------ + ::rtl::OUString OConfigurationNode::normalizeName(const ::rtl::OUString& _rName, NAMEORIGIN _eOrigin) const + { + ::rtl::OUString sName(_rName); + if (getEscape()) + { + Reference< XStringEscape > xEscaper(m_xDirectAccess, UNO_QUERY); + if (xEscaper.is() && sName.getLength()) + { + try + { + if (NO_CALLER == _eOrigin) + sName = xEscaper->escapeString(sName); + else + sName = xEscaper->unescapeString(sName); + } + catch(Exception&) + { + DBG_UNHANDLED_EXCEPTION(); + } + } + } + return sName; + } + + //------------------------------------------------------------------------ + Sequence< ::rtl::OUString > OConfigurationNode::getNodeNames() const throw() + { + OSL_ENSURE(m_xDirectAccess.is(), "OConfigurationNode::getNodeNames: object is invalid!"); + Sequence< ::rtl::OUString > aReturn; + if (m_xDirectAccess.is()) + { + try + { + aReturn = m_xDirectAccess->getElementNames(); + // normalize the names + ::rtl::OUString* pNames = aReturn.getArray(); + for (sal_Int32 i=0; i<aReturn.getLength(); ++i, ++pNames) + *pNames = normalizeName(*pNames, NO_CONFIGURATION); + } + catch(Exception&) + { + OSL_ENSURE(sal_False, "OConfigurationNode::getNodeNames: caught a generic exception!"); + } + } + + return aReturn; + } + + //------------------------------------------------------------------------ + sal_Bool OConfigurationNode::removeNode(const ::rtl::OUString& _rName) const throw() + { + OSL_ENSURE(m_xContainerAccess.is(), "OConfigurationNode::removeNode: object is invalid!"); + if (m_xContainerAccess.is()) + { + try + { + ::rtl::OUString sName = normalizeName(_rName, NO_CALLER); + m_xContainerAccess->removeByName(sName); + return sal_True; + } + catch (NoSuchElementException&) + { + #if OSL_DEBUG_LEVEL > 0 + rtl::OStringBuffer aBuf( 256 ); + aBuf.append("OConfigurationNode::removeNode: there is no element named!"); + aBuf.append( rtl::OUStringToOString( _rName, RTL_TEXTENCODING_ASCII_US ) ); + aBuf.append( "!" ); + OSL_ENSURE(sal_False, aBuf.getStr()); + #endif + } + catch (WrappedTargetException&) + { + OSL_ENSURE(sal_False, "OConfigurationNode::removeNode: caught a WrappedTargetException!"); + } + catch(Exception&) + { + OSL_ENSURE(sal_False, "OConfigurationNode::removeNode: caught a generic exception!"); + } + } + return sal_False; + } + //------------------------------------------------------------------------ + OConfigurationNode OConfigurationNode::insertNode(const ::rtl::OUString& _rName,const Reference< XInterface >& _xNode) const throw() + { + if(_xNode.is()) + { + try + { + ::rtl::OUString sName = normalizeName(_rName, NO_CALLER); + m_xContainerAccess->insertByName(sName, makeAny(_xNode)); + // if we're here, all was ok ... + return OConfigurationNode( _xNode ); + } + catch(const Exception&) + { + DBG_UNHANDLED_EXCEPTION(); + } + + // 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 ::rtl::OUString& _rName) const throw() + { + 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(); + } + return insertNode(_rName,xNewChild); + } + + return OConfigurationNode(); + } + + //------------------------------------------------------------------------ + OConfigurationNode OConfigurationNode::appendNode(const ::rtl::OUString& _rName,const OConfigurationNode& _aNewNode) const throw() + { + return insertNode(_rName,_aNewNode.m_xDirectAccess); + } + //------------------------------------------------------------------------ + OConfigurationNode OConfigurationNode::openNode(const ::rtl::OUString& _rPath) const throw() + { + OSL_ENSURE(m_xDirectAccess.is(), "OConfigurationNode::openNode: object is invalid!"); + OSL_ENSURE(m_xHierarchyAccess.is(), "OConfigurationNode::openNode: object is invalid!"); + try + { + ::rtl::OUString sNormalized = normalizeName(_rPath, NO_CALLER); + + Reference< XInterface > xNode; + if (m_xDirectAccess.is() && m_xDirectAccess->hasByName(sNormalized)) + { + if (!::cppu::extractInterface(xNode, m_xDirectAccess->getByName(sNormalized))) + OSL_ENSURE(sal_False, "OConfigurationNode::openNode: could not open the node!"); + } + else if (m_xHierarchyAccess.is()) + { + if (!::cppu::extractInterface(xNode, m_xHierarchyAccess->getByHierarchicalName(_rPath))) + OSL_ENSURE(sal_False, "OConfigurationNode::openNode: could not open the node!"); + } + if (xNode.is()) + return OConfigurationNode( xNode ); + } + catch(NoSuchElementException& e) + { + (void)e; + #if OSL_DEBUG_LEVEL > 0 + rtl::OStringBuffer aBuf( 256 ); + aBuf.append("OConfigurationNode::openNode: there is no element named "); + aBuf.append( rtl::OUStringToOString( _rPath, RTL_TEXTENCODING_ASCII_US ) ); + aBuf.append("!"); + OSL_ENSURE(sal_False, aBuf.getStr()); + #endif + } + catch(Exception&) + { + OSL_ENSURE(sal_False, "OConfigurationNode::openNode: caught an exception while retrieving the node!"); + } + return OConfigurationNode(); + } + + //------------------------------------------------------------------------ + void OConfigurationNode::setEscape(sal_Bool _bEnable) + { + m_bEscapeNames = _bEnable && Reference< XStringEscape >::query(m_xDirectAccess).is(); + } + + //------------------------------------------------------------------------ + sal_Bool OConfigurationNode::isSetNode() const + { + sal_Bool bIsSet = sal_False; + Reference< XServiceInfo > xSI(m_xHierarchyAccess, UNO_QUERY); + if (xSI.is()) + { + try { bIsSet = xSI->supportsService(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.configuration.SetAccess"))); } + catch(Exception&) { } + } + return bIsSet; + } + + sal_Bool OConfigurationNode::hasByHierarchicalName( const ::rtl::OUString& _rName ) const throw() + { + OSL_ENSURE( m_xHierarchyAccess.is(), "OConfigurationNode::hasByHierarchicalName: no hierarchy access!" ); + try + { + if ( m_xHierarchyAccess.is() ) + { + ::rtl::OUString sName = normalizeName( _rName, NO_CALLER ); + return m_xHierarchyAccess->hasByHierarchicalName( sName ); + } + } + catch(Exception&) + { + } + return sal_False; + } + + //------------------------------------------------------------------------ + sal_Bool OConfigurationNode::hasByName(const ::rtl::OUString& _rName) const throw() + { + OSL_ENSURE(m_xDirectAccess.is(), "OConfigurationNode::hasByName: object is invalid!"); + try + { + ::rtl::OUString sName = normalizeName(_rName, NO_CALLER); + if (m_xDirectAccess.is()) + return m_xDirectAccess->hasByName(sName); + } + catch(Exception&) + { + } + return sal_False; + } + + //------------------------------------------------------------------------ + sal_Bool OConfigurationNode::setNodeValue(const ::rtl::OUString& _rPath, const Any& _rValue) const throw() + { + sal_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 + ::rtl::OUString sNormalizedName = normalizeName(_rPath, NO_CALLER); + if (m_xReplaceAccess->hasByName(sNormalizedName)) + { + m_xReplaceAccess->replaceByName(sNormalizedName, _rValue); + bResult = true; + } + + // check if the name refers to a indirect descendant + else if (m_xHierarchyAccess.is() && m_xHierarchyAccess->hasByHierarchicalName(_rPath)) + { + OSL_ASSERT(_rPath.getLength()); + + ::rtl::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(IllegalArgumentException&) + { + OSL_ENSURE(sal_False, "OConfigurationNode::setNodeValue: could not replace the value: caught an IllegalArgumentException!"); + } + catch(NoSuchElementException&) + { + OSL_ENSURE(sal_False, "OConfigurationNode::setNodeValue: could not replace the value: caught a NoSuchElementException!"); + } + catch(WrappedTargetException&) + { + OSL_ENSURE(sal_False, "OConfigurationNode::setNodeValue: could not replace the value: caught a WrappedTargetException!"); + } + catch(Exception&) + { + OSL_ENSURE(sal_False, "OConfigurationNode::setNodeValue: could not replace the value: caught a generic Exception!"); + } + + + } + return bResult; + } + + //------------------------------------------------------------------------ + Any OConfigurationNode::getNodeValue(const ::rtl::OUString& _rPath) const throw() + { + OSL_ENSURE(m_xDirectAccess.is(), "OConfigurationNode::hasByName: object is invalid!"); + OSL_ENSURE(m_xHierarchyAccess.is(), "OConfigurationNode::hasByName: object is invalid!"); + Any aReturn; + try + { + ::rtl::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(); + } + return aReturn; + } + + //------------------------------------------------------------------------ + void OConfigurationNode::clear() throw() + { + m_xHierarchyAccess.clear(); + m_xDirectAccess.clear(); + m_xReplaceAccess.clear(); + m_xContainerAccess.clear(); + } + + //======================================================================== + //= helper + //======================================================================== + namespace + { + //-------------------------------------------------------------------- + static const ::rtl::OUString& lcl_getProviderServiceName( ) + { + static ::rtl::OUString s_sProviderServiceName( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.configuration.ConfigurationProvider" ) ); + return s_sProviderServiceName; + } + + //-------------------------------------------------------------------- + Reference< XMultiServiceFactory > lcl_getConfigProvider( const ::comphelper::ComponentContext& i_rContext ) + { + try + { + Reference< XMultiServiceFactory > xProvider( i_rContext.createComponent( lcl_getProviderServiceName() ), UNO_QUERY_THROW ); + return xProvider; + } + catch ( const Exception& ) + { + DBG_UNHANDLED_EXCEPTION(); + } + return NULL; + } + + //-------------------------------------------------------------------- + Reference< XInterface > lcl_createConfigurationRoot( const Reference< XMultiServiceFactory >& i_rxConfigProvider, + const ::rtl::OUString& i_rNodePath, const bool i_bUpdatable, const sal_Int32 i_nDepth, const bool i_bLazyWrite ) + { + ENSURE_OR_RETURN( i_rxConfigProvider.is(), "invalid provider", NULL ); + try + { + ::comphelper::NamedValueCollection aArgs; + aArgs.put( "nodepath", i_rNodePath ); + aArgs.put( "lazywrite", i_bLazyWrite ); + aArgs.put( "depth", i_nDepth ); + + ::rtl::OUString sAccessService( i_bUpdatable ? + ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.configuration.ConfigurationUpdateAccess" )) : + ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "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(); + } + return NULL; + } + } + //======================================================================== + //= OConfigurationTreeRoot + //======================================================================== + //------------------------------------------------------------------------ + OConfigurationTreeRoot::OConfigurationTreeRoot( const Reference< XChangesBatch >& _rxRootNode ) + :OConfigurationNode( _rxRootNode.get() ) + ,m_xCommitter(_rxRootNode) + { + } + + //------------------------------------------------------------------------ + OConfigurationTreeRoot::OConfigurationTreeRoot( const Reference< XInterface >& _rxRootNode ) + :OConfigurationNode( _rxRootNode ) + ,m_xCommitter( _rxRootNode, UNO_QUERY ) + { + } + + //------------------------------------------------------------------------ + OConfigurationTreeRoot::OConfigurationTreeRoot( const ::comphelper::ComponentContext& i_rContext, const sal_Char* i_pAsciiNodePath, const bool i_bUpdatable ) + :OConfigurationNode( lcl_createConfigurationRoot( lcl_getConfigProvider( i_rContext.getLegacyServiceFactory() ), + ::rtl::OUString::createFromAscii( i_pAsciiNodePath ), i_bUpdatable, -1, false ).get() ) + ,m_xCommitter() + { + if ( i_bUpdatable ) + { + m_xCommitter.set( getUNONode(), UNO_QUERY ); + OSL_ENSURE( m_xCommitter.is(), "OConfigurationTreeRoot::OConfigurationTreeRoot: could not create an updatable node!" ); + } + } + + //------------------------------------------------------------------------ + OConfigurationTreeRoot::OConfigurationTreeRoot( const ::comphelper::ComponentContext& i_rContext, const ::rtl::OUString& i_rNodePath, const bool i_bUpdatable ) + :OConfigurationNode( lcl_createConfigurationRoot( lcl_getConfigProvider( i_rContext.getLegacyServiceFactory() ), + i_rNodePath, i_bUpdatable, -1, false ).get() ) + ,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() throw() + { + OConfigurationNode::clear(); + m_xCommitter.clear(); + } + + //------------------------------------------------------------------------ + sal_Bool OConfigurationTreeRoot::commit() const throw() + { + OSL_ENSURE(isValid(), "OConfigurationTreeRoot::commit: object is invalid!"); + if (!isValid()) + return sal_False; + OSL_ENSURE(m_xCommitter.is(), "OConfigurationTreeRoot::commit: I'm a readonly node!"); + if (!m_xCommitter.is()) + return sal_False; + + try + { + m_xCommitter->commitChanges(); + return sal_True; + } + catch(const Exception&) + { + DBG_UNHANDLED_EXCEPTION(); + } + return sal_False; + } + + //------------------------------------------------------------------------ + OConfigurationTreeRoot OConfigurationTreeRoot::createWithProvider(const Reference< XMultiServiceFactory >& _rxConfProvider, const ::rtl::OUString& _rPath, sal_Int32 _nDepth, CREATION_MODE _eMode, sal_Bool _bLazyWrite) + { + Reference< XInterface > xRoot( lcl_createConfigurationRoot( + _rxConfProvider, _rPath, _eMode != CM_READONLY, _nDepth, _bLazyWrite ) ); + if ( xRoot.is() ) + return OConfigurationTreeRoot( xRoot ); + return OConfigurationTreeRoot(); + } + + //------------------------------------------------------------------------ + OConfigurationTreeRoot OConfigurationTreeRoot::createWithServiceFactory( const Reference< XMultiServiceFactory >& _rxORB, const ::rtl::OUString& _rPath, sal_Int32 _nDepth, CREATION_MODE _eMode, sal_Bool _bLazyWrite ) + { + return createWithProvider( lcl_getConfigProvider( _rxORB ), _rPath, _nDepth, _eMode, _bLazyWrite ); + } + + //------------------------------------------------------------------------ + OConfigurationTreeRoot OConfigurationTreeRoot::tryCreateWithServiceFactory( const Reference< XMultiServiceFactory >& _rxORB, + const ::rtl::OUString& _rPath, sal_Int32 _nDepth , CREATION_MODE _eMode , sal_Bool _bLazyWrite ) + { + OSL_ENSURE( _rxORB.is(), "OConfigurationTreeRoot::tryCreateWithServiceFactory: invalid service factory!" ); + if ( _rxORB.is() ) + { + try + { + Reference< XMultiServiceFactory > xConfigFactory( _rxORB->createInstance( lcl_getProviderServiceName( ) ), UNO_QUERY ); + if ( xConfigFactory.is() ) + return createWithProvider( xConfigFactory, _rPath, _nDepth, _eMode, _bLazyWrite ); + } + 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/configpathes.cxx b/unotools/source/config/configpathes.cxx new file mode 100644 index 000000000000..fd813d4c7a9a --- /dev/null +++ b/unotools/source/config/configpathes.cxx @@ -0,0 +1,311 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" + +#include "unotools/configpathes.hxx" +#include <rtl/ustring.hxx> +#include <rtl/ustrbuf.hxx> +#include <osl/diagnose.h> + +//---------------------------------------------------------------------------- +namespace utl +{ +//---------------------------------------------------------------------------- + + using ::rtl::OUString; + using ::rtl::OUStringBuffer; + +//---------------------------------------------------------------------------- + +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.matchAsciiL(RTL_CONSTASCII_STRINGPARAM("&"),nEscapePos)) + ch = '&'; + + else if (aLocalString.matchAsciiL(RTL_CONSTASCII_STRINGPARAM("'"),nEscapePos)) + ch = '\''; + + else if (aLocalString.matchAsciiL(RTL_CONSTASCII_STRINGPARAM("""),nEscapePos)) + ch = '"'; + + OSL_ENSURE(ch,"Configuration path contains '&' that is not part of a valid character escape"); + if (ch) + { + aResult.append(aLocalString.copy(nStart,nEscapePos-nStart)).append(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.copy(nStart)); + + aLocalString = aResult.makeStringAndClear(); +} + +//---------------------------------------------------------------------------- +sal_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 ] == sal_Unicode('/')) + { + OSL_ENSURE(false, "Invalid config path: trailing '/' is not allowed"); + --nPos; + } + + // check for predicate ['xxx'] or ["yyy"] + if (nPos > 0 && _sInPath[ nPos ] == sal_Unicode(']')) + { + 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 pathes + { + 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 != 0) + { + *_sOutPath = (nSep >= 0) ? _sInPath.copy(nSep + 1) : OUString(); + } + + return sResult; +} + +//---------------------------------------------------------------------------- + +// find the position after the prefix in the nested path +static inline +sal_Int32 lcl_findPrefixEnd(OUString const& _sNestedPath, OUString const& _sPrefixPath) +{ + // TODO: currently handles only exact prefix matches + sal_Int32 nPrefixLength = _sPrefixPath.getLength(); + + OSL_ENSURE(nPrefixLength == 0 || _sPrefixPath[nPrefixLength-1] != '/', + "Cannot handle slash-terminated prefix pathes"); + + sal_Bool bIsPrefix; + if (_sNestedPath.getLength() > nPrefixLength) + { + bIsPrefix = _sNestedPath[nPrefixLength] == '/' && + _sNestedPath.compareTo(_sPrefixPath,nPrefixLength) == 0; + ++nPrefixLength; + } + else if (_sNestedPath.getLength() == nPrefixLength) + { + bIsPrefix = _sNestedPath.equals(_sPrefixPath); + } + else + { + bIsPrefix = false; + } + + return bIsPrefix ? nPrefixLength : 0; +} + +//---------------------------------------------------------------------------- +sal_Bool isPrefixOfConfigurationPath(OUString const& _sNestedPath, + OUString const& _sPrefixPath) +{ + return _sPrefixPath.getLength() == 0 || lcl_findPrefixEnd(_sNestedPath,_sPrefixPath) != 0; +} + +//---------------------------------------------------------------------------- +OUString dropPrefixFromConfigurationPath(OUString const& _sNestedPath, + OUString const& _sPrefixPath) +{ + if ( sal_Int32 nPrefixEnd = lcl_findPrefixEnd(_sNestedPath,_sPrefixPath) ) + { + return _sNestedPath.copy(nPrefixEnd); + } + else + { + OSL_ENSURE(_sPrefixPath.getLength() == 0, "Path does not start with expected prefix"); + + return _sNestedPath; + } +} + +//---------------------------------------------------------------------------- +static +OUString lcl_wrapName(const OUString& _sContent, const OUString& _sType) +{ + const sal_Unicode * const pBeginContent = _sContent.getStr(); + const sal_Unicode * const pEndContent = pBeginContent + _sContent.getLength(); + + OSL_PRECOND(_sType.getLength(), "Unexpected config type name: empty"); + OSL_PRECOND(pBeginContent <= pEndContent, "Invalid config name: empty"); + + if (pBeginContent == pEndContent) + return _sType; + + rtl::OUStringBuffer aNormalized(_sType.getLength() + _sContent.getLength() + 4); // reserve approximate size initially + + // prefix: type, opening bracket and quote + aNormalized.append( _sType ).appendAscii( RTL_CONSTASCII_STRINGPARAM("['") ); + + // content: copy over each char and handle escaping + for(const sal_Unicode* pCur = pBeginContent; pCur != pEndContent; ++pCur) + { + // append (escape if needed) + switch(*pCur) + { + case sal_Unicode('&') : aNormalized.appendAscii( RTL_CONSTASCII_STRINGPARAM("&") ); break; + case sal_Unicode('\''): aNormalized.appendAscii( RTL_CONSTASCII_STRINGPARAM("'") ); break; + case sal_Unicode('\"'): aNormalized.appendAscii( RTL_CONSTASCII_STRINGPARAM(""") ); break; + + default: aNormalized.append( *pCur ); + } + } + + // suffix: closing quote and bracket + aNormalized.appendAscii( RTL_CONSTASCII_STRINGPARAM("']") ); + + return aNormalized.makeStringAndClear(); +} + +//---------------------------------------------------------------------------- + +OUString wrapConfigurationElementName(OUString const& _sElementName) +{ + return lcl_wrapName(_sElementName, OUString(RTL_CONSTASCII_USTRINGPARAM("*")) ); +} + +//---------------------------------------------------------------------------- + +OUString wrapConfigurationElementName(OUString const& _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 000000000000..a7fc30699218 --- /dev/null +++ b/unotools/source/config/configvaluecontainer.cxx @@ -0,0 +1,395 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" +#include <unotools/configvaluecontainer.hxx> +#include <unotools/confignode.hxx> +#include <tools/debug.hxx> +#include <comphelper/stl_types.hxx> +#include <uno/data.h> +#include <algorithm> + +#ifdef DBG_UTIL +#include <rtl/strbuf.hxx> +#endif + +//......................................................................... +namespace utl +{ +//......................................................................... + + using namespace ::com::sun::star::uno; + using namespace ::com::sun::star::lang; + + //===================================================================== + //= NodeValueAccessor + //===================================================================== + enum LocationType + { + ltSimplyObjectInstance, + ltAnyInstance, + + ltUnbound + }; + + struct NodeValueAccessor + { + private: + ::rtl::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: + NodeValueAccessor( const ::rtl::OUString& _rNodePath ); + + void bind( void* _pLocation, const Type& _rType ); + void bind( Any* _pLocation ); + + bool isBound( ) const { return ( ltUnbound != eLocationType ) && ( NULL != pLocation ); } + const ::rtl::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; + bool operator != ( const NodeValueAccessor& rhs ) const { return !operator == ( rhs ); } + }; + + NodeValueAccessor::NodeValueAccessor( const ::rtl::OUString& _rNodePath ) + :sRelativePath( _rNodePath ) + ,eLocationType( ltUnbound ) + ,pLocation( NULL ) + { + } + + 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 ) + { + DBG_ASSERT( !isBound(), "NodeValueAccessor::bind: already bound!" ); + + eLocationType = ltSimplyObjectInstance; + pLocation = _pLocation; + aDataType = _rType; + } + + void NodeValueAccessor::bind( Any* _pLocation ) + { + DBG_ASSERT( !isBound(), "NodeValueAccessor::bind: already bound!" ); + + eLocationType = ltAnyInstance; + pLocation = _pLocation; + aDataType = ::getCppuType( _pLocation ); + } + + #ifndef UNX + static + #endif + void lcl_copyData( const NodeValueAccessor& _rAccessor, const Any& _rData, ::osl::Mutex& _rMutex ) + { + ::osl::MutexGuard aGuard( _rMutex ); + + DBG_ASSERT( _rAccessor.isBound(), "::utl::lcl_copyData: invalid accessor!" ); + switch ( _rAccessor.getLocType() ) + { + case ltSimplyObjectInstance: + { + if ( _rData.hasValue() ) + { +#ifdef DBG_UTIL + sal_Bool bSuccess = +#endif + // assign the value + uno_type_assignData( + _rAccessor.getLocation(), _rAccessor.getDataType().getTypeLibType(), + const_cast< void* >( _rData.getValue() ), _rData.getValueType().getTypeLibType(), + (uno_QueryInterfaceFunc)cpp_queryInterface, (uno_AcquireFunc)cpp_acquire, (uno_ReleaseFunc)cpp_release + ); + #ifdef DBG_UTIL + rtl::OStringBuffer aBuf( 256 ); + aBuf.append("::utl::lcl_copyData( Accessor, Any ): could not assign the data (node path: "); + aBuf.append( rtl::OUStringToOString( _rAccessor.getPath(), RTL_TEXTENCODING_ASCII_US ) ); + aBuf.append( " !" ); + DBG_ASSERT( bSuccess, aBuf.getStr() ); + #endif + } + else { + DBG_WARNING( "::utl::lcl_copyData: NULL value lost!" ); + } + } + break; + case ltAnyInstance: + // a simple assignment of an Any ... + *static_cast< Any* >( _rAccessor.getLocation() ) = _rData; + break; + default: + break; + } + } + + #ifndef UNX + static + #endif + void lcl_copyData( Any& _rData, const NodeValueAccessor& _rAccessor, ::osl::Mutex& _rMutex ) + { + ::osl::MutexGuard aGuard( _rMutex ); + + DBG_ASSERT( _rAccessor.isBound(), "::utl::lcl_copyData: invalid accessor!" ); + switch ( _rAccessor.getLocType() ) + { + case ltSimplyObjectInstance: + // a simple setValue .... + _rData.setValue( _rAccessor.getLocation(), _rAccessor.getDataType() ); + break; + + case ltAnyInstance: + // a simple assignment of an Any ... + _rData = *static_cast< Any* >( _rAccessor.getLocation() ); + break; + default: + break; + } + } + + //===================================================================== + //= functors on NodeValueAccessor instances + //===================================================================== + + /// base class for functors syncronizing between exchange locations and config sub nodes + struct SubNodeAccess : public ::std::unary_function< NodeValueAccessor, void > + { + 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& _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& _rAccessor ) + { + Any aNewValue; + lcl_copyData( aNewValue, _rAccessor, m_rMutex ); + m_rRootNode.setNodeValue( _rAccessor.getPath( ), aNewValue ); + } + }; + + DECLARE_STL_VECTOR( NodeValueAccessor, NodeValueAccessors ); + + //===================================================================== + //= OConfigurationValueContainerImpl + //===================================================================== + struct OConfigurationValueContainerImpl + { + Reference< XMultiServiceFactory > xORB; // the service factory + ::osl::Mutex& rMutex; // the mutex for accessing the data containers + OConfigurationTreeRoot aConfigRoot; // the configuration node we're accessing + + NodeValueAccessors aAccessors; // the accessors to the node values + + OConfigurationValueContainerImpl( const Reference< XMultiServiceFactory >& _rxORB, ::osl::Mutex& _rMutex ) + :xORB( _rxORB ) + ,rMutex( _rMutex ) + { + } + }; + + //===================================================================== + //= OConfigurationValueContainer + //===================================================================== + + OConfigurationValueContainer::OConfigurationValueContainer( + const Reference< XMultiServiceFactory >& _rxORB, ::osl::Mutex& _rAccessSafety, + const sal_Char* _pConfigLocation, const sal_uInt16 _nAccessFlags, const sal_Int32 _nLevels ) + :m_pImpl( new OConfigurationValueContainerImpl( _rxORB, _rAccessSafety ) ) + { + implConstruct( ::rtl::OUString::createFromAscii( _pConfigLocation ), _nAccessFlags, _nLevels ); + } + + OConfigurationValueContainer::OConfigurationValueContainer( + const Reference< XMultiServiceFactory >& _rxORB, ::osl::Mutex& _rAccessSafety, + const ::rtl::OUString& _rConfigLocation, const sal_uInt16 _nAccessFlags, const sal_Int32 _nLevels ) + :m_pImpl( new OConfigurationValueContainerImpl( _rxORB, _rAccessSafety ) ) + { + implConstruct( _rConfigLocation, _nAccessFlags, _nLevels ); + } + + OConfigurationValueContainer::~OConfigurationValueContainer() + { + delete m_pImpl; + } + + const Reference< XMultiServiceFactory >& OConfigurationValueContainer::getServiceFactory( ) const + { + return m_pImpl->xORB; + } + + void OConfigurationValueContainer::implConstruct( const ::rtl::OUString& _rConfigLocation, + const sal_uInt16 _nAccessFlags, const sal_Int32 _nLevels ) + { + DBG_ASSERT( !m_pImpl->aConfigRoot.isValid(), "OConfigurationValueContainer::implConstruct: already initialized!" ); + + // ................................. + // create the configuration node we're about to work with + m_pImpl->aConfigRoot = OConfigurationTreeRoot::createWithServiceFactory( + m_pImpl->xORB, + _rConfigLocation, + _nLevels, + ( _nAccessFlags & CVC_UPDATE_ACCESS ) ? OConfigurationTreeRoot::CM_UPDATABLE : OConfigurationTreeRoot::CM_READONLY, + ( _nAccessFlags & CVC_IMMEDIATE_UPDATE ) ? sal_False : sal_True + ); + #ifdef DBG_UTIL + rtl::OStringBuffer aBuf(256); + aBuf.append("Could not access the configuration node located at "); + aBuf.append( rtl::OUStringToOString( _rConfigLocation, RTL_TEXTENCODING_ASCII_US ) ); + aBuf.append( " !" ); + DBG_ASSERT( m_pImpl->aConfigRoot.isValid(), aBuf.getStr() ); + #endif + } + + void OConfigurationValueContainer::registerExchangeLocation( const sal_Char* _pRelativePath, + void* _pContainer, const Type& _rValueType ) + { + // checks .... + DBG_ASSERT( _pContainer, "OConfigurationValueContainer::registerExchangeLocation: invalid container location!" ); + DBG_ASSERT( ( 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( ) ), + "OConfigurationValueContainer::registerExchangeLocation: invalid type!" ); + + // build an accessor for this container + NodeValueAccessor aNewAccessor( ::rtl::OUString::createFromAscii( _pRelativePath ) ); + aNewAccessor.bind( _pContainer, _rValueType ); + + // insert it into our structure + implRegisterExchangeLocation( aNewAccessor ); + } + + void OConfigurationValueContainer::registerNullValueExchangeLocation( const sal_Char* _pRelativePath, Any* _pContainer ) + { + // build an accessor for this container + NodeValueAccessor aNewAccessor( ::rtl::OUString::createFromAscii( _pRelativePath ) ); + aNewAccessor.bind( _pContainer ); + + // 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::write( sal_Bool _bCommit ) + { + // collect 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 (if requested) + if ( _bCommit ) + commit( sal_False ); + } + + void OConfigurationValueContainer::commit( sal_Bool _bWrite ) + { + // write the current values in the exchange locations (if requested) + if ( _bWrite ) + write( sal_False ); + + // commit the changes done + m_pImpl->aConfigRoot.commit( ); + } + + void OConfigurationValueContainer::implRegisterExchangeLocation( const NodeValueAccessor& _rAccessor ) + { + // some checks + DBG_ASSERT( !m_pImpl->aConfigRoot.isValid() || m_pImpl->aConfigRoot.hasByHierarchicalName( _rAccessor.getPath() ), + "OConfigurationValueContainer::implRegisterExchangeLocation: invalid relative path!" ); + +#ifdef DBG_UTIL + // another check (should be the first container for this node) + ConstNodeValueAccessorsIterator aExistent = ::std::find( + m_pImpl->aAccessors.begin(), + m_pImpl->aAccessors.end(), + _rAccessor + ); + DBG_ASSERT( m_pImpl->aAccessors.end() == aExistent, "OConfigurationValueContainer::implRegisterExchangeLocation: already registered a container for this subnode!" ); +#endif + + // 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 000000000000..a4611ab74ef5 --- /dev/null +++ b/unotools/source/config/defaultoptions.cxx @@ -0,0 +1,364 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" + +#include <unotools/defaultoptions.hxx> +#include <unotools/pathoptions.hxx> +#include <unotools/configitem.hxx> +#include <unotools/configmgr.hxx> +#include <tools/debug.hxx> +#include <tools/resmgr.hxx> +#include <tools/urlobj.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> +#include <osl/mutex.hxx> + +#include <unotools/localfilehelper.hxx> +#include <rtl/instance.hxx> + +#include <itemholder1.hxx> + +using namespace osl; +using namespace utl; +using namespace rtl; +using namespace com::sun::star::uno; + +// define ---------------------------------------------------------------- + +#define ASCII_STR(s) OUString( RTL_CONSTASCII_USTRINGPARAM(s) ) + +#define DEFAULTPATH__ADDIN 0 +#define DEFAULTPATH__AUTOCORRECT 1 +#define DEFAULTPATH__AUTOTEXT 2 +#define DEFAULTPATH__BACKUP 3 +#define DEFAULTPATH__BASIC 4 +#define DEFAULTPATH__BITMAP 5 +#define DEFAULTPATH__CONFIG 6 +#define DEFAULTPATH__DICTIONARY 7 +#define DEFAULTPATH__FAVORITES 8 +#define DEFAULTPATH__FILTER 9 +#define DEFAULTPATH__GALLERY 10 +#define DEFAULTPATH__GRAPHIC 11 +#define DEFAULTPATH__HELP 12 +#define DEFAULTPATH__LINGUISTIC 13 +#define DEFAULTPATH__MODULE 14 +#define DEFAULTPATH__PALETTE 15 +#define DEFAULTPATH__PLUGIN 16 +#define DEFAULTPATH__TEMP 17 +#define DEFAULTPATH__TEMPLATE 18 +#define DEFAULTPATH__USERCONFIG 19 +#define DEFAULTPATH__WORK 20 +#define DEFAULTPATH__USERDICTIONARY 21 + +// class SvtDefaultOptions_Impl ------------------------------------------ + +class SvtDefaultOptions_Impl : public utl::ConfigItem +{ +public: + String m_aAddinPath; + String m_aAutoCorrectPath; + String m_aAutoTextPath; + String m_aBackupPath; + String m_aBasicPath; + String m_aBitmapPath; + String m_aConfigPath; + String m_aDictionaryPath; + String m_aFavoritesPath; + String m_aFilterPath; + String m_aGalleryPath; + String m_aGraphicPath; + String m_aHelpPath; + String m_aLinguisticPath; + String m_aModulePath; + String m_aPalettePath; + String m_aPluginPath; + String m_aTempPath; + String m_aTemplatePath; + String m_aUserConfigPath; + String m_aWorkPath; + String m_aUserDictionaryPath; + + SvtDefaultOptions_Impl(); + + String GetDefaultPath( USHORT nId ) const; + virtual void Commit(); + virtual void Notify( const com::sun::star::uno::Sequence<rtl::OUString>& aPropertyNames); +}; + +// global ---------------------------------------------------------------- + +static SvtDefaultOptions_Impl* pOptions = NULL; +static sal_Int32 nRefCount = 0; + +typedef String SvtDefaultOptions_Impl:: *PathStrPtr; + +struct PathToDefaultMapping_Impl +{ + SvtPathOptions::Pathes _ePath; + PathStrPtr _pDefaultPath; +}; + +static PathToDefaultMapping_Impl __READONLY_DATA PathMap_Impl[] = +{ + { SvtPathOptions::PATH_ADDIN, &SvtDefaultOptions_Impl::m_aAddinPath }, + { SvtPathOptions::PATH_AUTOCORRECT, &SvtDefaultOptions_Impl::m_aAutoCorrectPath }, + { SvtPathOptions::PATH_AUTOTEXT, &SvtDefaultOptions_Impl::m_aAutoTextPath }, + { SvtPathOptions::PATH_BACKUP, &SvtDefaultOptions_Impl::m_aBackupPath }, + { SvtPathOptions::PATH_BASIC, &SvtDefaultOptions_Impl::m_aBasicPath }, + { SvtPathOptions::PATH_BITMAP, &SvtDefaultOptions_Impl::m_aBitmapPath }, + { SvtPathOptions::PATH_CONFIG, &SvtDefaultOptions_Impl::m_aConfigPath }, + { SvtPathOptions::PATH_DICTIONARY, &SvtDefaultOptions_Impl::m_aDictionaryPath }, + { SvtPathOptions::PATH_FAVORITES, &SvtDefaultOptions_Impl::m_aFavoritesPath }, + { SvtPathOptions::PATH_FILTER, &SvtDefaultOptions_Impl::m_aFilterPath }, + { SvtPathOptions::PATH_GALLERY, &SvtDefaultOptions_Impl::m_aGalleryPath }, + { SvtPathOptions::PATH_GRAPHIC, &SvtDefaultOptions_Impl::m_aGraphicPath }, + { SvtPathOptions::PATH_HELP, &SvtDefaultOptions_Impl::m_aHelpPath }, + { SvtPathOptions::PATH_LINGUISTIC, &SvtDefaultOptions_Impl::m_aLinguisticPath }, + { SvtPathOptions::PATH_MODULE, &SvtDefaultOptions_Impl::m_aModulePath }, + { SvtPathOptions::PATH_PALETTE, &SvtDefaultOptions_Impl::m_aPalettePath }, + { SvtPathOptions::PATH_PLUGIN, &SvtDefaultOptions_Impl::m_aPluginPath }, + { SvtPathOptions::PATH_TEMP, &SvtDefaultOptions_Impl::m_aTempPath }, + { SvtPathOptions::PATH_TEMPLATE, &SvtDefaultOptions_Impl::m_aTemplatePath }, + { SvtPathOptions::PATH_USERCONFIG, &SvtDefaultOptions_Impl::m_aUserConfigPath }, + { SvtPathOptions::PATH_WORK, &SvtDefaultOptions_Impl::m_aWorkPath } +}; + +// functions ------------------------------------------------------------- + +Sequence< OUString > GetDefaultPropertyNames() +{ + static const char* aPropNames[] = + { + "Addin", // PATH_ADDIN + "AutoCorrect", // PATH_AUTOCORRECT + "AutoText", // PATH_AUTOTEXT + "Backup", // PATH_BACKUP + "Basic", // PATH_BASIC + "Bitmap", // PATH_BITMAP + "Config", // PATH_CONFIG + "Dictionary", // PATH_DICTIONARY + "Favorite", // PATH_FAVORITES + "Filter", // PATH_FILTER + "Gallery", // PATH_GALLERY + "Graphic", // PATH_GRAPHIC + "Help", // PATH_HELP + "Linguistic", // PATH_LINGUISTIC + "Module", // PATH_MODULE + "Palette", // PATH_PALETTE + "Plugin", // PATH_PLUGIN + "Temp", // PATH_TEMP + "Template", // PATH_TEMPLATE + "UserConfig", // PATH_USERCONFIG + "Work" // PATH_WORK + }; + + const int nCount = sizeof( aPropNames ) / sizeof( const char* ); + Sequence< OUString > aNames( nCount ); + OUString* pNames = aNames.getArray(); + for ( int i = 0; i < nCount; i++ ) + pNames[i] = OUString::createFromAscii( aPropNames[i] ); + + return aNames; +} + +void SvtDefaultOptions_Impl::Notify( const Sequence< rtl::OUString >& ) +{ + // no notification, will never be changed +} + +void SvtDefaultOptions_Impl::Commit() +{ + // will never be changed +} + +// class SvtDefaultOptions_Impl ------------------------------------------ + +String SvtDefaultOptions_Impl::GetDefaultPath( USHORT nId ) const +{ + String aRet; + USHORT nIdx = 0; + + while ( PathMap_Impl[nIdx]._ePath <= SvtPathOptions::PATH_WORK ) + { + if ( nId == PathMap_Impl[nIdx]._ePath && PathMap_Impl[nIdx]._pDefaultPath ) + { + aRet = this->*(PathMap_Impl[nIdx]._pDefaultPath); + if ( nId == SvtPathOptions::PATH_ADDIN || + nId == SvtPathOptions::PATH_FILTER || + nId == SvtPathOptions::PATH_HELP || + nId == SvtPathOptions::PATH_MODULE || + nId == SvtPathOptions::PATH_PLUGIN ) + { + String aTmp; + ::utl::LocalFileHelper::ConvertPhysicalNameToURL( aRet, aTmp ); + aRet = aTmp; + } + + break; + } + ++nIdx; + } + + return aRet; +} + +// ----------------------------------------------------------------------- + +SvtDefaultOptions_Impl::SvtDefaultOptions_Impl() : ConfigItem( ASCII_STR("Office.Common/Path/Default") ) +{ + /*ConfigManager* pCfgMgr =*/ ConfigManager::GetConfigManager(); + Sequence< OUString > aNames = GetDefaultPropertyNames(); + Sequence< Any > aValues = GetProperties( aNames ); + EnableNotification( aNames ); + const Any* pValues = aValues.getConstArray(); + DBG_ASSERT( aValues.getLength() == aNames.getLength(), "GetProperties failed" ); + if ( aValues.getLength() == aNames.getLength() ) + { + SvtPathOptions aPathOpt; + OUString aTempStr, aFullPath; + + for ( int nProp = 0; nProp < aNames.getLength(); nProp++ ) + { + if ( pValues[nProp].hasValue() ) + { + switch ( pValues[nProp].getValueTypeClass() ) + { + case ::com::sun::star::uno::TypeClass_STRING : + { + // multi pathes + if ( pValues[nProp] >>= aTempStr ) + aFullPath = aPathOpt.SubstituteVariable( aTempStr ); + else + { + DBG_ERRORFILE( "any operator >>= failed" ); + } + break; + } + + case ::com::sun::star::uno::TypeClass_SEQUENCE : + { + // single pathes + aFullPath = OUString(); + Sequence < OUString > aList; + if ( pValues[nProp] >>= aList ) + { + sal_Int32 nCount = aList.getLength(); + for ( sal_Int32 nPosition = 0; nPosition < nCount; ++nPosition ) + { + aTempStr = aPathOpt.SubstituteVariable( aList[ nPosition ] ); + aFullPath += aTempStr; + if ( nPosition < nCount-1 ) + aFullPath += OUString( RTL_CONSTASCII_USTRINGPARAM(";") ); + } + } + else + { + DBG_ERRORFILE( "any operator >>= failed" ); + } + break; + } + + default: + { + DBG_ERRORFILE( "Wrong any type" ); + } + } + + switch ( nProp ) + { + case DEFAULTPATH__ADDIN: m_aAddinPath = String( aFullPath ); break; + case DEFAULTPATH__AUTOCORRECT: m_aAutoCorrectPath = String( aFullPath ); break; + case DEFAULTPATH__AUTOTEXT: m_aAutoTextPath = String( aFullPath ); break; + case DEFAULTPATH__BACKUP: m_aBackupPath = String( aFullPath ); break; + case DEFAULTPATH__BASIC: m_aBasicPath = String( aFullPath ); break; + case DEFAULTPATH__BITMAP: m_aBitmapPath = String( aFullPath ); break; + case DEFAULTPATH__CONFIG: m_aConfigPath = String( aFullPath ); break; + case DEFAULTPATH__DICTIONARY: m_aDictionaryPath = String( aFullPath ); break; + case DEFAULTPATH__FAVORITES: m_aFavoritesPath = String( aFullPath ); break; + case DEFAULTPATH__FILTER: m_aFilterPath = String( aFullPath ); break; + case DEFAULTPATH__GALLERY: m_aGalleryPath = String( aFullPath ); break; + case DEFAULTPATH__GRAPHIC: m_aGraphicPath = String( aFullPath ); break; + case DEFAULTPATH__HELP: m_aHelpPath = String( aFullPath ); break; + case DEFAULTPATH__LINGUISTIC: m_aLinguisticPath = String( aFullPath ); break; + case DEFAULTPATH__MODULE: m_aModulePath = String( aFullPath ); break; + case DEFAULTPATH__PALETTE: m_aPalettePath = String( aFullPath ); break; + case DEFAULTPATH__PLUGIN: m_aPluginPath = String( aFullPath ); break; + case DEFAULTPATH__TEMP: m_aTempPath = String( aFullPath ); break; + case DEFAULTPATH__TEMPLATE: m_aTemplatePath = String( aFullPath ); break; + case DEFAULTPATH__USERCONFIG: m_aUserConfigPath = String( aFullPath ); break; + case DEFAULTPATH__WORK: m_aWorkPath = String( aFullPath ); break; + case DEFAULTPATH__USERDICTIONARY: m_aUserDictionaryPath = String( aFullPath );break; + + default: + DBG_ERRORFILE( "invalid index to load a default path" ); + } + } + } + } +} + +// class SvtDefaultOptions ----------------------------------------------- +namespace { struct lclMutex : public rtl::Static< ::osl::Mutex, lclMutex > {}; } + +SvtDefaultOptions::SvtDefaultOptions() +{ + // Global access, must be guarded (multithreading) + ::osl::MutexGuard aGuard( lclMutex::get() ); + if ( !pOptions ) + { + pOptions = new SvtDefaultOptions_Impl; + ItemHolder1::holdConfigItem(E_DEFAULTOPTIONS); + } + ++nRefCount; + pImp = pOptions; +} + +// ----------------------------------------------------------------------- + +SvtDefaultOptions::~SvtDefaultOptions() +{ + // Global access, must be guarded (multithreading) + ::osl::MutexGuard aGuard( lclMutex::get() ); + if ( !--nRefCount ) + { + if ( pOptions->IsModified() ) + pOptions->Commit(); + DELETEZ( pOptions ); + } +} + +// ----------------------------------------------------------------------- + +String SvtDefaultOptions::GetDefaultPath( USHORT nId ) const +{ + return pImp->GetDefaultPath( nId ); +} + +/* 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 000000000000..beb381c51d37 --- /dev/null +++ b/unotools/source/config/docinfohelper.cxx @@ -0,0 +1,115 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" + +#include <rtl/ustrbuf.hxx> +#include <tools/inetdef.hxx> +#include <unotools/configmgr.hxx> +#include <unotools/bootstrap.hxx> +#include <unotools/docinfohelper.hxx> + +using namespace ::com::sun::star; + +namespace utl +{ + +::rtl::OUString DocInfoHelper::GetGeneratorString() +{ + rtl::OUStringBuffer aResult; + + // First product: branded name + version + // version is <product_versions>_<product_extension>$<platform> + utl::ConfigManager& rMgr = utl::ConfigManager::GetConfigManager(); + // plain product name + rtl::OUString aValue; + uno::Any aAny = rMgr.GetDirectConfigProperty( + utl::ConfigManager::PRODUCTNAME); + if ( (aAny >>= aValue) && aValue.getLength() ) + { + aResult.append( aValue.replace( ' ', '_' ) ); + aResult.append( (sal_Unicode)'/' ); + + aAny = rMgr.GetDirectConfigProperty( + utl::ConfigManager::PRODUCTVERSION); + if ( (aAny >>= aValue) && aValue.getLength() ) + { + aResult.append( aValue.replace( ' ', '_' ) ); + + aAny = rMgr.GetDirectConfigProperty( + utl::ConfigManager::PRODUCTEXTENSION); + if ( (aAny >>= aValue) && aValue.getLength() ) + { + aResult.append( (sal_Unicode)'_' ); + aResult.append( aValue.replace( ' ', '_' ) ); + } + } + + aResult.append( (sal_Unicode)'$' ); + aResult.append( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( + TOOLS_INETDEF_OS )).replace( ' ', '_' ) ); + + aResult.append( (sal_Unicode)' ' ); + } + + // second product: LibreOffice_project/<build_information> + // build_information has '(' and '[' encoded as '$', ')' and ']' ignored + // and ':' replaced by '-' + { + aResult.appendAscii( "LibreOffice_project/" ); + ::rtl::OUString aDefault; + ::rtl::OUString aBuildId( Bootstrap::getBuildIdData( aDefault ) ); + for( sal_Int32 i=0; i < aBuildId.getLength(); i++ ) + { + sal_Unicode c = aBuildId[i]; + switch( c ) + { + case '(': + case '[': + aResult.append( (sal_Unicode)'$' ); + break; + case ')': + case ']': + break; + case ':': + aResult.append( (sal_Unicode)'-' ); + break; + default: + aResult.append( c ); + break; + } + } + } + + return aResult.makeStringAndClear(); +} + +} // 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 000000000000..87f535f72399 --- /dev/null +++ b/unotools/source/config/dynamicmenuoptions.cxx @@ -0,0 +1,915 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" + +#include <unotools/dynamicmenuoptions.hxx> +#include <unotools/moduleoptions.hxx> +#include <unotools/configmgr.hxx> +#include <unotools/configitem.hxx> +#include <tools/debug.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> + +#include <vector> + +#include <itemholder1.hxx> + +#include <algorithm> + +//_________________________________________________________________________________________________________________ +// namespaces +//_________________________________________________________________________________________________________________ + +using namespace ::std ; +using namespace ::utl ; +using namespace ::rtl ; +using namespace ::osl ; +using namespace ::com::sun::star::uno ; +using namespace ::com::sun::star::beans ; + +//_________________________________________________________________________________________________________________ +// const +//_________________________________________________________________________________________________________________ + +#define ROOTNODE_MENUS OUString(RTL_CONSTASCII_USTRINGPARAM("Office.Common/Menus/" )) +#define PATHDELIMITER OUString(RTL_CONSTASCII_USTRINGPARAM("/" )) + +#define SETNODE_NEWMENU OUString(RTL_CONSTASCII_USTRINGPARAM("New" )) +#define SETNODE_WIZARDMENU OUString(RTL_CONSTASCII_USTRINGPARAM("Wizard" )) +#define SETNODE_HELPBOOKMARKS OUString(RTL_CONSTASCII_USTRINGPARAM("HelpBookmarks" )) + +#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 + +#define OFFSET_URL 0 +#define OFFSET_TITLE 1 +#define OFFSET_IMAGEIDENTIFIER 2 +#define OFFSET_TARGETNAME 3 + +#define PATHPREFIX_SETUP OUString(RTL_CONSTASCII_USTRINGPARAM("m" )) +#define PATHPREFIX_USER OUString(RTL_CONSTASCII_USTRINGPARAM("u" )) + +//_________________________________________________________________________________________________________________ +// private declarations! +//_________________________________________________________________________________________________________________ + +/*-**************************************************************************************************************** + @descr struct to hold information about one menu entry. +****************************************************************************************************************-*/ +struct SvtDynMenuEntry +{ + public: + SvtDynMenuEntry() {}; + + SvtDynMenuEntry( const OUString& sNewURL , + const OUString& sNewTitle , + const OUString& sNewImageIdentifier , + const OUString& sNewTargetName ) + { + sURL = sNewURL ; + sTitle = sNewTitle ; + sImageIdentifier = sNewImageIdentifier ; + sTargetName = sNewTargetName ; + } + + public: + OUString sName ; + OUString sURL ; + OUString sTitle ; + OUString sImageIdentifier ; + OUString sTargetName ; +}; + +/*-**************************************************************************************************************** + @descr support simple menu structures and operations on it +****************************************************************************************************************-*/ +class SvtDynMenu +{ + public: + //--------------------------------------------------------------------------------------------------------- + // append setup written menu entry + // Don't touch name of entry. It was defined by setup and must be the same everytime! + // Look for double menu entries here too ... may be some seperator items are supeflous ... + void AppendSetupEntry( const SvtDynMenuEntry& rEntry ) + { + if( + ( lSetupEntries.size() < 1 ) || + ( lSetupEntries.rbegin()->sURL != rEntry.sURL ) + ) + { + lSetupEntries.push_back( rEntry ); + } + } + + //--------------------------------------------------------------------------------------------------------- + // append user specific menu entry + // We must find unique name for it by using special prefix + // and next count of user setted entries! + // Look for double menu entries here too ... may be some seperator items are supeflous ... + void AppendUserEntry( SvtDynMenuEntry& rEntry ) + { + if( + ( lUserEntries.size() < 1 ) || + ( lUserEntries.rbegin()->sURL != rEntry.sURL ) + ) + { + rEntry.sName = PATHPREFIX_USER; + rEntry.sName += OUString::valueOf( (sal_Int32)impl_getNextUserEntryNr() ); + lUserEntries.push_back( rEntry ); + } + } + + //--------------------------------------------------------------------------------------------------------- + // the only way to free memory! + void Clear() + { + lSetupEntries.clear(); + lUserEntries.clear(); + } + + //--------------------------------------------------------------------------------------------------------- + // convert internal list to external format + // for using it on right menus realy + // Notice: We build a property list with 4 entries and set it on result list then. + // The while-loop starts with pointer on internal member list lSetupEntries, change to + // lUserEntries then and stop after that with NULL! + // Separator entries will be packed in another way then normal entries! We define + // special strings "sEmpty" and "sSeperator" to perform too ... + Sequence< Sequence< PropertyValue > > GetList() const + { + sal_Int32 nSetupCount = (sal_Int32)lSetupEntries.size(); + sal_Int32 nUserCount = (sal_Int32)lUserEntries.size(); + sal_Int32 nStep = 0; + Sequence< PropertyValue > lProperties ( PROPERTYCOUNT ); + Sequence< Sequence< PropertyValue > > lResult ( nSetupCount+nUserCount ); + OUString sSeperator ( RTL_CONSTASCII_USTRINGPARAM("private:separator") ); + OUString sEmpty ; + const vector< SvtDynMenuEntry >* pList = &lSetupEntries; + + lProperties[OFFSET_URL ].Name = PROPERTYNAME_URL ; + lProperties[OFFSET_TITLE ].Name = PROPERTYNAME_TITLE ; + lProperties[OFFSET_IMAGEIDENTIFIER].Name = PROPERTYNAME_IMAGEIDENTIFIER ; + lProperties[OFFSET_TARGETNAME ].Name = PROPERTYNAME_TARGETNAME ; + + while( pList != NULL ) + { + for( vector< SvtDynMenuEntry >::const_iterator pItem =pList->begin(); + pItem!=pList->end() ; + ++pItem ) + { + if( pItem->sURL == sSeperator ) + { + lProperties[OFFSET_URL ].Value <<= sSeperator ; + lProperties[OFFSET_TITLE ].Value <<= sEmpty ; + lProperties[OFFSET_IMAGEIDENTIFIER ].Value <<= sEmpty ; + lProperties[OFFSET_TARGETNAME ].Value <<= sEmpty ; + } + else + { + lProperties[OFFSET_URL ].Value <<= pItem->sURL ; + lProperties[OFFSET_TITLE ].Value <<= pItem->sTitle ; + lProperties[OFFSET_IMAGEIDENTIFIER ].Value <<= pItem->sImageIdentifier; + lProperties[OFFSET_TARGETNAME ].Value <<= pItem->sTargetName ; + } + lResult[nStep] = lProperties; + ++nStep; + } + if( pList == &lSetupEntries ) + pList = &lUserEntries; + else + pList = NULL; + } + return lResult; + } + + private: + //--------------------------------------------------------------------------------------------------------- + // search for an entry named "ux" with x=[0..i] inside our menu + // which has set highest number x. So we can add another user entry. + sal_Int32 impl_getNextUserEntryNr() const + { + sal_Int32 nNr = 0; + for( vector< SvtDynMenuEntry >::const_iterator pItem =lUserEntries.begin(); + pItem!=lUserEntries.end() ; + ++pItem ) + { + if( pItem->sName.compareTo( PATHPREFIX_USER, 1 ) == 0 ) + { + OUString sNr = pItem->sName.copy( 1, pItem->sName.getLength()-1 ); + sal_Int32 nCheckNr = sNr.toInt32(); + if( nCheckNr > nNr ) + nNr = nCheckNr; + } + } + // Attention: Code isn't prepared for recyling of unused fragmented numbers! + // If we reach end of sal_Int32 range ... we must stop further working ... + // But I think nobody expand a menu to more then 1000 ... 100000 ... entries ... or? + DBG_ASSERT( !(nNr>0x7fffffff), "Menu::impl_getNextUserEntryNr()\nUser count can be out of range next time ...\n" ); + return nNr; + } + + private: + vector< SvtDynMenuEntry > lSetupEntries; + vector< SvtDynMenuEntry > lUserEntries ; +}; + +class SvtDynamicMenuOptions_Impl : public ConfigItem +{ + //------------------------------------------------------------------------------------------------------------- + // public methods + //------------------------------------------------------------------------------------------------------------- + + public: + + //--------------------------------------------------------------------------------------------------------- + // constructor / destructor + //--------------------------------------------------------------------------------------------------------- + + SvtDynamicMenuOptions_Impl(); + ~SvtDynamicMenuOptions_Impl(); + + //--------------------------------------------------------------------------------------------------------- + // overloaded methods of baseclass + //--------------------------------------------------------------------------------------------------------- + + /*-****************************************************************************************************//** + @short called for notify of configmanager + @descr These method is called from the ConfigManager before 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. + @return - + + @onerror - + *//*-*****************************************************************************************************/ + + virtual void Notify( const Sequence< OUString >& lPropertyNames ); + + /*-****************************************************************************************************//** + @short write changes to configuration + @descr These method writes the changed values into the sub tree + and should always called in our destructor to guarantee consistency of config data. + + @seealso baseclass ConfigItem + + @param - + @return - + + @onerror - + *//*-*****************************************************************************************************/ + + virtual void Commit(); + + //--------------------------------------------------------------------------------------------------------- + // public interface + //--------------------------------------------------------------------------------------------------------- + + /*-****************************************************************************************************//** + @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! + + @seealso - + + @param - + @return - + + @onerror - + *//*-*****************************************************************************************************/ + + void Clear ( EDynamicMenuType eMenu ); + Sequence< Sequence< PropertyValue > > GetMenu ( EDynamicMenuType eMenu ) const ; + void AppendItem ( EDynamicMenuType eMenu , + const OUString& sURL , + const OUString& sTitle , + const OUString& sImageIdentifier, + const OUString& sTargetName ); + + //------------------------------------------------------------------------------------------------------------- + // private methods + //------------------------------------------------------------------------------------------------------------- + + private: + + /*-****************************************************************************************************//** + @short return list of key names of our configuration management which represent oue 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! + + @seealso - + + @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. + + @onerror - + *//*-*****************************************************************************************************/ + + Sequence< OUString > impl_GetPropertyNames( sal_uInt32& nNewCount, sal_uInt32& nWizardCount, sal_uInt32& nHelpBookmarksCount ); + + /*-****************************************************************************************************//** + @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. + + @onerror - + *//*-*****************************************************************************************************/ + + void impl_SortAndExpandPropertyNames( const Sequence< OUString >& lSource , + Sequence< OUString >& lDestination , + const OUString& sSetNode ); + + //------------------------------------------------------------------------------------------------------------- + // private member + //------------------------------------------------------------------------------------------------------------- + + private: + + SvtDynMenu m_aNewMenu ; + SvtDynMenu m_aWizardMenu ; + SvtDynMenu m_aHelpBookmarksMenu ; +}; + +//_________________________________________________________________________________________________________________ +// definitions +//_________________________________________________________________________________________________________________ + +//***************************************************************************************************************** +// constructor +//***************************************************************************************************************** +SvtDynamicMenuOptions_Impl::SvtDynamicMenuOptions_Impl() + // Init baseclasses first + : ConfigItem( ROOTNODE_MENUS ) + // Init member then... +{ + // Get names and values of all accessable menu entries and fill internal structures. + // See impl_GetPropertyNames() for further informations. + sal_uInt32 nNewCount = 0; + sal_uInt32 nWizardCount = 0; + sal_uInt32 nHelpBookmarksCount = 0; + Sequence< OUString > lNames = impl_GetPropertyNames ( nNewCount , + nWizardCount , + nHelpBookmarksCount ); + 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()), "SvtDynamicMenuOptions_Impl::SvtDynamicMenuOptions_Impl()\nI miss some values of configuration keys!\n" ); + + // Copy values from list in right order to ouer 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 "Neues Writer Dokument" + // /New/1/ImageIdentifier "icon_writer" + // /New/1/TargetName "_blank" + // + // /New/2/URL "private:factory/scalc" + // /New/2/Title "Neues Calc Dokument" + // /New/2/ImageIdentifier "icon_calc" + // /New/2/TargetName "_blank" + // + // second "Wizard" menu ... + // /Wizard/1/URL "file://b" + // /Wizard/1/Title "MalWas" + // /Wizard/1/ImageIdentifier "icon_?" + // /Wizard/1/TargetName "_self" + // + // ... and so on ... + + sal_uInt32 nItem = 0 ; + sal_uInt32 nPosition = 0 ; + OUString sName ; + + // We must use these one instance object(!) to get information about installed modules. + // These information are used to filter menu entries wich need not installed modules ... + // Such entries shouldnt be available then! + // see impl_IsEntrySupported() too + SvtModuleOptions aModuleOptions; + + // 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; + m_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; + m_aWizardMenu.AppendSetupEntry( aItem ); + } + + // Attention: Don't reset nPosition here! + + // Get names/values for wizard menu. + // 4 subkeys for every item! + for( nItem=0; nItem<nHelpBookmarksCount; ++nItem ) + { + SvtDynMenuEntry aItem ; + lValues[nPosition] >>= aItem.sURL ; + ++nPosition; + lValues[nPosition] >>= aItem.sTitle ; + ++nPosition; + lValues[nPosition] >>= aItem.sImageIdentifier ; + ++nPosition; + lValues[nPosition] >>= aItem.sTargetName ; + ++nPosition; + m_aHelpBookmarksMenu.AppendSetupEntry( aItem ); + } + +/*TODO: Not used in the moment! see Notify() ... + // Enable notification mechanism of ouer baseclass. + // We need it to get information about changes outside these class on ouer used configuration keys! + EnableNotification( lNames ); +*/ +} + +//***************************************************************************************************************** +// destructor +//***************************************************************************************************************** +SvtDynamicMenuOptions_Impl::~SvtDynamicMenuOptions_Impl() +{ + // We must save our current values .. if user forget it! + if( IsModified() == sal_True ) + { + Commit(); + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtDynamicMenuOptions_Impl::Notify( const Sequence< OUString >& ) +{ + DBG_ASSERT( sal_False, "SvtDynamicMenuOptions_Impl::Notify()\nNot implemented yet! I don't know how I can handle a dynamical list of unknown properties ...\n" ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtDynamicMenuOptions_Impl::Commit() +{ + DBG_ERROR( "SvtDynamicMenuOptions_Impl::Commit()\nNot implemented yet!\n" ); + /* + // Write all properties! + // Delete complete sets first. + ClearNodeSet( SETNODE_NEWMENU ); + ClearNodeSet( SETNODE_WIZARDMENU ); + ClearNodeSet( SETNODE_HELPBOOKMARKS ); + + MenuEntry aItem ; + OUString sNode ; + Sequence< PropertyValue > lPropertyValues( PROPERTYCOUNT ); + sal_uInt32 nItem = 0 ; + + // Copy "new" menu entries to save-list! + sal_uInt32 nNewCount = m_aNewMenu.size(); + for( nItem=0; nItem<nNewCount; ++nItem ) + { + aItem = m_aNewMenu[nItem]; + // Format: "New/1/URL" + // "New/1/Title" + // ... + sNode = SETNODE_NEWMENU + PATHDELIMITER + PATHPREFIX + OUString::valueOf( (sal_Int32)nItem ) + PATHDELIMITER; + + lPropertyValues[OFFSET_URL ].Name = sNode + PROPERTYNAME_URL ; + lPropertyValues[OFFSET_TITLE ].Name = sNode + PROPERTYNAME_TITLE ; + lPropertyValues[OFFSET_IMAGEIDENTIFIER ].Name = sNode + PROPERTYNAME_IMAGEIDENTIFIER ; + lPropertyValues[OFFSET_TARGETNAME ].Name = sNode + PROPERTYNAME_TARGETNAME ; + + lPropertyValues[OFFSET_URL ].Value <<= aItem.sURL ; + lPropertyValues[OFFSET_TITLE ].Value <<= aItem.sTitle ; + lPropertyValues[OFFSET_IMAGEIDENTIFIER ].Value <<= aItem.sImageIdentifier ; + lPropertyValues[OFFSET_TARGETNAME ].Value <<= aItem.sTargetName ; + + SetSetProperties( SETNODE_NEWMENU, lPropertyValues ); + } + + // Copy "wizard" menu entries to save-list! + sal_uInt32 nWizardCount = m_aWizardMenu.size(); + for( nItem=0; nItem<nWizardCount; ++nItem ) + { + aItem = m_aWizardMenu[nItem]; + // Format: "Wizard/1/URL" + // "Wizard/1/Title" + // ... + sNode = SETNODE_WIZARDMENU + PATHDELIMITER + PATHPREFIX + OUString::valueOf( (sal_Int32)nItem ) + PATHDELIMITER; + + lPropertyValues[OFFSET_URL ].Name = sNode + PROPERTYNAME_URL ; + lPropertyValues[OFFSET_TITLE ].Name = sNode + PROPERTYNAME_TITLE ; + lPropertyValues[OFFSET_IMAGEIDENTIFIER ].Name = sNode + PROPERTYNAME_IMAGEIDENTIFIER ; + lPropertyValues[OFFSET_TARGETNAME ].Name = sNode + PROPERTYNAME_TARGETNAME ; + + lPropertyValues[OFFSET_URL ].Value <<= aItem.sURL ; + lPropertyValues[OFFSET_TITLE ].Value <<= aItem.sTitle ; + lPropertyValues[OFFSET_IMAGEIDENTIFIER ].Value <<= aItem.sImageIdentifier ; + lPropertyValues[OFFSET_TARGETNAME ].Value <<= aItem.sTargetName ; + + SetSetProperties( SETNODE_WIZARDMENU, lPropertyValues ); + } + + // Copy help bookmarks entries to save-list! + sal_uInt32 nHelpBookmarksCount = m_aHelpBookmarksMenu.size(); + for( nItem=0; nItem<nHelpBookmarksCount; ++nItem ) + { + aItem = m_aHelpBookmarksMenu[nItem]; + // Format: "HelpBookmarks/1/URL" + // "HelpBookmarks/1/Title" + // ... + sNode = SETNODE_HELPBOOKMARKS + PATHDELIMITER + PATHPREFIX + OUString::valueOf( (sal_Int32)nItem ) + PATHDELIMITER; + + lPropertyValues[OFFSET_URL ].Name = sNode + PROPERTYNAME_URL ; + lPropertyValues[OFFSET_TITLE ].Name = sNode + PROPERTYNAME_TITLE ; + lPropertyValues[OFFSET_IMAGEIDENTIFIER ].Name = sNode + PROPERTYNAME_IMAGEIDENTIFIER ; + lPropertyValues[OFFSET_TARGETNAME ].Name = sNode + PROPERTYNAME_TARGETNAME ; + + lPropertyValues[OFFSET_URL ].Value <<= aItem.sURL ; + lPropertyValues[OFFSET_TITLE ].Value <<= aItem.sTitle ; + lPropertyValues[OFFSET_IMAGEIDENTIFIER ].Value <<= aItem.sImageIdentifier ; + lPropertyValues[OFFSET_TARGETNAME ].Value <<= aItem.sTargetName ; + + SetSetProperties( SETNODE_HELPBOOKMARKS, lPropertyValues ); + } + */ +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtDynamicMenuOptions_Impl::Clear( EDynamicMenuType eMenu ) +{ + switch( eMenu ) + { + case E_NEWMENU : { + m_aNewMenu.Clear(); + SetModified(); + } + break; + + case E_WIZARDMENU : { + m_aWizardMenu.Clear(); + SetModified(); + } + break; + + case E_HELPBOOKMARKS : { + m_aHelpBookmarksMenu.Clear(); + SetModified(); + } + break; + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +Sequence< Sequence< PropertyValue > > SvtDynamicMenuOptions_Impl::GetMenu( EDynamicMenuType eMenu ) const +{ + Sequence< Sequence< PropertyValue > > lReturn; + switch( eMenu ) + { + case E_NEWMENU : { + lReturn = m_aNewMenu.GetList(); + } + break; + + case E_WIZARDMENU : { + lReturn = m_aWizardMenu.GetList(); + } + break; + + case E_HELPBOOKMARKS : { + lReturn = m_aHelpBookmarksMenu.GetList(); + } + break; + } + return lReturn; +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtDynamicMenuOptions_Impl::AppendItem( EDynamicMenuType eMenu , + const OUString& sURL , + const OUString& sTitle , + const OUString& sImageIdentifier, + const OUString& sTargetName ) +{ + SvtDynMenuEntry aItem( sURL, sTitle, sImageIdentifier, sTargetName ); + + switch( eMenu ) + { + case E_NEWMENU : { + m_aNewMenu.AppendUserEntry( aItem ); + SetModified(); + } + break; + + case E_WIZARDMENU : { + m_aWizardMenu.AppendUserEntry( aItem ); + SetModified(); + } + break; + + case E_HELPBOOKMARKS : { + m_aHelpBookmarksMenu.AppendUserEntry( aItem ); + SetModified(); + } + break; + } +} + +//***************************************************************************************************************** +// private method +//***************************************************************************************************************** +Sequence< OUString > SvtDynamicMenuOptions_Impl::impl_GetPropertyNames( sal_uInt32& nNewCount, sal_uInt32& nWizardCount, sal_uInt32& nHelpBookmarksCount ) +{ + // First get ALL names of current existing list items in configuration! + Sequence< OUString > lNewItems = GetNodeNames( SETNODE_NEWMENU ); + Sequence< OUString > lWizardItems = GetNodeNames( SETNODE_WIZARDMENU ); + Sequence< OUString > lHelpBookmarksItems = GetNodeNames( SETNODE_HELPBOOKMARKS ); + + // Get information about list counts ... + nNewCount = lNewItems.getLength (); + nWizardCount = lWizardItems.getLength (); + nHelpBookmarksCount = lHelpBookmarksItems.getLength(); + + // Sort and expand all three list to result list ... + Sequence< OUString > lProperties; + impl_SortAndExpandPropertyNames( lNewItems , lProperties, SETNODE_NEWMENU ); + impl_SortAndExpandPropertyNames( lWizardItems , lProperties, SETNODE_WIZARDMENU ); + impl_SortAndExpandPropertyNames( lHelpBookmarksItems, lProperties, SETNODE_HELPBOOKMARKS ); + + // Return result. + return lProperties; +} + +//***************************************************************************************************************** +// private helper +//***************************************************************************************************************** +class CountWithPrefixSort +{ + public: + int operator() ( const OUString& s1 , + const OUString& s2 ) const + { + // Get order numbers from entry name without prefix. + // e.g. "m10" => 10 + // "m5" => 5 + sal_Int32 n1 = s1.copy( 1, s1.getLength()-1 ).toInt32(); + sal_Int32 n2 = s2.copy( 1, s2.getLength()-1 ).toInt32(); + // MUST be in [0,1] ... because it's a difference between + // insert-positions of given entries in sorted list! + return( n1<n2 ); + } +}; + +class SelectByPrefix +{ + public: + bool operator() ( const OUString& s ) const + { + // Prefer setup written entries by check first letter of given string. It must be a "s". + return( s.indexOf( PATHPREFIX_SETUP ) == 0 ); + } +}; + +//***************************************************************************************************************** +// private method +//***************************************************************************************************************** +void SvtDynamicMenuOptions_Impl::impl_SortAndExpandPropertyNames( const Sequence< OUString >& lSource , + Sequence< OUString >& lDestination , + const OUString& sSetNode ) +{ + OUString sFixPath ; + 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 ... + + // Copy all items to temp. vector to use fast sort operations :-) + for( sal_Int32 nSourceStep=0; nSourceStep<nSourceCount; ++nSourceStep ) + lTemp.push_back( lSource[nSourceStep] ); + + // Sort all entries by number ... + stable_sort( lTemp.begin(), lTemp.end(), CountWithPrefixSort() ); + // and split into setup & user written entries! + stable_partition( lTemp.begin(), lTemp.end(), SelectByPrefix() ); + + // Copy sorted entries to destination and expand every item with + // 4 supported sub properties. + for( vector< OUString >::const_iterator pItem =lTemp.begin() ; + pItem!=lTemp.end() ; + ++pItem ) + { + sFixPath = sSetNode ; + sFixPath += PATHDELIMITER ; + sFixPath += *pItem ; + sFixPath += PATHDELIMITER ; + + lDestination[nDestinationStep] = sFixPath ; + lDestination[nDestinationStep] += PROPERTYNAME_URL ; + ++nDestinationStep; + lDestination[nDestinationStep] = sFixPath ; + lDestination[nDestinationStep] += PROPERTYNAME_TITLE ; + ++nDestinationStep; + lDestination[nDestinationStep] = sFixPath ; + lDestination[nDestinationStep] += PROPERTYNAME_IMAGEIDENTIFIER ; + ++nDestinationStep; + lDestination[nDestinationStep] = sFixPath ; + lDestination[nDestinationStep] += PROPERTYNAME_TARGETNAME ; + ++nDestinationStep; + } +} + +//***************************************************************************************************************** +// initialize static member +// DON'T DO IT IN YOUR HEADER! +// see definition for further informations +//***************************************************************************************************************** +SvtDynamicMenuOptions_Impl* SvtDynamicMenuOptions::m_pDataContainer = NULL ; +sal_Int32 SvtDynamicMenuOptions::m_nRefCount = 0 ; + +//***************************************************************************************************************** +// constructor +//***************************************************************************************************************** +SvtDynamicMenuOptions::SvtDynamicMenuOptions() +{ + // Global access, must be guarded (multithreading!). + MutexGuard aGuard( GetOwnStaticMutex() ); + // Increase ouer refcount ... + ++m_nRefCount; + // ... and initialize ouer data container only if it not already exist! + if( m_pDataContainer == NULL ) + { + m_pDataContainer = new SvtDynamicMenuOptions_Impl; + ItemHolder1::holdConfigItem(E_DYNAMICMENUOPTIONS); + } +} + +//***************************************************************************************************************** +// destructor +//***************************************************************************************************************** +SvtDynamicMenuOptions::~SvtDynamicMenuOptions() +{ + // Global access, must be guarded (multithreading!) + MutexGuard aGuard( GetOwnStaticMutex() ); + // Decrease ouer refcount. + --m_nRefCount; + // If last instance was deleted ... + // we must destroy ouer static data container! + if( m_nRefCount <= 0 ) + { + delete m_pDataContainer; + m_pDataContainer = NULL; + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtDynamicMenuOptions::Clear( EDynamicMenuType eMenu ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->Clear( eMenu ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +Sequence< Sequence< PropertyValue > > SvtDynamicMenuOptions::GetMenu( EDynamicMenuType eMenu ) const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->GetMenu( eMenu ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtDynamicMenuOptions::AppendItem( EDynamicMenuType eMenu , + const OUString& sURL , + const OUString& sTitle , + const OUString& sImageIdentifier, + const OUString& sTargetName ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->AppendItem( eMenu, sURL, sTitle, sImageIdentifier, sTargetName ); +} + +//***************************************************************************************************************** +// private method +//***************************************************************************************************************** +Mutex& SvtDynamicMenuOptions::GetOwnStaticMutex() +{ + // Initialize static mutex only for one time! + static Mutex* pMutex = NULL; + // If these method first called (Mutex not already exist!) ... + if( pMutex == NULL ) + { + // ... we must create a new one. Protect follow code with the global mutex - + // It must be - we create a static variable! + MutexGuard aGuard( Mutex::getGlobalMutex() ); + // We must check our pointer again - because it can be that another instance of ouer class will be fastr then these! + if( pMutex == NULL ) + { + // Create the new mutex and set it for return on static variable. + static Mutex aMutex; + pMutex = &aMutex; + } + } + // Return new created or already existing mutex object. + return *pMutex; +} + +/* 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 000000000000..5008c70cdb92 --- /dev/null +++ b/unotools/source/config/eventcfg.cxx @@ -0,0 +1,455 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" + +#include <unotools/eventcfg.hxx> +#include <unotools/configmgr.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/beans/PropertyValue.hpp> +#include <cppuhelper/weakref.hxx> + +#include <hash_map> +#include <tools/urlobj.hxx> +#include <rtl/ustrbuf.hxx> + +#include <itemholder1.hxx> + +#include <algorithm> + +using namespace ::std ; +using namespace ::utl ; +using namespace ::rtl ; +using namespace ::osl ; +using namespace ::com::sun::star::uno ; +using namespace ::com::sun::star; + +#define ROOTNODE_EVENTS OUString(RTL_CONSTASCII_USTRINGPARAM("Office.Events/ApplicationEvents" )) +#define PATHDELIMITER OUString(RTL_CONSTASCII_USTRINGPARAM("/")) +#define SETNODE_BINDINGS OUString(RTL_CONSTASCII_USTRINGPARAM("Bindings" )) +#define PROPERTYNAME_BINDINGURL OUString(RTL_CONSTASCII_USTRINGPARAM("BindingURL")) + +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" +}; + +GlobalEventConfig_Impl::GlobalEventConfig_Impl() + : ConfigItem( ROOTNODE_EVENTS, CONFIG_MODE_IMMEDIATE_UPDATE ) +{ + // the supported event names + m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_STARTAPP] ) ); + m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_CLOSEAPP] ) ); + m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_DOCCREATED] ) ); + m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_CREATEDOC] ) ); + m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_LOADFINISHED] ) ); + m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_OPENDOC] ) ); + m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_PREPARECLOSEDOC] ) ); + m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_CLOSEDOC] ) ); + m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_SAVEDOC] ) ); + m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_SAVEDOCDONE] ) ); + m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_SAVEDOCFAILED] ) ); + m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_SAVEASDOC] ) ); + m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_SAVEASDOCDONE] ) ); + m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_SAVEASDOCFAILED] ) ); + m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_SAVETODOC] ) ); + m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_SAVETODOCDONE] ) ); + m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_SAVETODOCFAILED] ) ); + m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_ACTIVATEDOC] ) ); + m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_DEACTIVATEDOC] ) ); + m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_PRINTDOC] ) ); + m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_VIEWCREATED] ) ); + m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_PREPARECLOSEVIEW] ) ); + m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_CLOSEVIEW] ) ); + m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_MODIFYCHANGED] ) ); + m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_TITLECHANGED] ) ); + m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_VISAREACHANGED] ) ); + m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_MODECHANGED] ) ); + m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_STORAGECHANGED] ) ); + + 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( 1 ); + aNotifySeq[0] = OUString( RTL_CONSTASCII_USTRINGPARAM( "Events" )); + EnableNotification( aNotifySeq, sal_True ); +} + +//***************************************************************************************************************** +// destructor +//***************************************************************************************************************** +GlobalEventConfig_Impl::~GlobalEventConfig_Impl() +{ + // We must save our current values .. if user forget it! + if( IsModified() == sal_True ) + { + Commit(); + } +} + +::rtl::OUString GlobalEventConfig_Impl::GetEventName( sal_Int32 nIndex ) +{ + if ( nIndex < (sal_Int32) m_supportedEvents.size() ) + return m_supportedEvents[nIndex]; + else + return rtl::OUString(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void GlobalEventConfig_Impl::Notify( const Sequence< OUString >& ) +{ + MutexGuard aGuard( GlobalEventConfig::GetOwnStaticMutex() ); + + initBindingInfo(); + + // dont 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 (FrameVector::const_iterator pIt = m_lFrames.begin(); + pIt != m_lFrames.end() ; + ++pIt ) + { + ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame(pIt->get(), ::com::sun::star::uno::UNO_QUERY); + if (xFrame.is()) + xFrame->contextChanged(); + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void GlobalEventConfig_Impl::Commit() +{ + //DF need to check it this is correct?? + OSL_TRACE("In GlobalEventConfig_Impl::Commit"); + EventBindingHash::const_iterator it = m_eventBindingHash.begin(); + EventBindingHash::const_iterator it_end = m_eventBindingHash.end(); + // clear the existing nodes + ClearNodeSet( SETNODE_BINDINGS ); + Sequence< beans::PropertyValue > seqValues( 1 ); + OUString sNode; + static const OUString sPrefix(SETNODE_BINDINGS + PATHDELIMITER + OUString(RTL_CONSTASCII_USTRINGPARAM("BindingType['"))); + static const OUString sPostfix(OUString(RTL_CONSTASCII_USTRINGPARAM("']")) + PATHDELIMITER + PROPERTYNAME_BINDINGURL); + //step through the list of events + for(int i=0;it!=it_end;++it,++i) + { + //no point in writing out empty bindings! + if(it->second.getLength() == 0 ) + continue; + sNode = sPrefix + it->first + sPostfix; + OSL_TRACE("writing binding for: %s",::rtl::OUStringToOString(sNode , RTL_TEXTENCODING_ASCII_US ).pData->buffer); + seqValues[ 0 ].Name = sNode; + seqValues[ 0 ].Value <<= it->second; + //write the data to the registry + SetSetProperties(SETNODE_BINDINGS,seqValues); + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void GlobalEventConfig_Impl::EstablishFrameCallback(const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame) +{ + // check if frame already exists inside list + // ignore double registrations + // every frame must be notified one times only! + ::com::sun::star::uno::WeakReference< ::com::sun::star::frame::XFrame > xWeak(xFrame); + FrameVector::const_iterator pIt = ::std::find(m_lFrames.begin(), m_lFrames.end(), xWeak); + if (pIt == m_lFrames.end()) + m_lFrames.push_back(xWeak); +} + +//***************************************************************************************************************** +// private method +//***************************************************************************************************************** +void GlobalEventConfig_Impl::initBindingInfo() +{ + // Get ALL names of current existing list items in configuration! + Sequence< OUString > lEventNames = GetNodeNames( SETNODE_BINDINGS, utl::CONFIG_NAME_LOCAL_PATH ); + + OUString aSetNode( SETNODE_BINDINGS ); + aSetNode += PATHDELIMITER; + + OUString aCommandKey( PATHDELIMITER ); + aCommandKey += PROPERTYNAME_BINDINGURL; + + // Expand all keys + Sequence< OUString > lMacros(1); + for (sal_Int32 i=0; i<lEventNames.getLength(); ++i ) + { + OUStringBuffer aBuffer( 32 ); + aBuffer.append( aSetNode ); + aBuffer.append( lEventNames[i] ); + aBuffer.append( aCommandKey ); + lMacros[0] = aBuffer.makeStringAndClear(); + OSL_TRACE("reading binding for: %s",::rtl::OUStringToOString(lMacros[0] , RTL_TEXTENCODING_ASCII_US ).pData->buffer); + Sequence< Any > lValues = GetProperties( lMacros ); + OUString sMacroURL; + if( lValues.getLength() > 0 ) + { + lValues[0] >>= sMacroURL; + sal_Int32 startIndex = lEventNames[i].indexOf('\''); + sal_Int32 endIndex = lEventNames[i].lastIndexOf('\''); + if( startIndex >=0 && endIndex > 0 ) + { + startIndex++; + OUString eventName = lEventNames[i].copy(startIndex,endIndex-startIndex); + m_eventBindingHash[ eventName ] = sMacroURL; + } + } + } +} + +Reference< container::XNameReplace > SAL_CALL GlobalEventConfig_Impl::getEvents() throw (::com::sun::star::uno::RuntimeException) +{ + //how to return this object as an XNameReplace? + Reference< container::XNameReplace > ret; + return ret; +} + +void SAL_CALL GlobalEventConfig_Impl::replaceByName( const OUString& aName, const Any& aElement ) throw (lang::IllegalArgumentException, container::NoSuchElementException, lang::WrappedTargetException, RuntimeException) +{ + Sequence< beans::PropertyValue > props; + //DF should we prepopulate the hash with a list of valid event Names? + if( sal_False == ( aElement >>= props ) ) + { + throw lang::IllegalArgumentException( OUString(), + Reference< XInterface > (), 2); + } + OUString macroURL; + sal_Int32 nPropCount = props.getLength(); + for( sal_Int32 index = 0 ; index < nPropCount ; ++index ) + { + if ( props[ index ].Name.compareToAscii( "Script" ) == 0 ) + props[ index ].Value >>= macroURL; + } + m_eventBindingHash[ aName ] = macroURL; + SetModified(); +} + +Any SAL_CALL GlobalEventConfig_Impl::getByName( const OUString& aName ) throw (container::NoSuchElementException, lang::WrappedTargetException, RuntimeException) +{ + Any aRet; + Sequence< beans::PropertyValue > props(2); + props[0].Name = OUString(RTL_CONSTASCII_USTRINGPARAM("EventType")); + props[0].Value <<= OUString(RTL_CONSTASCII_USTRINGPARAM("Script")); + props[1].Name = OUString(RTL_CONSTASCII_USTRINGPARAM("Script")); + EventBindingHash::const_iterator it = m_eventBindingHash.find( aName ); + if( it != m_eventBindingHash.end() ) + { + props[1].Value <<= it->second; + } + else + { + // not yet accessed - is it a supported name? + SupportedEventsVector::const_iterator pos = ::std::find( + m_supportedEvents.begin(), m_supportedEvents.end(), aName ); + if ( pos == m_supportedEvents.end() ) + throw container::NoSuchElementException( aName, NULL ); + + props[1].Value <<= OUString(); + } + aRet <<= props; + return aRet; +} + +Sequence< OUString > SAL_CALL GlobalEventConfig_Impl::getElementNames( ) throw (RuntimeException) +{ + const ::rtl::OUString* pRet = m_supportedEvents.empty() ? NULL : &m_supportedEvents[0]; + return uno::Sequence< ::rtl::OUString >(pRet, m_supportedEvents.size()); +} + +sal_Bool SAL_CALL GlobalEventConfig_Impl::hasByName( const OUString& aName ) throw (RuntimeException) +{ + if ( m_eventBindingHash.find( aName ) != m_eventBindingHash.end() ) + return sal_True; + + // never accessed before - is it supported in general? + SupportedEventsVector::const_iterator pos = ::std::find( + m_supportedEvents.begin(), m_supportedEvents.end(), aName ); + if ( pos != m_supportedEvents.end() ) + return sal_True; + + return sal_False; +} + +Type SAL_CALL GlobalEventConfig_Impl::getElementType( ) throw (RuntimeException) +{ + //DF definitly not sure about this?? + return ::getCppuType((const Sequence<beans::PropertyValue>*)0); +} + +sal_Bool SAL_CALL GlobalEventConfig_Impl::hasElements( ) throw (RuntimeException) +{ + return ( m_eventBindingHash.empty() ); +} + +// and now the wrapper + + +//initialize static member +GlobalEventConfig_Impl* GlobalEventConfig::m_pImpl = NULL ; +sal_Int32 GlobalEventConfig::m_nRefCount = 0 ; + +GlobalEventConfig::GlobalEventConfig() +{ + // Global access, must be guarded (multithreading!). + MutexGuard aGuard( GetOwnStaticMutex() ); + // Increase our refcount ... + ++m_nRefCount; + // ... and initialize our data container only if it not already exist! + if( m_pImpl == NULL ) + { + m_pImpl = new GlobalEventConfig_Impl; + ItemHolder1::holdConfigItem(E_EVENTCFG); + } +} + +GlobalEventConfig::~GlobalEventConfig() +{ + // Global access, must be guarded (multithreading!) + MutexGuard 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 = NULL; + } +} + +void GlobalEventConfig::EstablishFrameCallback(const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pImpl->EstablishFrameCallback( xFrame ); +} + +Reference< container::XNameReplace > SAL_CALL GlobalEventConfig::getEvents() throw (::com::sun::star::uno::RuntimeException) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + Reference< container::XNameReplace > ret(this); + return ret; +} + +void SAL_CALL GlobalEventConfig::replaceByName( const OUString& aName, const Any& aElement ) throw (lang::IllegalArgumentException, container::NoSuchElementException, lang::WrappedTargetException, RuntimeException) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pImpl->replaceByName( aName, aElement ); +} +Any SAL_CALL GlobalEventConfig::getByName( const OUString& aName ) throw (container::NoSuchElementException, lang::WrappedTargetException, RuntimeException) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pImpl->getByName( aName ); +} +Sequence< OUString > SAL_CALL GlobalEventConfig::getElementNames( ) throw (RuntimeException) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pImpl->getElementNames( ); +} +sal_Bool SAL_CALL GlobalEventConfig::hasByName( const OUString& aName ) throw (RuntimeException) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pImpl->hasByName( aName ); +} +Type SAL_CALL GlobalEventConfig::getElementType( ) throw (RuntimeException) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pImpl->getElementType( ); +} +sal_Bool SAL_CALL GlobalEventConfig::hasElements( ) throw (RuntimeException) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pImpl->hasElements( ); +} + +Mutex& GlobalEventConfig::GetOwnStaticMutex() +{ + // Initialize static mutex only for one time! + static Mutex* pMutex = NULL; + // If these method first called (Mutex not already exist!) ... + if( pMutex == NULL ) + { + // ... we must create a new one. Protect following code with + // the global mutex - + // It must be - we create a static variable! + MutexGuard aGuard( Mutex::getGlobalMutex() ); + // We must check our pointer again - because it can be that + // another instance of our class will be faster then these! + if( pMutex == NULL ) + { + // Create the new mutex and set it for return on static variable. + static Mutex aMutex; + pMutex = &aMutex; + } + } + // Return new created or already existing mutex object. + return *pMutex; +} + +::rtl::OUString GlobalEventConfig::GetEventName( sal_Int32 nIndex ) +{ + return GlobalEventConfig().m_pImpl->GetEventName( nIndex ); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/extendedsecurityoptions.cxx b/unotools/source/config/extendedsecurityoptions.cxx new file mode 100644 index 000000000000..74ddfe622c0b --- /dev/null +++ b/unotools/source/config/extendedsecurityoptions.cxx @@ -0,0 +1,537 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" + +//_________________________________________________________________________________________________________________ +// includes +//_________________________________________________________________________________________________________________ + +#include <unotools/extendedsecurityoptions.hxx> +#include <unotools/configmgr.hxx> +#include <unotools/configitem.hxx> +#include <tools/debug.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> +#include <tools/urlobj.hxx> +#include <tools/wldcrd.hxx> +#include <rtl/ustrbuf.hxx> + +#include <unotools/pathoptions.hxx> + +#include <hash_map> + +#include <rtl/logfile.hxx> +#include "itemholder1.hxx" + +//_________________________________________________________________________________________________________________ +// namespaces +//_________________________________________________________________________________________________________________ + +using namespace ::utl ; +using namespace ::rtl ; +using namespace ::osl ; +using namespace ::com::sun::star::uno ; + +//_________________________________________________________________________________________________________________ +// const +//_________________________________________________________________________________________________________________ + +#define ROOTNODE_SECURITY OUString(RTL_CONSTASCII_USTRINGPARAM("Office.Security")) + +#define SECURE_EXTENSIONS_SET OUString(RTL_CONSTASCII_USTRINGPARAM("SecureExtensions")) +#define EXTENSION_PROPNAME OUString(RTL_CONSTASCII_USTRINGPARAM("/Extension")) + +#define PROPERTYNAME_HYPERLINKS_OPEN OUString(RTL_CONSTASCII_USTRINGPARAM("Hyperlinks/Open")) + +#define PROPERTYHANDLE_HYPERLINKS_OPEN 0 + +#define PROPERTYCOUNT 1 + +//_________________________________________________________________________________________________________________ +// private declarations! +//_________________________________________________________________________________________________________________ + +struct OUStringHashCode +{ + size_t operator()( const ::rtl::OUString& sString ) const + { + return sString.hashCode(); + } +}; + +class ExtensionHashMap : public ::std::hash_map< ::rtl::OUString, + sal_Int32, + OUStringHashCode, + ::std::equal_to< ::rtl::OUString > > +{ + public: + inline void free() + { + ExtensionHashMap().swap( *this ); + } +}; + +class SvtExtendedSecurityOptions_Impl : public ConfigItem +{ + //------------------------------------------------------------------------------------------------------------- + // public methods + //------------------------------------------------------------------------------------------------------------- + + public: + + //--------------------------------------------------------------------------------------------------------- + // constructor / destructor + //--------------------------------------------------------------------------------------------------------- + + SvtExtendedSecurityOptions_Impl(); + ~SvtExtendedSecurityOptions_Impl(); + + //--------------------------------------------------------------------------------------------------------- + // overloaded methods of baseclass + //--------------------------------------------------------------------------------------------------------- + + /*-****************************************************************************************************//** + @short called for notify of configmanager + @descr These method is called from the ConfigManager before application ends or from the + PropertyChangeListener if the sub tree broadcasts changes. You must update your + internal values. + + @seealso baseclass ConfigItem + + @param "seqPropertyNames" is the list of properties which should be updated. + @return - + + @onerror - + *//*-*****************************************************************************************************/ + + virtual void Notify( const Sequence< OUString >& seqPropertyNames ); + + /*-****************************************************************************************************//** + @short write changes to configuration + @descr These method writes the changed values into the sub tree + and should always called in our destructor to guarantee consistency of config data. + + @seealso baseclass ConfigItem + + @param - + @return - + + @onerror - + *//*-*****************************************************************************************************/ + + virtual void Commit(); + + //--------------------------------------------------------------------------------------------------------- + // public interface + //--------------------------------------------------------------------------------------------------------- + + /*-****************************************************************************************************//** + @short Access method to check for security problems + @descr Different methods to check for security related problems. + + @seealso - + + @param - + @return - + + @onerror - + *//*-*****************************************************************************************************/ + + sal_Bool IsSecureHyperlink( const rtl::OUString& aURL ) const; + Sequence< rtl::OUString > GetSecureExtensionList() const; + + SvtExtendedSecurityOptions::OpenHyperlinkMode GetOpenHyperlinkMode(); + void SetOpenHyperlinkMode( SvtExtendedSecurityOptions::OpenHyperlinkMode aMode ); + sal_Bool IsOpenHyperlinkModeReadOnly() const; + + //------------------------------------------------------------------------------------------------------------- + // private methods + //------------------------------------------------------------------------------------------------------------- + + private: + + /*-****************************************************************************************************//** + @short return list of key names of ouer configuration management which represent oue module tree + @descr These methods return a static const list of key names. We need it to get needed values from our + configuration management. + + @seealso - + + @param - + @return A list of needed configuration keys is returned. + + @onerror - + *//*-*****************************************************************************************************/ + + static Sequence< OUString > GetPropertyNames(); + + /*-****************************************************************************************************//** + @short Fills the hash map with all extensions known to be secure + @descr These methods fills the given hash map object with all extensions known to be secure. + + @seealso - + + @param aHashMap + A hash map to be filled with secure extension strings. + @return - + + @onerror - + *//*-*****************************************************************************************************/ + void FillExtensionHashMap( ExtensionHashMap& aHashMap ); + + //------------------------------------------------------------------------------------------------------------- + // private member + //------------------------------------------------------------------------------------------------------------- + + private: + OUString m_aSecureExtensionsSetName; + OUString m_aExtensionPropName; + + SvtExtendedSecurityOptions::OpenHyperlinkMode m_eOpenHyperlinkMode; + sal_Bool m_bROOpenHyperlinkMode; + ExtensionHashMap m_aExtensionHashMap; +}; + +//_________________________________________________________________________________________________________________ +// definitions +//_________________________________________________________________________________________________________________ + +//***************************************************************************************************************** +// constructor +//***************************************************************************************************************** +SvtExtendedSecurityOptions_Impl::SvtExtendedSecurityOptions_Impl() + // Init baseclasses first + : ConfigItem ( ROOTNODE_SECURITY ), + m_aSecureExtensionsSetName( SECURE_EXTENSIONS_SET ), + m_aExtensionPropName( EXTENSION_PROPNAME ), + m_bROOpenHyperlinkMode(sal_False) + // Init member then. +{ + // Fill the extension hash map with all secure extension strings + FillExtensionHashMap( m_aExtensionHashMap ); + + Sequence< OUString > seqNames = GetPropertyNames(); + Sequence< Any > seqValues = GetProperties( seqNames ); + Sequence< sal_Bool > seqRO = GetReadOnlyStates ( seqNames ); + + sal_Int32 nPropertyCount = seqValues.getLength(); + for( sal_Int32 nProperty=0; nProperty<nPropertyCount; ++nProperty ) + { + // Safe impossible cases. + // Check any for valid value. + DBG_ASSERT( !(seqValues[nProperty].hasValue()==sal_False), "SvtExtendedSecurityOptions_Impl::SvtExtendedSecurityOptions_Impl()\nInvalid property value detected!\n" ); + switch( nProperty ) + { + case PROPERTYHANDLE_HYPERLINKS_OPEN: + { + DBG_ASSERT( ( seqValues[nProperty].getValueTypeClass() == TypeClass_LONG ), "SvtExtendedSecurityOptions_Impl::SvtExtendedSecurityOptions_Impl()\nWho has changed the value type of 'Hyperlink/Open'?" ); + + sal_Int32 nMode = SvtExtendedSecurityOptions::OPEN_WITHSECURITYCHECK; + if ( seqValues[nProperty] >>= nMode ) + m_eOpenHyperlinkMode = (SvtExtendedSecurityOptions::OpenHyperlinkMode)nMode; + else { + DBG_ERROR("Wrong type for Open mode!"); + } + m_bROOpenHyperlinkMode = seqRO[nProperty]; + } + break; + } + } + + // Enable notification mechanism of our baseclass. + // We need it to get information about changes outside these class on ouer used configuration keys! + Sequence< OUString > seqNotifyNames( 1 ); + seqNotifyNames[0] = m_aSecureExtensionsSetName; + EnableNotification( seqNotifyNames ); +} + +//***************************************************************************************************************** +// destructor +//***************************************************************************************************************** +SvtExtendedSecurityOptions_Impl::~SvtExtendedSecurityOptions_Impl() +{ + // We must save our current values .. if user forget it! + if( IsModified() == sal_True ) + { + Commit(); + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtExtendedSecurityOptions_Impl::Notify( const Sequence< OUString >& ) +{ + // Not implemented +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtExtendedSecurityOptions_Impl::Commit() +{ + // Get names of supported properties, create a list for values and copy current values to it. + Sequence< OUString > seqNames = GetPropertyNames (); + sal_Int32 nCount = seqNames.getLength(); + Sequence< Any > seqValues ( nCount ); + for( sal_Int32 nProperty=0; nProperty<nCount; ++nProperty ) + { + switch( nProperty ) + { + case PROPERTYHANDLE_HYPERLINKS_OPEN: { + seqValues[nProperty] <<= (sal_Int32)m_eOpenHyperlinkMode; + } + break; + } + } + + // Set properties in configuration. + PutProperties( seqNames, seqValues ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Bool SvtExtendedSecurityOptions_Impl::IsSecureHyperlink( const OUString& aURL ) const +{ + INetURLObject aURLObject( aURL ); + + String aExtension = aURLObject.getExtension(); + aExtension.ToLowerAscii(); + + ExtensionHashMap::const_iterator pIter = m_aExtensionHashMap.find( aExtension ); + if ( pIter != m_aExtensionHashMap.end() ) + return sal_True; + else + return sal_False; +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +Sequence< OUString > SvtExtendedSecurityOptions_Impl::GetSecureExtensionList() const +{ + Sequence< OUString > aResult( m_aExtensionHashMap.size() ); + + sal_Int32 nIndex = 0; + for ( ExtensionHashMap::const_iterator pIter = m_aExtensionHashMap.begin(); + pIter != m_aExtensionHashMap.end(); pIter++ ) + { + aResult[nIndex++] = pIter->first; + } + + return aResult; +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +SvtExtendedSecurityOptions::OpenHyperlinkMode SvtExtendedSecurityOptions_Impl::GetOpenHyperlinkMode() +{ + return m_eOpenHyperlinkMode; +} + +sal_Bool SvtExtendedSecurityOptions_Impl::IsOpenHyperlinkModeReadOnly() const +{ + return m_bROOpenHyperlinkMode; +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtExtendedSecurityOptions_Impl::SetOpenHyperlinkMode( SvtExtendedSecurityOptions::OpenHyperlinkMode eNewMode ) +{ + m_eOpenHyperlinkMode = eNewMode; + SetModified(); +} + +//***************************************************************************************************************** +// private method +//***************************************************************************************************************** +void SvtExtendedSecurityOptions_Impl::FillExtensionHashMap( ExtensionHashMap& aHashMap ) +{ + // Get sequence with secure extensions from configuration + Sequence< OUString > seqNodes = GetNodeNames( m_aSecureExtensionsSetName ); + + OUString aValue; + Sequence< Any > aValues; + Sequence< OUString > aPropSeq( 1 ); + for ( int i = 0; i < seqNodes.getLength(); i++ ) + { + // Create access name for property + OUStringBuffer aExtEntryProp( m_aSecureExtensionsSetName ); + aExtEntryProp.appendAscii( "/" ); + aExtEntryProp.append( seqNodes[i] ); + aExtEntryProp.append( m_aExtensionPropName ); + + aPropSeq[0] = aExtEntryProp.makeStringAndClear(); + aValues = GetProperties( aPropSeq ); + if ( aValues.getLength() == 1 ) + { + // Don't use value if sequence has not the correct length + if ( aValues[0] >>= aValue ) + // Add extension into secure extensions hash map + aHashMap.insert( ExtensionHashMap::value_type( aValue.toAsciiLowerCase(), 1 ) ); + else + { + DBG_ERRORFILE( "SvtExtendedSecurityOptions_Impl::FillExtensionHashMap(): not string value?" ); + } + } + } +} + +//***************************************************************************************************************** +// private method (currently not used) +//***************************************************************************************************************** +Sequence< OUString > SvtExtendedSecurityOptions_Impl::GetPropertyNames() +{ + // Build static list of configuration key names. + static const OUString pProperties[] = + { + PROPERTYNAME_HYPERLINKS_OPEN + }; + // Initialize return sequence with these list ... + static const Sequence< OUString > seqPropertyNames( pProperties, PROPERTYCOUNT ); + // ... and return it. + return seqPropertyNames; +} + +//***************************************************************************************************************** +// initialize static member +// DON'T DO IT IN YOUR HEADER! +// see definition for further informations +//***************************************************************************************************************** +SvtExtendedSecurityOptions_Impl* SvtExtendedSecurityOptions::m_pDataContainer = NULL ; +sal_Int32 SvtExtendedSecurityOptions::m_nRefCount = 0 ; + +//***************************************************************************************************************** +// constructor +//***************************************************************************************************************** +SvtExtendedSecurityOptions::SvtExtendedSecurityOptions() +{ + // Global access, must be guarded (multithreading!). + MutexGuard aGuard( GetInitMutex() ); + // Increase ouer refcount ... + ++m_nRefCount; + // ... and initialize ouer data container only if it not already exist! + if( m_pDataContainer == NULL ) + { + RTL_LOGFILE_CONTEXT(aLog, "unotools ( ??? ) ::SvtExtendedSecurityOptions_Impl::ctor()"); + m_pDataContainer = new SvtExtendedSecurityOptions_Impl; + + ItemHolder1::holdConfigItem(E_EXTENDEDSECURITYOPTIONS); + } +} + +//***************************************************************************************************************** +// destructor +//***************************************************************************************************************** +SvtExtendedSecurityOptions::~SvtExtendedSecurityOptions() +{ + // Global access, must be guarded (multithreading!) + MutexGuard aGuard( GetInitMutex() ); + // Decrease ouer refcount. + --m_nRefCount; + // If last instance was deleted ... + // we must destroy ouer static data container! + if( m_nRefCount <= 0 ) + { + delete m_pDataContainer; + m_pDataContainer = NULL; + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Bool SvtExtendedSecurityOptions::IsSecureHyperlink( const rtl::OUString& aURL ) const +{ + MutexGuard aGuard( GetInitMutex() ); + return m_pDataContainer->IsSecureHyperlink( aURL ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +Sequence< rtl::OUString > SvtExtendedSecurityOptions::GetSecureExtensionList() const +{ + MutexGuard aGuard( GetInitMutex() ); + return m_pDataContainer->GetSecureExtensionList(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +SvtExtendedSecurityOptions::OpenHyperlinkMode SvtExtendedSecurityOptions::GetOpenHyperlinkMode() +{ + MutexGuard aGuard( GetInitMutex() ); + return m_pDataContainer->GetOpenHyperlinkMode(); +} + +sal_Bool SvtExtendedSecurityOptions::IsOpenHyperlinkModeReadOnly() const +{ + return m_pDataContainer->IsOpenHyperlinkModeReadOnly(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtExtendedSecurityOptions::SetOpenHyperlinkMode( SvtExtendedSecurityOptions::OpenHyperlinkMode eMode ) +{ + MutexGuard aGuard( GetInitMutex() ); + m_pDataContainer->SetOpenHyperlinkMode( eMode ); +} + +//***************************************************************************************************************** +// private method +//***************************************************************************************************************** +Mutex& SvtExtendedSecurityOptions::GetInitMutex() +{ + // Initialize static mutex only for one time! + static Mutex* pMutex = NULL; + // If these method first called (Mutex not already exist!) ... + if( pMutex == NULL ) + { + // ... we must create a new one. Protect follow code with the global mutex - + // It must be - we create a static variable! + MutexGuard aGuard( Mutex::getGlobalMutex() ); + // We must check our pointer again - because it can be that another instance of ouer class will be fastr then these! + if( pMutex == NULL ) + { + // Create the new mutex and set it for return on static variable. + static Mutex aMutex; + pMutex = &aMutex; + } + } + // Return new created or already existing mutex object. + return *pMutex; +} + +/* 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 000000000000..8e2f5ea2900f --- /dev/null +++ b/unotools/source/config/fltrcfg.cxx @@ -0,0 +1,650 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" + +#include <unotools/fltrcfg.hxx> +#include <tools/debug.hxx> + +#include <rtl/logfile.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> + +using namespace utl; +using namespace rtl; +using namespace com::sun::star::uno; + +#define C2U(cChar) OUString::createFromAscii(cChar) + +// ----------------------------------------------------------------------- +#define FILTERCFG_WORD_CODE 0x0001 +#define FILTERCFG_WORD_STORAGE 0x0002 +#define FILTERCFG_EXCEL_CODE 0x0004 +#define FILTERCFG_EXCEL_STORAGE 0x0008 +#define FILTERCFG_PPOINT_CODE 0x0010 +#define FILTERCFG_PPOINT_STORAGE 0x0020 +#define FILTERCFG_MATH_LOAD 0x0100 +#define FILTERCFG_MATH_SAVE 0x0200 +#define FILTERCFG_WRITER_LOAD 0x0400 +#define FILTERCFG_WRITER_SAVE 0x0800 +#define FILTERCFG_CALC_LOAD 0x1000 +#define FILTERCFG_CALC_SAVE 0x2000 +#define FILTERCFG_IMPRESS_LOAD 0x4000 +#define FILTERCFG_IMPRESS_SAVE 0x8000 +#define FILTERCFG_EXCEL_EXECTBL 0x10000 +#define FILTERCFG_ENABLE_PPT_PREVIEW 0x20000 +#define FILTERCFG_ENABLE_EXCEL_PREVIEW 0x40000 +#define FILTERCFG_ENABLE_WORD_PREVIEW 0x80000 +#define FILTERCFG_USE_ENHANCED_FIELDS 0x100000 +#define FILTERCFG_WORD_WBCTBL 0x200000 + +static SvtFilterOptions* pOptions=0; + +class SvtAppFilterOptions_Impl : public utl::ConfigItem +{ + sal_Bool bLoadVBA; + sal_Bool bSaveVBA; +public: + SvtAppFilterOptions_Impl(const OUString& rRoot) : + utl::ConfigItem(rRoot), + bLoadVBA(sal_False), + bSaveVBA(sal_False) {} + ~SvtAppFilterOptions_Impl(); + virtual void Commit(); + virtual void Notify( const com::sun::star::uno::Sequence<rtl::OUString>& aPropertyNames); + void Load(); + + sal_Bool IsLoad() const {return bLoadVBA;} + void SetLoad(sal_Bool bSet) + { + if(bSet != bLoadVBA) + SetModified(); + bLoadVBA = bSet; + } + sal_Bool IsSave() const {return bSaveVBA;} + void SetSave(sal_Bool bSet) + { + if(bSet != bSaveVBA) + SetModified(); + bSaveVBA = bSet; + } +}; + +SvtAppFilterOptions_Impl::~SvtAppFilterOptions_Impl() +{ + if(IsModified()) + Commit(); +} + +void SvtAppFilterOptions_Impl::Commit() +{ + Sequence<OUString> aNames(2); + OUString* pNames = aNames.getArray(); + pNames[0] = C2U("Load"); + pNames[1] = C2U("Save"); + Sequence<Any> aValues(aNames.getLength()); + Any* pValues = aValues.getArray(); + + const Type& rType = ::getBooleanCppuType(); + pValues[0].setValue(&bLoadVBA, rType); + pValues[1].setValue(&bSaveVBA, rType); + + PutProperties(aNames, aValues); +} + +void SvtAppFilterOptions_Impl::Notify( const Sequence< rtl::OUString >& ) +{ + // no listeners supported yet +} + +void SvtAppFilterOptions_Impl::Load() +{ + Sequence<OUString> aNames(2); + OUString* pNames = aNames.getArray(); + pNames[0] = C2U("Load"); + pNames[1] = C2U("Save"); + + Sequence<Any> aValues = GetProperties(aNames); + const Any* pValues = aValues.getConstArray(); + + if(pValues[0].hasValue()) + bLoadVBA = *(sal_Bool*)pValues[0].getValue(); + if(pValues[1].hasValue()) + bSaveVBA = *(sal_Bool*)pValues[1].getValue(); +} + +// ----------------------------------------------------------------------- +class SvtWriterFilterOptions_Impl : public SvtAppFilterOptions_Impl +{ + sal_Bool bLoadExecutable; +public: + SvtWriterFilterOptions_Impl(const OUString& rRoot) : + SvtAppFilterOptions_Impl(rRoot), + bLoadExecutable(sal_False) + {} + virtual void Commit(); + void Load(); + + sal_Bool IsLoadExecutable() const {return bLoadExecutable;} + void SetLoadExecutable(sal_Bool bSet) + { + if(bSet != bLoadExecutable) + SetModified(); + bLoadExecutable = bSet; + } +}; + +void SvtWriterFilterOptions_Impl::Commit() +{ + SvtAppFilterOptions_Impl::Commit(); + + Sequence<OUString> aNames(1); + aNames[0] = C2U("Executable"); + Sequence<Any> aValues(1); + aValues[0] <<= bLoadExecutable; + + PutProperties(aNames, aValues); +} + +void SvtWriterFilterOptions_Impl::Load() +{ + SvtAppFilterOptions_Impl::Load(); + + Sequence<OUString> aNames(1); + aNames[0] = C2U("Executable"); + + Sequence<Any> aValues = GetProperties(aNames); + const Any* pValues = aValues.getConstArray(); + if(pValues[0].hasValue()) + bLoadExecutable = *(sal_Bool*)pValues[0].getValue(); +} + +// ----------------------------------------------------------------------- +class SvtCalcFilterOptions_Impl : public SvtAppFilterOptions_Impl +{ + sal_Bool bLoadExecutable; +public: + SvtCalcFilterOptions_Impl(const OUString& rRoot) : + SvtAppFilterOptions_Impl(rRoot), + bLoadExecutable(sal_False) + {} + virtual void Commit(); + void Load(); + + sal_Bool IsLoadExecutable() const {return bLoadExecutable;} + void SetLoadExecutable(sal_Bool bSet) + { + if(bSet != bLoadExecutable) + SetModified(); + bLoadExecutable = bSet; + } +}; + +void SvtCalcFilterOptions_Impl::Commit() +{ + SvtAppFilterOptions_Impl::Commit(); + + Sequence<OUString> aNames(1); + aNames[0] = C2U("Executable"); + Sequence<Any> aValues(1); + aValues[0] <<= bLoadExecutable; + + PutProperties(aNames, aValues); +} + +void SvtCalcFilterOptions_Impl::Load() +{ + SvtAppFilterOptions_Impl::Load(); + + Sequence<OUString> aNames(1); + aNames[0] = C2U("Executable"); + + Sequence<Any> aValues = GetProperties(aNames); + const Any* pValues = aValues.getConstArray(); + if(pValues[0].hasValue()) + bLoadExecutable = *(sal_Bool*)pValues[0].getValue(); +} + +struct SvtFilterOptions_Impl +{ + ULONG nFlags; + SvtWriterFilterOptions_Impl aWriterCfg; + SvtCalcFilterOptions_Impl aCalcCfg; + SvtAppFilterOptions_Impl aImpressCfg; + + SvtFilterOptions_Impl() : + aWriterCfg(C2U("Office.Writer/Filter/Import/VBA")), + aCalcCfg(C2U("Office.Calc/Filter/Import/VBA")), + aImpressCfg(C2U("Office.Impress/Filter/Import/VBA")) + { + nFlags = FILTERCFG_WORD_CODE | + FILTERCFG_WORD_STORAGE | + FILTERCFG_EXCEL_CODE | + FILTERCFG_EXCEL_STORAGE | + FILTERCFG_PPOINT_CODE | + FILTERCFG_PPOINT_STORAGE | + FILTERCFG_MATH_LOAD | + FILTERCFG_MATH_SAVE | + FILTERCFG_WRITER_LOAD | + FILTERCFG_WRITER_SAVE | + FILTERCFG_CALC_LOAD | + FILTERCFG_CALC_SAVE | + FILTERCFG_IMPRESS_LOAD | + FILTERCFG_IMPRESS_SAVE | + FILTERCFG_USE_ENHANCED_FIELDS; + Load(); + } + + void SetFlag( ULONG nFlag, BOOL bSet ); + BOOL IsFlag( ULONG nFlag ) const; + void Load() + { + aWriterCfg.Load(); + aCalcCfg.Load(); + aImpressCfg.Load(); + } +}; + +void SvtFilterOptions_Impl::SetFlag( ULONG nFlag, BOOL bSet ) +{ + switch(nFlag) + { + case FILTERCFG_WORD_CODE: aWriterCfg.SetLoad(bSet);break; + case FILTERCFG_WORD_STORAGE: aWriterCfg.SetSave(bSet);break; + case FILTERCFG_WORD_WBCTBL: aWriterCfg.SetLoadExecutable(bSet);break; + case FILTERCFG_EXCEL_CODE: aCalcCfg.SetLoad(bSet);break; + case FILTERCFG_EXCEL_STORAGE: aCalcCfg.SetSave(bSet);break; + case FILTERCFG_EXCEL_EXECTBL: aCalcCfg.SetLoadExecutable(bSet);break; + case FILTERCFG_PPOINT_CODE: aImpressCfg.SetLoad(bSet);break; + case FILTERCFG_PPOINT_STORAGE: aImpressCfg.SetSave(bSet);break; + default: + if( bSet ) + nFlags |= nFlag; + else + nFlags &= ~nFlag; + } +} + +BOOL SvtFilterOptions_Impl::IsFlag( ULONG nFlag ) const +{ + BOOL bRet; + switch(nFlag) + { + case FILTERCFG_WORD_CODE : bRet = aWriterCfg.IsLoad();break; + case FILTERCFG_WORD_STORAGE : bRet = aWriterCfg.IsSave();break; + case FILTERCFG_WORD_WBCTBL : bRet = aWriterCfg.IsLoadExecutable();break; + case FILTERCFG_EXCEL_CODE : bRet = aCalcCfg.IsLoad();break; + case FILTERCFG_EXCEL_STORAGE : bRet = aCalcCfg.IsSave();break; + case FILTERCFG_EXCEL_EXECTBL : bRet = aCalcCfg.IsLoadExecutable();break; + case FILTERCFG_PPOINT_CODE : bRet = aImpressCfg.IsLoad();break; + case FILTERCFG_PPOINT_STORAGE : bRet = aImpressCfg.IsSave();break; + default: + bRet = 0 != (nFlags & nFlag ); + } + return bRet; +} + +// ----------------------------------------------------------------------- + +SvtFilterOptions::SvtFilterOptions() : + ConfigItem( C2U("Office.Common/Filter/Microsoft") ), + pImp(new SvtFilterOptions_Impl) +{ + RTL_LOGFILE_CONTEXT(aLog, "unotools SvtFilterOptions::SvtFilterOptions()"); + EnableNotification(GetPropertyNames()); + Load(); +} +// ----------------------------------------------------------------------- +SvtFilterOptions::~SvtFilterOptions() +{ + delete pImp; +} + +const Sequence<OUString>& SvtFilterOptions::GetPropertyNames() +{ + static Sequence<OUString> aNames; + if(!aNames.getLength()) + { + int nCount = 12; + aNames.realloc(nCount); + static const char* aPropNames[] = + { + "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 + }; + OUString* pNames = aNames.getArray(); + for(int i = 0; i < nCount; i++) + pNames[i] = C2U(aPropNames[i]); + } + return aNames; +} +//----------------------------------------------------------------------- +static ULONG lcl_GetFlag(sal_Int32 nProp) +{ + ULONG nFlag = 0; + switch(nProp) + { + case 0: nFlag = FILTERCFG_MATH_LOAD; break; + case 1: nFlag = FILTERCFG_WRITER_LOAD; break; + case 2: nFlag = FILTERCFG_IMPRESS_LOAD; break; + case 3: nFlag = FILTERCFG_CALC_LOAD; break; + case 4: nFlag = FILTERCFG_MATH_SAVE; break; + case 5: nFlag = FILTERCFG_WRITER_SAVE; break; + case 6: nFlag = FILTERCFG_IMPRESS_SAVE; break; + case 7: nFlag = FILTERCFG_CALC_SAVE; break; + case 8: nFlag = FILTERCFG_ENABLE_PPT_PREVIEW; break; + case 9: nFlag = FILTERCFG_ENABLE_EXCEL_PREVIEW; break; + case 10: nFlag = FILTERCFG_ENABLE_WORD_PREVIEW; break; + case 11: nFlag = FILTERCFG_USE_ENHANCED_FIELDS; break; + + default: DBG_ERROR("illegal value"); + } + return nFlag; +} + +void SvtFilterOptions::Notify( const Sequence<OUString>& ) +{ + Load(); +} + +void SvtFilterOptions::Commit() +{ + const Sequence<OUString>& aNames = GetPropertyNames(); + Sequence<Any> aValues(aNames.getLength()); + Any* pValues = aValues.getArray(); + + const Type& rType = ::getBooleanCppuType(); + for(int nProp = 0; nProp < aNames.getLength(); nProp++) + { + ULONG nFlag = lcl_GetFlag(nProp); + sal_Bool bVal = pImp->IsFlag( nFlag); + pValues[nProp].setValue(&bVal, rType); + + } + PutProperties(aNames, aValues); +} + +void SvtFilterOptions::Load() +{ + pImp->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()) + { + sal_Bool bVal = *(sal_Bool*)pValues[nProp].getValue(); + ULONG nFlag = lcl_GetFlag(nProp); + pImp->SetFlag( nFlag, bVal); + } + } + } +} +// ----------------------------------------------------------------------- + +void SvtFilterOptions::SetLoadWordBasicCode( sal_Bool bFlag ) +{ + pImp->SetFlag( FILTERCFG_WORD_CODE, bFlag ); + SetModified(); +} + +sal_Bool SvtFilterOptions::IsLoadWordBasicCode() const +{ + return pImp->IsFlag( FILTERCFG_WORD_CODE ); +} + +void SvtFilterOptions::SetLoadWordBasicExecutable( sal_Bool bFlag ) +{ + pImp->SetFlag( FILTERCFG_WORD_WBCTBL, bFlag ); + SetModified(); +} + +BOOL SvtFilterOptions::IsLoadWordBasicExecutable() const +{ + return pImp->IsFlag( FILTERCFG_WORD_WBCTBL ); +} + +void SvtFilterOptions::SetLoadWordBasicStorage( sal_Bool bFlag ) +{ + pImp->SetFlag( FILTERCFG_WORD_STORAGE, bFlag ); + SetModified(); +} + +sal_Bool SvtFilterOptions::IsLoadWordBasicStorage() const +{ + return pImp->IsFlag( FILTERCFG_WORD_STORAGE ); +} + +// ----------------------------------------------------------------------- + +void SvtFilterOptions::SetLoadExcelBasicCode( sal_Bool bFlag ) +{ + pImp->SetFlag( FILTERCFG_EXCEL_CODE, bFlag ); + SetModified(); +} + +sal_Bool SvtFilterOptions::IsLoadExcelBasicCode() const +{ + return pImp->IsFlag( FILTERCFG_EXCEL_CODE ); +} + +void SvtFilterOptions::SetLoadExcelBasicExecutable( sal_Bool bFlag ) +{ + pImp->SetFlag( FILTERCFG_EXCEL_EXECTBL, bFlag ); + SetModified(); +} + +sal_Bool SvtFilterOptions::IsLoadExcelBasicExecutable() const +{ + return pImp->IsFlag( FILTERCFG_EXCEL_EXECTBL ); +} + +void SvtFilterOptions::SetLoadExcelBasicStorage( sal_Bool bFlag ) +{ + pImp->SetFlag( FILTERCFG_EXCEL_STORAGE, bFlag ); + SetModified(); +} + +sal_Bool SvtFilterOptions::IsLoadExcelBasicStorage() const +{ + return pImp->IsFlag( FILTERCFG_EXCEL_STORAGE ); +} + +// ----------------------------------------------------------------------- + +void SvtFilterOptions::SetLoadPPointBasicCode( sal_Bool bFlag ) +{ + pImp->SetFlag( FILTERCFG_PPOINT_CODE, bFlag ); + SetModified(); +} + +sal_Bool SvtFilterOptions::IsLoadPPointBasicCode() const +{ + return pImp->IsFlag( FILTERCFG_PPOINT_CODE ); +} + +void SvtFilterOptions::SetLoadPPointBasicStorage( sal_Bool bFlag ) +{ + pImp->SetFlag( FILTERCFG_PPOINT_STORAGE, bFlag ); + SetModified(); +} + +sal_Bool SvtFilterOptions::IsLoadPPointBasicStorage() const +{ + return pImp->IsFlag( FILTERCFG_PPOINT_STORAGE ); +} + +// ----------------------------------------------------------------------- + +sal_Bool SvtFilterOptions::IsMathType2Math() const +{ + return pImp->IsFlag( FILTERCFG_MATH_LOAD ); +} + +void SvtFilterOptions::SetMathType2Math( sal_Bool bFlag ) +{ + pImp->SetFlag( FILTERCFG_MATH_LOAD, bFlag ); + SetModified(); +} + +sal_Bool SvtFilterOptions::IsMath2MathType() const +{ + return pImp->IsFlag( FILTERCFG_MATH_SAVE ); +} + +void SvtFilterOptions::SetMath2MathType( sal_Bool bFlag ) +{ + pImp->SetFlag( FILTERCFG_MATH_SAVE, bFlag ); + SetModified(); +} + + +// ----------------------------------------------------------------------- +sal_Bool SvtFilterOptions::IsWinWord2Writer() const +{ + return pImp->IsFlag( FILTERCFG_WRITER_LOAD ); +} + +void SvtFilterOptions::SetWinWord2Writer( sal_Bool bFlag ) +{ + pImp->SetFlag( FILTERCFG_WRITER_LOAD, bFlag ); + SetModified(); +} + +sal_Bool SvtFilterOptions::IsWriter2WinWord() const +{ + return pImp->IsFlag( FILTERCFG_WRITER_SAVE ); +} + +void SvtFilterOptions::SetWriter2WinWord( sal_Bool bFlag ) +{ + pImp->SetFlag( FILTERCFG_WRITER_SAVE, bFlag ); + SetModified(); +} + +sal_Bool SvtFilterOptions::IsUseEnhancedFields() const +{ + return pImp->IsFlag( FILTERCFG_USE_ENHANCED_FIELDS ); +} + +void SvtFilterOptions::SetUseEnhancedFields( sal_Bool bFlag ) +{ + pImp->SetFlag( FILTERCFG_USE_ENHANCED_FIELDS, bFlag ); + SetModified(); +} + +// ----------------------------------------------------------------------- +sal_Bool SvtFilterOptions::IsExcel2Calc() const +{ + return pImp->IsFlag( FILTERCFG_CALC_LOAD ); +} + +void SvtFilterOptions::SetExcel2Calc( sal_Bool bFlag ) +{ + pImp->SetFlag( FILTERCFG_CALC_LOAD, bFlag ); + SetModified(); +} + +sal_Bool SvtFilterOptions::IsCalc2Excel() const +{ + return pImp->IsFlag( FILTERCFG_CALC_SAVE ); +} + +void SvtFilterOptions::SetCalc2Excel( sal_Bool bFlag ) +{ + pImp->SetFlag( FILTERCFG_CALC_SAVE, bFlag ); + SetModified(); +} + + +// ----------------------------------------------------------------------- +sal_Bool SvtFilterOptions::IsPowerPoint2Impress() const +{ + return pImp->IsFlag( FILTERCFG_IMPRESS_LOAD ); +} + +void SvtFilterOptions::SetPowerPoint2Impress( sal_Bool bFlag ) +{ + pImp->SetFlag( FILTERCFG_IMPRESS_LOAD, bFlag ); + SetModified(); +} + +sal_Bool SvtFilterOptions::IsImpress2PowerPoint() const +{ + return pImp->IsFlag( FILTERCFG_IMPRESS_SAVE ); +} + +void SvtFilterOptions::SetImpress2PowerPoint( sal_Bool bFlag ) +{ + pImp->SetFlag( FILTERCFG_IMPRESS_SAVE, bFlag ); + SetModified(); +} + +SvtFilterOptions* SvtFilterOptions::Get() +{ + if ( !pOptions ) + pOptions = new SvtFilterOptions; + return pOptions; +} + +// ----------------------------------------------------------------------- + +sal_Bool SvtFilterOptions::IsEnablePPTPreview() const +{ + return pImp->IsFlag( FILTERCFG_ENABLE_PPT_PREVIEW ); +} + + +sal_Bool SvtFilterOptions::IsEnableCalcPreview() const +{ + return pImp->IsFlag( FILTERCFG_ENABLE_EXCEL_PREVIEW ); +} + + +sal_Bool SvtFilterOptions::IsEnableWordPreview() const +{ + return pImp->IsFlag( FILTERCFG_ENABLE_WORD_PREVIEW ); +} + + +/* 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 000000000000..408a208e7bee --- /dev/null +++ b/unotools/source/config/fontcfg.cxx @@ -0,0 +1,1227 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.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/beans/PropertyValue.hpp> +#include <unotools/configpathes.hxx> +#include <unotools/syslocale.hxx> +#include <rtl/ustrbuf.hxx> +#include <sal/macros.h> +#include <tools/debug.hxx> + +#if OSL_DEBUG_LEVEL > 1 +#include <stdio.h> +#endif + +#include <string.h> +#include <list> +#include <algorithm> + +#define DEFAULTFONT_CONFIGNODE "VCL/DefaultFonts" +#define SUBSTFONT_CONFIGNODE "VCL/FontSubstitutions" + +using namespace rtl; +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; + +static DefaultFontConfiguration* mpDefaultFontConfiguration = 0; + +static FontSubstConfiguration* mpFontSubstConfiguration = 0; + +/* + * DefaultFontConfiguration + */ + +static const char* getKeyType( int nKeyType ) +{ + switch( nKeyType ) + { + case DEFAULTFONT_CJK_DISPLAY: return "CJK_DISPLAY"; + case DEFAULTFONT_CJK_HEADING: return "CJK_HEADING"; + case DEFAULTFONT_CJK_PRESENTATION: return "CJK_PRESENTATION"; + case DEFAULTFONT_CJK_SPREADSHEET: return "CJK_SPREADSHEET"; + case DEFAULTFONT_CJK_TEXT: return "CJK_TEXT"; + case DEFAULTFONT_CTL_DISPLAY: return "CTL_DISPLAY"; + case DEFAULTFONT_CTL_HEADING: return "CTL_HEADING"; + case DEFAULTFONT_CTL_PRESENTATION: return "CTL_PRESENTATION"; + case DEFAULTFONT_CTL_SPREADSHEET: return "CTL_SPREADSHEET"; + case DEFAULTFONT_CTL_TEXT: return "CTL_TEXT"; + case DEFAULTFONT_FIXED: return "FIXED"; + case DEFAULTFONT_LATIN_DISPLAY: return "LATIN_DISPLAY"; + case DEFAULTFONT_LATIN_FIXED: return "LATIN_FIXED"; + case DEFAULTFONT_LATIN_HEADING: return "LATIN_HEADING"; + case DEFAULTFONT_LATIN_PRESENTATION: return "LATIN_PRESENTATION"; + case DEFAULTFONT_LATIN_SPREADSHEET: return "LATIN_SPREADSHEET"; + case DEFAULTFONT_LATIN_TEXT: return "LATIN_TEXT"; + case DEFAULTFONT_SANS: return "SANS"; + case DEFAULTFONT_SANS_UNICODE: return "SANS_UNICODE"; + case DEFAULTFONT_SERIF: return "SERIF"; + case DEFAULTFONT_SYMBOL: return "SYMBOL"; + case DEFAULTFONT_UI_FIXED: return "UI_FIXED"; + case DEFAULTFONT_UI_SANS: return "UI_SANS"; + default: + DBG_ERROR( "unmatched type" ); + return ""; + } +} + +DefaultFontConfiguration* DefaultFontConfiguration::get() +{ + if( !mpDefaultFontConfiguration ) + mpDefaultFontConfiguration = new DefaultFontConfiguration(); + return mpDefaultFontConfiguration; +} + +DefaultFontConfiguration::DefaultFontConfiguration() +{ + try + { + // get service provider + Reference< XMultiServiceFactory > xSMgr( comphelper::getProcessServiceFactory() ); + // create configuration hierachical access name + if( xSMgr.is() ) + { + try + { + m_xConfigProvider = + Reference< XMultiServiceFactory >( + xSMgr->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( + "com.sun.star.configuration.ConfigurationProvider" ))), + UNO_QUERY ); + if( m_xConfigProvider.is() ) + { + Sequence< Any > aArgs(1); + PropertyValue aVal; + aVal.Name = OUString( RTL_CONSTASCII_USTRINGPARAM( "nodepath" ) ); + aVal.Value <<= OUString( RTL_CONSTASCII_USTRINGPARAM( "/org.openoffice.VCL/DefaultFonts" ) ); + aArgs.getArray()[0] <<= aVal; + m_xConfigAccess = + Reference< XNameAccess >( + m_xConfigProvider->createInstanceWithArguments( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( + "com.sun.star.configuration.ConfigurationAccess" )), + aArgs ), + UNO_QUERY ); + if( m_xConfigAccess.is() ) + { + Sequence< OUString > aLocales = m_xConfigAccess->getElementNames(); + // fill config hash with empty interfaces + int nLocales = aLocales.getLength(); + const OUString* pLocaleStrings = aLocales.getConstArray(); + Locale aLoc; + for( int i = 0; i < nLocales; i++ ) + { + sal_Int32 nIndex = 0; + aLoc.Language = pLocaleStrings[i].getToken( 0, sal_Unicode('-'), nIndex ).toAsciiLowerCase(); + if( nIndex != -1 ) + aLoc.Country = pLocaleStrings[i].getToken( 0, sal_Unicode('-'), nIndex ).toAsciiUpperCase(); + else + aLoc.Country = OUString(); + if( nIndex != -1 ) + aLoc.Variant = pLocaleStrings[i].getToken( 0, sal_Unicode('-'), nIndex ).toAsciiUpperCase(); + else + aLoc.Variant = OUString(); + m_aConfig[ aLoc ] = LocaleAccess(); + m_aConfig[ aLoc ].aConfigLocaleString = pLocaleStrings[i]; + } + } + } + } + catch( Exception& ) + { + // configuration is awry + m_xConfigProvider.clear(); + m_xConfigAccess.clear(); + } + } + } + catch( WrappedTargetException& ) + { + } + #if OSL_DEBUG_LEVEL > 1 + fprintf( stderr, "config provider: %s, config access: %s\n", + m_xConfigProvider.is() ? "true" : "false", + m_xConfigAccess.is() ? "true" : "false" + ); + #endif +} + +DefaultFontConfiguration::~DefaultFontConfiguration() +{ + // release all nodes + m_aConfig.clear(); + // release top node + m_xConfigAccess.clear(); + // release config provider + m_xConfigProvider.clear(); +} + +OUString DefaultFontConfiguration::tryLocale( const Locale& rLocale, const OUString& rType ) const +{ + OUString aRet; + + std::hash_map< Locale, LocaleAccess, LocaleHash >::const_iterator it = + m_aConfig.find( rLocale ); + 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( NoSuchElementException ) + { + } + catch( WrappedTargetException ) + { + } + } + if( it->second.xAccess.is() ) + { + try + { + if ( it->second.xAccess->hasByName( rType ) ) + { + Any aAny = it->second.xAccess->getByName( rType ); + aAny >>= aRet; + } + } + catch( NoSuchElementException& ) + { + } + catch( WrappedTargetException& ) + { + } + } + } + + return aRet; +} + +OUString DefaultFontConfiguration::getDefaultFont( const Locale& rLocale, int nType ) const +{ + Locale aLocale; + aLocale.Language = rLocale.Language.toAsciiLowerCase(); + aLocale.Country = rLocale.Country.toAsciiUpperCase(); + aLocale.Variant = rLocale.Variant.toAsciiUpperCase(); + + OUString aType = OUString::createFromAscii( getKeyType( nType ) ); + OUString aRet = tryLocale( aLocale, aType ); + if( ! aRet.getLength() && aLocale.Variant.getLength() ) + { + aLocale.Variant = OUString(); + aRet = tryLocale( aLocale, aType ); + } + if( ! aRet.getLength() && aLocale.Country.getLength() ) + { + aLocale.Country = OUString(); + aRet = tryLocale( aLocale, aType ); + } + if( ! aRet.getLength() ) + { + aLocale.Language = OUString( RTL_CONSTASCII_USTRINGPARAM( "en" ) ); + aRet = tryLocale( aLocale, aType ); + } + return aRet; +} + +OUString DefaultFontConfiguration::getUserInterfaceFont( const Locale& rLocale ) const +{ + Locale aLocale = rLocale; + if( ! aLocale.Language.getLength() ) + aLocale = SvtSysLocale().GetUILocale(); + + OUString aUIFont = getDefaultFont( aLocale, DEFAULTFONT_UI_SANS ); + + if( aUIFont.getLength() ) + return aUIFont; + + // fallback mechanism (either no configuration or no entry in configuration + + #define FALLBACKFONT_UI_SANS "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" + #define FALLBACKFONT_UI_SANS_LATIN2 "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" + #define FALLBACKFONT_UI_SANS_ARABIC "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" + #define FALLBACKFONT_UI_SANS_THAI "OONaksit;Tahoma;Lucidasans;Arial Unicode MS" + #define FALLBACKFONT_UI_SANS_KOREAN "SunGulim;BaekmukGulim;Gulim;Roundgothic;Arial Unicode MS;Lucida Sans Unicode;gnu-unifont;Andale Sans UI" + #define FALLBACKFONT_UI_SANS_JAPANESE1 "HG-GothicB-Sun;Andale Sans UI;HG MhinchoLightJ" + #define FALLBACKFONT_UI_SANS_JAPANESE2 "Kochi Gothic;Gothic" + #define FALLBACKFONT_UI_SANS_CHINSIM "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;" + #define FALLBACKFONT_UI_SANS_CHINTRD "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;" + + // we need localized names for japanese fonts + static sal_Unicode const aMSGothic[] = { 0xFF2D, 0xFF33, ' ', 0x30B4, 0x30B7, 0x30C3, 0x30AF, 0, 0 }; + static sal_Unicode const aMSPGothic[] = { 0xFF2D, 0xFF33, ' ', 0xFF30, 0x30B4, 0x30B7, 0x30C3, 0x30AF, 0, 0 }; + static sal_Unicode const aTLPGothic[] = { 0x0054, 0x004C, 0x0050, 0x30B4, 0x30B7, 0x30C3, 0x30AF, 0, 0 }; + static sal_Unicode const aLXGothic[] = { 0x004C, 0x0058, 0x30B4, 0x30B7, 0x30C3, 0x30AF, 0, 0 }; + static sal_Unicode const aKochiGothic[] = { 0x6771, 0x98A8, 0x30B4, 0x30B7, 0x30C3, 0x30AF, 0, 0 }; + + String aFallBackJapaneseLocalized( RTL_CONSTASCII_USTRINGPARAM( "MS UI Gothic;" ) ); + aFallBackJapaneseLocalized += String( RTL_CONSTASCII_USTRINGPARAM( FALLBACKFONT_UI_SANS_JAPANESE1 ) ); + aFallBackJapaneseLocalized += String( aMSPGothic ); + aFallBackJapaneseLocalized += String(RTL_CONSTASCII_USTRINGPARAM( ";" ) ); + aFallBackJapaneseLocalized += String( aMSGothic ); + aFallBackJapaneseLocalized += String(RTL_CONSTASCII_USTRINGPARAM( ";" ) ); + aFallBackJapaneseLocalized += String( aTLPGothic ); + aFallBackJapaneseLocalized += String(RTL_CONSTASCII_USTRINGPARAM( ";" ) ); + aFallBackJapaneseLocalized += String( aLXGothic ); + aFallBackJapaneseLocalized += String(RTL_CONSTASCII_USTRINGPARAM( ";" ) ); + aFallBackJapaneseLocalized += String( aKochiGothic ); + aFallBackJapaneseLocalized += String(RTL_CONSTASCII_USTRINGPARAM( ";" ) ); + aFallBackJapaneseLocalized += String(RTL_CONSTASCII_USTRINGPARAM( FALLBACKFONT_UI_SANS_JAPANESE2 ) ); + static const OUString aFallBackJapanese( aFallBackJapaneseLocalized ); + static const OUString aFallback (RTL_CONSTASCII_USTRINGPARAM(FALLBACKFONT_UI_SANS)); + static const OUString aFallbackLatin2 (RTL_CONSTASCII_USTRINGPARAM(FALLBACKFONT_UI_SANS_LATIN2)); + static const OUString aFallBackArabic (RTL_CONSTASCII_USTRINGPARAM( FALLBACKFONT_UI_SANS_ARABIC ) ); + static const OUString aFallBackThai (RTL_CONSTASCII_USTRINGPARAM( FALLBACKFONT_UI_SANS_THAI ) ); + static const OUString aFallBackChineseSIM (RTL_CONSTASCII_USTRINGPARAM( FALLBACKFONT_UI_SANS_CHINSIM ) ); + static const OUString aFallBackChineseTRD (RTL_CONSTASCII_USTRINGPARAM( FALLBACKFONT_UI_SANS_CHINTRD ) ); + + // we need localized names for korean fonts + static sal_Unicode const aSunGulim[] = { 0xC36C, 0xAD74, 0xB9BC, 0 }; + static sal_Unicode const aBaekmukGulim[] = { 0xBC31, 0xBC35, 0xAD74, 0xB9BC, 0 }; + String aFallBackKoreanLocalized( aSunGulim ); + aFallBackKoreanLocalized += String(RTL_CONSTASCII_USTRINGPARAM( ";" ) ); + aFallBackKoreanLocalized += String( aBaekmukGulim ); + aFallBackKoreanLocalized += String(RTL_CONSTASCII_USTRINGPARAM( ";" ) ); + aFallBackKoreanLocalized += String(RTL_CONSTASCII_USTRINGPARAM( FALLBACKFONT_UI_SANS_KOREAN ) ); + static const OUString aFallBackKorean( aFallBackKoreanLocalized ); + + // optimize font list for some locales, as long as Andale Sans UI does not support them + if( aLocale.Language.equalsAscii( "ar" ) || + aLocale.Language.equalsAscii( "he" ) || + aLocale.Language.equalsAscii( "iw" ) ) + { + return aFallBackArabic; + } + else if( aLocale.Language.equalsAscii( "th" ) ) + { + return aFallBackThai; + } + else if( aLocale.Language.equalsAscii( "ko" ) ) + { + return aFallBackKorean; + } + else if( aLocale.Language.equalsAscii( "cs" ) || + aLocale.Language.equalsAscii( "hu" ) || + aLocale.Language.equalsAscii( "pl" ) || + aLocale.Language.equalsAscii( "ro" ) || + aLocale.Language.equalsAscii( "rm" ) || + aLocale.Language.equalsAscii( "hr" ) || + aLocale.Language.equalsAscii( "sk" ) || + aLocale.Language.equalsAscii( "sl" ) || + aLocale.Language.equalsAscii( "sb" ) ) + { + return aFallbackLatin2; + } + else if( aLocale.Language.equalsAscii( "zh" ) ) + { + if( ! aLocale.Country.equalsAscii( "cn" ) ) + return aFallBackChineseTRD; + else + return aFallBackChineseSIM; + } + else if( aLocale.Language.equalsAscii( "ja" ) ) + { + return aFallBackJapanese; + } + + return aFallback; +} + +// ------------------------------------------------------------------------------------ + +/* + * FontSubstConfigItem::get + */ + +FontSubstConfiguration* FontSubstConfiguration::get() +{ + if( !mpFontSubstConfiguration ) + mpFontSubstConfiguration = new FontSubstConfiguration(); + return mpFontSubstConfiguration; +} + +/* + * FontSubstConfigItem::FontSubstConfigItem + */ + +FontSubstConfiguration::FontSubstConfiguration() : + maSubstHash( 300 ) +{ + try + { + // get service provider + Reference< XMultiServiceFactory > xSMgr( comphelper::getProcessServiceFactory() ); + // create configuration hierachical access name + if( xSMgr.is() ) + { + try + { + m_xConfigProvider = + Reference< XMultiServiceFactory >( + xSMgr->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( + "com.sun.star.configuration.ConfigurationProvider" ))), + UNO_QUERY ); + if( m_xConfigProvider.is() ) + { + Sequence< Any > aArgs(1); + PropertyValue aVal; + aVal.Name = OUString( RTL_CONSTASCII_USTRINGPARAM( "nodepath" ) ); + aVal.Value <<= OUString( RTL_CONSTASCII_USTRINGPARAM( "/org.openoffice.VCL/FontSubstitutions" ) ); + aArgs.getArray()[0] <<= aVal; + m_xConfigAccess = + Reference< XNameAccess >( + m_xConfigProvider->createInstanceWithArguments( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( + "com.sun.star.configuration.ConfigurationAccess" )), + aArgs ), + UNO_QUERY ); + if( m_xConfigAccess.is() ) + { + Sequence< OUString > aLocales = m_xConfigAccess->getElementNames(); + // fill config hash with empty interfaces + int nLocales = aLocales.getLength(); + const OUString* pLocaleStrings = aLocales.getConstArray(); + Locale aLoc; + for( int i = 0; i < nLocales; i++ ) + { + sal_Int32 nIndex = 0; + aLoc.Language = pLocaleStrings[i].getToken( 0, sal_Unicode('-'), nIndex ).toAsciiLowerCase(); + if( nIndex != -1 ) + aLoc.Country = pLocaleStrings[i].getToken( 0, sal_Unicode('-'), nIndex ).toAsciiUpperCase(); + else + aLoc.Country = OUString(); + if( nIndex != -1 ) + aLoc.Variant = pLocaleStrings[i].getToken( 0, sal_Unicode('-'), nIndex ).toAsciiUpperCase(); + else + aLoc.Variant = OUString(); + m_aSubst[ aLoc ] = LocaleSubst(); + m_aSubst[ aLoc ].aConfigLocaleString = pLocaleStrings[i]; + } + } + } + } + catch( Exception& ) + { + // configuration is awry + m_xConfigProvider.clear(); + m_xConfigAccess.clear(); + } + } + } + catch( WrappedTargetException& ) + { + } + #if OSL_DEBUG_LEVEL > 1 + fprintf( stderr, "config provider: %s, config access: %s\n", + m_xConfigProvider.is() ? "true" : "false", + m_xConfigAccess.is() ? "true" : "false" + ); + #endif +} + +/* + * FontSubstConfigItem::~FontSubstConfigItem + */ + +FontSubstConfiguration::~FontSubstConfiguration() +{ + // release config access + m_xConfigAccess.clear(); + // release config provider + m_xConfigProvider.clear(); +} + +/* + * FontSubstConfigItem::getMapName + */ +// ======================================================================= + +static const char* const aImplKillLeadingList[] = +{ + "microsoft", + "monotype", + "linotype", + "baekmuk", + "adobe", + "nimbus", + "zycjk", + "itc", + "sun", + "amt", + "ms", + "mt", + "cg", + "hg", + "fz", + "ipa", + "sazanami", + "kochi", + NULL +}; + +// ----------------------------------------------------------------------- + +static 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", + NULL +}; + +// ----------------------------------------------------------------------- + +static const char* const aImplKillTrailingWithExceptionsList[] = +{ + "ce", "monospace", "oldface", NULL, + "ps", "caps", NULL, + NULL +}; + +// ----------------------------------------------------------------------- + +struct ImplFontAttrWeightSearchData +{ + const char* mpStr; + FontWeight meWeight; +}; + +static 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 }, +{ NULL, WEIGHT_DONTKNOW }, +}; + +// ----------------------------------------------------------------------- + +struct ImplFontAttrWidthSearchData +{ + const char* mpStr; + FontWidth meWidth; +}; + +static 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 }, +{ NULL, WIDTH_DONTKNOW }, +}; + +struct ImplFontAttrTypeSearchData +{ + const char* mpStr; + ULONG mnType; +}; + +static ImplFontAttrTypeSearchData const aImplTypeAttrSearchList[] = +{ +{ "monotype", 0 }, +{ "linotype", 0 }, +{ "titling", IMPL_FONT_ATTR_TITLING }, +{ "captitals", IMPL_FONT_ATTR_CAPITALS }, +{ "captital", IMPL_FONT_ATTR_CAPITALS }, +{ "caps", IMPL_FONT_ATTR_CAPITALS }, +{ "italic", IMPL_FONT_ATTR_ITALIC }, +{ "oblique", IMPL_FONT_ATTR_ITALIC }, +{ "rounded", IMPL_FONT_ATTR_ROUNDED }, +{ "outline", IMPL_FONT_ATTR_OUTLINE }, +{ "shadow", IMPL_FONT_ATTR_SHADOW }, +{ "handwriting", IMPL_FONT_ATTR_HANDWRITING | IMPL_FONT_ATTR_SCRIPT }, +{ "hand", IMPL_FONT_ATTR_HANDWRITING | IMPL_FONT_ATTR_SCRIPT }, +{ "signet", IMPL_FONT_ATTR_HANDWRITING | IMPL_FONT_ATTR_SCRIPT }, +{ "script", IMPL_FONT_ATTR_BRUSHSCRIPT | IMPL_FONT_ATTR_SCRIPT }, +{ "calligraphy", IMPL_FONT_ATTR_CHANCERY | IMPL_FONT_ATTR_SCRIPT }, +{ "chancery", IMPL_FONT_ATTR_CHANCERY | IMPL_FONT_ATTR_SCRIPT }, +{ "corsiva", IMPL_FONT_ATTR_CHANCERY | IMPL_FONT_ATTR_SCRIPT }, +{ "gothic", IMPL_FONT_ATTR_SANSSERIF | IMPL_FONT_ATTR_GOTHIC }, +{ "schoolbook", IMPL_FONT_ATTR_SERIF | IMPL_FONT_ATTR_SCHOOLBOOK }, +{ "schlbk", IMPL_FONT_ATTR_SERIF | IMPL_FONT_ATTR_SCHOOLBOOK }, +{ "typewriter", IMPL_FONT_ATTR_TYPEWRITER | IMPL_FONT_ATTR_FIXED }, +{ "lineprinter", IMPL_FONT_ATTR_TYPEWRITER | IMPL_FONT_ATTR_FIXED }, +{ "monospaced", IMPL_FONT_ATTR_FIXED }, +{ "monospace", IMPL_FONT_ATTR_FIXED }, +{ "mono", IMPL_FONT_ATTR_FIXED }, +{ "fixed", IMPL_FONT_ATTR_FIXED }, +{ "sansserif", IMPL_FONT_ATTR_SANSSERIF }, +{ "sans", IMPL_FONT_ATTR_SANSSERIF }, +{ "swiss", IMPL_FONT_ATTR_SANSSERIF }, +{ "serif", IMPL_FONT_ATTR_SERIF }, +{ "bright", IMPL_FONT_ATTR_SERIF }, +{ "symbols", IMPL_FONT_ATTR_SYMBOL }, +{ "symbol", IMPL_FONT_ATTR_SYMBOL }, +{ "dingbats", IMPL_FONT_ATTR_SYMBOL }, +{ "dings", IMPL_FONT_ATTR_SYMBOL }, +{ "ding", IMPL_FONT_ATTR_SYMBOL }, +{ "bats", IMPL_FONT_ATTR_SYMBOL }, +{ "math", IMPL_FONT_ATTR_SYMBOL }, +{ "oldstyle", IMPL_FONT_ATTR_OTHERSTYLE }, +{ "oldface", IMPL_FONT_ATTR_OTHERSTYLE }, +{ "old", IMPL_FONT_ATTR_OTHERSTYLE }, +{ "new", 0 }, +{ "modern", 0 }, +{ "lucida", 0 }, +{ "regular", 0 }, +{ "extended", 0 }, +{ "extra", IMPL_FONT_ATTR_OTHERSTYLE }, +{ "ext", 0 }, +{ "scalable", 0 }, +{ "scale", 0 }, +{ "nimbus", 0 }, +{ "adobe", 0 }, +{ "itc", 0 }, +{ "amt", 0 }, +{ "mt", 0 }, +{ "ms", 0 }, +{ "cpi", 0 }, +{ "no", 0 }, +{ NULL, 0 }, +}; + +// ----------------------------------------------------------------------- + +static bool ImplKillLeading( String& rName, const char* const* ppStr ) +{ + for(; *ppStr; ++ppStr ) + { + const char* pStr = *ppStr; + const xub_Unicode* pNameStr = rName.GetBuffer(); + while ( (*pNameStr == (xub_Unicode)(unsigned char)*pStr) && *pStr ) + { + pNameStr++; + pStr++; + } + if ( !*pStr ) + { + xub_StrLen nLen = sal::static_int_cast<xub_StrLen>(pNameStr - rName.GetBuffer()); + rName.Erase( 0, nLen ); + return true; + } + } + + // special case for Baekmuk + // TODO: allow non-ASCII KillLeading list + const xub_Unicode* pNameStr = rName.GetBuffer(); + if( (pNameStr[0]==0xBC31) && (pNameStr[1]==0xBC35) ) + { + xub_StrLen nLen = (pNameStr[2]==0x0020) ? 3 : 2; + rName.Erase( 0, nLen ); + return true; + } + + return false; +} + +// ----------------------------------------------------------------------- + +static xub_StrLen ImplIsTrailing( const String& rName, const char* pStr ) +{ + xub_StrLen nStrLen = static_cast<xub_StrLen>( strlen( pStr ) ); + if( nStrLen >= rName.Len() ) + return 0; + + const xub_Unicode* pEndName = rName.GetBuffer() + rName.Len(); + const sal_Unicode* pNameStr = pEndName - nStrLen; + do if( *(pNameStr++) != *(pStr++) ) + return 0; + while( *pStr ); + + return nStrLen; +} + +// ----------------------------------------------------------------------- + +static bool ImplKillTrailing( String& rName, const char* const* ppStr ) +{ + for(; *ppStr; ++ppStr ) + { + xub_StrLen nTrailLen = ImplIsTrailing( rName, *ppStr ); + if( nTrailLen ) + { + rName.Erase( rName.Len()-nTrailLen ); + return true; + } + } + + return false; +} + +// ----------------------------------------------------------------------- + +static bool ImplKillTrailingWithExceptions( String& rName, const char* const* ppStr ) +{ + for(; *ppStr; ++ppStr ) + { + xub_StrLen nTrailLen = ImplIsTrailing( rName, *ppStr ); + if( nTrailLen ) + { + // check string match against string exceptions + while( *++ppStr ) + if( ImplIsTrailing( rName, *ppStr ) ) + return false; + + rName.Erase( rName.Len()-nTrailLen ); + return true; + } + else + { + // skip exception strings + while( *++ppStr ) ; + } + } + + return false; +} + +// ----------------------------------------------------------------------- + +static BOOL ImplFindAndErase( String& rName, const char* pStr ) +{ + xub_StrLen nPos = rName.SearchAscii( pStr ); + if ( nPos == STRING_NOTFOUND ) + return FALSE; + + const char* pTempStr = pStr; + while ( *pTempStr ) + pTempStr++; + rName.Erase( nPos, (xub_StrLen)(pTempStr-pStr) ); + return TRUE; +} + +// ======================================================================= + +void FontSubstConfiguration::getMapName( const String& rOrgName, String& rShortName, + String& rFamilyName, FontWeight& rWeight, FontWidth& rWidth, ULONG& 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 = 0; + 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 + xub_StrLen i = 0; + while ( i < rFamilyName.Len() ) + { + sal_Unicode c = rFamilyName.GetChar( i ); + if ( (c >= 0x0030) && (c <= 0x0039) ) + rFamilyName.Erase( i, 1 ); + else + i++; + } +} + + +struct StrictStringSort : public ::std::binary_function< const FontNameAttr&, const FontNameAttr&, bool > +{ + bool operator()( const FontNameAttr& rLeft, const FontNameAttr& rRight ) + { return rLeft.Name.CompareTo( rRight.Name ) == COMPARE_LESS ; } +}; + +static 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" +}; + +struct enum_convert +{ + const char* pName; + int nEnum; +}; + + +static 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 } +}; + +static 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 com::sun::star::uno::Reference< XNameAccess > xFont, + const rtl::OUString& rType, + std::vector< String >& rSubstVector ) const +{ + try + { + Any aAny = xFont->getByName( rType ); + if( aAny.getValueTypeClass() == TypeClass_STRING ) + { + const OUString* pLine = (const OUString*)aAny.getValue(); + sal_Int32 nIndex = 0; + sal_Int32 nLength = pLine->getLength(); + if( nLength ) + { + const sal_Unicode* pStr = pLine->getStr(); + sal_Int32 nTokens = 0; + // count tokens + while( nLength-- ) + { + if( *pStr++ == sal_Unicode(';') ) + nTokens++; + } + rSubstVector.clear(); + // optimize performance, heap fragmentation + rSubstVector.reserve( nTokens ); + while( nIndex != -1 ) + { + OUString aSubst( pLine->getToken( 0, ';', nIndex ) ); + if( aSubst.getLength() ) + { + UniqueSubstHash::iterator aEntry = maSubstHash.find( aSubst ); + if (aEntry != maSubstHash.end()) + aSubst = *aEntry; + else + maSubstHash.insert( aSubst ); + rSubstVector.push_back( aSubst ); + } + } + } + } + } + catch( NoSuchElementException ) + { + } + catch( WrappedTargetException ) + { + } +} + +FontWeight FontSubstConfiguration::getSubstWeight( const com::sun::star::uno::Reference< XNameAccess > xFont, + const rtl::OUString& rType ) const +{ + int weight = -1; + try + { + Any aAny = xFont->getByName( rType ); + if( aAny.getValueTypeClass() == TypeClass_STRING ) + { + const OUString* pLine = (const OUString*)aAny.getValue(); + if( pLine->getLength() ) + { + for( weight=SAL_N_ELEMENTS(pWeightNames)-1; weight >= 0; weight-- ) + if( pLine->equalsIgnoreAsciiCaseAscii( pWeightNames[weight].pName ) ) + break; + } +#if OSL_DEBUG_LEVEL > 1 + if( weight < 0 ) + fprintf( stderr, "Error: invalid weight %s\n", + OUStringToOString( *pLine, RTL_TEXTENCODING_ASCII_US ).getStr() ); +#endif + } + } + catch( NoSuchElementException ) + { + } + catch( WrappedTargetException ) + { + } + return (FontWeight)( weight >= 0 ? pWeightNames[weight].nEnum : WEIGHT_DONTKNOW ); +} + +FontWidth FontSubstConfiguration::getSubstWidth( const com::sun::star::uno::Reference< XNameAccess > xFont, + const rtl::OUString& rType ) const +{ + int width = -1; + try + { + Any aAny = xFont->getByName( rType ); + if( aAny.getValueTypeClass() == TypeClass_STRING ) + { + const OUString* pLine = (const OUString*)aAny.getValue(); + if( pLine->getLength() ) + { + for( width=SAL_N_ELEMENTS(pWidthNames)-1; width >= 0; width-- ) + if( pLine->equalsIgnoreAsciiCaseAscii( pWidthNames[width].pName ) ) + break; + } +#if OSL_DEBUG_LEVEL > 1 + if( width < 0 ) + fprintf( stderr, "Error: invalid width %s\n", + OUStringToOString( *pLine, RTL_TEXTENCODING_ASCII_US ).getStr() ); +#endif + } + } + catch( NoSuchElementException ) + { + } + catch( WrappedTargetException ) + { + } + return (FontWidth)( width >= 0 ? pWidthNames[width].nEnum : WIDTH_DONTKNOW ); +} + +unsigned long FontSubstConfiguration::getSubstType( const com::sun::star::uno::Reference< XNameAccess > xFont, + const rtl::OUString& rType ) const +{ + unsigned long type = 0; + try + { + Any aAny = xFont->getByName( rType ); + if( aAny.getValueTypeClass() == TypeClass_STRING ) + { + const OUString* pLine = (const OUString*)aAny.getValue(); + if( pLine->getLength() ) + { + sal_Int32 nIndex = 0; + while( nIndex != -1 ) + { + String aToken( pLine->getToken( 0, ',', nIndex ) ); + for( int k = 0; k < 32; k++ ) + if( aToken.EqualsIgnoreCaseAscii( pAttribNames[k] ) ) + { + type |= 1 << k; + break; + } + } + } + } + } + catch( NoSuchElementException ) + { + } + catch( WrappedTargetException ) + { + } + + return type; +} + +void FontSubstConfiguration::readLocaleSubst( const com::sun::star::lang::Locale& rLocale ) const +{ + std::hash_map< Locale, LocaleSubst, LocaleHash >::const_iterator it = + m_aSubst.find( rLocale ); + if( it != m_aSubst.end() ) + { + if( ! it->second.bConfigRead ) + { + it->second.bConfigRead = true; + Reference< XNameAccess > xNode; + try + { + Any aAny = m_xConfigAccess->getByName( it->second.aConfigLocaleString ); + aAny >>= xNode; + } + catch( NoSuchElementException ) + { + } + catch( WrappedTargetException ) + { + } + if( xNode.is() ) + { + Sequence< OUString > aFonts = xNode->getElementNames(); + int nFonts = aFonts.getLength(); + const OUString* pFontNames = aFonts.getConstArray(); + // improve performance, heap fragmentation + it->second.aSubstAttributes.reserve( nFonts ); + + // strings for subst retrieval, construct only once + OUString aSubstFontsStr ( RTL_CONSTASCII_USTRINGPARAM( "SubstFonts" ) ); + OUString aSubstFontsMSStr ( RTL_CONSTASCII_USTRINGPARAM( "SubstFontsMS" ) ); + OUString aSubstFontsPSStr ( RTL_CONSTASCII_USTRINGPARAM( "SubstFontsPS" ) ); + OUString aSubstFontsHTMLStr ( RTL_CONSTASCII_USTRINGPARAM( "SubstFontsHTML" ) ); + OUString aSubstWeightStr ( RTL_CONSTASCII_USTRINGPARAM( "FontWeight" ) ); + OUString aSubstWidthStr ( RTL_CONSTASCII_USTRINGPARAM( "FontWidth" ) ); + OUString aSubstTypeStr ( RTL_CONSTASCII_USTRINGPARAM( "FontType" ) ); + for( int i = 0; i < nFonts; i++ ) + { + Reference< XNameAccess > xFont; + try + { + Any aAny = xNode->getByName( pFontNames[i] ); + aAny >>= xFont; + } + catch( NoSuchElementException ) + { + } + catch( WrappedTargetException ) + { + } + if( ! xFont.is() ) + { + #if OSL_DEBUG_LEVEL > 1 + fprintf( stderr, "did not get font attributes for %s\n", + OUStringToOString( pFontNames[i], RTL_TEXTENCODING_UTF8 ).getStr() ); + #endif + continue; + } + + FontNameAttr aAttr; + // read subst attributes from config + aAttr.Name = pFontNames[i]; + fillSubstVector( xFont, aSubstFontsStr, aAttr.Substitutions ); + fillSubstVector( xFont, aSubstFontsMSStr, aAttr.MSSubstitutions ); + fillSubstVector( xFont, aSubstFontsPSStr, aAttr.PSSubstitutions ); + fillSubstVector( xFont, aSubstFontsHTMLStr, aAttr.HTMLSubstitutions ); + 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 String& rFontName, const Locale& rLocale ) const +{ + if( !rFontName.Len() ) + return NULL; + + // search if a (language dep.) replacement table for the given font exists + // fallback is english + String aSearchFont( rFontName ); + aSearchFont.ToLowerAscii(); + FontNameAttr aSearchAttr; + aSearchAttr.Name = aSearchFont; + + Locale aLocale; + aLocale.Language = rLocale.Language.toAsciiLowerCase(); + aLocale.Country = rLocale.Country.toAsciiUpperCase(); + aLocale.Variant = rLocale.Variant.toAsciiUpperCase(); + + if( ! aLocale.Language.getLength() ) + aLocale = SvtSysLocale().GetUILocale(); + + while( aLocale.Language.getLength() ) + { + std::hash_map< Locale, LocaleSubst, LocaleHash >::const_iterator lang = m_aSubst.find( aLocale ); + if( lang != m_aSubst.end() ) + { + if( ! lang->second.bConfigRead ) + readLocaleSubst( aLocale ); + // 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.Len() <= aSearchFont.Len() ) + if( aSearchFont.CompareTo( rFoundAttr.Name, rFoundAttr.Name.Len() ) == COMPARE_EQUAL ) + return &rFoundAttr; + } + } + // gradually become more unspecific + if( aLocale.Variant.getLength() ) + aLocale.Variant = OUString(); + else if( aLocale.Country.getLength() ) + aLocale.Country = OUString(); + else if( ! aLocale.Language.equalsAscii( "en" ) ) + aLocale.Language = OUString( RTL_CONSTASCII_USTRINGPARAM( "en" ) ); + else + aLocale.Language = OUString(); + } + return NULL; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/fontoptions.cxx b/unotools/source/config/fontoptions.cxx new file mode 100644 index 000000000000..13126e5612b9 --- /dev/null +++ b/unotools/source/config/fontoptions.cxx @@ -0,0 +1,508 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" + +#include <unotools/fontoptions.hxx> +#include <unotools/configmgr.hxx> +#include <unotools/configitem.hxx> +#include <tools/debug.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> + +#include <rtl/logfile.hxx> +#include "itemholder1.hxx" + +//_________________________________________________________________________________________________________________ +// namespaces +//_________________________________________________________________________________________________________________ + +using namespace ::utl ; +using namespace ::rtl ; +using namespace ::osl ; +using namespace ::com::sun::star::uno ; + +//_________________________________________________________________________________________________________________ +// const +//_________________________________________________________________________________________________________________ + +#define ROOTNODE_FONT OUString(RTL_CONSTASCII_USTRINGPARAM("Office.Common/Font" )) + +#define PROPERTYNAME_REPLACEMENTTABLE OUString(RTL_CONSTASCII_USTRINGPARAM("Substitution/Replacement" )) +#define PROPERTYNAME_FONTHISTORY OUString(RTL_CONSTASCII_USTRINGPARAM("View/History" )) +#define PROPERTYNAME_FONTWYSIWYG OUString(RTL_CONSTASCII_USTRINGPARAM("View/ShowFontBoxWYSIWYG" )) + +#define PROPERTYHANDLE_REPLACEMENTTABLE 0 +#define PROPERTYHANDLE_FONTHISTORY 1 +#define PROPERTYHANDLE_FONTWYSIWYG 2 + +#define PROPERTYCOUNT 3 + +//_________________________________________________________________________________________________________________ +// private declarations! +//_________________________________________________________________________________________________________________ + +class SvtFontOptions_Impl : public ConfigItem +{ + //------------------------------------------------------------------------------------------------------------- + // public methods + //------------------------------------------------------------------------------------------------------------- + + public: + + //--------------------------------------------------------------------------------------------------------- + // constructor / destructor + //--------------------------------------------------------------------------------------------------------- + + SvtFontOptions_Impl(); + ~SvtFontOptions_Impl(); + + //--------------------------------------------------------------------------------------------------------- + // overloaded methods of baseclass + //--------------------------------------------------------------------------------------------------------- + + /*-****************************************************************************************************//** + @short called for notify of configmanager + @descr These method is called from the ConfigManager before application ends or from the + PropertyChangeListener if the sub tree broadcasts changes. You must update your + internal values. + + @seealso baseclass ConfigItem + + @param "seqPropertyNames" is the list of properties which should be updated. + @return - + + @onerror - + *//*-*****************************************************************************************************/ + + virtual void Notify( const Sequence< OUString >& seqPropertyNames ); + + /*-****************************************************************************************************//** + @short write changes to configuration + @descr These method writes the changed values into the sub tree + and should always called in our destructor to guarantee consistency of config data. + + @seealso baseclass ConfigItem + + @param - + @return - + + @onerror - + *//*-*****************************************************************************************************/ + + virtual void Commit(); + + //--------------------------------------------------------------------------------------------------------- + // public interface + //--------------------------------------------------------------------------------------------------------- + + /*-****************************************************************************************************//** + @short access method to get internal values + @descr These method give us a chance to regulate acces to ouer internal values. + It's not used in the moment - but it's possible for the feature! + + @seealso - + + @param - + @return - + + @onerror - + *//*-*****************************************************************************************************/ + + sal_Bool IsReplacementTableEnabled ( ) const ; + void EnableReplacementTable ( sal_Bool bState ) ; + + sal_Bool IsFontHistoryEnabled ( ) const ; + void EnableFontHistory ( sal_Bool bState ) ; + + sal_Bool IsFontWYSIWYGEnabled ( ) const ; + void EnableFontWYSIWYG ( sal_Bool bState ) ; + + //------------------------------------------------------------------------------------------------------------- + // private methods + //------------------------------------------------------------------------------------------------------------- + + private: + + /*-****************************************************************************************************//** + @short return list of key names of ouer configuration management which represent oue module tree + @descr These methods return a static const list of key names. We need it to get needed values from our + configuration management. + + @seealso - + + @param - + @return A list of needed configuration keys is returned. + + @onerror - + *//*-*****************************************************************************************************/ + + static Sequence< OUString > impl_GetPropertyNames(); + + //------------------------------------------------------------------------------------------------------------- + // private member + //------------------------------------------------------------------------------------------------------------- + + private: + + sal_Bool m_bReplacementTable ; + sal_Bool m_bFontHistory ; + sal_Bool m_bFontWYSIWYG ; +}; + +//_________________________________________________________________________________________________________________ +// definitions +//_________________________________________________________________________________________________________________ + +//***************************************************************************************************************** +// constructor +//***************************************************************************************************************** +SvtFontOptions_Impl::SvtFontOptions_Impl() + // Init baseclasses first + : ConfigItem ( ROOTNODE_FONT ) + // Init member then. + , m_bReplacementTable ( sal_False ) + , m_bFontHistory ( sal_False ) + , m_bFontWYSIWYG ( sal_False ) +{ + // Use our static list of configuration keys to get his values. + Sequence< OUString > seqNames = impl_GetPropertyNames ( ); + Sequence< Any > seqValues = GetProperties ( seqNames ); + + // 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( !(seqNames.getLength()!=seqValues.getLength()), "SvtFontOptions_Impl::SvtFontOptions_Impl()\nI miss some values of configuration keys!\n" ); + + // Copy values from list in right order to ouer internal member. + sal_Int32 nPropertyCount = seqValues.getLength(); + for( sal_Int32 nProperty=0; nProperty<nPropertyCount; ++nProperty ) + { + // Safe impossible cases. + // Check any for valid value. + DBG_ASSERT( !(seqValues[nProperty].hasValue()==sal_False), "SvtFontOptions_Impl::SvtFontOptions_Impl()\nInvalid property value detected!\n" ); + switch( nProperty ) + { + case PROPERTYHANDLE_REPLACEMENTTABLE : { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtFontOptions_Impl::SvtFontOptions_Impl()\nWho has changed the value type of \"Office.Common\\Font\\Substitution\\Replacement\"?" ); + seqValues[nProperty] >>= m_bReplacementTable; + } + break; + case PROPERTYHANDLE_FONTHISTORY : { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtFontOptions_Impl::SvtFontOptions_Impl()\nWho has changed the value type of \"Office.Common\\Font\\View\\History\"?" ); + seqValues[nProperty] >>= m_bFontHistory; + } + break; + case PROPERTYHANDLE_FONTWYSIWYG : { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtFontOptions_Impl::SvtFontOptions_Impl()\nWho has changed the value type of \"Office.Common\\Font\\View\\ShowFontBoxWYSIWYG\"?" ); + seqValues[nProperty] >>= m_bFontWYSIWYG; + } + break; + } + } + + // Enable notification mechanism of ouer baseclass. + // We need it to get information about changes outside these class on ouer used configuration keys! + EnableNotification( seqNames ); +} + +//***************************************************************************************************************** +// destructor +//***************************************************************************************************************** +SvtFontOptions_Impl::~SvtFontOptions_Impl() +{ + // We must save our current values .. if user forget it! + if( IsModified() == sal_True ) + { + Commit(); + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtFontOptions_Impl::Notify( const Sequence< OUString >& seqPropertyNames ) +{ + // Use given list of updated properties to get his values from configuration directly! + Sequence< Any > seqValues = GetProperties( seqPropertyNames ); + // Safe impossible cases. + // We need values from ALL notified configuration keys. + DBG_ASSERT( !(seqPropertyNames.getLength()!=seqValues.getLength()), "SvtFontOptions_Impl::Notify()\nI miss some values of configuration keys!\n" ); + // Step over list of property names and get right value from coreesponding value list to set it on internal members! + sal_Int32 nCount = seqPropertyNames.getLength(); + for( sal_Int32 nProperty=0; nProperty<nCount; ++nProperty ) + { + if( seqPropertyNames[nProperty] == PROPERTYNAME_REPLACEMENTTABLE ) + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtFontOptions_Impl::Notify()\nWho has changed the value type of \"Office.Common\\Font\\Substitution\\Replacement\"?" ); + seqValues[nProperty] >>= m_bReplacementTable; + } + else + if( seqPropertyNames[nProperty] == PROPERTYNAME_FONTHISTORY ) + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtFontOptions_Impl::Notify()\nWho has changed the value type of \"Office.Common\\Font\\View\\History\"?" ); + seqValues[nProperty] >>= m_bFontHistory; + } + else + if( seqPropertyNames[nProperty] == PROPERTYNAME_FONTWYSIWYG ) + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtFontOptions_Impl::Notify()\nWho has changed the value type of \"Office.Common\\Font\\View\\ShowFontBoxWYSIWYG\"?" ); + seqValues[nProperty] >>= m_bFontWYSIWYG; + } + #if OSL_DEBUG_LEVEL > 1 + else DBG_ASSERT( sal_False, "SvtFontOptions_Impl::Notify()\nUnkown property detected ... I can't handle these!\n" ); + #endif + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtFontOptions_Impl::Commit() +{ + // Get names of supported properties, create a list for values and copy current values to it. + Sequence< OUString > seqNames = impl_GetPropertyNames(); + sal_Int32 nCount = seqNames.getLength(); + Sequence< Any > seqValues ( nCount ); + for( sal_Int32 nProperty=0; nProperty<nCount; ++nProperty ) + { + switch( nProperty ) + { + case PROPERTYHANDLE_REPLACEMENTTABLE : { + seqValues[nProperty] <<= m_bReplacementTable; + } + break; + case PROPERTYHANDLE_FONTHISTORY : { + seqValues[nProperty] <<= m_bFontHistory; + } + break; + case PROPERTYHANDLE_FONTWYSIWYG : { + seqValues[nProperty] <<= m_bFontWYSIWYG; + } + break; + } + } + // Set properties in configuration. + PutProperties( seqNames, seqValues ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Bool SvtFontOptions_Impl::IsReplacementTableEnabled() const +{ + return m_bReplacementTable; +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtFontOptions_Impl::EnableReplacementTable( sal_Bool bState ) +{ + m_bReplacementTable = bState; + SetModified(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Bool SvtFontOptions_Impl::IsFontHistoryEnabled() const +{ + return m_bFontHistory; +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtFontOptions_Impl::EnableFontHistory( sal_Bool bState ) +{ + m_bFontHistory = bState; + SetModified(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Bool SvtFontOptions_Impl::IsFontWYSIWYGEnabled() const +{ + return m_bFontWYSIWYG; +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtFontOptions_Impl::EnableFontWYSIWYG( sal_Bool bState ) +{ + m_bFontWYSIWYG = bState; + SetModified(); +} + +//***************************************************************************************************************** +// private method +//***************************************************************************************************************** +Sequence< OUString > SvtFontOptions_Impl::impl_GetPropertyNames() +{ + // Build static list of configuration key names. + static const OUString pProperties[] = + { + PROPERTYNAME_REPLACEMENTTABLE , + PROPERTYNAME_FONTHISTORY , + PROPERTYNAME_FONTWYSIWYG , + }; + // Initialize return sequence with these list ... + static const Sequence< OUString > seqPropertyNames( pProperties, PROPERTYCOUNT ); + // ... and return it. + return seqPropertyNames; +} + +//***************************************************************************************************************** +// initialize static member +// DON'T DO IT IN YOUR HEADER! +// see definition for further informations +//***************************************************************************************************************** +SvtFontOptions_Impl* SvtFontOptions::m_pDataContainer = NULL ; +sal_Int32 SvtFontOptions::m_nRefCount = 0 ; + +//***************************************************************************************************************** +// constructor +//***************************************************************************************************************** +SvtFontOptions::SvtFontOptions() +{ + // Global access, must be guarded (multithreading!). + MutexGuard aGuard( impl_GetOwnStaticMutex() ); + // Increase ouer refcount ... + ++m_nRefCount; + // ... and initialize ouer data container only if it not already exist! + if( m_pDataContainer == NULL ) + { + RTL_LOGFILE_CONTEXT(aLog, "unotools ( ??? ) ::SvtFontOptions_Impl::ctor()"); + m_pDataContainer = new SvtFontOptions_Impl; + + ItemHolder1::holdConfigItem(E_FONTOPTIONS); + } +} + +//***************************************************************************************************************** +// destructor +//***************************************************************************************************************** +SvtFontOptions::~SvtFontOptions() +{ + // Global access, must be guarded (multithreading!) + MutexGuard aGuard( impl_GetOwnStaticMutex() ); + // Decrease ouer refcount. + --m_nRefCount; + // If last instance was deleted ... + // we must destroy ouer static data container! + if( m_nRefCount <= 0 ) + { + delete m_pDataContainer; + m_pDataContainer = NULL; + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Bool SvtFontOptions::IsReplacementTableEnabled() const +{ + MutexGuard aGuard( impl_GetOwnStaticMutex() ); + return m_pDataContainer->IsReplacementTableEnabled(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtFontOptions::EnableReplacementTable( sal_Bool bState ) +{ + MutexGuard aGuard( impl_GetOwnStaticMutex() ); + m_pDataContainer->EnableReplacementTable( bState ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Bool SvtFontOptions::IsFontHistoryEnabled() const +{ + MutexGuard aGuard( impl_GetOwnStaticMutex() ); + return m_pDataContainer->IsFontHistoryEnabled(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtFontOptions::EnableFontHistory( sal_Bool bState ) +{ + MutexGuard aGuard( impl_GetOwnStaticMutex() ); + m_pDataContainer->EnableFontHistory( bState ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Bool SvtFontOptions::IsFontWYSIWYGEnabled() const +{ + MutexGuard aGuard( impl_GetOwnStaticMutex() ); + return m_pDataContainer->IsFontWYSIWYGEnabled(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtFontOptions::EnableFontWYSIWYG( sal_Bool bState ) +{ + MutexGuard aGuard( impl_GetOwnStaticMutex() ); + m_pDataContainer->EnableFontWYSIWYG( bState ); +} + +//***************************************************************************************************************** +// private method +//***************************************************************************************************************** +Mutex& SvtFontOptions::impl_GetOwnStaticMutex() +{ + // Initialize static mutex only for one time! + static Mutex* pMutex = NULL; + // If these method first called (Mutex not already exist!) ... + if( pMutex == NULL ) + { + // ... we must create a new one. Protect follow code with the global mutex - + // It must be - we create a static variable! + MutexGuard aGuard( Mutex::getGlobalMutex() ); + // We must check our pointer again - because it can be that another instance of ouer class will be fastr then these! + if( pMutex == NULL ) + { + // Create the new mutex and set it for return on static variable. + static Mutex aMutex; + pMutex = &aMutex; + } + } + // Return new created or already existing mutex object. + return *pMutex; +} + +/* 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 000000000000..7cc8d4eedefd --- /dev/null +++ b/unotools/source/config/historyoptions.cxx @@ -0,0 +1,727 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" + +#include <unotools/historyoptions.hxx> +#include <unotools/historyoptions_const.hxx> +#include <unotools/configmgr.hxx> +#include <unotools/configitem.hxx> +#include <tools/debug.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> + +#include <deque> +#include <algorithm> + +#include <rtl/logfile.hxx> +#include "itemholder1.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 <unotools/processfactory.hxx> + +#include <unotools/loghelper.hxx> + +//_________________________________________________________________________________________________________________ +// namespaces +//_________________________________________________________________________________________________________________ + +using namespace ::std ; +using namespace ::utl ; +using namespace ::rtl ; +using namespace ::osl ; +using namespace ::com::sun::star::uno ; +using namespace ::com::sun::star::beans ; + +namespace css = ::com::sun::star; + +//_________________________________________________________________________________________________________________ +// const +//_________________________________________________________________________________________________________________ + +namespace { + static const ::sal_Int32 s_nOffsetURL = 0; + static const ::sal_Int32 s_nOffsetFilter = 1; + static const ::sal_Int32 s_nOffsetTitle = 2; + static const ::sal_Int32 s_nOffsetPassword = 3; +} + +//_________________________________________________________________________________________________________________ +// private declarations! +//_________________________________________________________________________________________________________________ + +struct IMPL_THistoryItem +{ + IMPL_THistoryItem() + { + } + + IMPL_THistoryItem( const OUString& sNewURL , + const OUString& sNewFilter , + const OUString& sNewTitle , + const OUString& sNewPassword ) + { + sURL = sNewURL ; + sFilter = sNewFilter ; + sTitle = sNewTitle ; + sPassword = sNewPassword ; + } + + sal_Bool operator==( const OUString& sSearchedURL ) const + { + return( sURL == sSearchedURL ); + } + + OUString sURL ; + OUString sFilter ; + OUString sTitle ; + OUString sPassword ; +}; + +//***************************************************************************************************************** +// class SvtHistoryOptions_Impl +// redesigned +//***************************************************************************************************************** +class SvtHistoryOptions_Impl +{ +public: + SvtHistoryOptions_Impl(); + ~SvtHistoryOptions_Impl(); + + sal_uInt32 GetSize( EHistoryType eHistory ); + void SetSize( EHistoryType eHistory, sal_uInt32 nSize ); + void Clear( EHistoryType eHistory ); + Sequence< Sequence< PropertyValue > > GetList( EHistoryType eHistory ); + void AppendItem( EHistoryType eHistory , + const OUString& sURL , + const OUString& sFilter , + const OUString& sTitle , + const OUString& sPassword ); + +private: + void impl_truncateList (EHistoryType eHistory, sal_uInt32 nSize); + +private: + css::uno::Reference< css::container::XNameAccess > m_xCfg; + css::uno::Reference< css::container::XNameAccess > m_xCommonXCU; +}; + +//***************************************************************************************************************** +// constructor +//***************************************************************************************************************** +SvtHistoryOptions_Impl::SvtHistoryOptions_Impl() +{ + try + { + m_xCfg = Reference< css::container::XNameAccess > ( + ::comphelper::ConfigurationHelper::openConfig( + utl::getProcessServiceFactory(), + s_sHistories, + ::comphelper::ConfigurationHelper::E_STANDARD), + css::uno::UNO_QUERY ); + + m_xCommonXCU = Reference< css::container::XNameAccess > ( + ::comphelper::ConfigurationHelper::openConfig( + utl::getProcessServiceFactory(), + s_sCommonHistory, + ::comphelper::ConfigurationHelper::E_STANDARD), + css::uno::UNO_QUERY ); + } + catch(const css::uno::Exception& ex) + { + m_xCfg.clear(); + m_xCommonXCU.clear(); + + LogHelper::logIt(ex); + } +} + +//***************************************************************************************************************** +// destructor +//***************************************************************************************************************** +SvtHistoryOptions_Impl::~SvtHistoryOptions_Impl() +{ +} + +//***************************************************************************************************************** +// public method +// Attention: We return the max. size of our internal lists - That is the capacity not the size! +//***************************************************************************************************************** +sal_uInt32 SvtHistoryOptions_Impl::GetSize( EHistoryType eHistory ) +{ + css::uno::Reference< css::beans::XPropertySet > xListAccess(m_xCommonXCU, css::uno::UNO_QUERY); + + if (!xListAccess.is()) + return 0; + + sal_uInt32 nSize = 0 ; + + try + { + switch( eHistory ) + { + case ePICKLIST: + xListAccess->getPropertyValue(s_sPickListSize) >>= nSize; + break; + + case eHISTORY: + xListAccess->getPropertyValue(s_sURLHistorySize) >>= nSize; + break; + + case eHELPBOOKMARKS: + xListAccess->getPropertyValue(s_sHelpBookmarksSize) >>= nSize; + break; + + default: + break; + } + } + catch(const css::uno::Exception& ex) + { + LogHelper::logIt(ex); + } + + return nSize; +} + +//***************************************************************************************************************** +// public method +// Attention: We return the max. size of our internal lists - That is the capacity not the size! +//***************************************************************************************************************** +void SvtHistoryOptions_Impl::SetSize( EHistoryType eHistory, sal_uInt32 nSize ) +{ + css::uno::Reference< css::beans::XPropertySet > xListAccess(m_xCommonXCU, css::uno::UNO_QUERY); + if (! xListAccess.is ()) + return; + + try + { + switch( eHistory ) + { + case ePICKLIST: + if(nSize!=GetSize(ePICKLIST)) + { + xListAccess->setPropertyValue(s_sPickListSize, css::uno::makeAny(nSize)); + ::comphelper::ConfigurationHelper::flush(m_xCommonXCU); + } + break; + + case eHISTORY: + if(nSize!=GetSize(eHISTORY)) + { + xListAccess->setPropertyValue(s_sURLHistorySize, css::uno::makeAny(nSize)); + ::comphelper::ConfigurationHelper::flush(m_xCommonXCU); + } + break; + + case eHELPBOOKMARKS: + if(nSize!=GetSize(eHELPBOOKMARKS)) + { + xListAccess->setPropertyValue(s_sHelpBookmarksSize, css::uno::makeAny(nSize)); + ::comphelper::ConfigurationHelper::flush(m_xCommonXCU); + } + break; + + default: + break; + } + + impl_truncateList (eHistory, nSize); + } + catch(const css::uno::Exception& ex) + { + LogHelper::logIt(ex); + } +} + +//***************************************************************************************************************** +void SvtHistoryOptions_Impl::impl_truncateList ( EHistoryType eHistory, sal_uInt32 nSize ) +{ + css::uno::Reference< css::container::XNameAccess > xList; + css::uno::Reference< css::container::XNameContainer > xItemList; + css::uno::Reference< css::container::XNameContainer > xOrderList; + css::uno::Reference< css::beans::XPropertySet > xSet; + + try + { + switch( eHistory ) + { + case ePICKLIST: + m_xCfg->getByName(s_sPickList) >>= xList; + break; + + case eHISTORY: + m_xCfg->getByName(s_sURLHistory) >>= xList; + break; + + case eHELPBOOKMARKS: + m_xCfg->getByName(s_sHelpBookmarks) >>= xList; + break; + + default: + break; + } + + // If too much items in current list ... + // truncate the oldest items BEFORE you set the new one. + if ( ! xList.is()) + return; + + xList->getByName(s_sOrderList) >>= xOrderList; + xList->getByName(s_sItemList) >>= xItemList; + + const sal_uInt32 nLength = xOrderList->getElementNames().getLength(); + if (nSize < nLength) + { + for (sal_uInt32 i=nLength-1; i>=nSize; --i) + { + ::rtl::OUString sTmp; + const ::rtl::OUString sRemove = ::rtl::OUString::valueOf((sal_Int32)i); + xOrderList->getByName(sRemove) >>= xSet; + xSet->getPropertyValue(s_sHistoryItemRef) >>= sTmp; + xItemList->removeByName(sTmp); + xOrderList->removeByName(sRemove); + } + + ::comphelper::ConfigurationHelper::flush(m_xCfg); + } + } + catch(const css::uno::Exception& ex) + { + LogHelper::logIt(ex); + } +} + +//***************************************************************************************************************** +// public method +// Clear specified history list +//***************************************************************************************************************** +void SvtHistoryOptions_Impl::Clear( EHistoryType eHistory ) +{ + css::uno::Reference< css::container::XNameAccess > xListAccess; + css::uno::Reference< css::container::XNameContainer > xNode; + Sequence< ::rtl::OUString > lOrders; + + try + { + switch( eHistory ) + { + case ePICKLIST: + { + m_xCfg->getByName(s_sPickList) >>= xListAccess; + break; + } + + case eHISTORY: + { + m_xCfg->getByName(s_sURLHistory) >>= xListAccess; + break; + } + + case eHELPBOOKMARKS: + { + m_xCfg->getByName(s_sHelpBookmarks) >>= xListAccess; + break; + } + + default: + break; + } + + if (xListAccess.is()) + { + // clear ItemList + xListAccess->getByName(s_sItemList) >>= xNode ; + lOrders = xNode->getElementNames(); + const sal_Int32 nLength = lOrders.getLength(); + for(sal_Int32 i=0; i<nLength; ++i) + xNode->removeByName(lOrders[i]); + + // clear OrderList + xListAccess->getByName(s_sOrderList) >>= xNode ; + lOrders = xNode->getElementNames(); + for(sal_Int32 j=0; j<nLength; ++j) + xNode->removeByName(lOrders[j]); + + ::comphelper::ConfigurationHelper::flush(m_xCfg); + } + } + catch(const css::uno::Exception& ex) + { + LogHelper::logIt(ex); + } +} + +//***************************************************************************************************************** +// public method +// get a sequence list from the items +//***************************************************************************************************************** +Sequence< Sequence< PropertyValue > > SvtHistoryOptions_Impl::GetList( EHistoryType eHistory ) +{ + impl_truncateList (eHistory, GetSize (eHistory)); + + Sequence< Sequence< PropertyValue > > seqReturn; // Set default return value. + Sequence< PropertyValue > seqProperties( 4 ); + Sequence< ::rtl::OUString > lOrders; + + css::uno::Reference< css::container::XNameAccess > xListAccess; + css::uno::Reference< css::container::XNameAccess > xItemList; + css::uno::Reference< css::container::XNameAccess > xOrderList; + css::uno::Reference< css::beans::XPropertySet > xSet; + + seqProperties[s_nOffsetURL ].Name = HISTORY_PROPERTYNAME_URL; + seqProperties[s_nOffsetFilter ].Name = HISTORY_PROPERTYNAME_FILTER; + seqProperties[s_nOffsetTitle ].Name = HISTORY_PROPERTYNAME_TITLE; + seqProperties[s_nOffsetPassword ].Name = HISTORY_PROPERTYNAME_PASSWORD; + + try + { + switch( eHistory ) + { + case ePICKLIST: + { + m_xCfg->getByName(s_sPickList) >>= xListAccess; + break; + } + + case eHISTORY: + { + m_xCfg->getByName(s_sURLHistory) >>= xListAccess; + break; + } + + case eHELPBOOKMARKS: + { + m_xCfg->getByName(s_sHelpBookmarks) >>= xListAccess; + break; + } + + default: + break; + } + + if (xListAccess.is()) + { + xListAccess->getByName(s_sItemList) >>= xItemList; + xListAccess->getByName(s_sOrderList) >>= xOrderList; + + const sal_Int32 nLength = xOrderList->getElementNames().getLength(); + Sequence< Sequence< PropertyValue > > aRet(nLength); + + for(sal_Int32 nItem=0; nItem<nLength; ++nItem) + { + ::rtl::OUString sUrl; + xOrderList->getByName(::rtl::OUString::valueOf(nItem)) >>= xSet; + xSet->getPropertyValue(s_sHistoryItemRef) >>= sUrl; + + xItemList->getByName(sUrl) >>= xSet; + seqProperties[s_nOffsetURL ].Value <<= sUrl; + xSet->getPropertyValue(s_sFilter) >>= seqProperties[s_nOffsetFilter ].Value; + xSet->getPropertyValue(s_sTitle) >>= seqProperties[s_nOffsetTitle ].Value; + xSet->getPropertyValue(s_sPassword) >>= seqProperties[s_nOffsetPassword ].Value; + aRet[nItem] = seqProperties; + } + seqReturn = aRet; + } + } + catch(const css::uno::Exception& ex) + { + LogHelper::logIt(ex); + } + + return seqReturn; +} + +//***************************************************************************************************************** +// public method +// implements a deque in XML +//***************************************************************************************************************** +void SvtHistoryOptions_Impl::AppendItem( EHistoryType eHistory , + const OUString& sURL , + const OUString& sFilter , + const OUString& sTitle , + const OUString& sPassword ) +{ + impl_truncateList (eHistory, GetSize (eHistory)); + + css::uno::Reference< css::container::XNameAccess > xListAccess; + sal_Int32 nMaxSize = 0; + + switch(eHistory) + { + case ePICKLIST: + { + m_xCfg->getByName(s_sPickList) >>= xListAccess; + nMaxSize = GetSize(ePICKLIST); + } + break; + case eHISTORY: + { + m_xCfg->getByName(s_sURLHistory) >>= xListAccess; + nMaxSize = GetSize(eHISTORY); + } + break; + case eHELPBOOKMARKS: + { + m_xCfg->getByName(s_sHelpBookmarks) >>= xListAccess; + nMaxSize = GetSize(eHELPBOOKMARKS); + } + break; + default: + break; + } + + if (nMaxSize==0) + return; + + css::uno::Reference< css::container::XNameContainer > xItemList; + css::uno::Reference< css::container::XNameContainer > xOrderList; + css::uno::Reference< css::beans::XPropertySet > xSet; + + try + { + xListAccess->getByName(s_sItemList) >>= xItemList; + xListAccess->getByName(s_sOrderList) >>= xOrderList; + sal_Int32 nLength = xOrderList->getElementNames().getLength(); + + // The item to be appended is already existing! + if (xItemList->hasByName(sURL)) + { + for (sal_Int32 i=0; i<nLength; ++i) + { + ::rtl::OUString sTmp; + xOrderList->getByName(::rtl::OUString::valueOf(i)) >>= xSet; + xSet->getPropertyValue(s_sHistoryItemRef) >>= sTmp; + + if(sURL == sTmp) + { + ::rtl::OUString sFind; + xOrderList->getByName( ::rtl::OUString::valueOf(i) ) >>= xSet; + xSet->getPropertyValue(s_sHistoryItemRef) >>= sFind; + for (sal_Int32 j=i-1; j>=0; --j) + { + css::uno::Reference< css::beans::XPropertySet > xPrevSet; + css::uno::Reference< css::beans::XPropertySet > xNextSet; + xOrderList->getByName( ::rtl::OUString::valueOf(j+1) ) >>= xPrevSet; + xOrderList->getByName( ::rtl::OUString::valueOf(j) ) >>= xNextSet; + + ::rtl::OUString sTemp; + xNextSet->getPropertyValue(s_sHistoryItemRef) >>= sTemp; + xPrevSet->setPropertyValue(s_sHistoryItemRef, css::uno::makeAny(sTemp)); + } + xOrderList->getByName( ::rtl::OUString::valueOf((sal_Int32)0) ) >>= xSet; + xSet->setPropertyValue(s_sHistoryItemRef, css::uno::makeAny(sFind)); + + ::comphelper::ConfigurationHelper::flush(m_xCfg); + break; + } + } + } + + // The item to be appended is not existing! + else + { + css::uno::Reference< css::lang::XSingleServiceFactory > xFac; + css::uno::Reference< css::uno::XInterface > xInst; + css::uno::Reference< css::beans::XPropertySet > xPrevSet; + css::uno::Reference< css::beans::XPropertySet > xNextSet; + + // Append new item to OrderList. + if ( nLength == nMaxSize ) + { + ::rtl::OUString sRemove; + xOrderList->getByName(::rtl::OUString::valueOf(nLength-1)) >>= xSet; + xSet->getPropertyValue(s_sHistoryItemRef) >>= sRemove; + xItemList->removeByName(sRemove); + } + if ( nLength != nMaxSize ) + { + xFac = css::uno::Reference< css::lang::XSingleServiceFactory >(xOrderList, css::uno::UNO_QUERY); + xInst = xFac->createInstance(); + ::rtl::OUString sPush = ::rtl::OUString::valueOf(nLength++); + xOrderList->insertByName(sPush, css::uno::makeAny(xInst)); + } + for (sal_Int32 j=nLength-1; j>0; --j) + { + xOrderList->getByName( ::rtl::OUString::valueOf(j) ) >>= xPrevSet; + xOrderList->getByName( ::rtl::OUString::valueOf(j-1) ) >>= xNextSet; + ::rtl::OUString sTemp; + xNextSet->getPropertyValue(s_sHistoryItemRef) >>= sTemp; + xPrevSet->setPropertyValue(s_sHistoryItemRef, css::uno::makeAny(sTemp)); + } + xOrderList->getByName( ::rtl::OUString::valueOf((sal_Int32)0) ) >>= xSet; + xSet->setPropertyValue(s_sHistoryItemRef, css::uno::makeAny(sURL)); + + // Append the item to ItemList. + xFac = css::uno::Reference< css::lang::XSingleServiceFactory >(xItemList, css::uno::UNO_QUERY); + xInst = xFac->createInstance(); + xItemList->insertByName(sURL, css::uno::makeAny(xInst)); + xSet = css::uno::Reference< css::beans::XPropertySet >(xInst, css::uno::UNO_QUERY); + xSet->setPropertyValue(s_sFilter, css::uno::makeAny(sFilter)); + xSet->setPropertyValue(s_sTitle, css::uno::makeAny(sTitle)); + xSet->setPropertyValue(s_sPassword, css::uno::makeAny(sPassword)); + + ::comphelper::ConfigurationHelper::flush(m_xCfg); + } + } + catch(const css::uno::Exception& ex) + { + LogHelper::logIt(ex); + } +} + +//***************************************************************************************************************** +// initialize static member +// DON'T DO IT IN YOUR HEADER! +// see definition for further informations +//***************************************************************************************************************** +SvtHistoryOptions_Impl* SvtHistoryOptions::m_pDataContainer = NULL ; +sal_Int32 SvtHistoryOptions::m_nRefCount = 0 ; + +//***************************************************************************************************************** +// constructor +//***************************************************************************************************************** +SvtHistoryOptions::SvtHistoryOptions() +{ + // Global access, must be guarded (multithreading!). + MutexGuard aGuard( GetOwnStaticMutex() ); + // Increase ouer refcount ... + ++m_nRefCount; + // ... and initialize ouer data container only if it not already exist! + if( m_pDataContainer == NULL ) + { + RTL_LOGFILE_CONTEXT(aLog, "unotools ( ??? ) ::SvtHistoryOptions_Impl::ctor()"); + m_pDataContainer = new SvtHistoryOptions_Impl; + + ItemHolder1::holdConfigItem(E_HISTORYOPTIONS); + } +} + +//***************************************************************************************************************** +// destructor +//***************************************************************************************************************** +SvtHistoryOptions::~SvtHistoryOptions() +{ + // Global access, must be guarded (multithreading!) + MutexGuard aGuard( GetOwnStaticMutex() ); + // Decrease ouer refcount. + --m_nRefCount; + // If last instance was deleted ... + // we must destroy ouer static data container! + if( m_nRefCount <= 0 ) + { + delete m_pDataContainer; + m_pDataContainer = NULL; + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_uInt32 SvtHistoryOptions::GetSize( EHistoryType eHistory ) const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->GetSize( eHistory ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtHistoryOptions::SetSize( EHistoryType eHistory, sal_uInt32 nSize ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetSize( eHistory, nSize ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtHistoryOptions::Clear( EHistoryType eHistory ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->Clear( eHistory ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +Sequence< Sequence< PropertyValue > > SvtHistoryOptions::GetList( EHistoryType eHistory ) const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->GetList( eHistory ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtHistoryOptions::AppendItem( EHistoryType eHistory , + const OUString& sURL , + const OUString& sFilter , + const OUString& sTitle , + const OUString& sPassword ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->AppendItem( eHistory, sURL, sFilter, sTitle, sPassword ); +} + +//***************************************************************************************************************** +// private method +//***************************************************************************************************************** +Mutex& SvtHistoryOptions::GetOwnStaticMutex() +{ + // Initialize static mutex only for one time! + static Mutex* pMutex = NULL; + // If these method first called (Mutex not already exist!) ... + if( pMutex == NULL ) + { + // ... we must create a new one. Protect follow code with the global mutex - + // It must be - we create a static variable! + MutexGuard aGuard( Mutex::getGlobalMutex() ); + // We must check our pointer again - because it can be that another instance of ouer class will be fastr then these! + if( pMutex == NULL ) + { + // Create the new mutex and set it for return on static variable. + static Mutex aMutex; + pMutex = &aMutex; + } + } + // Return new created or already existing mutex object. + return *pMutex; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/inetoptions.cxx b/unotools/source/config/inetoptions.cxx new file mode 100644 index 000000000000..bc6f3c493aff --- /dev/null +++ b/unotools/source/config/inetoptions.cxx @@ -0,0 +1,555 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" +#include <unotools/inetoptions.hxx> +#include "rtl/instance.hxx" +#include <tools/urlobj.hxx> +#include <tools/wldcrd.hxx> + +#include <algorithm> +#include <map> +#include <set> +#include <vector> +#include <utility> +#include <com/sun/star/beans/PropertyChangeEvent.hpp> +#include <com/sun/star/beans/XPropertiesChangeListener.hpp> +#include <com/sun/star/lang/XMultiServiceFactory.hpp> +#include <com/sun/star/system/XProxySettings.hpp> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Exception.hpp> +#include <com/sun/star/uno/Reference.hxx> +#include <com/sun/star/uno/RuntimeException.hpp> +#include <osl/mutex.hxx> +#include <rtl/ustring.h> +#include <rtl/ustring.hxx> +#include <sal/types.h> +#include <unotools/configitem.hxx> +#include <unotools/processfactory.hxx> +#include <osl/diagnose.h> +#include <salhelper/refobj.hxx> +#include <rtl/logfile.hxx> +#include "itemholder1.hxx" + +using namespace com::sun; + +//============================================================================ +// +// takeAny +// +//============================================================================ + +namespace { + +template< typename T > inline T takeAny(star::uno::Any const & rAny) +{ + T aValue = T(); + rAny >>= aValue; + return aValue; +} + +} + +//============================================================================ +// +// SvtInetOptions::Impl +// +//============================================================================ + +class SvtInetOptions::Impl: public salhelper::ReferenceObject, + public utl::ConfigItem +{ +public: + enum Index + { + INDEX_NO_PROXY, + INDEX_PROXY_TYPE, + INDEX_FTP_PROXY_NAME, + INDEX_FTP_PROXY_PORT, + INDEX_HTTP_PROXY_NAME, + INDEX_HTTP_PROXY_PORT + }; + + Impl(); + + star::uno::Any getProperty(Index nIndex); + + void + setProperty(Index nIndex, star::uno::Any const & rValue, bool bFlush); + + inline void flush() { Commit(); } + + void + addPropertiesChangeListener( + star::uno::Sequence< rtl::OUString > const & rPropertyNames, + star::uno::Reference< star::beans::XPropertiesChangeListener > const & + rListener); + + void + removePropertiesChangeListener( + star::uno::Sequence< rtl::OUString > const & rPropertyNames, + star::uno::Reference< star::beans::XPropertiesChangeListener > const & + rListener); + +private: + enum { ENTRY_COUNT = INDEX_HTTP_PROXY_PORT + 1 }; + + struct Entry + { + enum State { UNKNOWN, KNOWN, MODIFIED }; + + inline Entry(): m_eState(UNKNOWN) {} + + rtl::OUString m_aName; + star::uno::Any m_aValue; + State m_eState; + }; + + // MSVC has problems with the below Map type when + // star::uno::Reference< star::beans::XPropertiesChangeListener > is not + // wrapped in class Listener: + class Listener: + public star::uno::Reference< star::beans::XPropertiesChangeListener > + { + public: + Listener(star::uno::Reference< + star::beans::XPropertiesChangeListener > const & + rListener): + star::uno::Reference< star::beans::XPropertiesChangeListener >( + rListener) + {} + }; + + typedef std::map< Listener, std::set< rtl::OUString > > Map; + + osl::Mutex m_aMutex; + Entry m_aEntries[ENTRY_COUNT]; + Map m_aListeners; + + virtual inline ~Impl() { Commit(); } + + virtual void Notify(star::uno::Sequence< rtl::OUString > const & rKeys); + + virtual void Commit(); + + void notifyListeners(star::uno::Sequence< rtl::OUString > const & rKeys); +}; + +//============================================================================ +// virtual +void +SvtInetOptions::Impl::Notify(star::uno::Sequence< rtl::OUString > const & + rKeys) +{ + { + osl::MutexGuard aGuard(m_aMutex); + for (sal_Int32 i = 0; i < rKeys.getLength(); ++i) + for (sal_Int32 j = 0; j < ENTRY_COUNT; ++j) + if (rKeys[i] == m_aEntries[j].m_aName) + { + m_aEntries[j].m_eState = Entry::UNKNOWN; + break; + } + } + notifyListeners(rKeys); +} + +//============================================================================ +// virtual +void SvtInetOptions::Impl::Commit() +{ + star::uno::Sequence< rtl::OUString > aKeys(ENTRY_COUNT); + star::uno::Sequence< star::uno::Any > aValues(ENTRY_COUNT); + sal_Int32 nCount = 0; + { + osl::MutexGuard aGuard(m_aMutex); + for (sal_Int32 i = 0; i < ENTRY_COUNT; ++i) + if (m_aEntries[i].m_eState == Entry::MODIFIED) + { + aKeys[nCount] = m_aEntries[i].m_aName; + aValues[nCount] = m_aEntries[i].m_aValue; + ++nCount; + m_aEntries[i].m_eState = Entry::KNOWN; + } + } + if (nCount > 0) + { + aKeys.realloc(nCount); + aValues.realloc(nCount); + PutProperties(aKeys, aValues); + } +} + +//============================================================================ +void +SvtInetOptions::Impl::notifyListeners( + star::uno::Sequence< rtl::OUString > const & rKeys) +{ + typedef + std::vector< std::pair< star::uno::Reference< + star::beans::XPropertiesChangeListener >, + star::uno::Sequence< + star::beans::PropertyChangeEvent > > > + List; + List aNotifications; + { + osl::MutexGuard aGuard(m_aMutex); + aNotifications.reserve(m_aListeners.size()); + Map::const_iterator aMapEnd(m_aListeners.end()); + for (Map::const_iterator aIt(m_aListeners.begin()); aIt != aMapEnd; + ++aIt) + { + const Map::mapped_type &rSet = aIt->second; + Map::mapped_type::const_iterator aSetEnd(rSet.end()); + star::uno::Sequence< star::beans::PropertyChangeEvent > + aEvents(rKeys.getLength()); + sal_Int32 nCount = 0; + for (sal_Int32 i = 0; i < rKeys.getLength(); ++i) + { + rtl::OUString + aTheKey(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( + "Inet/"))); + aTheKey += rKeys[i]; + if (rSet.find(aTheKey) != aSetEnd) + { + aEvents[nCount].PropertyName = aTheKey; + aEvents[nCount].PropertyHandle = -1; + ++nCount; + } + } + if (nCount > 0) + { + aEvents.realloc(nCount); + aNotifications. + push_back(std::pair< List::value_type::first_type, + List::value_type::second_type >( + aIt->first, aEvents)); + } + } + } + for (List::size_type i = 0; i < aNotifications.size(); ++i) + if (aNotifications[i].first.is()) + aNotifications[i].first-> + propertiesChange(aNotifications[i].second); +} + +//============================================================================ +SvtInetOptions::Impl::Impl(): + ConfigItem(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Inet/Settings"))) +{ + m_aEntries[INDEX_NO_PROXY].m_aName + = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ooInetNoProxy")); + m_aEntries[INDEX_PROXY_TYPE].m_aName + = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ooInetProxyType")); + m_aEntries[INDEX_FTP_PROXY_NAME].m_aName + = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ooInetFTPProxyName")); + m_aEntries[INDEX_FTP_PROXY_PORT].m_aName + = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ooInetFTPProxyPort")); + m_aEntries[INDEX_HTTP_PROXY_NAME].m_aName + = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ooInetHTTPProxyName")); + m_aEntries[INDEX_HTTP_PROXY_PORT].m_aName + = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ooInetHTTPProxyPort")); + + star::uno::Sequence< rtl::OUString > aKeys(ENTRY_COUNT); + for (sal_Int32 i = 0; i < ENTRY_COUNT; ++i) + aKeys[i] = m_aEntries[i].m_aName; + if (!EnableNotification(aKeys)) + OSL_ENSURE(false, + "SvtInetOptions::Impl::Impl(): Bad EnableNotifications()"); +} + +//============================================================================ +star::uno::Any SvtInetOptions::Impl::getProperty(Index nPropIndex) +{ + for (int nTryCount = 0; nTryCount < 10; ++nTryCount) + { + { + osl::MutexGuard aGuard(m_aMutex); + if (m_aEntries[nPropIndex].m_eState != Entry::UNKNOWN) + return m_aEntries[nPropIndex].m_aValue; + } + star::uno::Sequence< rtl::OUString > aKeys(ENTRY_COUNT); + int nIndices[ENTRY_COUNT]; + sal_Int32 nCount = 0; + { + osl::MutexGuard aGuard(m_aMutex); + for (int i = 0; i < ENTRY_COUNT; ++i) + if (m_aEntries[i].m_eState == Entry::UNKNOWN) + { + aKeys[nCount] = m_aEntries[i].m_aName; + nIndices[nCount] = i; + ++nCount; + } + } + if (nCount > 0) + { + aKeys.realloc(nCount); + star::uno::Sequence< star::uno::Any > + aValues(GetProperties(aKeys)); + OSL_ENSURE(aValues.getLength() == nCount, + "SvtInetOptions::Impl::getProperty():" + " Bad GetProperties() result"); + nCount = std::min(nCount, aValues.getLength()); + { + osl::MutexGuard aGuard(m_aMutex); + for (sal_Int32 i = 0; i < nCount; ++i) + { + int nIndex = nIndices[i]; + if (m_aEntries[nIndex].m_eState == Entry::UNKNOWN) + { + m_aEntries[nIndices[i]].m_aValue = aValues[i]; + m_aEntries[nIndices[i]].m_eState = Entry::KNOWN; + } + } + } + } + } + OSL_ENSURE(false, + "SvtInetOptions::Impl::getProperty(): Possible life lock"); + { + osl::MutexGuard aGuard(m_aMutex); + return m_aEntries[nPropIndex].m_aValue; + } +} + +//============================================================================ +void SvtInetOptions::Impl::setProperty(Index nIndex, + star::uno::Any const & rValue, + bool bFlush) +{ + SetModified(); + { + osl::MutexGuard aGuard(m_aMutex); + m_aEntries[nIndex].m_aValue = rValue; + m_aEntries[nIndex].m_eState = bFlush ? Entry::KNOWN : Entry::MODIFIED; + } + + star::uno::Sequence< rtl::OUString > aKeys(1); + aKeys[0] = m_aEntries[nIndex].m_aName; + if (bFlush) + { + star::uno::Sequence< star::uno::Any > aValues(1); + aValues[0] = rValue; + PutProperties(aKeys, aValues); + } + else + notifyListeners(aKeys); +} + +//============================================================================ +void +SvtInetOptions::Impl::addPropertiesChangeListener( + star::uno::Sequence< rtl::OUString > const & rPropertyNames, + star::uno::Reference< star::beans::XPropertiesChangeListener > const & + rListener) +{ + osl::MutexGuard aGuard(m_aMutex); + Map::mapped_type & rEntry = m_aListeners[rListener]; + for (sal_Int32 i = 0; i < rPropertyNames.getLength(); ++i) + rEntry.insert(rPropertyNames[i]); +} + +//============================================================================ +void +SvtInetOptions::Impl::removePropertiesChangeListener( + star::uno::Sequence< rtl::OUString > const & rPropertyNames, + star::uno::Reference< star::beans::XPropertiesChangeListener > const & + rListener) +{ + osl::MutexGuard aGuard(m_aMutex); + Map::iterator aIt(m_aListeners.find(rListener)); + if (aIt != m_aListeners.end()) + { + for (sal_Int32 i = 0; i < rPropertyNames.getLength(); ++i) + aIt->second.erase(rPropertyNames[i]); + if (aIt->second.empty()) + m_aListeners.erase(aIt); + } +} + +//============================================================================ +// +// SvtInetOptions +// +//============================================================================ + +namespace +{ + class LocalSingleton : public rtl::Static< osl::Mutex, LocalSingleton > + { + }; +} + +// static +SvtInetOptions::Impl * SvtInetOptions::m_pImpl = 0; + +//============================================================================ +SvtInetOptions::SvtInetOptions() +{ + osl::MutexGuard aGuard(LocalSingleton::get()); + if (!m_pImpl) + { + RTL_LOGFILE_CONTEXT(aLog, "unotools ( ??? ) ::SvtInetOptions_Impl::ctor()"); + m_pImpl = new Impl; + + ItemHolder1::holdConfigItem(E_INETOPTIONS); + } + m_pImpl->acquire(); +} + +//============================================================================ +SvtInetOptions::~SvtInetOptions() +{ + osl::MutexGuard aGuard(LocalSingleton::get()); + if (m_pImpl->release() == 0) + m_pImpl = 0; +} + +//============================================================================ +rtl::OUString SvtInetOptions::GetProxyNoProxy() const +{ + return takeAny< rtl::OUString >(m_pImpl-> + getProperty(Impl::INDEX_NO_PROXY)); +} + +//============================================================================ +sal_Int32 SvtInetOptions::GetProxyType() const +{ + return takeAny< sal_Int32 >(m_pImpl-> + getProperty(Impl::INDEX_PROXY_TYPE)); +} + +//============================================================================ +rtl::OUString SvtInetOptions::GetProxyFtpName() const +{ + return takeAny< rtl::OUString >(m_pImpl-> + getProperty( + Impl::INDEX_FTP_PROXY_NAME)); +} + +//============================================================================ +sal_Int32 SvtInetOptions::GetProxyFtpPort() const +{ + return takeAny< sal_Int32 >(m_pImpl-> + getProperty(Impl::INDEX_FTP_PROXY_PORT)); +} + +//============================================================================ +rtl::OUString SvtInetOptions::GetProxyHttpName() const +{ + return takeAny< rtl::OUString >(m_pImpl-> + getProperty( + Impl::INDEX_HTTP_PROXY_NAME)); +} + +//============================================================================ +sal_Int32 SvtInetOptions::GetProxyHttpPort() const +{ + return takeAny< sal_Int32 >(m_pImpl-> + getProperty(Impl::INDEX_HTTP_PROXY_PORT)); +} + +//============================================================================ +void SvtInetOptions::SetProxyNoProxy(rtl::OUString const & rValue, + bool bFlush) +{ + m_pImpl->setProperty(Impl::INDEX_NO_PROXY, + star::uno::makeAny(rValue), + bFlush); +} + +//============================================================================ +void SvtInetOptions::SetProxyType(ProxyType eValue, bool bFlush) +{ + m_pImpl->setProperty(Impl::INDEX_PROXY_TYPE, + star::uno::makeAny(sal_Int32(eValue)), + bFlush); +} + +//============================================================================ +void SvtInetOptions::SetProxyFtpName(rtl::OUString const & rValue, + bool bFlush) +{ + m_pImpl->setProperty(Impl::INDEX_FTP_PROXY_NAME, + star::uno::makeAny(rValue), + bFlush); +} + +//============================================================================ +void SvtInetOptions::SetProxyFtpPort(sal_Int32 nValue, bool bFlush) +{ + m_pImpl->setProperty(Impl::INDEX_FTP_PROXY_PORT, + star::uno::makeAny(nValue), + bFlush); +} + +//============================================================================ +void SvtInetOptions::SetProxyHttpName(rtl::OUString const & rValue, + bool bFlush) +{ + m_pImpl->setProperty(Impl::INDEX_HTTP_PROXY_NAME, + star::uno::makeAny(rValue), + bFlush); +} + +//============================================================================ +void SvtInetOptions::SetProxyHttpPort(sal_Int32 nValue, bool bFlush) +{ + m_pImpl->setProperty(Impl::INDEX_HTTP_PROXY_PORT, + star::uno::makeAny(nValue), + bFlush); +} + +//============================================================================ +void SvtInetOptions::flush() +{ + m_pImpl->flush(); +} + +//============================================================================ +void +SvtInetOptions::addPropertiesChangeListener( + star::uno::Sequence< rtl::OUString > const & rPropertyNames, + star::uno::Reference< star::beans::XPropertiesChangeListener > const & + rListener) +{ + m_pImpl->addPropertiesChangeListener(rPropertyNames, rListener); +} + +//============================================================================ +void +SvtInetOptions::removePropertiesChangeListener( + star::uno::Sequence< rtl::OUString > const & rPropertyNames, + star::uno::Reference< star::beans::XPropertiesChangeListener > const & + rListener) +{ + m_pImpl->removePropertiesChangeListener(rPropertyNames, rListener); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/internaloptions.cxx b/unotools/source/config/internaloptions.cxx new file mode 100644 index 000000000000..d1501a612128 --- /dev/null +++ b/unotools/source/config/internaloptions.cxx @@ -0,0 +1,588 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" + +#include <deque> + +#include <unotools/internaloptions.hxx> +#include <unotools/configmgr.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/beans/PropertyValue.hpp> + +#include <rtl/logfile.hxx> +#include "itemholder1.hxx" + +//_________________________________________________________________________________________________________________ +// namespaces +//_________________________________________________________________________________________________________________ + +using namespace ::utl ; +using namespace ::rtl ; +using namespace ::osl ; +using namespace ::std ; +using namespace ::com::sun::star::uno ; +using namespace ::com::sun::star::beans ; + +//_________________________________________________________________________________________________________________ +// const +//_________________________________________________________________________________________________________________ + +#define ROOTNODE_INTERNAL OUString(RTL_CONSTASCII_USTRINGPARAM("Office.Common/Internal" )) +#define DEFAULT_SLOTCFG sal_False +#define DEFAULT_SENDCRASHMAIL sal_False +#define DEFAULT_USEMAILUI sal_True +#define DEFAULT_CURRENTTEMPURL OUString(RTL_CONSTASCII_USTRINGPARAM("")) + +#define FIXPROPERTYNAME_SLOTCFG OUString(RTL_CONSTASCII_USTRINGPARAM("Slot" )) +#define FIXPROPERTYNAME_SENDCRASHMAIL OUString(RTL_CONSTASCII_USTRINGPARAM("SendCrashMail" )) +#define FIXPROPERTYNAME_USEMAILUI OUString(RTL_CONSTASCII_USTRINGPARAM("UseMailUI" )) +#define FIXPROPERTYNAME_CURRENTTEMPURL OUString(RTL_CONSTASCII_USTRINGPARAM("CurrentTempURL" )) +//#define FIXPROPERTYNAME_REMOVEMENUENTRYCLOSE OUString(RTL_CONSTASCII_USTRINGPARAM("RemoveMenuEntryClose")) +//#define FIXPROPERTYNAME_REMOVEMENUENTRYBACKTOWEBTOP OUString(RTL_CONSTASCII_USTRINGPARAM("RemoveMenuEntryBackToWebtop")) +//#define FIXPROPERTYNAME_REMOVEMENUENTRYNEWWEBTOP OUString(RTL_CONSTASCII_USTRINGPARAM("RemoveMenuEntryNewWebtop")) +//#define FIXPROPERTYNAME_REMOVEMENUENTRYLOGOUT OUString(RTL_CONSTASCII_USTRINGPARAM("RemoveMenuEntryLogout")) + +#define FIXPROPERTYHANDLE_SLOTCFG 0 +#define FIXPROPERTYHANDLE_SENDCRASHMAIL 1 +#define FIXPROPERTYHANDLE_USEMAILUI 2 +#define FIXPROPERTYHANDLE_CURRENTTEMPURL 3 +//#define FIXPROPERTYHANDLE_REMOVEMENUENTRYCLOSE 3 +//#define FIXPROPERTYHANDLE_REMOVEMENUENTRYBACKTOWEBTOP 4 +//#define FIXPROPERTYHANDLE_REMOVEMENUENTRYNEWWEBTOP 5 +//#define FIXPROPERTYHANDLE_REMOVEMENUENTRYLOGOUT 6 + +#define FIXPROPERTYCOUNT 4 +/* +#define PROPERTYNAME_RECOVERYLIST OUString(RTL_CONSTASCII_USTRINGPARAM("RecoveryList" )) +#define PROPERTYNAME_URL OUString(RTL_CONSTASCII_USTRINGPARAM("OrgURL" )) +#define PROPERTYNAME_FILTER OUString(RTL_CONSTASCII_USTRINGPARAM("FilterName" )) +#define PROPERTYNAME_TEMPNAME OUString(RTL_CONSTASCII_USTRINGPARAM("TempURL" )) + +#define OFFSET_URL 0 +#define OFFSET_FILTER 1 +#define OFFSET_TEMPNAME 2 +*/ +#define PATHDELIMITER OUString(RTL_CONSTASCII_USTRINGPARAM("/" )) +#define FIXR OUString(RTL_CONSTASCII_USTRINGPARAM("r" )) + +//_________________________________________________________________________________________________________________ +// private declarations! +//_________________________________________________________________________________________________________________ +/* +struct tIMPL_RecoveryEntry +{ + OUString sURL ; + OUString sFilter ; + OUString sTempName ; + + tIMPL_RecoveryEntry() + { + sURL = OUString(); + sFilter = OUString(); + sTempName = OUString(); + } + + tIMPL_RecoveryEntry( const OUString& sNewURL , + const OUString& sNewFilter , + const OUString& sNewTempName ) + { + sURL = sNewURL ; + sFilter = sNewFilter ; + sTempName = sNewTempName ; + } +}; + +typedef deque< tIMPL_RecoveryEntry > tIMPL_RecoveryStack; +*/ +class SvtInternalOptions_Impl : public ConfigItem +{ + //------------------------------------------------------------------------------------------------------------- + // private member + //------------------------------------------------------------------------------------------------------------- + + private: + + sal_Bool m_bRemoveMenuEntryClose; + sal_Bool m_bRemoveMenuEntryBackToWebtop; + sal_Bool m_bRemoveMenuEntryNewWebtop; + sal_Bool m_bRemoveMenuEntryLogout; + sal_Bool m_bSlotCFG ; /// cache "Slot" of Internal section + sal_Bool m_bSendCrashMail ; /// cache "SendCrashMail" of Internal section + sal_Bool m_bUseMailUI; + OUString m_aCurrentTempURL ; + // tIMPL_RecoveryStack m_aRecoveryList ; /// cache "RecoveryList" of Internal section + //------------------------------------------------------------------------------------------------------------- + // public methods + //------------------------------------------------------------------------------------------------------------- + + public: + + //--------------------------------------------------------------------------------------------------------- + // constructor / destructor + //--------------------------------------------------------------------------------------------------------- + + SvtInternalOptions_Impl(); + ~SvtInternalOptions_Impl(); + + //--------------------------------------------------------------------------------------------------------- + // overloaded methods of baseclass + //--------------------------------------------------------------------------------------------------------- + + /*-****************************************************************************************************//** + @short called for notify of configmanager + @descr These method is called from the ConfigManager before application ends or from the + PropertyChangeListener if the sub tree broadcasts changes. You must update your + internal values. + + @seealso baseclass ConfigItem + + @param "seqPropertyNames" is the list of properties which should be updated. + @return - + + @onerror - + *//*-*****************************************************************************************************/ + + virtual void Notify( const Sequence< OUString >& ) + { + DBG_ASSERT( sal_False, "SvtInternalOptions::Notify()\nNot used yet ... but called!?\n" ); + } + + /*-****************************************************************************************************//** + @short write changes to configuration + @descr These method writes the changed values into the sub tree + and should always called in our destructor to guarantee consistency of config data. + + @seealso baseclass ConfigItem + + @param - + @return - + + @onerror - + *//*-*****************************************************************************************************/ + + virtual void Commit(); + + //--------------------------------------------------------------------------------------------------------- + // public interface + //--------------------------------------------------------------------------------------------------------- + + /*-****************************************************************************************************//** + @short access method to get internal values + @descr These method give us a chance to regulate acces to ouer internal values. + It's not used in the moment - but it's possible for the feature! + + @seealso - + + @param - + @return - + + @onerror - + *//*-*****************************************************************************************************/ + + sal_Bool IsRemoveMenuEntryClose() const { return m_bRemoveMenuEntryClose; } + sal_Bool IsRemoveMenuEntryBackToWebtop() const { return m_bRemoveMenuEntryBackToWebtop; } + sal_Bool IsRemoveMenuEntryNewWebtop() const { return m_bRemoveMenuEntryNewWebtop; } + sal_Bool IsRemoveMenuEntryLogout() const { return m_bRemoveMenuEntryLogout; } + sal_Bool SlotCFGEnabled () const { return m_bSlotCFG; } + sal_Bool CrashMailEnabled () const { return m_bSendCrashMail; } + sal_Bool MailUIEnabled () const { return m_bUseMailUI; } + + OUString GetCurrentTempURL() const { return m_aCurrentTempURL; } + void SetCurrentTempURL( const OUString& aNewCurrentTempURL ); +/* + void PushRecoveryItem ( const OUString& sURL , + const OUString& sFilter , + const OUString& sTempName ); + void PopRecoveryItem ( OUString& sURL , + OUString& sFilter , + OUString& sTempName ); + sal_Bool IsRecoveryListEmpty ( ) const; +*/ + //------------------------------------------------------------------------------------------------------------- + // private methods + //------------------------------------------------------------------------------------------------------------- + + private: + + /*-****************************************************************************************************//** + @short return list of fix key names of ouer configuration management which represent oue module tree + @descr These methods return a static const list of key names. We need it to get needed values from our + configuration management. We return well known key names only - because the "UserData" node + is handled in a special way! + + @seealso - + + @param - + @return A list of needed configuration keys is returned. + + @onerror - + *//*-*****************************************************************************************************/ + + Sequence< OUString > impl_GetPropertyNames(); +}; + +//_________________________________________________________________________________________________________________ +// definitions +//_________________________________________________________________________________________________________________ + +//***************************************************************************************************************** +// constructor +//***************************************************************************************************************** +SvtInternalOptions_Impl::SvtInternalOptions_Impl() + // Init baseclasses first + : ConfigItem ( ROOTNODE_INTERNAL, CONFIG_MODE_IMMEDIATE_UPDATE ) + // Init member then. + , m_bRemoveMenuEntryClose ( sal_False ) + , m_bRemoveMenuEntryBackToWebtop ( sal_False ) + , m_bRemoveMenuEntryNewWebtop ( sal_False ) + , m_bRemoveMenuEntryLogout ( sal_False ) + , m_bSlotCFG ( DEFAULT_SLOTCFG ) + , m_bSendCrashMail ( DEFAULT_SENDCRASHMAIL ) + , m_bUseMailUI ( DEFAULT_USEMAILUI ) + , m_aCurrentTempURL ( DEFAULT_CURRENTTEMPURL ) +{ + // Use our list of configuration keys to get his values. + // structure of internal section: (first 2 entries are fixed - all other are member of a set!) + // "Slot" + // "SendCrashMail" + // "RecoveryList/r1/URL" + // "RecoveryList/r1/Filter" + // "RecoveryList/r1/TempName" + // "RecoveryList/r2/URL" + // "RecoveryList/r2/Filter" + // "RecoveryList/r2/TempName" + // "RecoveryList/.." + Sequence< OUString > seqNames = impl_GetPropertyNames() ; + Sequence< Any > seqValues = GetProperties( seqNames ) ; + + // 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( !(seqNames.getLength()!=seqValues.getLength()), "SvtInternalOptions_Impl::SvtInternalOptions_Impl()\nI miss some values of configuration keys!\n" ); + + // Read fixed values first! + DBG_ASSERT(!(seqValues[FIXPROPERTYHANDLE_SLOTCFG].getValueTypeClass()!=TypeClass_BOOLEAN) , "SvtInternalOptions_Impl::SvtInternalOptions_Impl()\nWho has changed the value type of \"Office.Common\\Internal\\Slot\"?" ); + DBG_ASSERT(!(seqValues[FIXPROPERTYHANDLE_SENDCRASHMAIL].getValueTypeClass()!=TypeClass_BOOLEAN) , "SvtInternalOptions_Impl::SvtInternalOptions_Impl()\nWho has changed the value type of \"Office.Common\\Internal\\SendCrashMail\"?" ); + seqValues[FIXPROPERTYHANDLE_SLOTCFG ] >>= m_bSlotCFG ; + seqValues[FIXPROPERTYHANDLE_SENDCRASHMAIL ] >>= m_bSendCrashMail ; + seqValues[FIXPROPERTYHANDLE_USEMAILUI ] >>= m_bUseMailUI ; + seqValues[FIXPROPERTYHANDLE_CURRENTTEMPURL ] >>= m_aCurrentTempURL ; +// seqValues[FIXPROPERTYHANDLE_REMOVEMENUENTRYCLOSE ] >>= m_bRemoveMenuEntryClose ; +// seqValues[FIXPROPERTYHANDLE_REMOVEMENUENTRYBACKTOWEBTOP ] >>= m_bRemoveMenuEntryBackToWebtop ; +// seqValues[FIXPROPERTYHANDLE_REMOVEMENUENTRYNEWWEBTOP ] >>= m_bRemoveMenuEntryNewWebtop ; +// seqValues[FIXPROPERTYHANDLE_REMOVEMENUENTRYLOGOUT ] >>= m_bRemoveMenuEntryLogout ; +/* + // Read dynamical set "RecoveryList" then. + // 3 subkeys for every item! + // Attention: Start at next element after last fixed entry! We must ignore "Slot" and "SendCrashMail" ... + tIMPL_RecoveryEntry aEntry; + sal_uInt32 nCount = seqValues.getLength() ; + sal_uInt32 nPosition = FIXPROPERTYCOUNT ; + + while( nPosition<nCount ) + { + seqValues[nPosition] >>= aEntry.sURL ; + ++nPosition; + seqValues[nPosition] >>= aEntry.sFilter ; + ++nPosition; + seqValues[nPosition] >>= aEntry.sTempName ; + ++nPosition; + m_aRecoveryList.push_front( aEntry ); + } +*/ + // We don't need any notifications here. + // "Slot" and "SendCrashMail" are readonly(!) and our recovery list should not modified during runtime - it's used + // by our crash guard only ... otherwise we have a big problem. +} + +//***************************************************************************************************************** +// destructor +//***************************************************************************************************************** +SvtInternalOptions_Impl::~SvtInternalOptions_Impl() +{ + if( IsModified() == sal_True ) + { + Commit(); + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtInternalOptions_Impl::Commit() +{ + // We have to write our current temp URL + Sequence< OUString > aNames( 1 ); + OUString* pNames = aNames.getArray(); + Sequence< Any > aValues( 1 ); + Any* pValues = aValues.getArray(); + + pNames[0] = FIXPROPERTYNAME_CURRENTTEMPURL; + pValues[0] <<= m_aCurrentTempURL; + + PutProperties( aNames, aValues ); + +/* + // Write set of dynamic properties then. + ClearNodeSet( PROPERTYNAME_RECOVERYLIST ); + + tIMPL_RecoveryEntry aItem ; + OUString sNode ; + Sequence< PropertyValue > seqPropertyValues( 3 ) ; // Every node in set has 3 sub-nodes!( url, filter, tempname ) + + // Copy list entries to save-list and write it to configuration. + + sal_uInt32 nCount = m_aRecoveryList.size(); + for( sal_uInt32 nItem=0; nItem<nCount; ++nItem ) + { + aItem = m_aRecoveryList.top(); + m_aRecoveryList.pop(); + sNode = PROPERTYNAME_RECOVERYLIST + PATHDELIMITER + FIXR + OUString::valueOf( (sal_Int32)nItem ) + PATHDELIMITER; + seqPropertyValues[OFFSET_URL ].Name = sNode + PROPERTYNAME_URL ; + seqPropertyValues[OFFSET_FILTER ].Name = sNode + PROPERTYNAME_FILTER ; + seqPropertyValues[OFFSET_TEMPNAME ].Name = sNode + PROPERTYNAME_TEMPNAME ; + seqPropertyValues[OFFSET_URL ].Value <<= aItem.sURL ; + seqPropertyValues[OFFSET_FILTER ].Value <<= aItem.sFilter ; + seqPropertyValues[OFFSET_TEMPNAME ].Value <<= aItem.sTempName ; + + SetSetProperties( PROPERTYNAME_RECOVERYLIST, seqPropertyValues ); + } + + tIMPL_RecoveryStack::iterator iRecovery = m_aRecoveryList.begin(); + for ( sal_uInt32 nItem=0; iRecovery != m_aRecoveryList.end(); ++nItem, ++iRecovery) + { + aItem = *iRecovery; + sNode = PROPERTYNAME_RECOVERYLIST + PATHDELIMITER + FIXR + + OUString::valueOf( (sal_Int32)nItem ) + PATHDELIMITER; + seqPropertyValues[OFFSET_URL ].Name = sNode + PROPERTYNAME_URL ; + seqPropertyValues[OFFSET_FILTER ].Name = sNode + PROPERTYNAME_FILTER ; + seqPropertyValues[OFFSET_TEMPNAME ].Name = sNode + PROPERTYNAME_TEMPNAME ; + seqPropertyValues[OFFSET_URL ].Value <<= iRecovery->sURL ; + seqPropertyValues[OFFSET_FILTER ].Value <<= iRecovery->sFilter ; + seqPropertyValues[OFFSET_TEMPNAME ].Value <<= iRecovery->sTempName ; + SetSetProperties( PROPERTYNAME_RECOVERYLIST, seqPropertyValues ); + } + + */ +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtInternalOptions_Impl::SetCurrentTempURL( const OUString& aNewCurrentTempURL ) +{ + m_aCurrentTempURL = aNewCurrentTempURL; + SetModified(); + Commit(); +} + +//***************************************************************************************************************** +// private method +//***************************************************************************************************************** +Sequence< OUString > SvtInternalOptions_Impl::impl_GetPropertyNames() +{ + /* + // First get ALL names of current existing list items in configuration! + Sequence< OUString > seqRecoveryItems = GetNodeNames( PROPERTYNAME_RECOVERYLIST ); + // Get information about list counts ... + sal_Int32 nRecoveryCount = seqRecoveryItems.getLength(); + // ... and create a property list with right size! (+2...for fix properties!) (*3 ... = sub nodes for every set node!) + Sequence< OUString > seqProperties( FIXPROPERTYCOUNT + (nRecoveryCount*3) ); + */ + Sequence< OUString > seqProperties(4); + + // Add names of fix properties to list. + seqProperties[FIXPROPERTYHANDLE_SLOTCFG ] = FIXPROPERTYNAME_SLOTCFG ; + seqProperties[FIXPROPERTYHANDLE_SENDCRASHMAIL ] = FIXPROPERTYNAME_SENDCRASHMAIL ; + seqProperties[FIXPROPERTYHANDLE_USEMAILUI ] = FIXPROPERTYNAME_USEMAILUI ; + seqProperties[FIXPROPERTYHANDLE_CURRENTTEMPURL ] = FIXPROPERTYNAME_CURRENTTEMPURL ; +// seqProperties[FIXPROPERTYHANDLE_REMOVEMENUENTRYCLOSE ] = FIXPROPERTYNAME_REMOVEMENUENTRYCLOSE; +// seqProperties[FIXPROPERTYHANDLE_REMOVEMENUENTRYBACKTOWEBTOP ] = FIXPROPERTYNAME_REMOVEMENUENTRYBACKTOWEBTOP; +// seqProperties[FIXPROPERTYHANDLE_REMOVEMENUENTRYNEWWEBTOP ] = FIXPROPERTYNAME_REMOVEMENUENTRYNEWWEBTOP; +// seqProperties[FIXPROPERTYHANDLE_REMOVEMENUENTRYLOGOUT ] = FIXPROPERTYNAME_REMOVEMENUENTRYLOGOUT; +/* + sal_uInt32 nPosition = FIXPROPERTYCOUNT; + // Add names for recovery list to list. + // 3 subkeys for every item! + // nPosition is the start point of an list item, nItem an index into right list of node names! + for( sal_Int32 nItem=0; nItem<nRecoveryCount; ++nItem ) + { + seqProperties[nPosition] = PROPERTYNAME_RECOVERYLIST + PATHDELIMITER + seqRecoveryItems[nItem] + PATHDELIMITER + PROPERTYNAME_URL ; + ++nPosition; + seqProperties[nPosition] = PROPERTYNAME_RECOVERYLIST + PATHDELIMITER + seqRecoveryItems[nItem] + PATHDELIMITER + PROPERTYNAME_FILTER ; + ++nPosition; + seqProperties[nPosition] = PROPERTYNAME_RECOVERYLIST + PATHDELIMITER + seqRecoveryItems[nItem] + PATHDELIMITER + PROPERTYNAME_TEMPNAME ; + ++nPosition; + } +*/ + // Return result. + return seqProperties; +} + +//***************************************************************************************************************** +// initialize static member +// DON'T DO IT IN YOUR HEADER! +// see definition for further informations +//***************************************************************************************************************** +SvtInternalOptions_Impl* SvtInternalOptions::m_pDataContainer = NULL ; +sal_Int32 SvtInternalOptions::m_nRefCount = 0 ; + +//***************************************************************************************************************** +// constructor +//***************************************************************************************************************** +SvtInternalOptions::SvtInternalOptions() +{ + // Global access, must be guarded (multithreading!). + MutexGuard aGuard( GetOwnStaticMutex() ); + // Increase ouer refcount ... + ++m_nRefCount; + // ... and initialize ouer data container only if it not already! + if( m_pDataContainer == NULL ) + { + RTL_LOGFILE_CONTEXT(aLog, "unotools ( ??? ) ::SvtInternalOptions_Impl::ctor()"); + m_pDataContainer = new SvtInternalOptions_Impl(); + + ItemHolder1::holdConfigItem(E_INTERNALOPTIONS); + } +} + +//***************************************************************************************************************** +// destructor +//***************************************************************************************************************** +SvtInternalOptions::~SvtInternalOptions() +{ + // Global access, must be guarded (multithreading!) + MutexGuard aGuard( GetOwnStaticMutex() ); + // Decrease ouer refcount. + --m_nRefCount; + // If last instance was deleted ... + // we must destroy ouer static data container! + if( m_nRefCount <= 0 ) + { + delete m_pDataContainer; + m_pDataContainer = NULL; + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Bool SvtInternalOptions::SlotCFGEnabled() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->SlotCFGEnabled(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Bool SvtInternalOptions::CrashMailEnabled() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->CrashMailEnabled(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Bool SvtInternalOptions::MailUIEnabled() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->MailUIEnabled(); +} + +//***************************************************************************************************************** +// public methods +//***************************************************************************************************************** +sal_Bool SvtInternalOptions::IsRemoveMenuEntryClose() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsRemoveMenuEntryClose(); +} + +sal_Bool SvtInternalOptions::IsRemoveMenuEntryBackToWebtop() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsRemoveMenuEntryBackToWebtop(); +} + +sal_Bool SvtInternalOptions::IsRemoveMenuEntryNewWebtop() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsRemoveMenuEntryNewWebtop(); +} + +sal_Bool SvtInternalOptions::IsRemoveMenuEntryLogout() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsRemoveMenuEntryLogout(); +} + +OUString SvtInternalOptions::GetCurrentTempURL() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->GetCurrentTempURL(); +} + +void SvtInternalOptions::SetCurrentTempURL( const OUString& aNewCurrentTempURL ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetCurrentTempURL( aNewCurrentTempURL ); +} + +//***************************************************************************************************************** +// private method +//***************************************************************************************************************** +Mutex& SvtInternalOptions::GetOwnStaticMutex() +{ + // Initialize static mutex only for one time! + static Mutex* pMutex = NULL; + // If these method first called (Mutex not already exist!) ... + if( pMutex == NULL ) + { + // ... we must create a new one. Protect follow code with the global mutex - + // It must be - we create a static variable! + MutexGuard aGuard( Mutex::getGlobalMutex() ); + // We must check our pointer again - because it can be that another instance of ouer class will be fastr then these! + if( pMutex == NULL ) + { + // Create the new mutex and set it for return on static variable. + static Mutex aMutex; + pMutex = &aMutex; + } + } + // Return new created or already existing mutex object. + return *pMutex; +} + +/* 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 000000000000..283c9a2b5bed --- /dev/null +++ b/unotools/source/config/itemholder1.cxx @@ -0,0 +1,331 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" + +#include "itemholder1.hxx" + +//----------------------------------------------- +// includes +#include <comphelper/processfactory.hxx> +#include <com/sun/star/lang/XComponent.hpp> + +#include <unotools/misccfg.hxx> +#include <unotools/undoopt.hxx> +#include <unotools/useroptions.hxx> +#include <unotools/accelcfg.hxx> +#include <unotools/cacheoptions.hxx> +#include <unotools/cmdoptions.hxx> +#include <unotools/compatibility.hxx> +#include <unotools/defaultoptions.hxx> +#include <unotools/dynamicmenuoptions.hxx> +#include <unotools/eventcfg.hxx> +#include <unotools/extendedsecurityoptions.hxx> +#include <unotools/fltrcfg.hxx> +#include <unotools/fontoptions.hxx> +#include <unotools/historyoptions.hxx> +#include <unotools/inetoptions.hxx> +#include <unotools/internaloptions.hxx> +#include <unotools/javaoptions.hxx> +#include <unotools/lingucfg.hxx> +#include <unotools/localisationoptions.hxx> +#include <unotools/moduleoptions.hxx> +#include <unotools/pathoptions.hxx> +#include <unotools/printwarningoptions.hxx> +#include <unotools/regoptions.hxx> +#include <unotools/optionsdlg.hxx> +#include <unotools/saveopt.hxx> +#include <unotools/searchopt.hxx> +#include <unotools/securityoptions.hxx> +#include <unotools/sourceviewconfig.hxx> +#include <unotools/startoptions.hxx> +#include <unotools/viewoptions.hxx> +#include <unotools/workingsetoptions.hxx> +#include <unotools/xmlaccelcfg.hxx> +#include <unotools/options.hxx> +#include <unotools/syslocaleoptions.hxx> + +//----------------------------------------------- +// namespaces + +namespace css = ::com::sun::star; + +//----------------------------------------------- +// declarations + +//----------------------------------------------- +ItemHolder1::ItemHolder1() + : ItemHolderMutexBase() +{ + try + { + css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = ::comphelper::getProcessServiceFactory(); + css::uno::Reference< css::lang::XComponent > xCfg( + xSMGR->createInstance(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.configuration.ConfigurationProvider"))), + css::uno::UNO_QUERY); + if (xCfg.is()) + xCfg->addEventListener(static_cast< css::lang::XEventListener* >(this)); + } +// #i37892 got errorhandling from ConfigManager::GetConfigurationProvider() +#ifdef DBG_UTIL + catch(css::uno::Exception& rEx) + { + static sal_Bool bMessage = sal_True; + if(bMessage) + { + bMessage = sal_False; + ::rtl::OString sMsg("CreateInstance with arguments exception: "); + sMsg += ::rtl::OString(rEx.Message.getStr(), + rEx.Message.getLength(), + RTL_TEXTENCODING_ASCII_US); + OSL_ENSURE(sal_False, sMsg.getStr()); + } + } +#else + catch(css::uno::Exception&){} +#endif +} + +//----------------------------------------------- +ItemHolder1::~ItemHolder1() +{ + impl_releaseAllItems(); +} + +//----------------------------------------------- +void ItemHolder1::holdConfigItem(EItem eItem) +{ + static ItemHolder1* pHolder = new ItemHolder1(); + pHolder->impl_addItem(eItem); +} + +//----------------------------------------------- +void SAL_CALL ItemHolder1::disposing(const css::lang::EventObject&) + throw(css::uno::RuntimeException) +{ + 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) +{ + ::osl::ResettableMutexGuard aLock(m_aLock); + + TItems::const_iterator pIt; + for ( pIt = m_lItems.begin(); + pIt != m_lItems.end() ; + ++pIt ) + { + const TItemInfo& rInfo = *pIt; + if (rInfo.eItem == eItem) + return; + } + + TItemInfo aNewItem; + aNewItem.eItem = eItem; + impl_newItem(aNewItem); + if (aNewItem.pItem) + m_lItems.push_back(aNewItem); +} + +//----------------------------------------------- +void ItemHolder1::impl_releaseAllItems() +{ + ::osl::ResettableMutexGuard aLock(m_aLock); + + TItems::iterator pIt; + for ( pIt = m_lItems.begin(); + pIt != m_lItems.end() ; + ++pIt ) + { + TItemInfo& rInfo = *pIt; + impl_deleteItem(rInfo); + } + m_lItems.clear(); +} + +//----------------------------------------------- +void ItemHolder1::impl_newItem(TItemInfo& rItem) +{ + switch(rItem.eItem) + { + case E_ACCELCFG : + rItem.pItem = new SvtAcceleratorConfiguration(); + break; + + case E_CMDOPTIONS : + rItem.pItem = new SvtCommandOptions(); + break; + + case E_COMPATIBILITY : + rItem.pItem = new SvtCompatibilityOptions(); + break; + + case E_DEFAULTOPTIONS : + rItem.pItem = new SvtDefaultOptions(); + break; + + case E_DYNAMICMENUOPTIONS : + rItem.pItem = new SvtDynamicMenuOptions(); + break; + + case E_EVENTCFG : + //rItem.pItem = new GlobalEventConfig(); + break; + + case E_EXTENDEDSECURITYOPTIONS : + rItem.pItem = new SvtExtendedSecurityOptions(); + break; + + case E_FLTRCFG : +// no ref count rItem.pItem = new SvtFilterOptions(); + break; + + case E_FONTOPTIONS : + rItem.pItem = new SvtFontOptions(); + break; + + case E_HISTORYOPTIONS : + rItem.pItem = new SvtHistoryOptions(); + break; + + case E_INETOPTIONS : + rItem.pItem = new SvtInetOptions(); + break; + + case E_INTERNALOPTIONS : + rItem.pItem = new SvtInternalOptions(); + break; + + case E_JAVAOPTIONS : +// no ref count rItem.pItem = new SvtJavaOptions(); + break; + + case E_LINGUCFG : + rItem.pItem = new SvtLinguConfig(); + break; + + case E_LOCALISATIONOPTIONS : + rItem.pItem = new SvtLocalisationOptions(); + break; + + case E_MODULEOPTIONS : + rItem.pItem = new SvtModuleOptions(); + break; + + case E_OPTIONSDLGOPTIONS : + rItem.pItem = new SvtOptionsDialogOptions(); + break; + + case E_PATHOPTIONS : + rItem.pItem = new SvtPathOptions(); + break; + + case E_PRINTWARNINGOPTIONS : + rItem.pItem = new SvtPrintWarningOptions(); + break; + + case E_MISCCFG : + rItem.pItem = new ::utl::MiscCfg(); + break; + + case E_SAVEOPTIONS : + rItem.pItem = new SvtSaveOptions(); + break; + + case E_SEARCHOPT : +// no ref count rItem.pItem = new SvtSearchOptions(); + break; + + case E_SECURITYOPTIONS : + rItem.pItem = new SvtSecurityOptions(); + break; + + case E_SOURCEVIEWCONFIG : + rItem.pItem = new ::utl::SourceViewConfig(); + break; + + case E_STARTOPTIONS : + rItem.pItem = new SvtStartOptions(); + break; + + case E_VIEWOPTIONS_DIALOG : + rItem.pItem = new SvtViewOptions(E_DIALOG, ::rtl::OUString()); + break; + + case E_VIEWOPTIONS_TABDIALOG : + rItem.pItem = new SvtViewOptions(E_TABDIALOG, ::rtl::OUString()); + break; + + case E_VIEWOPTIONS_TABPAGE : + rItem.pItem = new SvtViewOptions(E_TABPAGE, ::rtl::OUString()); + break; + + case E_VIEWOPTIONS_WINDOW : + rItem.pItem = new SvtViewOptions(E_WINDOW, ::rtl::OUString()); + break; + + case E_WORKINGSETOPTIONS : + rItem.pItem = new SvtWorkingSetOptions(); + break; + + case E_XMLACCELCFG : + // ??? TODO + break; + + case E_UNDOOPTIONS : + rItem.pItem = new SvtUndoOptions(); + break; + + case E_USEROPTIONS : + rItem.pItem = new SvtUserOptions(); + break; + + case E_SYSLOCALEOPTIONS : + rItem.pItem = new SvtSysLocaleOptions(); + break; + + default: + OSL_ASSERT( "unknown item type" ); + break; + } +} + +//----------------------------------------------- +void ItemHolder1::impl_deleteItem(TItemInfo& rItem) +{ + if (rItem.pItem) + { + delete rItem.pItem; + rItem.pItem = 0; + } +} + +/* 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 000000000000..e04b423152ba --- /dev/null +++ b/unotools/source/config/itemholder1.hxx @@ -0,0 +1,92 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +#ifndef INCLUDED_unotools_ITEMHOLDER1_HXX_ +#define INCLUDED_unotools_ITEMHOLDER1_HXX_ + +//----------------------------------------------- +// includes + +#include <unotools/itemholderbase.hxx> +#include <cppuhelper/implbase1.hxx> +#include <com/sun/star/lang/XEventListener.hpp> + +//----------------------------------------------- +// namespaces + +#ifdef css +#error "Cant use css as namespace alias." +#else +#define css ::com::sun::star +#endif + +//----------------------------------------------- +// definitions + +class ItemHolder1 : private ItemHolderMutexBase + , public ::cppu::WeakImplHelper1< css::lang::XEventListener > +{ + //........................................... + // member + private: + + TItems m_lItems; + + //........................................... + // c++ interface + public: + + ItemHolder1(); + virtual ~ItemHolder1(); + static void holdConfigItem(EItem eItem); + + //........................................... + // uno interface + public: + + virtual void SAL_CALL disposing(const css::lang::EventObject& aEvent) + throw(css::uno::RuntimeException); + + //........................................... + // helper + private: + + void impl_addItem(EItem eItem); + void impl_releaseAllItems(); + void impl_newItem(TItemInfo& rItem); + void impl_deleteItem(TItemInfo& rItem); +}; + +//----------------------------------------------- +// namespaces + +#undef css + +#endif // INCLUDED_unotools_ITEMHOLDER1_HXX_ + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/javaoptions.cxx b/unotools/source/config/javaoptions.cxx new file mode 100644 index 000000000000..ef9d5f10de41 --- /dev/null +++ b/unotools/source/config/javaoptions.cxx @@ -0,0 +1,334 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" + +#include <unotools/javaoptions.hxx> +#include <com/sun/star/uno/Any.h> +#include <com/sun/star/uno/Sequence.hxx> +#include <rtl/logfile.hxx> + + +using namespace ::com::sun::star::uno; +using namespace ::rtl; + +#define C2U(cChar) OUString::createFromAscii(cChar) +#define CFG_READONLY_DEFAULT sal_False + +class SvtExecAppletsItem_Impl : public utl::ConfigItem +{ + sal_Bool bExecute; + sal_Bool bRO; +public: + SvtExecAppletsItem_Impl(); + + virtual void Commit(); + void Notify( const Sequence< rtl::OUString >& ); + + sal_Bool IsExecuteApplets() const {return bExecute;} + void SetExecuteApplets(sal_Bool bSet); + sal_Bool IsReadOnly() const {return bRO;} +}; + +void SvtExecAppletsItem_Impl::SetExecuteApplets(sal_Bool bSet) +{ + OSL_ENSURE(!bRO, "SvtExecAppletsItem_Impl::SetExecuteApplets()\nYou tried to write on a readonly value!\n"); + if (!bRO) + { + bExecute = bSet; + SetModified(); + } +} + +SvtExecAppletsItem_Impl::SvtExecAppletsItem_Impl() : + utl::ConfigItem(C2U("Office.Common/Java/Applet")), + bExecute (sal_False ), + bRO (CFG_READONLY_DEFAULT ) +{ + RTL_LOGFILE_CONTEXT(aLog, "unotools SvtExecAppletsItem_Impl::SvtExecAppletsItem_Impl()"); + + Sequence< OUString > aNames(1); + aNames.getArray()[0] = C2U("Enable"); + Sequence< Any > aValues = GetProperties(aNames); + Sequence< sal_Bool > aROStates = GetReadOnlyStates(aNames); + const Any* pValues = aValues.getConstArray(); + const sal_Bool* pROStates = aROStates.getConstArray(); + if(aValues.getLength() && aROStates.getLength() && pValues[0].hasValue()) + { + bExecute = *(sal_Bool*)pValues[0].getValue(); + bRO = pROStates[0]; + } +} +void SvtExecAppletsItem_Impl::Commit() +{ + if (bRO) + return; + + Sequence< OUString > aNames(1); + aNames.getArray()[0] = C2U("Enable"); + Sequence< Any > aValues(1); + aValues.getArray()[0].setValue(&bExecute, ::getBooleanCppuType()); + PutProperties(aNames, aValues); +} + +void SvtExecAppletsItem_Impl::Notify( const Sequence< rtl::OUString >& ) +{ + // no listeners supported yet +} + +struct SvtJavaOptions_Impl +{ + SvtExecAppletsItem_Impl aExecItem; + Sequence<OUString> aPropertyNames; + sal_Bool bEnabled; + sal_Bool bSecurity; + sal_Int32 nNetAccess; + rtl::OUString sUserClassPath; + + sal_Bool bROEnabled; + sal_Bool bROSecurity; + sal_Bool bRONetAccess; + sal_Bool bROUserClassPath; + + SvtJavaOptions_Impl() : + aPropertyNames(4), + bEnabled (sal_False), + bSecurity (sal_False), + nNetAccess (0), + bROEnabled (CFG_READONLY_DEFAULT), + bROSecurity (CFG_READONLY_DEFAULT), + bRONetAccess (CFG_READONLY_DEFAULT), + bROUserClassPath (CFG_READONLY_DEFAULT) + { + OUString* pNames = aPropertyNames.getArray(); + pNames[0] = C2U("Enable"); + pNames[1] = C2U("Security"); + pNames[2] = C2U("NetAccess"); + pNames[3] = C2U("UserClassPath"); + } +}; + +SvtJavaOptions::SvtJavaOptions() : + utl::ConfigItem(C2U("Office.Java/VirtualMachine")), + pImpl(new SvtJavaOptions_Impl) +{ + RTL_LOGFILE_CONTEXT(aLog, "unotools SvtJavaOptions::SvtJavaOptions()"); + + Sequence< Any > aValues = GetProperties(pImpl->aPropertyNames); + Sequence< sal_Bool > aROStates = GetReadOnlyStates(pImpl->aPropertyNames); + const Any* pValues = aValues.getConstArray(); + const sal_Bool* pROStates = aROStates.getConstArray(); + if ( aValues.getLength() == pImpl->aPropertyNames.getLength() && aROStates.getLength() == pImpl->aPropertyNames.getLength() ) + { + for ( int nProp = 0; nProp < pImpl->aPropertyNames.getLength(); nProp++ ) + { + if( pValues[nProp].hasValue() ) + { + switch ( nProp ) + { + case 0: pImpl->bEnabled = *(sal_Bool*)pValues[nProp].getValue(); break; + case 1: pImpl->bSecurity = *(sal_Bool*)pValues[nProp].getValue();break; + case 2: pValues[nProp] >>= pImpl->nNetAccess; break; + case 3: pValues[nProp] >>= pImpl->sUserClassPath; break; + } + } + } + pImpl->bROEnabled = pROStates[0]; + pImpl->bROSecurity = pROStates[1]; + pImpl->bRONetAccess = pROStates[2]; + pImpl->bROUserClassPath = pROStates[3]; + } +} + +SvtJavaOptions::~SvtJavaOptions() +{ + delete pImpl; +} + +void SvtJavaOptions::Commit() +{ + pImpl->aExecItem.Commit(); + + sal_Int32 nOrgCount = pImpl->aPropertyNames.getLength(); + Sequence< OUString > aNames(nOrgCount); + Sequence< Any > aValues(nOrgCount); + sal_Int32 nRealCount = 0; + + const Type& rType = ::getBooleanCppuType(); + for(int nProp = 0; nProp < nOrgCount; nProp++) + { + switch(nProp) + { + case 0: + { + if (!pImpl->bROEnabled) + { + aValues[nRealCount].setValue(&pImpl->bEnabled, rType); + aNames[nRealCount] = pImpl->aPropertyNames[nProp]; + ++nRealCount; + } + } + break; + case 1: + { + if (!pImpl->bROSecurity) + { + aValues[nRealCount].setValue(&pImpl->bSecurity, rType); + aNames[nRealCount] = pImpl->aPropertyNames[nProp]; + ++nRealCount; + } + } + break; + case 2: + { + if (!pImpl->bRONetAccess) + { + aValues[nRealCount] <<= pImpl->nNetAccess; + aNames[nRealCount] = pImpl->aPropertyNames[nProp]; + ++nRealCount; + } + } + break; + case 3: + { + if (!pImpl->bROUserClassPath) + { + aValues[nRealCount] <<= pImpl->sUserClassPath; + aNames[nRealCount] = pImpl->aPropertyNames[nProp]; + ++nRealCount; + } + } + break; + } + } + aValues.realloc(nRealCount); + aNames.realloc(nRealCount); + PutProperties(aNames,aValues); +} + +sal_Bool SvtJavaOptions::IsEnabled() const +{ + return pImpl->bEnabled; +} + +sal_Bool SvtJavaOptions::IsSecurity()const +{ + return pImpl->bSecurity; +} + +sal_Int32 SvtJavaOptions::GetNetAccess() const +{ + return pImpl->nNetAccess; +} + +rtl::OUString& SvtJavaOptions::GetUserClassPath()const +{ + return pImpl->sUserClassPath; +} + +void SvtJavaOptions::SetEnabled(sal_Bool bSet) +{ + OSL_ENSURE(!pImpl->bROEnabled, "SvtJavaOptions::SetEnabled()\nYou tried to write on a readonly value!\n"); + if(!pImpl->bROEnabled && pImpl->bEnabled != bSet) + { + pImpl->bEnabled = bSet; + SetModified(); + } +} + +void SvtJavaOptions::SetSecurity(sal_Bool bSet) +{ + OSL_ENSURE(!pImpl->bROSecurity, "SvtJavaOptions::SetSecurity()\nYou tried to write on a readonly value!\n"); + if(!pImpl->bROSecurity && pImpl->bSecurity != bSet) + { + pImpl->bSecurity = bSet; + SetModified(); + } +} + +void SvtJavaOptions::SetNetAccess(sal_Int32 nSet) +{ + OSL_ENSURE(!pImpl->bRONetAccess, "SvtJavaOptions::SetNetAccess()\nYou tried to write on a readonly value!\n"); + if(!pImpl->bRONetAccess && pImpl->nNetAccess != nSet) + { + pImpl->nNetAccess = nSet; + SetModified(); + } +} + +void SvtJavaOptions::SetUserClassPath(const rtl::OUString& rSet) +{ + OSL_ENSURE(!pImpl->bROUserClassPath, "SvtJavaOptions::SetUserClassPath()\nYou tried to write on a readonly value!\n"); + if(!pImpl->bROUserClassPath && pImpl->sUserClassPath != rSet) + { + pImpl->sUserClassPath = rSet; + SetModified(); + } +} + + +sal_Bool SvtJavaOptions::IsExecuteApplets() const +{ + return pImpl->aExecItem.IsExecuteApplets(); +} + +void SvtJavaOptions::SetExecuteApplets(sal_Bool bSet) +{ + if(!pImpl->aExecItem.IsReadOnly() && pImpl->aExecItem.IsExecuteApplets() != bSet) + { + pImpl->aExecItem.SetExecuteApplets(bSet); + SetModified(); + } +} + +sal_Bool SvtJavaOptions::IsReadOnly( EOption eOption ) const +{ + sal_Bool bRO = sal_True; + switch(eOption) + { + case E_ENABLED : + bRO = pImpl->bROEnabled; + break; + case E_SECURITY : + bRO = pImpl->bROSecurity; + break; + case E_NETACCESS : + bRO = pImpl->bRONetAccess; + break; + case E_USERCLASSPATH : + bRO = pImpl->bROUserClassPath; + break; + case E_EXECUTEAPPLETS : + bRO = pImpl->aExecItem.IsReadOnly(); + break; + } + return bRO; +} + +/* 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 000000000000..cab39e74f212 --- /dev/null +++ b/unotools/source/config/lingucfg.cxx @@ -0,0 +1,1504 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" + + +#include <com/sun/star/lang/Locale.hpp> +#include <com/sun/star/lang/XMultiServiceFactory.hpp> +#include <com/sun/star/lang/XSingleServiceFactory.hpp> +#include <com/sun/star/container/XNameAccess.hpp> +#include <com/sun/star/container/XNameContainer.hpp> +#include <com/sun/star/container/XNameReplace.hpp> +#include "com/sun/star/util/XMacroExpander.hpp" +#include "com/sun/star/beans/XPropertySet.hpp" +#include <rtl/uri.hxx> +#include <osl/mutex.hxx> +#include <i18npool/mslangid.hxx> +#include <tools/debug.hxx> +#include <tools/string.hxx> +#include <unotools/lingucfg.hxx> +#include <unotools/linguprops.hxx> +#include <sal/macros.h> + +#include <comphelper/processfactory.hxx> + +#include <itemholder1.hxx> + +using namespace rtl; +using namespace com::sun::star; + +#define A2OU(x) ::rtl::OUString::createFromAscii( x ) +#define EXPAND_PROTOCOL "vnd.sun.star.expand:" +#define FILE_PROTOCOL "file:///" + +/////////////////////////////////////////////////////////////////////////// + + +static osl::Mutex & GetOwnMutex() +{ + static osl::Mutex aMutex; + return aMutex; +} + + +/////////////////////////////////////////////////////////////////////////// + + +static BOOL lcl_SetLocale( INT16 &rLanguage, const uno::Any &rVal ) +{ + BOOL bSucc = FALSE; + + lang::Locale aNew; + if (rVal >>= aNew) // conversion successful? + { + INT16 nNew = MsLangId::convertLocaleToLanguage( aNew ); + if (nNew != rLanguage) + { + rLanguage = nNew; + bSucc = TRUE; + } + } + return bSucc; +} + + +static inline const OUString lcl_LanguageToCfgLocaleStr( INT16 nLanguage ) +{ + OUString aRes; + if (LANGUAGE_SYSTEM != nLanguage) + aRes = MsLangId::convertLanguageToIsoString( nLanguage ); + return aRes; +} + + +static INT16 lcl_CfgAnyToLanguage( const uno::Any &rVal ) +{ + OUString aTmp; + rVal >>= aTmp; + return (aTmp.getLength() == 0) ? LANGUAGE_SYSTEM : MsLangId::convertIsoStringToLanguage( aTmp ); +} + + +////////////////////////////////////////////////////////////////////// + +SvtLinguOptions::SvtLinguOptions() +{ + nDefaultLanguage = LANGUAGE_NONE; + nDefaultLanguage_CJK = LANGUAGE_NONE; + nDefaultLanguage_CTL = LANGUAGE_NONE; + + // general options + bIsUseDictionaryList = + bIsIgnoreControlCharacters = TRUE; + + // spelling options + bIsSpellCapitalization = + bIsSpellSpecial = TRUE; + bIsSpellAuto = + bIsSpellReverse = + bIsSpellWithDigits = + bIsSpellUpperCase = FALSE; + + // text conversion options + bIsIgnorePostPositionalWord = TRUE; + bIsAutoCloseDialog = + bIsShowEntriesRecentlyUsedFirst = + bIsAutoReplaceUniqueEntries = FALSE; + bIsDirectionToSimplified = TRUE; + bIsUseCharacterVariants = + bIsTranslateCommonTerms = + bIsReverseMapping = FALSE; + + bROIsDirectionToSimplified = + bROIsUseCharacterVariants = + bROIsTranslateCommonTerms = + bROIsReverseMapping = FALSE; + + // hyphenation options + bIsHyphSpecial = TRUE; + bIsHyphAuto = FALSE; + nHyphMinLeading = + nHyphMinTrailing = 2; + nHyphMinWordLength = 0; + + nDataFilesChangedCheckValue = 0; + + //grammar options + bIsGrammarAuto = sal_False, + bIsGrammarInteractive = sal_False; + +} + + +////////////////////////////////////////////////////////////////////// + + +class SvtLinguConfigItem : public utl::ConfigItem +{ + SvtLinguOptions aOpt; + + // disallow copy-constructor and assignment-operator for now + SvtLinguConfigItem( const SvtLinguConfigItem & ); + SvtLinguConfigItem & operator = ( const SvtLinguConfigItem & ); + + static BOOL GetHdlByName( INT32 &rnHdl, const OUString &rPropertyName, sal_Bool bFullPropName = sal_False ); + static const uno::Sequence< OUString > & GetPropertyNames(); + BOOL LoadOptions( const uno::Sequence< OUString > &rProperyNames ); + BOOL SaveOptions( const uno::Sequence< OUString > &rProperyNames ); + +public: + SvtLinguConfigItem(); + virtual ~SvtLinguConfigItem(); + + // utl::ConfigItem + virtual void Notify( const com::sun::star::uno::Sequence< rtl::OUString > &rPropertyNames ); + virtual void Commit(); + + // 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; + + + com::sun::star::uno::Any + GetProperty( const rtl::OUString &rPropertyName ) const; + com::sun::star::uno::Any + GetProperty( INT32 nPropertyHandle ) const; + + BOOL SetProperty( const rtl::OUString &rPropertyName, + const com::sun::star::uno::Any &rValue ); + BOOL SetProperty( INT32 nPropertyHandle, + const com::sun::star::uno::Any &rValue ); + + BOOL GetOptions( SvtLinguOptions &rOptions ) const; + BOOL SetOptions( const SvtLinguOptions &rOptions ); + + BOOL IsReadOnly( const rtl::OUString &rPropertyName ) const; + BOOL IsReadOnly( INT32 nPropertyHandle ) const; +}; + + +SvtLinguConfigItem::SvtLinguConfigItem() : + utl::ConfigItem( String::CreateFromAscii( "Office.Linguistic" ) ) +{ + LoadOptions( GetPropertyNames() ); + ClearModified(); + + // request notify events when properties change + EnableNotification( GetPropertyNames() ); +} + + +SvtLinguConfigItem::~SvtLinguConfigItem() +{ + //! Commit (SaveOptions) will be called by the d-tor of the base called ! +} + + +void SvtLinguConfigItem::Notify( const uno::Sequence< OUString > &rPropertyNames ) +{ + LoadOptions( rPropertyNames ); + NotifyListeners(0); +} + + +void SvtLinguConfigItem::Commit() +{ + SaveOptions( GetPropertyNames() ); +} + + +static struct NamesToHdl +{ + const char *pFullPropName; // full qualified name as used in configuration + const char *pPropName; // property name only (atom) of above + INT32 nHdl; // numeric handle representing the property +}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 */ +{ NULL, UPN_DEFAULT_LANGUAGE, UPH_DEFAULT_LANGUAGE}, + +{ NULL, NULL, -1} +}; + + +const uno::Sequence< OUString > & SvtLinguConfigItem::GetPropertyNames() +{ + static uno::Sequence< OUString > aNames; + static sal_Bool bInitialized = sal_False; + + if (!bInitialized) + { + INT32 nMax = SAL_N_ELEMENTS(aNamesToHdl); + + aNames.realloc( nMax ); + OUString *pNames = aNames.getArray(); + INT32 nIdx = 0; + for (INT32 i = 0; i < nMax; ++i) + { + const sal_Char *pFullPropName = aNamesToHdl[i].pFullPropName; + if (pFullPropName) + pNames[ nIdx++ ] = A2OU( pFullPropName ); + } + aNames.realloc( nIdx ); + bInitialized = sal_True; + } + return aNames; +} + + +BOOL SvtLinguConfigItem::GetHdlByName( + INT32 &rnHdl, + const OUString &rPropertyName, + sal_Bool bFullPropName ) +{ + NamesToHdl *pEntry = &aNamesToHdl[0]; + + if (bFullPropName) + { + while (pEntry && pEntry->pFullPropName != NULL) + { + if (0 == rPropertyName.compareToAscii( pEntry->pFullPropName )) + { + rnHdl = pEntry->nHdl; + break; + } + ++pEntry; + } + return pEntry && pEntry->pFullPropName != NULL; + } + else + { + while (pEntry && pEntry->pPropName != NULL) + { + if (0 == rPropertyName.compareToAscii( pEntry->pPropName )) + { + rnHdl = pEntry->nHdl; + break; + } + ++pEntry; + } + return pEntry && pEntry->pPropName != NULL; + } +} + + +uno::Any SvtLinguConfigItem::GetProperty( const OUString &rPropertyName ) const +{ + osl::MutexGuard aGuard( GetOwnMutex() ); + + INT32 nHdl; + return GetHdlByName( nHdl, rPropertyName ) ? GetProperty( nHdl ) : uno::Any(); +} + + +uno::Any SvtLinguConfigItem::GetProperty( INT32 nPropertyHandle ) const +{ + osl::MutexGuard aGuard( GetOwnMutex() ); + + uno::Any aRes; + + const INT16 *pnVal = 0; + const BOOL *pbVal = 0; + const INT32 *pnInt32Val = 0; + + 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 : pnVal = &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 : + { + lang::Locale aLocale( MsLangId::convertLanguageToLocale( rOpt.nDefaultLanguage, false ) ); + aRes.setValue( &aLocale, ::getCppuType((lang::Locale*)0 )); + break; + } + case UPH_DEFAULT_LOCALE_CJK : + { + lang::Locale aLocale( MsLangId::convertLanguageToLocale( rOpt.nDefaultLanguage_CJK, false ) ); + aRes.setValue( &aLocale, ::getCppuType((lang::Locale*)0 )); + break; + } + case UPH_DEFAULT_LOCALE_CTL : + { + lang::Locale aLocale( MsLangId::convertLanguageToLocale( rOpt.nDefaultLanguage_CTL, false ) ); + aRes.setValue( &aLocale, ::getCppuType((lang::Locale*)0 )); + 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 : + DBG_ASSERT( 0, "unexpected property handle" ); + } + + if (pbVal) + aRes <<= *pbVal; + else if (pnVal) + aRes <<= *pnVal; + else if (pnInt32Val) + aRes <<= *pnInt32Val; + + return aRes; +} + + +BOOL SvtLinguConfigItem::SetProperty( const OUString &rPropertyName, const uno::Any &rValue ) +{ + osl::MutexGuard aGuard( GetOwnMutex() ); + + BOOL bSucc = FALSE; + INT32 nHdl; + if (GetHdlByName( nHdl, rPropertyName )) + bSucc = SetProperty( nHdl, rValue ); + return bSucc; +} + + +BOOL SvtLinguConfigItem::SetProperty( INT32 nPropertyHandle, const uno::Any &rValue ) +{ + osl::MutexGuard aGuard( GetOwnMutex() ); + + BOOL bSucc = FALSE; + if (!rValue.hasValue()) + return bSucc; + + BOOL bMod = FALSE; + + INT16 *pnVal = 0; + BOOL *pbVal = 0; + INT32 *pnInt32Val = 0; + + 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 : pnVal = &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 : + DBG_ASSERT( 0, "unexpected property handle" ); + } + + if (pbVal) + { + BOOL bNew = BOOL(); + if (rValue >>= bNew) + { + if (bNew != *pbVal) + { + *pbVal = bNew; + bMod = TRUE; + } + bSucc = TRUE; + } + } + else if (pnVal) + { + INT16 nNew = INT16(); + if (rValue >>= nNew) + { + if (nNew != *pnVal) + { + *pnVal = nNew; + bMod = TRUE; + } + bSucc = TRUE; + } + } + else if (pnInt32Val) + { + INT32 nNew = INT32(); + if (rValue >>= nNew) + { + if (nNew != *pnInt32Val) + { + *pnInt32Val = nNew; + bMod = TRUE; + } + bSucc = TRUE; + } + } + + if (bMod) + SetModified(); + + NotifyListeners(0); + return bSucc; +} + + +BOOL SvtLinguConfigItem::GetOptions( SvtLinguOptions &rOptions ) const +{ + osl::MutexGuard aGuard( GetOwnMutex() ); + + rOptions = aOpt; + return TRUE; +} + + +BOOL SvtLinguConfigItem::SetOptions( const SvtLinguOptions &rOptions ) +{ + osl::MutexGuard aGuard( GetOwnMutex() ); + + aOpt = rOptions; + SetModified(); + NotifyListeners(0); + return TRUE; +} + + +BOOL SvtLinguConfigItem::LoadOptions( const uno::Sequence< OUString > &rProperyNames ) +{ + osl::MutexGuard aGuard( GetOwnMutex() ); + + BOOL bRes = FALSE; + + const OUString *pProperyNames = rProperyNames.getConstArray(); + 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 (INT32 i = 0; i < nProps; ++i) + { + const uno::Any &rVal = pValue[i]; + INT32 nPropertyHandle; + GetHdlByName( nPropertyHandle, pProperyNames[i], sal_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( rOpt.nDefaultLanguage_CJK == LANGUAGE_CHINESE_HONGKONG + || rOpt.nDefaultLanguage_CJK == LANGUAGE_CHINESE_MACAU + || rOpt.nDefaultLanguage_CJK == LANGUAGE_CHINESE_TRADITIONAL ) + { + 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: + DBG_ASSERT( 0, "unexpected case" ); + } + } + + bRes = TRUE; + } + DBG_ASSERT( bRes, "LoadOptions failed" ); + + return bRes; +} + + +BOOL SvtLinguConfigItem::SaveOptions( const uno::Sequence< OUString > &rProperyNames ) +{ + if (!IsModified()) + return TRUE; + + osl::MutexGuard aGuard( GetOwnMutex() ); + + BOOL bRet = FALSE; + const uno::Type &rBOOL = ::getBooleanCppuType(); + const uno::Type &rINT16 = ::getCppuType( (INT16 *) NULL ); + const uno::Type &rINT32 = ::getCppuType( (INT32 *) NULL ); + + 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++ = uno::makeAny( aTmp ); // 0 + *pValue++ = uno::makeAny( rOpt.aActiveDics ); // 1 + pValue++->setValue( &rOpt.bIsUseDictionaryList, rBOOL ); // 2 + pValue++->setValue( &rOpt.bIsIgnoreControlCharacters, rBOOL ); // 3 + aTmp = lcl_LanguageToCfgLocaleStr( rOpt.nDefaultLanguage_CJK ); + *pValue++ = uno::makeAny( aTmp ); // 5 + aTmp = lcl_LanguageToCfgLocaleStr( rOpt.nDefaultLanguage_CTL ); + *pValue++ = uno::makeAny( aTmp ); // 6 + + pValue++->setValue( &rOpt.bIsSpellUpperCase, rBOOL ); // 7 + pValue++->setValue( &rOpt.bIsSpellWithDigits, rBOOL ); // 8 + pValue++->setValue( &rOpt.bIsSpellCapitalization, rBOOL ); // 9 + pValue++->setValue( &rOpt.bIsSpellAuto, rBOOL ); // 10 + pValue++->setValue( &rOpt.bIsSpellSpecial, rBOOL ); // 11 + pValue++->setValue( &rOpt.bIsSpellReverse, rBOOL ); // 14 + + pValue++->setValue( &rOpt.nHyphMinLeading, rINT16 ); // 15 + pValue++->setValue( &rOpt.nHyphMinTrailing, rINT16 ); // 16 + pValue++->setValue( &rOpt.nHyphMinWordLength, rINT16 ); // 17 + pValue++->setValue( &rOpt.bIsHyphSpecial, rBOOL ); // 18 + pValue++->setValue( &rOpt.bIsHyphAuto, rBOOL ); // 19 + + *pValue++ = uno::makeAny( rOpt.aActiveConvDics ); // 20 + + pValue++->setValue( &rOpt.bIsIgnorePostPositionalWord, rBOOL ); // 21 + pValue++->setValue( &rOpt.bIsAutoCloseDialog, rBOOL ); // 22 + pValue++->setValue( &rOpt.bIsShowEntriesRecentlyUsedFirst, rBOOL ); // 23 + pValue++->setValue( &rOpt.bIsAutoReplaceUniqueEntries, rBOOL ); // 24 + + pValue++->setValue( &rOpt.bIsDirectionToSimplified, rBOOL ); // 25 + pValue++->setValue( &rOpt.bIsUseCharacterVariants, rBOOL ); // 26 + pValue++->setValue( &rOpt.bIsTranslateCommonTerms, rBOOL ); // 27 + pValue++->setValue( &rOpt.bIsReverseMapping, rBOOL ); // 28 + + pValue++->setValue( &rOpt.nDataFilesChangedCheckValue, rINT32 ); // 29 + pValue++->setValue( &rOpt.bIsGrammarAuto, rBOOL ); // 30 + pValue++->setValue( &rOpt.bIsGrammarInteractive, rBOOL ); // 31 + + bRet |= PutProperties( rProperyNames, aValues ); + } + + if (bRet) + ClearModified(); + + return bRet; +} + +BOOL SvtLinguConfigItem::IsReadOnly( const rtl::OUString &rPropertyName ) const +{ + osl::MutexGuard aGuard( GetOwnMutex() ); + + BOOL bReadOnly = FALSE; + INT32 nHdl; + if (GetHdlByName( nHdl, rPropertyName )) + bReadOnly = IsReadOnly( nHdl ); + return bReadOnly; +} + +BOOL SvtLinguConfigItem::IsReadOnly( INT32 nPropertyHandle ) const +{ + osl::MutexGuard aGuard( GetOwnMutex() ); + + 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 : + DBG_ASSERT( 0, "unexpected property handle" ); + } + return bReadOnly; +} + +////////////////////////////////////////////////////////////////////// + +static SvtLinguConfigItem *pCfgItem = 0; +static sal_Int32 nCfgItemRefCount = 0; + +static const rtl::OUString aG_SupportedDictionaryFormats(RTL_CONSTASCII_USTRINGPARAM("SupportedDictionaryFormats")); +static const rtl::OUString aG_Dictionaries(RTL_CONSTASCII_USTRINGPARAM("Dictionaries")); +static const rtl::OUString aG_Locations(RTL_CONSTASCII_USTRINGPARAM("Locations")); +static const rtl::OUString aG_Format(RTL_CONSTASCII_USTRINGPARAM("Format")); +static const rtl::OUString aG_Locales(RTL_CONSTASCII_USTRINGPARAM("Locales")); +static const rtl::OUString aG_DisabledDictionaries(RTL_CONSTASCII_USTRINGPARAM("DisabledDictionaries")); +static const rtl::OUString aG_LastActiveDictionaries(RTL_CONSTASCII_USTRINGPARAM("LastActiveDictionaries")); + +SvtLinguConfig::SvtLinguConfig() +{ + // Global access, must be guarded (multithreading) + osl::MutexGuard aGuard( GetOwnMutex() ); + ++nCfgItemRefCount; +} + + +SvtLinguConfig::~SvtLinguConfig() +{ + osl::MutexGuard aGuard( GetOwnMutex() ); + + if (pCfgItem && pCfgItem->IsModified()) + pCfgItem->Commit(); + + if (--nCfgItemRefCount <= 0) + { + if (pCfgItem) + delete pCfgItem; + pCfgItem = 0; + } +} + + +SvtLinguConfigItem & SvtLinguConfig::GetConfigItem() +{ + // Global access, must be guarded (multithreading) + osl::MutexGuard aGuard( GetOwnMutex() ); + if (!pCfgItem) + { + pCfgItem = new SvtLinguConfigItem; + ItemHolder1::holdConfigItem(E_LINGUCFG); + } + return *pCfgItem; +} + + +uno::Sequence< OUString > SvtLinguConfig::GetNodeNames( const OUString &rNode ) +{ + return GetConfigItem().GetNodeNames( rNode ); +} + + +uno::Sequence< uno::Any > SvtLinguConfig::GetProperties( const uno::Sequence< OUString > &rNames ) +{ + return GetConfigItem().GetProperties(rNames); +} + + +sal_Bool SvtLinguConfig::ReplaceSetProperties( + const OUString &rNode, uno::Sequence< beans::PropertyValue > rValues ) +{ + return GetConfigItem().ReplaceSetProperties( rNode, rValues ); +} + + +uno::Any SvtLinguConfig::GetProperty( const OUString &rPropertyName ) const +{ + return GetConfigItem().GetProperty( rPropertyName ); +} + + +uno::Any SvtLinguConfig::GetProperty( INT32 nPropertyHandle ) const +{ + return GetConfigItem().GetProperty( nPropertyHandle ); +} + + +BOOL SvtLinguConfig::SetProperty( const OUString &rPropertyName, const uno::Any &rValue ) +{ + return GetConfigItem().SetProperty( rPropertyName, rValue ); +} + + +BOOL SvtLinguConfig::SetProperty( INT32 nPropertyHandle, const uno::Any &rValue ) +{ + return GetConfigItem().SetProperty( nPropertyHandle, rValue ); +} + + +BOOL SvtLinguConfig::GetOptions( SvtLinguOptions &rOptions ) const +{ + return GetConfigItem().GetOptions( rOptions ); +} + + +BOOL SvtLinguConfig::SetOptions( const SvtLinguOptions &rOptions ) +{ + return GetConfigItem().SetOptions( rOptions ); +} + + +BOOL SvtLinguConfig::IsReadOnly( const rtl::OUString &rPropertyName ) const +{ + return GetConfigItem().IsReadOnly( rPropertyName ); +} + +BOOL SvtLinguConfig::IsReadOnly( INT32 nPropertyHandle ) const +{ + return GetConfigItem().IsReadOnly( nPropertyHandle ); +} + +BOOL SvtLinguConfig::GetElementNamesFor( + const rtl::OUString &rNodeName, + uno::Sequence< rtl::OUString > &rElementNames ) const +{ + bool bSuccess = false; + try + { + uno::Reference< container::XNameAccess > xNA( GetMainUpdateAccess(), uno::UNO_QUERY_THROW ); + xNA.set( xNA->getByName(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ServiceManager"))), uno::UNO_QUERY_THROW ); + xNA.set( xNA->getByName( rNodeName ), uno::UNO_QUERY_THROW ); + rElementNames = xNA->getElementNames(); + bSuccess = true; + } + catch (uno::Exception &) + { + } + return bSuccess; +} + +static uno::Reference< container::XNameAccess > GetOrCreateSetEntry_Impl( + const uno::Reference< container::XNameAccess > &rxSetNameAccess, + const rtl::OUString &rEntryName ) +{ + uno::Reference< container::XNameAccess > xResult; + try + { + if (!rxSetNameAccess->hasByName( rEntryName )) + { + uno::Reference< lang::XSingleServiceFactory > xFactory( rxSetNameAccess, uno::UNO_QUERY_THROW); + uno::Reference< uno::XInterface > xNewEntry( xFactory->createInstance() ); + uno::Reference< container::XNameContainer > xNC( rxSetNameAccess, uno::UNO_QUERY_THROW ); + xNC->insertByName( rEntryName, makeAny( xNewEntry ) ); + } + xResult.set( rxSetNameAccess->getByName( rEntryName ), uno::UNO_QUERY_THROW ); + } + catch (uno::Exception &) + { + } + return xResult; +} + +BOOL SvtLinguConfig::GetSupportedDictionaryFormatsFor( + const rtl::OUString &rSetName, + const rtl::OUString &rSetEntry, + uno::Sequence< rtl::OUString > &rFormatList ) const +{ + if (rSetName.getLength() == 0 || rSetEntry.getLength() == 0) + return sal_False; + bool bSuccess = false; + try + { + uno::Reference< container::XNameAccess > xNA( GetMainUpdateAccess(), uno::UNO_QUERY_THROW ); + xNA.set( xNA->getByName(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("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( aG_SupportedDictionaryFormats ) >>= rFormatList) + bSuccess = true; + DBG_ASSERT( rFormatList.getLength(), "supported dictionary format list is empty" ); + } + catch (uno::Exception &) + { + } + return bSuccess; +} + +void SvtLinguConfig::SetOrCreateSupportedDictionaryFormatsFor( + const rtl::OUString &rSetName, + const rtl::OUString &rSetEntry, + const uno::Sequence< rtl::OUString > &rFormatList ) const +{ + if (rSetName.getLength() == 0 || rSetEntry.getLength() == 0) + return; + try + { + DBG_ASSERT( rFormatList.getLength(), "applying empty format list. Really??" ); + + uno::Reference< util::XChangesBatch > xUpdateAccess( GetMainUpdateAccess() ); + uno::Reference< container::XNameAccess > xNA( xUpdateAccess, uno::UNO_QUERY_THROW ); + xNA.set( xNA->getByName(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ServiceManager"))), uno::UNO_QUERY_THROW ); + xNA.set( xNA->getByName( rSetName ), uno::UNO_QUERY_THROW ); + xNA = GetOrCreateSetEntry_Impl( xNA, rSetEntry ); + + uno::Reference< container::XNameReplace > xNR( xNA, uno::UNO_QUERY_THROW ); + xNR->replaceByName( aG_SupportedDictionaryFormats, uno::makeAny( rFormatList ) ); + + xUpdateAccess->commitChanges(); + } + catch (uno::Exception &) + { + } +} + + +static uno::WeakReference< util::XMacroExpander > aG_xMacroExpander; + +static uno::Reference< util::XMacroExpander > lcl_GetMacroExpander() +{ + uno::Reference< util::XMacroExpander > xMacroExpander( aG_xMacroExpander ); + if ( !xMacroExpander.is() ) + { + if ( !xMacroExpander.is() ) + { + uno::Reference< uno::XComponentContext > xContext; + uno::Reference< beans::XPropertySet > xProps( ::comphelper::getProcessServiceFactory(), uno::UNO_QUERY ); + xProps->getPropertyValue( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("DefaultContext"))) >>= xContext; + if ( xContext.is() ) + { + aG_xMacroExpander = uno::Reference< com::sun::star::util::XMacroExpander >( xContext->getValueByName( + OUString(RTL_CONSTASCII_USTRINGPARAM("/singletons/com.sun.star.util.theMacroExpander"))), + uno::UNO_QUERY ); + xMacroExpander = aG_xMacroExpander; + } + } + } + + return xMacroExpander; +} + + +static bool lcl_GetFileUrlFromOrigin( + OUString /*out*/ &rFileUrl, + const OUString &rOrigin, + uno::Reference< util::XMacroExpander > &rxMacroExpander ) +{ + bool bSuccess = false; + if (rOrigin.getLength() > 0 && rxMacroExpander.is()) + { + rtl::OUString aURL( rOrigin ); + if (( aURL.compareToAscii( RTL_CONSTASCII_STRINGPARAM( EXPAND_PROTOCOL )) == 0 ) && + rxMacroExpander.is() ) + { + // cut protocol + OUString aMacro( aURL.copy( sizeof ( EXPAND_PROTOCOL ) -1 ) ); + // decode uric class chars + aMacro = Uri::decode( aMacro, rtl_UriDecodeWithCharset, RTL_TEXTENCODING_UTF8 ); + // expand macro string + aURL = rxMacroExpander->expandMacros( aMacro ); + + bool bIsFileUrl = aURL.compareToAscii( RTL_CONSTASCII_STRINGPARAM( FILE_PROTOCOL )) == 0; + if (bIsFileUrl) + { + rFileUrl = aURL; + bSuccess = true; + } + else + { + DBG_ASSERT( bIsFileUrl, "not a file URL"); + } + } + else + { + DBG_ASSERT( 0, "failed to get file URL" ); + } + } + return bSuccess; +} + + +BOOL SvtLinguConfig::GetDictionaryEntry( + const rtl::OUString &rNodeName, + SvtLinguConfigDictionaryEntry &rDicEntry ) const +{ + if (rNodeName.getLength() == 0) + return sal_False; + bool bSuccess = false; + try + { + uno::Reference< container::XNameAccess > xNA( GetMainUpdateAccess(), uno::UNO_QUERY_THROW ); + xNA.set( xNA->getByName(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("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< rtl::OUString > aLocations; + rtl::OUString aFormatName; + uno::Sequence< rtl::OUString > aLocaleNames; + bSuccess = (xNA->getByName( aG_Locations ) >>= aLocations) && + (xNA->getByName( aG_Format ) >>= aFormatName) && + (xNA->getByName( aG_Locales ) >>= aLocaleNames); + DBG_ASSERT( aLocations.getLength(), "Dictionary locations not set" ); + DBG_ASSERT( aFormatName.getLength(), "Dictionary format name not set" ); + DBG_ASSERT( aLocaleNames.getLength(), "No locales set for the dictionary" ); + + // if sucessful continue + if (bSuccess) + { + // get file URL's for the locations + uno::Reference< util::XMacroExpander > xMacroExpander( lcl_GetMacroExpander() ); + for (sal_Int32 i = 0; i < aLocations.getLength(); ++i) + { + rtl::OUString &rLocation = aLocations[i]; + if (!lcl_GetFileUrlFromOrigin( rLocation, rLocation, xMacroExpander )) + 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; +} + +void SvtLinguConfig::SetOrCreateDictionaryEntry( + const rtl::OUString &rNodeName, + const SvtLinguConfigDictionaryEntry &rDicEntry ) const +{ + if (rNodeName.getLength() == 0) + return; + try + { + uno::Reference< util::XChangesBatch > xUpdateAccess( GetMainUpdateAccess() ); + uno::Reference< container::XNameAccess > xNA( xUpdateAccess, uno::UNO_QUERY_THROW ); + xNA.set( xNA->getByName(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ServiceManager"))), uno::UNO_QUERY_THROW ); + xNA.set( xNA->getByName( aG_Dictionaries ), uno::UNO_QUERY_THROW ); + xNA = GetOrCreateSetEntry_Impl( xNA, rNodeName ); + + DBG_ASSERT( rDicEntry.aLocations.getLength(), "Applying empty dictionary locations. Really correct??" ); + DBG_ASSERT( rDicEntry.aFormatName.getLength(), "Applying empty dictionary format name. Really correct??" ); + DBG_ASSERT( rDicEntry.aLocaleNames.getLength(), "Applying empty list of locales for the dictionary. Really correct??" ); + + uno::Reference< container::XNameReplace > xNR( xNA, uno::UNO_QUERY_THROW ); + xNR->replaceByName( aG_Locations, uno::makeAny( rDicEntry.aLocations ) ); + xNR->replaceByName( aG_Format, uno::makeAny( rDicEntry.aFormatName ) ); + xNR->replaceByName( aG_Locales, uno::makeAny( rDicEntry.aLocaleNames ) ); + + xUpdateAccess->commitChanges(); + } + catch (uno::Exception &) + { + } +} + +uno::Sequence< rtl::OUString > SvtLinguConfig::GetDisabledDictionaries() const +{ + uno::Sequence< rtl::OUString > aResult; + try + { + uno::Reference< container::XNameAccess > xNA( GetMainUpdateAccess(), uno::UNO_QUERY_THROW ); + xNA.set( xNA->getByName(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ServiceManager"))), uno::UNO_QUERY_THROW ); + xNA->getByName( aG_DisabledDictionaries ) >>= aResult; + } + catch (uno::Exception &) + { + } + return aResult; +} + +void SvtLinguConfig::SetDisabledDictionaries( + const uno::Sequence< rtl::OUString > &rDictionaries ) const +{ + try + { + uno::Reference< util::XChangesBatch > xUpdateAccess( GetMainUpdateAccess() ); + uno::Reference< container::XNameAccess > xNA( xUpdateAccess, uno::UNO_QUERY_THROW ); + xNA.set( xNA->getByName(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ServiceManager"))), uno::UNO_QUERY_THROW ); + if (xNA->hasByName( aG_DisabledDictionaries )) + { + uno::Reference< container::XNameReplace > xNR( xNA, uno::UNO_QUERY_THROW ); + xNR->replaceByName( aG_DisabledDictionaries, makeAny( rDictionaries ) ); + } + else + { + uno::Reference< container::XNameContainer > xNC( xNA, uno::UNO_QUERY_THROW ); + xNC->insertByName( aG_DisabledDictionaries, makeAny( rDictionaries ) ); + } + + xUpdateAccess->commitChanges(); + } + catch (uno::Exception &) + { + } +} + +std::vector< SvtLinguConfigDictionaryEntry > SvtLinguConfig::GetActiveDictionariesByFormat( + const rtl::OUString &rFormatName ) +{ + std::vector< SvtLinguConfigDictionaryEntry > aRes; + if (rFormatName.getLength() == 0) + return aRes; + + try + { + uno::Sequence< rtl::OUString > aElementNames; + GetElementNamesFor( aG_Dictionaries, aElementNames ); + sal_Int32 nLen = aElementNames.getLength(); + const rtl::OUString *pElementNames = aElementNames.getConstArray(); + + SvtLinguConfigDictionaryEntry aDicEntry; + for (sal_Int32 i = 0; i < nLen; ++i) + { + // does dictionary match the format we are looking for? + if (GetDictionaryEntry( pElementNames[i], aDicEntry ) && + aDicEntry.aFormatName == rFormatName) + { + // check if it is active or not + bool bDicIsActive = true; + const uno::Sequence< rtl::OUString > aDisabledDics( GetDisabledDictionaries() ); + for (sal_Int32 k = 0; bDicIsActive && k < aDisabledDics.getLength(); ++k) + { + if (aDisabledDics[k] == pElementNames[i]) + bDicIsActive = false; + } + + if (bDicIsActive) + { + DBG_ASSERT( aDicEntry.aFormatName.getLength(), + "FormatName not set" ); + DBG_ASSERT( aDicEntry.aLocations.getLength(), + "Locations not set" ); + DBG_ASSERT( aDicEntry.aLocaleNames.getLength(), + "Locales not set" ); + aRes.push_back( aDicEntry ); + } + } + } + } + catch (uno::Exception &) + { + } + + return aRes; +} + + +uno::Reference< util::XChangesBatch > SvtLinguConfig::GetMainUpdateAccess() const +{ + if (!m_xMainUpdateAccess.is()) + { + try + { + // get configuration provider + uno::Reference< lang::XMultiServiceFactory > xConfigurationProvider; + uno::Reference< lang::XMultiServiceFactory > xMgr = comphelper::getProcessServiceFactory(); + if (xMgr.is()) + { + xConfigurationProvider = uno::Reference< lang::XMultiServiceFactory > ( + xMgr->createInstance(OUString(RTL_CONSTASCII_USTRINGPARAM( + "com.sun.star.configuration.ConfigurationProvider"))), + uno::UNO_QUERY_THROW ) ; + } + + // get configuration update access + beans::PropertyValue aValue; + aValue.Name = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("nodepath")); + aValue.Value = uno::makeAny(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("org.openoffice.Office.Linguistic"))); + uno::Sequence< uno::Any > aProps(1); + aProps[0] <<= aValue; + m_xMainUpdateAccess = uno::Reference< util::XChangesBatch >( + xConfigurationProvider->createInstanceWithArguments( + rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.configuration.ConfigurationUpdateAccess")), aProps), + uno::UNO_QUERY_THROW ); + } + catch (uno::Exception &) + { + } + } + + return m_xMainUpdateAccess; +} + + +rtl::OUString SvtLinguConfig::GetVendorImageUrl_Impl( + const rtl::OUString &rServiceImplName, + const rtl::OUString &rImageName ) const +{ + rtl::OUString aRes; + try + { + uno::Reference< container::XNameAccess > xImagesNA( GetMainUpdateAccess(), uno::UNO_QUERY_THROW ); + xImagesNA.set( xImagesNA->getByName(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Images"))), uno::UNO_QUERY_THROW ); + + uno::Reference< container::XNameAccess > xNA( xImagesNA->getByName(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ServiceNameEntries"))), uno::UNO_QUERY_THROW ); + xNA.set( xNA->getByName( rServiceImplName ), uno::UNO_QUERY_THROW ); + uno::Any aAny(xNA->getByName(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("VendorImagesNode")))); + rtl::OUString aVendorImagesNode; + if (aAny >>= aVendorImagesNode) + { + xNA = xImagesNA; + xNA.set( xNA->getByName(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("VendorImages"))), uno::UNO_QUERY_THROW ); + xNA.set( xNA->getByName( aVendorImagesNode ), uno::UNO_QUERY_THROW ); + aAny = xNA->getByName( rImageName ); + rtl::OUString aTmp; + if (aAny >>= aTmp) + { + uno::Reference< util::XMacroExpander > xMacroExpander( lcl_GetMacroExpander() ); + if (lcl_GetFileUrlFromOrigin( aTmp, aTmp, xMacroExpander )) + aRes = aTmp; + } + } + } + catch (uno::Exception &) + { + DBG_ASSERT( 0, "exception caught. GetVendorImageUrl_Impl failed" ); + } + return aRes; +} + + +rtl::OUString SvtLinguConfig::GetSpellAndGrammarDialogImage( + const rtl::OUString &rServiceImplName +) const +{ + rtl::OUString aRes; + if (rServiceImplName.getLength() > 0) + { + rtl::OUString aImageName( A2OU( "SpellAndGrammarDialogImage" )); + rtl::OUString aPath( GetVendorImageUrl_Impl( rServiceImplName, aImageName ) ); + aRes = aPath; + } + return aRes; +} + + +rtl::OUString SvtLinguConfig::GetSpellAndGrammarContextSuggestionImage( + const rtl::OUString &rServiceImplName +) const +{ + rtl::OUString aRes; + if (rServiceImplName.getLength() > 0) + { + rtl::OUString aImageName( A2OU( "SpellAndGrammarContextMenuSuggestionImage" )); + rtl::OUString aPath( GetVendorImageUrl_Impl( rServiceImplName, aImageName ) ); + aRes = aPath; + } + return aRes; +} + + +rtl::OUString SvtLinguConfig::GetSpellAndGrammarContextDictionaryImage( + const rtl::OUString &rServiceImplName +) const +{ + rtl::OUString aRes; + if (rServiceImplName.getLength() > 0) + { + rtl::OUString aImageName( A2OU( "SpellAndGrammarContextMenuDictionaryImage" )); + rtl::OUString aPath( GetVendorImageUrl_Impl( rServiceImplName, aImageName ) ); + aRes = aPath; + } + return aRes; +} + + +::rtl::OUString SvtLinguConfig::GetThesaurusDialogImage( + const ::rtl::OUString &rServiceImplName +) const +{ + rtl::OUString aRes; + if (rServiceImplName.getLength() > 0) + { + rtl::OUString aImageName( A2OU( "ThesaurusDialogImage" )); + rtl::OUString aPath( GetVendorImageUrl_Impl( rServiceImplName, aImageName ) ); + aRes = aPath; + } + return aRes; +} + + +::rtl::OUString SvtLinguConfig::GetSynonymsContextImage( + const ::rtl::OUString &rServiceImplName +) const +{ + rtl::OUString aRes; + if (rServiceImplName.getLength() > 0) + { + rtl::OUString aImageName( A2OU( "SynonymsContextMenuImage" )); + rtl::OUString aPath( GetVendorImageUrl_Impl( rServiceImplName, aImageName ) ); + aRes = aPath; + } + return aRes; +} + + +bool SvtLinguConfig::HasVendorImages( const char *pImageName ) const +{ + bool bRes = false; + if (pImageName) + { + try + { + uno::Reference< container::XNameAccess > xNA( GetMainUpdateAccess(), uno::UNO_QUERY_THROW ); + xNA.set( xNA->getByName( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Images")) ), uno::UNO_QUERY_THROW ); + xNA.set( xNA->getByName( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("VendorImages")) ), uno::UNO_QUERY_THROW ); + + uno::Sequence< rtl::OUString > aElementNames( xNA->getElementNames() ); + sal_Int32 nVendors = aElementNames.getLength(); + const rtl::OUString *pVendor = aElementNames.getConstArray(); + for (sal_Int32 i = 0; i < nVendors; ++i) + { + uno::Reference< container::XNameAccess > xNA2( xNA->getByName( pVendor[i] ), uno::UNO_QUERY_THROW ); + uno::Sequence< rtl::OUString > aPropNames( xNA2->getElementNames() ); + sal_Int32 nProps = aPropNames.getLength(); + const rtl::OUString *pPropNames = aPropNames.getConstArray(); + for (sal_Int32 k = 0; k < nProps; ++k) + { + // for a quicker check we ignore the HC image names here + const OUString &rName = pPropNames[k]; + if (rName.equalsAscii( pImageName )) + { + bRes = true; + break; + } + } + } + } + catch (uno::Exception &) + { + DBG_ASSERT( 0, "exception caught. HasVendorImages failed" ); + } + } + return bRes; +} + + +bool SvtLinguConfig::HasGrammarChecker() const +{ + bool bRes = false; + + try + { + uno::Reference< container::XNameAccess > xNA( GetMainUpdateAccess(), uno::UNO_QUERY_THROW ); + xNA.set( xNA->getByName( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ServiceManager")) ), uno::UNO_QUERY_THROW ); + xNA.set( xNA->getByName( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("GrammarCheckerList")) ), uno::UNO_QUERY_THROW ); + + uno::Sequence< rtl::OUString > aElementNames( xNA->getElementNames() ); + bRes = aElementNames.getLength() > 0; + } + catch (uno::Exception &) + { + } + + return bRes; +} + +////////////////////////////////////////////////////////////////////// + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/localisationoptions.cxx b/unotools/source/config/localisationoptions.cxx new file mode 100644 index 000000000000..3f7713e3b854 --- /dev/null +++ b/unotools/source/config/localisationoptions.cxx @@ -0,0 +1,455 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" + +#include <unotools/localisationoptions.hxx> +#include <unotools/configmgr.hxx> +#include <unotools/configitem.hxx> +#include <tools/debug.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> + +#include <rtl/logfile.hxx> +#include "itemholder1.hxx" + +//_________________________________________________________________________________________________________________ +// namespaces +//_________________________________________________________________________________________________________________ + +using namespace ::utl ; +using namespace ::rtl ; +using namespace ::osl ; +using namespace ::com::sun::star::uno ; + +//_________________________________________________________________________________________________________________ +// const +//_________________________________________________________________________________________________________________ + +#define ROOTNODE_LOCALISATION OUString(RTL_CONSTASCII_USTRINGPARAM("Office.Common/View/Localisation")) +#define DEFAULT_AUTOMNEMONIC sal_False +#define DEFAULT_DIALOGSCALE 0 + +#define PROPERTYNAME_AUTOMNEMONIC OUString(RTL_CONSTASCII_USTRINGPARAM("AutoMnemonic" )) +#define PROPERTYNAME_DIALOGSCALE OUString(RTL_CONSTASCII_USTRINGPARAM("DialogScale" )) + +#define PROPERTYHANDLE_AUTOMNEMONIC 0 +#define PROPERTYHANDLE_DIALOGSCALE 1 + +#define PROPERTYCOUNT 2 + +//_________________________________________________________________________________________________________________ +// private declarations! +//_________________________________________________________________________________________________________________ + +class SvtLocalisationOptions_Impl : public ConfigItem +{ + //------------------------------------------------------------------------------------------------------------- + // public methods + //------------------------------------------------------------------------------------------------------------- + + public: + + //--------------------------------------------------------------------------------------------------------- + // constructor / destructor + //--------------------------------------------------------------------------------------------------------- + + SvtLocalisationOptions_Impl(); + ~SvtLocalisationOptions_Impl(); + + //--------------------------------------------------------------------------------------------------------- + // overloaded methods of baseclass + //--------------------------------------------------------------------------------------------------------- + + /*-****************************************************************************************************//** + @short called for notify of configmanager + @descr These method is called from the ConfigManager before application ends or from the + PropertyChangeListener if the sub tree broadcasts changes. You must update your + internal values. + + @seealso baseclass ConfigItem + + @param "seqPropertyNames" is the list of properties which should be updated. + @return - + + @onerror - + *//*-*****************************************************************************************************/ + + virtual void Notify( const Sequence< OUString >& seqPropertyNames ); + + /*-****************************************************************************************************//** + @short write changes to configuration + @descr These method writes the changed values into the sub tree + and should always called in our destructor to guarantee consistency of config data. + + @seealso baseclass ConfigItem + + @param - + @return - + + @onerror - + *//*-*****************************************************************************************************/ + + virtual void Commit(); + + //--------------------------------------------------------------------------------------------------------- + // public interface + //--------------------------------------------------------------------------------------------------------- + + /*-****************************************************************************************************//** + @short access method to get internal values + @descr These method give us a chance to regulate acces to ouer internal values. + It's not used in the moment - but it's possible for the feature! + + @seealso - + + @param - + @return - + + @onerror - + *//*-*****************************************************************************************************/ + + sal_Bool IsAutoMnemonic ( ) const ; + void SetAutoMnemonic ( sal_Bool bState ) ; + sal_Int32 GetDialogScale ( ) const ; + void SetDialogScale ( sal_Int32 nScale ) ; + + //------------------------------------------------------------------------------------------------------------- + // private methods + //------------------------------------------------------------------------------------------------------------- + + private: + + /*-****************************************************************************************************//** + @short return list of key names of ouer configuration management which represent oue module tree + @descr These methods return a static const list of key names. We need it to get needed values from our + configuration management. + + @seealso - + + @param - + @return A list of needed configuration keys is returned. + + @onerror - + *//*-*****************************************************************************************************/ + + static Sequence< OUString > GetPropertyNames(); + + //------------------------------------------------------------------------------------------------------------- + // private member + //------------------------------------------------------------------------------------------------------------- + + private: + + sal_Bool m_bAutoMnemonic ; + sal_Int32 m_nDialogScale ; +}; + +//_________________________________________________________________________________________________________________ +// definitions +//_________________________________________________________________________________________________________________ + +//***************************************************************************************************************** +// constructor +//***************************************************************************************************************** +SvtLocalisationOptions_Impl::SvtLocalisationOptions_Impl() + // Init baseclasses first + : ConfigItem ( ROOTNODE_LOCALISATION ) + // Init member then. + , m_bAutoMnemonic ( DEFAULT_AUTOMNEMONIC ) + , m_nDialogScale ( DEFAULT_DIALOGSCALE ) +{ + // Use our static list of configuration keys to get his values. + Sequence< OUString > seqNames = GetPropertyNames ( ); + Sequence< Any > seqValues = GetProperties ( seqNames ); + + // 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( !(seqNames.getLength()!=seqValues.getLength()), "SvtLocalisationOptions_Impl::SvtLocalisationOptions_Impl()\nI miss some values of configuration keys!\n" ); + + // Copy values from list in right order to ouer internal member. + sal_Int32 nPropertyCount = seqValues.getLength(); + for( sal_Int32 nProperty=0; nProperty<nPropertyCount; ++nProperty ) + { + // Safe impossible cases. + // Check any for valid value. + DBG_ASSERT( !(seqValues[nProperty].hasValue()==sal_False), "SvtLocalisationOptions_Impl::SvtLocalisationOptions_Impl()\nInvalid property value detected!\n" ); + switch( nProperty ) + { + case PROPERTYHANDLE_AUTOMNEMONIC : { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtLocalisationOptions_Impl::SvtLocalisationOptions_Impl()\nWho has changed the value type of \"Office.Common\\View\\Localisation\\AutoMnemonic\"?" ); + seqValues[nProperty] >>= m_bAutoMnemonic; + } + break; + + case PROPERTYHANDLE_DIALOGSCALE : { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_LONG), "SvtLocalisationOptions_Impl::SvtLocalisationOptions_Impl()\nWho has changed the value type of \"Office.Common\\View\\Localisation\\DialogScale\"?" ); + seqValues[nProperty] >>= m_nDialogScale; + } + break; + } + } + + // Enable notification mechanism of ouer baseclass. + // We need it to get information about changes outside these class on ouer used configuration keys! + EnableNotification( seqNames ); +} + +//***************************************************************************************************************** +// destructor +//***************************************************************************************************************** +SvtLocalisationOptions_Impl::~SvtLocalisationOptions_Impl() +{ + // We must save our current values .. if user forget it! + if( IsModified() == sal_True ) + { + Commit(); + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtLocalisationOptions_Impl::Notify( const Sequence< OUString >& seqPropertyNames ) +{ + // Use given list of updated properties to get his values from configuration directly! + Sequence< Any > seqValues = GetProperties( seqPropertyNames ); + // Safe impossible cases. + // We need values from ALL notified configuration keys. + DBG_ASSERT( !(seqPropertyNames.getLength()!=seqValues.getLength()), "SvtLocalisationOptions_Impl::Notify()\nI miss some values of configuration keys!\n" ); + // Step over list of property names and get right value from coreesponding value list to set it on internal members! + sal_Int32 nCount = seqPropertyNames.getLength(); + for( sal_Int32 nProperty=0; nProperty<nCount; ++nProperty ) + { + if( seqPropertyNames[nProperty] == PROPERTYNAME_AUTOMNEMONIC ) + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtLocalisationOptions_Impl::SvtLocalisationOptions_Impl()\nWho has changed the value type of \"Office.Common\\View\\Localisation\\AutoMnemonic\"?" ); + seqValues[nProperty] >>= m_bAutoMnemonic; + } + else + if( seqPropertyNames[nProperty] == PROPERTYNAME_DIALOGSCALE ) + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_LONG), "SvtLocalisationOptions_Impl::SvtLocalisationOptions_Impl()\nWho has changed the value type of \"Office.Common\\View\\Localisation\\DialogScale\"?" ); + seqValues[nProperty] >>= m_nDialogScale; + } + #if OSL_DEBUG_LEVEL > 1 + else DBG_ASSERT( sal_False, "SvtLocalisationOptions_Impl::Notify()\nUnkown property detected ... I can't handle these!\n" ); + #endif + } + + NotifyListeners(0); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtLocalisationOptions_Impl::Commit() +{ + // Get names of supported properties, create a list for values and copy current values to it. + Sequence< OUString > seqNames = GetPropertyNames (); + sal_Int32 nCount = seqNames.getLength(); + Sequence< Any > seqValues ( nCount ); + for( sal_Int32 nProperty=0; nProperty<nCount; ++nProperty ) + { + switch( nProperty ) + { + case PROPERTYHANDLE_AUTOMNEMONIC : { + seqValues[nProperty] <<= m_bAutoMnemonic; + } + break; + + case PROPERTYHANDLE_DIALOGSCALE : { + seqValues[nProperty] <<= m_nDialogScale; + } + break; + } + } + // Set properties in configuration. + PutProperties( seqNames, seqValues ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Bool SvtLocalisationOptions_Impl::IsAutoMnemonic() const +{ + return m_bAutoMnemonic; +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtLocalisationOptions_Impl::SetAutoMnemonic( sal_Bool bState ) +{ + m_bAutoMnemonic = bState; + SetModified(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Int32 SvtLocalisationOptions_Impl::GetDialogScale() const +{ + return m_nDialogScale; +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtLocalisationOptions_Impl::SetDialogScale( sal_Int32 nScale ) +{ + m_nDialogScale = nScale; + SetModified(); +} + +//***************************************************************************************************************** +// private method +//***************************************************************************************************************** +Sequence< OUString > SvtLocalisationOptions_Impl::GetPropertyNames() +{ + // Build static list of configuration key names. + static const OUString pProperties[] = + { + PROPERTYNAME_AUTOMNEMONIC , + PROPERTYNAME_DIALOGSCALE , + }; + // Initialize return sequence with these list ... + static const Sequence< OUString > seqPropertyNames( pProperties, PROPERTYCOUNT ); + // ... and return it. + return seqPropertyNames; +} + +//***************************************************************************************************************** +// initialize static member +// DON'T DO IT IN YOUR HEADER! +// see definition for further informations +//***************************************************************************************************************** +SvtLocalisationOptions_Impl* SvtLocalisationOptions::m_pDataContainer = NULL ; +sal_Int32 SvtLocalisationOptions::m_nRefCount = 0 ; + +//***************************************************************************************************************** +// constructor +//***************************************************************************************************************** +SvtLocalisationOptions::SvtLocalisationOptions() +{ + // Global access, must be guarded (multithreading!). + MutexGuard aGuard( GetOwnStaticMutex() ); + // Increase ouer refcount ... + ++m_nRefCount; + // ... and initialize ouer data container only if it not already exist! + if( m_pDataContainer == NULL ) + { + RTL_LOGFILE_CONTEXT(aLog, "unotools ( ??? ) ::SvtLocalisationOptions_Impl::ctor()"); + m_pDataContainer = new SvtLocalisationOptions_Impl; + + ItemHolder1::holdConfigItem(E_LOCALISATIONOPTIONS); + } +} + +//***************************************************************************************************************** +// destructor +//***************************************************************************************************************** +SvtLocalisationOptions::~SvtLocalisationOptions() +{ + // Global access, must be guarded (multithreading!) + MutexGuard aGuard( GetOwnStaticMutex() ); + // Decrease ouer refcount. + --m_nRefCount; + // If last instance was deleted ... + // we must destroy ouer static data container! + if( m_nRefCount <= 0 ) + { + delete m_pDataContainer; + m_pDataContainer = NULL; + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Bool SvtLocalisationOptions::IsAutoMnemonic() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsAutoMnemonic(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtLocalisationOptions::SetAutoMnemonic( sal_Bool bState ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetAutoMnemonic( bState ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Int32 SvtLocalisationOptions::GetDialogScale() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->GetDialogScale(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtLocalisationOptions::SetDialogScale( sal_Int32 nScale ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetDialogScale( nScale ); +} + +//***************************************************************************************************************** +// private method +//***************************************************************************************************************** +Mutex& SvtLocalisationOptions::GetOwnStaticMutex() +{ + // Initialize static mutex only for one time! + static Mutex* pMutex = NULL; + // If these method first called (Mutex not already exist!) ... + if( pMutex == NULL ) + { + // ... we must create a new one. Protect follow code with the global mutex - + // It must be - we create a static variable! + MutexGuard aGuard( Mutex::getGlobalMutex() ); + // We must check our pointer again - because it can be that another instance of ouer class will be fastr then these! + if( pMutex == NULL ) + { + // Create the new mutex and set it for return on static variable. + static Mutex aMutex; + pMutex = &aMutex; + } + } + // Return new created or already existing mutex object. + return *pMutex; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/makefile.mk b/unotools/source/config/makefile.mk new file mode 100644 index 000000000000..27e8f67f8888 --- /dev/null +++ b/unotools/source/config/makefile.mk @@ -0,0 +1,91 @@ +#************************************************************************* +# +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# +# OpenOffice.org - a multi-platform office productivity suite +# +# This file is part of OpenOffice.org. +# +# OpenOffice.org is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License version 3 +# only, as published by the Free Software Foundation. +# +# OpenOffice.org is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License version 3 for more details +# (a copy is included in the LICENSE file that accompanied this code). +# +# You should have received a copy of the GNU Lesser General Public License +# version 3 along with OpenOffice.org. If not, see +# <http://www.openoffice.org/license.html> +# for a copy of the LGPLv3 License. +# +#************************************************************************* + +PRJ=..$/.. +PRJINC=..$/..$/inc +PRJNAME=unotools +TARGET=config + +ENABLE_EXCEPTIONS=TRUE + +# --- Settings ---------------------------------- + +.INCLUDE : settings.mk +.INCLUDE : $(PRJ)$/util$/makefile.pmk + + +# --- Files ------------------------------------- + +SLOFILES=\ + $(SLO)$/syslocaleoptions.obj \ + $(SLO)$/configvaluecontainer.obj \ + $(SLO)$/confignode.obj \ + $(SLO)$/configitem.obj \ + $(SLO)$/configmgr.obj \ + $(SLO)$/configpathes.obj \ + $(SLO)$/docinfohelper.obj \ + $(SLO)$/bootstrap.obj \ + $(SLO)$/accelcfg.obj \ + $(SLO)$/cacheoptions.obj \ + $(SLO)$/cmdoptions.obj \ + $(SLO)$/compatibility.obj \ + $(SLO)$/defaultoptions.obj \ + $(SLO)$/dynamicmenuoptions.obj \ + $(SLO)$/eventcfg.obj \ + $(SLO)$/extendedsecurityoptions.obj \ + $(SLO)$/fltrcfg.obj \ + $(SLO)$/fontcfg.obj \ + $(SLO)$/fontoptions.obj \ + $(SLO)$/historyoptions.obj \ + $(SLO)$/inetoptions.obj \ + $(SLO)$/internaloptions.obj \ + $(SLO)$/itemholder1.obj \ + $(SLO)$/javaoptions.obj \ + $(SLO)$/lingucfg.obj \ + $(SLO)$/localisationoptions.obj \ + $(SLO)$/misccfg.obj \ + $(SLO)$/moduleoptions.obj \ + $(SLO)$/options.obj \ + $(SLO)$/optionsdlg.obj \ + $(SLO)$/pathoptions.obj \ + $(SLO)$/printwarningoptions.obj \ + $(SLO)$/regoptions.obj \ + $(SLO)$/saveopt.obj \ + $(SLO)$/searchopt.obj \ + $(SLO)$/securityoptions.obj \ + $(SLO)$/sourceviewconfig.obj \ + $(SLO)$/startoptions.obj \ + $(SLO)$/undoopt.obj \ + $(SLO)$/useroptions.obj \ + $(SLO)$/viewoptions.obj \ + $(SLO)$/workingsetoptions.obj \ + $(SLO)$/xmlaccelcfg.obj + +# --- Targets ---------------------------------- + +.INCLUDE : target.mk + diff --git a/unotools/source/config/misccfg.cxx b/unotools/source/config/misccfg.cxx new file mode 100644 index 000000000000..2e05d2a77837 --- /dev/null +++ b/unotools/source/config/misccfg.cxx @@ -0,0 +1,286 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" + +#include <unotools/misccfg.hxx> +#include "rtl/instance.hxx" +#include <unotools/configmgr.hxx> +#include <unotools/configitem.hxx> +#include <tools/debug.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> +#include <osl/mutex.hxx> +#include <osl/mutex.hxx> +#include <rtl/logfile.hxx> +#include "itemholder1.hxx" + +#define DEFAULT_TAB 2000 + +#define DEF_INCH 2540L +#define DEF_RELTWIP 1440L + +using namespace rtl; +using namespace com::sun::star::uno; + +#define C2U(cChar) OUString::createFromAscii(cChar) + +namespace utl +{ + +static SfxMiscCfg* pOptions = NULL; +static sal_Int32 nRefCount = 0; + +class SfxMiscCfg : public utl::ConfigItem +{ + BOOL bPaperSize; // printer warnings + BOOL bPaperOrientation; + BOOL bNotFound; + sal_Int32 nYear2000; // two digit year representation + + const com::sun::star::uno::Sequence<rtl::OUString>& GetPropertyNames(); + void Load(); + +public: + SfxMiscCfg( ); + ~SfxMiscCfg( ); + + virtual void Notify( const com::sun::star::uno::Sequence<rtl::OUString>& aPropertyNames); + virtual void Commit(); + + BOOL IsNotFoundWarning() const {return bNotFound;} + void SetNotFoundWarning( BOOL bSet); + + BOOL IsPaperSizeWarning() const {return bPaperSize;} + void SetPaperSizeWarning(BOOL bSet); + + BOOL IsPaperOrientationWarning() const {return bPaperOrientation;} + void SetPaperOrientationWarning( BOOL bSet); + + // 0 ... 99 + sal_Int32 GetYear2000() const { return nYear2000; } + void SetYear2000( sal_Int32 nSet ); + +}; + +SfxMiscCfg::SfxMiscCfg() : + ConfigItem(C2U("Office.Common") ), + bPaperSize(FALSE), + bPaperOrientation (FALSE), + bNotFound (FALSE), + nYear2000( 1930 ) +{ + RTL_LOGFILE_CONTEXT(aLog, "svl SfxMiscCfg::SfxMiscCfg()"); + + Load(); +} + +SfxMiscCfg::~SfxMiscCfg() +{ +} + +void SfxMiscCfg::SetNotFoundWarning( BOOL bSet) +{ + if(bNotFound != bSet) + SetModified(); + bNotFound = bSet; +} + +void SfxMiscCfg::SetPaperSizeWarning( BOOL bSet) +{ + if(bPaperSize != bSet) + SetModified(); + bPaperSize = bSet; +} + +void SfxMiscCfg::SetPaperOrientationWarning( BOOL bSet) +{ + if(bPaperOrientation != bSet) + SetModified(); + bPaperOrientation = bSet; +} + +void SfxMiscCfg::SetYear2000( sal_Int32 nSet ) +{ + if(nYear2000 != nSet) + SetModified(); + nYear2000 = nSet; +} + +const Sequence<OUString>& SfxMiscCfg::GetPropertyNames() +{ + static Sequence<OUString> aNames; + if(!aNames.getLength()) + { + static const char* aPropNames[] = + { + "Print/Warning/PaperSize", // 0 + "Print/Warning/PaperOrientation", // 1 + "Print/Warning/NotFound", // 2 + "DateFormat/TwoDigitYear", // 3 + }; + const int nCount = 4; + aNames.realloc(nCount); + OUString* pNames = aNames.getArray(); + for(int i = 0; i < nCount; i++) + pNames[i] = OUString::createFromAscii(aPropNames[i]); + } + return aNames; +} + +void SfxMiscCfg::Load() +{ + const Sequence<OUString>& aNames = GetPropertyNames(); + Sequence<Any> aValues = GetProperties(aNames); + EnableNotification(aNames); + const Any* pValues = aValues.getConstArray(); + DBG_ASSERT(aValues.getLength() == aNames.getLength(), "GetProperties failed"); + if(aValues.getLength() == aNames.getLength()) + { + for(int nProp = 0; nProp < aNames.getLength(); nProp++) + { + if(pValues[nProp].hasValue()) + { + switch(nProp) + { + case 0: bPaperSize = *(sal_Bool*)pValues[nProp].getValue(); break; //"Print/Warning/PaperSize", + case 1: bPaperOrientation = *(sal_Bool*)pValues[nProp].getValue(); break; //"Print/Warning/PaperOrientation", + case 2: bNotFound = *(sal_Bool*)pValues[nProp].getValue() ; break; //"Print/Warning/NotFound", + case 3: pValues[nProp] >>= nYear2000;break; //"DateFormat/TwoDigitYear", + } + } + } + } +} + +void SfxMiscCfg::Notify( const com::sun::star::uno::Sequence<rtl::OUString>& ) +{ + Load(); +} + +void SfxMiscCfg::Commit() +{ + const Sequence<OUString>& aNames = GetPropertyNames(); + Sequence<Any> aValues(aNames.getLength()); + Any* pValues = aValues.getArray(); + + const Type& rType = ::getBooleanCppuType(); + for(int nProp = 0; nProp < aNames.getLength(); nProp++) + { + switch(nProp) + { + case 0: pValues[nProp].setValue(&bPaperSize, rType);break; //"Print/Warning/PaperSize", + case 1: pValues[nProp].setValue(&bPaperOrientation, rType);break; //"Print/Warning/PaperOrientation", + case 2: pValues[nProp].setValue(&bNotFound, rType);break; //"Print/Warning/NotFound", + case 3: pValues[nProp] <<= nYear2000;break; //"DateFormat/TwoDigitYear", + } + } + PutProperties(aNames, aValues); +} +// ----------------------------------------------------------------------- +namespace +{ + class LocalSingleton : public rtl::Static< osl::Mutex, LocalSingleton > + { + }; +} + +MiscCfg::MiscCfg( ) +{ + // Global access, must be guarded (multithreading) + ::osl::MutexGuard aGuard( LocalSingleton::get() ); + if ( !pOptions ) + { + RTL_LOGFILE_CONTEXT(aLog, "unotools ( ??? ) SfxMiscCfg::ctor()"); + pOptions = new SfxMiscCfg; + + ItemHolder1::holdConfigItem(E_MISCCFG); + } + + ++nRefCount; + pImpl = pOptions; + pImpl->AddListener(this); +} + +MiscCfg::~MiscCfg( ) +{ + // Global access, must be guarded (multithreading) + ::osl::MutexGuard aGuard( LocalSingleton::get() ); + pImpl->RemoveListener(this); + if ( !--nRefCount ) + { + if ( pOptions->IsModified() ) + pOptions->Commit(); + DELETEZ( pOptions ); + } +} + +BOOL MiscCfg::IsNotFoundWarning() const +{ + return pImpl->IsNotFoundWarning(); +} + +void MiscCfg::SetNotFoundWarning( BOOL bSet) +{ + pImpl->SetNotFoundWarning( bSet ); +} + +BOOL MiscCfg::IsPaperSizeWarning() const +{ + return pImpl->IsPaperSizeWarning(); +} + +void MiscCfg::SetPaperSizeWarning(BOOL bSet) +{ + pImpl->SetPaperSizeWarning( bSet ); +} + +BOOL MiscCfg::IsPaperOrientationWarning() const +{ + return pImpl->IsPaperOrientationWarning(); +} + +void MiscCfg::SetPaperOrientationWarning( BOOL bSet) +{ + pImpl->SetPaperOrientationWarning( bSet ); +} + +sal_Int32 MiscCfg::GetYear2000() const +{ + return pImpl->GetYear2000(); +} + +void MiscCfg::SetYear2000( sal_Int32 nSet ) +{ + pImpl->SetYear2000( nSet ); +} + +} + +/* 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 000000000000..396f5cedf2b8 --- /dev/null +++ b/unotools/source/config/moduleoptions.cxx @@ -0,0 +1,1593 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" + +#include <unotools/moduleoptions.hxx> +#include <comphelper/sequenceashashmap.hxx> +#include <unotools/configmgr.hxx> +#include <unotools/configitem.hxx> +#include <unotools/processfactory.hxx> +#include <osl/diagnose.h> +#include <rtl/ustrbuf.hxx> + +#include <rtl/logfile.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/lang/XMultiServiceFactory.hpp> +#include <com/sun/star/lang/XServiceInfo.hpp> +#include <com/sun/star/document/XTypeDetection.hpp> +#include <com/sun/star/util/XStringSubstitution.hpp> + +#include "itemholder1.hxx" + +//_________________________________________________________________________________________________________________ +// namespaces +//_________________________________________________________________________________________________________________ + +#ifndef css +namespace css = ::com::sun::star; +#endif + +//_________________________________________________________________________________________________________________ +// const +//_________________________________________________________________________________________________________________ + +/*-************************************************************************************************************//** + @descr These values are used to define neccessary keys from our configuration management to support + all functionality of these implementation. + It's a fast way to make changes if some keys change his name or location! + + Property handle are neccessary to specify right position in return list of configuration + for asked values. We ask it with a list of properties to get his values. The returned list + has the same order like our given name list! + e.g.: + NAMELIST[ PROPERTYHANDLE_xxx ] => VALUELIST[ PROPERTYHANDLE_xxx ] +*//*-*************************************************************************************************************/ +#define ROOTNODE_FACTORIES ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Setup/Office/Factories" )) +#define PATHSEPERATOR ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/" )) + +// 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 ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ooSetupFactoryShortName" )) +#define PROPERTYNAME_TEMPLATEFILE ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ooSetupFactoryTemplateFile" )) +#define PROPERTYNAME_WINDOWATTRIBUTES ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ooSetupFactoryWindowAttributes")) +#define PROPERTYNAME_EMPTYDOCUMENTURL ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ooSetupFactoryEmptyDocumentURL")) +#define PROPERTYNAME_DEFAULTFILTER ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ooSetupFactoryDefaultFilter" )) +#define PROPERTYNAME_ICON ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("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 + +#define FACTORYNAME_WRITER ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.text.TextDocument" )) +#define FACTORYNAME_WRITERWEB ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.text.WebDocument" )) +#define FACTORYNAME_WRITERGLOBAL ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.text.GlobalDocument" )) +#define FACTORYNAME_CALC ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.sheet.SpreadsheetDocument" )) +#define FACTORYNAME_DRAW ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.DrawingDocument" )) +#define FACTORYNAME_IMPRESS ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.presentation.PresentationDocument")) +#define FACTORYNAME_MATH ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.formula.FormulaProperties" )) +#define FACTORYNAME_CHART ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.chart2.ChartDocument" )) +#define FACTORYNAME_DATABASE ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.sdb.OfficeDatabaseDocument" )) +#define FACTORYNAME_STARTMODULE ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.frame.StartModule" )) + +#define FACTORYCOUNT 10 + +/*-************************************************************************************************************//** + @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 these informations. +*//*-*************************************************************************************************************/ +struct FactoryInfo +{ + public: + //--------------------------------------------------------------------------------------------------------- + // initialize empty struct + FactoryInfo() + { + free(); + // @@@ should be supplied from outside! + xSMgr = ::utl::getProcessServiceFactory(); + } + + //--------------------------------------------------------------------------------------------------------- + // easy way to reset struct member! + void free() + { + bInstalled = sal_False ; + sFactory = ::rtl::OUString() ; + sShortName = ::rtl::OUString() ; + sTemplateFile = ::rtl::OUString() ; + sWindowAttributes = ::rtl::OUString() ; + sEmptyDocumentURL = ::rtl::OUString() ; + sDefaultFilter = ::rtl::OUString() ; + nIcon = 0 ; + bChangedTemplateFile = sal_False ; + bChangedWindowAttributes = sal_False ; + bChangedEmptyDocumentURL = sal_False ; + bChangedDefaultFilter = sal_False ; + bChangedIcon = sal_False ; + bDefaultFilterReadonly = sal_False ; + } + + //--------------------------------------------------------------------------------------------------------- + // returns list of properties, which has changed only! + // We use given value of sNodeBase to build full qualified pathes ... + // Last sign of it must be "/". Beacuse we use it directly, without any additional things! + css::uno::Sequence< css::beans::PropertyValue > getChangedProperties( const ::rtl::OUString& 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 ); + sal_Int8 nRealyChanged = 0 ; + + if( bChangedTemplateFile == sal_True ) + { + lProperties[nRealyChanged].Name = sNodeBase + PROPERTYNAME_TEMPLATEFILE; + + if ( sTemplateFile.getLength() > 0 ) + { + lProperties[nRealyChanged].Value + <<= getStringSubstitution() + ->reSubstituteVariables( sTemplateFile ); + } + else + { + lProperties[nRealyChanged].Value <<= sTemplateFile; + } + + ++nRealyChanged; + } + if( bChangedWindowAttributes == sal_True ) + { + lProperties[nRealyChanged].Name = sNodeBase + PROPERTYNAME_WINDOWATTRIBUTES; + lProperties[nRealyChanged].Value <<= sWindowAttributes; + ++nRealyChanged; + } + if( bChangedEmptyDocumentURL == sal_True ) + { + lProperties[nRealyChanged].Name = sNodeBase + PROPERTYNAME_EMPTYDOCUMENTURL; + lProperties[nRealyChanged].Value <<= sEmptyDocumentURL; + ++nRealyChanged; + } + if( bChangedDefaultFilter == sal_True ) + { + lProperties[nRealyChanged].Name = sNodeBase + PROPERTYNAME_DEFAULTFILTER; + lProperties[nRealyChanged].Value <<= sDefaultFilter; + ++nRealyChanged; + } + if( bChangedIcon == sal_True ) + { + lProperties[nRealyChanged].Name = sNodeBase + PROPERTYNAME_ICON; + lProperties[nRealyChanged].Value <<= nIcon; + ++nRealyChanged; + } + + // Don't forget to reset changed flags! Otherwise we save it again and again and ... + bChangedTemplateFile = sal_False ; + bChangedWindowAttributes = sal_False ; + bChangedEmptyDocumentURL = sal_False ; + bChangedDefaultFilter = sal_False ; + bChangedIcon = sal_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! + sal_Bool getInstalled () const { return bInstalled; }; + ::rtl::OUString getFactory () const { return sFactory; }; + ::rtl::OUString getShortName () const { return sShortName; }; + ::rtl::OUString getTemplateFile () const { return sTemplateFile; }; + ::rtl::OUString getWindowAttributes () const { return sWindowAttributes; }; + ::rtl::OUString getEmptyDocumentURL () const { return sEmptyDocumentURL; }; + ::rtl::OUString getDefaultFilter () const { return sDefaultFilter; }; + sal_Bool isDefaultFilterReadonly() const { return bDefaultFilterReadonly; } + sal_Int32 getIcon () const { return nIcon; }; + + //--------------------------------------------------------------------------------------------------------- + // If you call set-methods - we check for changes of valkues and mark it. + // But if you whish to set it without that ... you must initialize it! + void initInstalled ( sal_Bool bNewInstalled ) { bInstalled = bNewInstalled ; } + void initFactory ( const ::rtl::OUString& sNewFactory ) { sFactory = sNewFactory ; } + void initShortName ( const ::rtl::OUString& sNewShortName ) { sShortName = sNewShortName ; } + void initWindowAttributes ( const ::rtl::OUString& sNewWindowAttributes ) { sWindowAttributes = sNewWindowAttributes ; } + void initEmptyDocumentURL ( const ::rtl::OUString& sNewEmptyDocumentURL ) { sEmptyDocumentURL = sNewEmptyDocumentURL ; } + void initDefaultFilter ( const ::rtl::OUString& sNewDefaultFilter ) { sDefaultFilter = sNewDefaultFilter ; } + void setDefaultFilterReadonly( const sal_Bool bVal){bDefaultFilterReadonly = bVal;} + void initIcon ( sal_Int32 nNewIcon ) { nIcon = nNewIcon ; } + + //--------------------------------------------------------------------------------------------------------- + void initTemplateFile( const ::rtl::OUString& sNewTemplateFile ) + { + if ( sNewTemplateFile.getLength() > 0 ) + { + sTemplateFile + = getStringSubstitution() + ->substituteVariables( sNewTemplateFile, sal_False ); + } + else + { + sTemplateFile = sNewTemplateFile; + } + } + + //--------------------------------------------------------------------------------------------------------- + void setInstalled( sal_Bool bNewInstalled ) + { + bInstalled = bNewInstalled; + }; + + //--------------------------------------------------------------------------------------------------------- + void setFactory( const ::rtl::OUString& sNewFactory ) + { + sFactory = sNewFactory; + }; + + //--------------------------------------------------------------------------------------------------------- + void setShortName( const ::rtl::OUString& sNewShortName ) + { + sShortName = sNewShortName; + }; + + //--------------------------------------------------------------------------------------------------------- + void setTemplateFile( const ::rtl::OUString& sNewTemplateFile ) + { + if( sTemplateFile != sNewTemplateFile ) + { + sTemplateFile = sNewTemplateFile; + bChangedTemplateFile = sal_True ; + } + }; + + //--------------------------------------------------------------------------------------------------------- + void setWindowAttributes( const ::rtl::OUString& sNewWindowAttributes ) + { + if( sWindowAttributes != sNewWindowAttributes ) + { + sWindowAttributes = sNewWindowAttributes; + bChangedWindowAttributes = sal_True ; + } + }; + + //--------------------------------------------------------------------------------------------------------- + void setEmptyDocumentURL( const ::rtl::OUString& sNewEmptyDocumentURL ) + { + if( sEmptyDocumentURL != sNewEmptyDocumentURL ) + { + sEmptyDocumentURL = sNewEmptyDocumentURL; + bChangedEmptyDocumentURL = sal_True ; + } + }; + + //--------------------------------------------------------------------------------------------------------- + void setDefaultFilter( const ::rtl::OUString& sNewDefaultFilter ) + { + if( sDefaultFilter != sNewDefaultFilter ) + { + sDefaultFilter = sNewDefaultFilter; + bChangedDefaultFilter = sal_True ; + } + }; + + //--------------------------------------------------------------------------------------------------------- + void setIcon( sal_Int32 nNewIcon ) + { + if( nNewIcon != nNewIcon ) + { + nNewIcon = nNewIcon; + bChangedIcon = sal_True; + } + }; + + private: + css::uno::Reference< css::util::XStringSubstitution > getStringSubstitution() + { + if ( !xSubstVars.is() ) + { + xSubstVars + = css::uno::Reference< css::util::XStringSubstitution >( + xSMgr->createInstance( + ::rtl::OUString( + RTL_CONSTASCII_USTRINGPARAM( + "com.sun.star.util.PathSubstitution" ) ) ), + css::uno::UNO_QUERY ); + if ( !xSubstVars.is() ) + throw css::uno::RuntimeException( + ::rtl::OUString( + RTL_CONSTASCII_USTRINGPARAM( + "Cannot instanciate service " + "com.sun.star.util.PathSubstitution" ) ), + css::uno::Reference< css::uno::XInterface >() ); + } + return xSubstVars; + } + + sal_Bool bInstalled ; + ::rtl::OUString sFactory ; + ::rtl::OUString sShortName ; + ::rtl::OUString sTemplateFile ; + ::rtl::OUString sWindowAttributes ; + ::rtl::OUString sEmptyDocumentURL ; + ::rtl::OUString sDefaultFilter ; + sal_Int32 nIcon ; + + sal_Bool bChangedTemplateFile :1 ; + sal_Bool bChangedWindowAttributes :1 ; + sal_Bool bChangedEmptyDocumentURL :1 ; + sal_Bool bChangedDefaultFilter :1 ; + sal_Bool bChangedIcon :1 ; + sal_Bool bDefaultFilterReadonly :1 ; + + css::uno::Reference< css::lang::XMultiServiceFactory > xSMgr; + css::uno::Reference< css::util::XStringSubstitution > xSubstVars; +}; + +typedef FactoryInfo FactoryInfoList[FACTORYCOUNT]; + +/*-************************************************************************************************************//** + @short IMPL data container for wrapper class SvtModulOptions! + @descr These class is used as a static data container of class SvtModuleOptions. The hold it by using + a refcount and make it threadsafe by using an osl mutex. So we don't must do anything for that. + We can implement pure functionality to read/write configuration data only. + + @implements - + @base ConfigItem + + @devstatus ready to use + @threadsafe no +*//*-*************************************************************************************************************/ +class SvtModuleOptions_Impl : public ::utl::ConfigItem +{ + //------------------------------------------------------------------------------------------------------------- + // public methods + //------------------------------------------------------------------------------------------------------------- + public: + //--------------------------------------------------------------------------------------------------------- + // constructor / destructor + //--------------------------------------------------------------------------------------------------------- + SvtModuleOptions_Impl(SvtModuleOptions* pOutsideClass); + ~SvtModuleOptions_Impl(); + + //--------------------------------------------------------------------------------------------------------- + // overloaded methods of baseclass + //--------------------------------------------------------------------------------------------------------- + virtual void Notify( const css::uno::Sequence< ::rtl::OUString >& lPropertyNames ); + virtual void Commit( ); + + //--------------------------------------------------------------------------------------------------------- + // public interface + //--------------------------------------------------------------------------------------------------------- + sal_Bool IsModuleInstalled ( SvtModuleOptions::EModule eModule ) const; + ::com::sun::star::uno::Sequence < ::rtl::OUString > GetAllServiceNames(); + ::rtl::OUString GetFactoryName ( SvtModuleOptions::EFactory eFactory ) const; + ::rtl::OUString GetFactoryShortName ( SvtModuleOptions::EFactory eFactory ) const; + ::rtl::OUString GetFactoryStandardTemplate( SvtModuleOptions::EFactory eFactory ) const; + ::rtl::OUString GetFactoryWindowAttributes( SvtModuleOptions::EFactory eFactory ) const; + ::rtl::OUString GetFactoryEmptyDocumentURL( SvtModuleOptions::EFactory eFactory ) const; + ::rtl::OUString GetFactoryDefaultFilter ( SvtModuleOptions::EFactory eFactory ) const; + sal_Bool IsDefaultFilterReadonly( SvtModuleOptions::EFactory eFactory ) const; + sal_Int32 GetFactoryIcon ( SvtModuleOptions::EFactory eFactory ) const; + static sal_Bool ClassifyFactoryByName ( const ::rtl::OUString& sName , + SvtModuleOptions::EFactory& eFactory ); + void SetFactoryStandardTemplate( SvtModuleOptions::EFactory eFactory , + const ::rtl::OUString& sTemplate ); + void SetFactoryWindowAttributes( SvtModuleOptions::EFactory eFactory , + const ::rtl::OUString& sAttributes); + void SetFactoryDefaultFilter ( SvtModuleOptions::EFactory eFactory , + const ::rtl::OUString& sFilter ); + void MakeReadonlyStatesAvailable(); + + //------------------------------------------------------------------------------------------------------------- + // private methods + //------------------------------------------------------------------------------------------------------------- + private: + static css::uno::Sequence< ::rtl::OUString > impl_ExpandSetNames ( const css::uno::Sequence< ::rtl::OUString >& lSetNames ); + void impl_Read ( const css::uno::Sequence< ::rtl::OUString >& lSetNames ); + + //------------------------------------------------------------------------------------------------------------- + // private types + //------------------------------------------------------------------------------------------------------------- + private: + + //------------------------------------------------------------------------------------------------------------- + // private member + //------------------------------------------------------------------------------------------------------------- + private: + FactoryInfoList m_lFactories; + sal_Bool m_bReadOnlyStatesWellKnown; + SvtModuleOptions* m_pOutsideClass; +}; + +//_________________________________________________________________________________________________________________ +// definitions +//_________________________________________________________________________________________________________________ + +/*-************************************************************************************************************//** + @short default ctor + @descr We open our configuration here and read all neccessary 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() + + @param - + @return - + + @onerror - + @threadsafe no +*//*-*************************************************************************************************************/ +SvtModuleOptions_Impl::SvtModuleOptions_Impl(SvtModuleOptions* pOutsideClass) + : ::utl::ConfigItem( ROOTNODE_FACTORIES ) + , m_bReadOnlyStatesWellKnown( sal_False ) + , m_pOutsideClass( pOutsideClass ) +{ + // First initialize list of factory infos! Otherwise we couldnt gurantee right working of these class. + for( sal_Int32 nFactory=0; nFactory<FACTORYCOUNT; ++nFactory ) + m_lFactories[nFactory].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< ::rtl::OUString > lFactories = GetNodeNames( ::rtl::OUString() ); + impl_Read( lFactories ); + + // Enable notification for changes by using configuration directly. + // So we can update our internal values immediatly. + EnableNotification( lFactories ); +} + +/*-************************************************************************************************************//** + @short default dtor + @descr If any values of our cache was modified we should write it back to configuration. + + @attention Don't forget to call "SetModified()" method of base class ConfigItem if any interface method + of this class modify internal member list m_lFactories! Otherwise Commit() will never be called!!! + + @seealso baseclass ConfigItem + + @param - + @return - + + @onerror - + @threadsafe no +*//*-*************************************************************************************************************/ +SvtModuleOptions_Impl::~SvtModuleOptions_Impl() +{ + if( IsModified() == sal_True ) + { + Commit(); + } +} + +/*-************************************************************************************************************//** + @short called for notify of configmanager + @descr These 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 - these 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. + @return - + + @onerror - + @threadsafe no +*//*-*************************************************************************************************************/ +void SvtModuleOptions_Impl::Notify( const css::uno::Sequence< ::rtl::OUString >& ) +{ + OSL_ENSURE( sal_False, "SvtModuleOptions_Impl::Notify()\nNot implemented yet!\n" ); +} + +/*-****************************************************************************************************//** + @short write changes to configuration + @descr These 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 completly 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 + + @param - + @return - + + @onerror - + @threadsafe no +*//*-*****************************************************************************************************/ +void SvtModuleOptions_Impl::Commit() +{ + // Reserve memory for ALL possible factory properties! + // Step over all factories and get her realy changed values only. + // Build list of these ones and use it for commit. + css::uno::Sequence< css::beans::PropertyValue > lCommitProperties( FACTORYCOUNT*PROPERTYCOUNT ); + FactoryInfo* pInfo = NULL ; + sal_Int32 nRealCount = 0 ; + ::rtl::OUString sBasePath ; + for( sal_Int32 nFactory=0; nFactory<FACTORYCOUNT; ++nFactory ) + { + pInfo = &(m_lFactories[nFactory]); + + // These path is used to build full qualified property names .... + // See pInfo->getChangedProperties() for further informations + sBasePath = PATHSEPERATOR + pInfo->getFactory() + PATHSEPERATOR; + + const css::uno::Sequence< css::beans::PropertyValue > lChangedProperties = pInfo->getChangedProperties ( sBasePath ); + const css::beans::PropertyValue* pChangedProperties = lChangedProperties.getConstArray(); + sal_Int32 nPropertyCount = lChangedProperties.getLength(); + for( sal_Int32 nProperty=0; nProperty<nPropertyCount; ++nProperty ) + { + lCommitProperties[nRealCount] = pChangedProperties[nProperty]; + ++nRealCount; + } + } + // Resize commit list to real size. + // If nothing to do - suppress calling of configuration ... + // It could be to expensive :-) + if( nRealCount > 0 ) + { + lCommitProperties.realloc( nRealCount ); + SetSetProperties( ::rtl::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 poeple 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. + + @seealso - + + @param "eModule" , index in list - specify module + @param "eFactory" , index in list - specify factory + @param "sTemplate", set new standard template for these factory + @return Queried information. + + @onerror We return default values. (mostly "not installed"!) + @threadsafe no +*//*-*****************************************************************************************************/ +sal_Bool SvtModuleOptions_Impl::IsModuleInstalled( SvtModuleOptions::EModule eModule ) const +{ + sal_Bool bInstalled = sal_False; + switch( eModule ) + { + case SvtModuleOptions::E_SWRITER : bInstalled = m_lFactories[SvtModuleOptions::E_WRITER].getInstalled(); + break; + case SvtModuleOptions::E_SWEB : bInstalled = m_lFactories[SvtModuleOptions::E_WRITERWEB].getInstalled(); + break; + case SvtModuleOptions::E_SGLOBAL : bInstalled = m_lFactories[SvtModuleOptions::E_WRITERGLOBAL].getInstalled(); + break; + case SvtModuleOptions::E_SCALC : bInstalled = m_lFactories[SvtModuleOptions::E_CALC].getInstalled(); + break; + case SvtModuleOptions::E_SDRAW : bInstalled = m_lFactories[SvtModuleOptions::E_DRAW].getInstalled(); + break; + case SvtModuleOptions::E_SIMPRESS : bInstalled = m_lFactories[SvtModuleOptions::E_IMPRESS].getInstalled(); + break; + case SvtModuleOptions::E_SMATH : bInstalled = m_lFactories[SvtModuleOptions::E_MATH].getInstalled(); + break; + case SvtModuleOptions::E_SCHART : bInstalled = m_lFactories[SvtModuleOptions::E_CHART].getInstalled(); + break; + case SvtModuleOptions::E_SSTARTMODULE : bInstalled = m_lFactories[SvtModuleOptions::E_STARTMODULE].getInstalled(); + break; + case SvtModuleOptions::E_SBASIC : bInstalled = sal_True; // Couldn't be deselected by setup yet! + break; + case SvtModuleOptions::E_SDATABASE : bInstalled = m_lFactories[SvtModuleOptions::E_DATABASE].getInstalled(); + break; + } + + return bInstalled; +} + +::com::sun::star::uno::Sequence < ::rtl::OUString > SvtModuleOptions_Impl::GetAllServiceNames() +{ + sal_uInt32 nCount=0; + if( m_lFactories[SvtModuleOptions::E_WRITER].getInstalled() ) + nCount++; + if ( m_lFactories[SvtModuleOptions::E_WRITERWEB].getInstalled() ) + nCount++; + if ( m_lFactories[SvtModuleOptions::E_WRITERGLOBAL].getInstalled() ) + nCount++; + if( m_lFactories[SvtModuleOptions::E_SCALC].getInstalled() ) + nCount++; + if( m_lFactories[SvtModuleOptions::E_SDRAW].getInstalled() ) + nCount++; + if( m_lFactories[SvtModuleOptions::E_SIMPRESS].getInstalled() ) + nCount++; + if( m_lFactories[SvtModuleOptions::E_SCHART].getInstalled() ) + nCount++; + if( m_lFactories[SvtModuleOptions::E_SMATH].getInstalled() ) + nCount++; + if( m_lFactories[SvtModuleOptions::E_SBASIC].getInstalled() ) + nCount++; + if( m_lFactories[SvtModuleOptions::E_SDATABASE].getInstalled() ) + nCount++; + + css::uno::Sequence < ::rtl::OUString > aRet( nCount ); + sal_Int32 n=0; + if( m_lFactories[SvtModuleOptions::E_WRITER].getInstalled() ) + aRet[n++] = m_lFactories[SvtModuleOptions::E_WRITER].getFactory(); + if ( m_lFactories[SvtModuleOptions::E_WRITERWEB].getInstalled() ) + aRet[n++] = m_lFactories[SvtModuleOptions::E_WRITERWEB].getFactory(); + if ( m_lFactories[SvtModuleOptions::E_WRITERGLOBAL].getInstalled() ) + aRet[n++] = m_lFactories[SvtModuleOptions::E_WRITERGLOBAL].getFactory(); + if( m_lFactories[SvtModuleOptions::E_SCALC].getInstalled() ) + aRet[n++] = m_lFactories[SvtModuleOptions::E_SCALC].getFactory(); + if( m_lFactories[SvtModuleOptions::E_SDRAW].getInstalled() ) + aRet[n++] = m_lFactories[SvtModuleOptions::E_SDRAW].getFactory(); + if( m_lFactories[SvtModuleOptions::E_SIMPRESS].getInstalled() ) + aRet[n++] = m_lFactories[SvtModuleOptions::E_SIMPRESS].getFactory(); + if( m_lFactories[SvtModuleOptions::E_SCHART].getInstalled() ) + aRet[n++] = m_lFactories[SvtModuleOptions::E_SCHART].getFactory(); + if( m_lFactories[SvtModuleOptions::E_SMATH].getInstalled() ) + aRet[n++] = m_lFactories[SvtModuleOptions::E_SMATH].getFactory(); + if( m_lFactories[SvtModuleOptions::E_SBASIC].getInstalled() ) + aRet[n++] = m_lFactories[SvtModuleOptions::E_SBASIC].getFactory(); + if( m_lFactories[SvtModuleOptions::E_SDATABASE].getInstalled() ) + aRet[n++] = m_lFactories[SvtModuleOptions::E_SDATABASE].getFactory(); + + return aRet; +} + +//***************************************************************************************************************** +::rtl::OUString SvtModuleOptions_Impl::GetFactoryName( SvtModuleOptions::EFactory eFactory ) const +{ + ::rtl::OUString sName; + + if( eFactory>=0 && eFactory<FACTORYCOUNT ) + { + sName = m_lFactories[eFactory].getFactory(); + } + + return sName; +} + +//***************************************************************************************************************** +::rtl::OUString SvtModuleOptions_Impl::GetFactoryShortName( SvtModuleOptions::EFactory eFactory ) const +{ + // 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; + + ::rtl::OUString sShortName; + switch( eFactory ) + { + case SvtModuleOptions::E_WRITER : sShortName = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("swriter")); + break; + case SvtModuleOptions::E_WRITERWEB : sShortName = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("swriter/web")); + break; + case SvtModuleOptions::E_WRITERGLOBAL : sShortName = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("swriter/GlobalDocument")); + break; + case SvtModuleOptions::E_CALC : sShortName = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("scalc")); + break; + case SvtModuleOptions::E_DRAW : sShortName = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("sdraw")); + break; + case SvtModuleOptions::E_IMPRESS : sShortName = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("simpress")); + break; + case SvtModuleOptions::E_MATH : sShortName = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("smath")); + break; + case SvtModuleOptions::E_CHART : sShortName = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("schart")); + break; + case SvtModuleOptions::E_BASIC : sShortName = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("sbasic")); + break; + case SvtModuleOptions::E_DATABASE : sShortName = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("sdatabase")); + break; + default: + OSL_ASSERT( "unknown factory" ); + break; + } + + return sShortName; +} + +//***************************************************************************************************************** +::rtl::OUString SvtModuleOptions_Impl::GetFactoryStandardTemplate( SvtModuleOptions::EFactory eFactory ) const +{ + ::rtl::OUString sFile; + + if( eFactory>=0 && eFactory<FACTORYCOUNT ) + { + sFile = m_lFactories[eFactory].getTemplateFile(); + } + + return sFile; +} + +//***************************************************************************************************************** +::rtl::OUString SvtModuleOptions_Impl::GetFactoryWindowAttributes( SvtModuleOptions::EFactory eFactory ) const +{ + ::rtl::OUString sAttributes; + + if( eFactory>=0 && eFactory<FACTORYCOUNT ) + { + sAttributes = m_lFactories[eFactory].getWindowAttributes(); + } + + return sAttributes; +} + +//***************************************************************************************************************** +::rtl::OUString SvtModuleOptions_Impl::GetFactoryEmptyDocumentURL( SvtModuleOptions::EFactory eFactory ) const +{ + // 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(); + + ::rtl::OUString sURL; + switch( eFactory ) + { + case SvtModuleOptions::E_WRITER : sURL = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("private:factory/swriter")); + break; + case SvtModuleOptions::E_WRITERWEB : sURL = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("private:factory/swriter/web")); + break; + case SvtModuleOptions::E_WRITERGLOBAL : sURL = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("private:factory/swriter/GlobalDocument")); + break; + case SvtModuleOptions::E_CALC : sURL = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("private:factory/scalc")); + break; + case SvtModuleOptions::E_DRAW : sURL = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("private:factory/sdraw")); + break; + case SvtModuleOptions::E_IMPRESS : sURL = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("private:factory/simpress?slot=6686")); + break; + case SvtModuleOptions::E_MATH : sURL = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("private:factory/smath")); + break; + case SvtModuleOptions::E_CHART : sURL = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("private:factory/schart")); + break; + case SvtModuleOptions::E_BASIC : sURL = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("private:factory/sbasic")); + break; + case SvtModuleOptions::E_DATABASE : sURL = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("private:factory/sdatabase?Interactive")); + break; + default: + OSL_ASSERT( "unknown factory" ); + break; + } + return sURL; +} + +//***************************************************************************************************************** +::rtl::OUString SvtModuleOptions_Impl::GetFactoryDefaultFilter( SvtModuleOptions::EFactory eFactory ) const +{ + ::rtl::OUString sDefaultFilter; + + if( eFactory>=0 && eFactory<FACTORYCOUNT ) + { + sDefaultFilter = m_lFactories[eFactory].getDefaultFilter(); + } + return sDefaultFilter; +} +//***************************************************************************************************************** +sal_Bool SvtModuleOptions_Impl::IsDefaultFilterReadonly( SvtModuleOptions::EFactory eFactory ) const +{ + sal_Bool bRet = sal_False; + if( eFactory>=0 && eFactory<FACTORYCOUNT ) + { + bRet = m_lFactories[eFactory].isDefaultFilterReadonly(); + } + return bRet; +} + +//***************************************************************************************************************** +sal_Int32 SvtModuleOptions_Impl::GetFactoryIcon( SvtModuleOptions::EFactory eFactory ) const +{ + sal_Int32 nIcon = 0; + + if( eFactory>=0 && eFactory<FACTORYCOUNT ) + { + nIcon = m_lFactories[eFactory].getIcon(); + } + + return nIcon; +} + +//***************************************************************************************************************** +void SvtModuleOptions_Impl::SetFactoryStandardTemplate( SvtModuleOptions::EFactory eFactory , + const ::rtl::OUString& sTemplate ) +{ + if( eFactory>=0 && eFactory<FACTORYCOUNT ) + { + m_lFactories[eFactory].setTemplateFile( sTemplate ); + SetModified(); + } +} + +//***************************************************************************************************************** +void SvtModuleOptions_Impl::SetFactoryWindowAttributes( SvtModuleOptions::EFactory eFactory , + const ::rtl::OUString& sAttributes) +{ + if( eFactory>=0 && eFactory<FACTORYCOUNT ) + { + m_lFactories[eFactory].setWindowAttributes( sAttributes ); + SetModified(); + } +} + +//***************************************************************************************************************** +void SvtModuleOptions_Impl::SetFactoryDefaultFilter( SvtModuleOptions::EFactory eFactory, + const ::rtl::OUString& sFilter ) +{ + if( eFactory>=0 && eFactory<FACTORYCOUNT ) + { + m_lFactories[eFactory].setDefaultFilter( sFilter ); + SetModified(); + } +} + +/*-************************************************************************************************************//** + @short return list of key names of ouer 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 neccessary for this implementation. + These full expanded list should be used to get values of this properties. + + @seealso ctor + + @param - + @return List of all relative addressed properties of given set entry names. + + @onerror List will be empty. + @threadsafe no +*//*-*************************************************************************************************************/ +css::uno::Sequence< ::rtl::OUString > SvtModuleOptions_Impl::impl_ExpandSetNames( const css::uno::Sequence< ::rtl::OUString >& lSetNames ) +{ + sal_Int32 nCount = lSetNames.getLength() ; + css::uno::Sequence< ::rtl::OUString > lPropNames ( nCount*PROPERTYCOUNT ); + ::rtl::OUString* pPropNames = lPropNames.getArray() ; + sal_Int32 nPropStart = 0 ; + + for( sal_Int32 nName=0; nName<nCount; ++nName ) + { + pPropNames[nPropStart+PROPERTYHANDLE_SHORTNAME ] = lSetNames[nName] + PATHSEPERATOR + PROPERTYNAME_SHORTNAME ; + pPropNames[nPropStart+PROPERTYHANDLE_TEMPLATEFILE ] = lSetNames[nName] + PATHSEPERATOR + PROPERTYNAME_TEMPLATEFILE ; + pPropNames[nPropStart+PROPERTYHANDLE_WINDOWATTRIBUTES] = lSetNames[nName] + PATHSEPERATOR + PROPERTYNAME_WINDOWATTRIBUTES; + pPropNames[nPropStart+PROPERTYHANDLE_EMPTYDOCUMENTURL] = lSetNames[nName] + PATHSEPERATOR + PROPERTYNAME_EMPTYDOCUMENTURL; + pPropNames[nPropStart+PROPERTYHANDLE_DEFAULTFILTER ] = lSetNames[nName] + PATHSEPERATOR + PROPERTYNAME_DEFAULTFILTER ; + pPropNames[nPropStart+PROPERTYHANDLE_ICON ] = lSetNames[nName] + PATHSEPERATOR + PROPERTYNAME_ICON ; + nPropStart += PROPERTYCOUNT; + } + + return lPropNames; +} + +/*-************************************************************************************************************//** + @short helper to classify given factory by name + @descr Every factory has his 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 TRUE! + Algorithm: Set out-parameter to propably value ... and check the longname. + If it match 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! + + @seealso - + + @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 +*//*-*************************************************************************************************************/ +sal_Bool SvtModuleOptions_Impl::ClassifyFactoryByName( const ::rtl::OUString& sName, SvtModuleOptions::EFactory& eFactory ) +{ + sal_Bool bState; + + eFactory = SvtModuleOptions::E_WRITER ; + bState = ( sName == FACTORYNAME_WRITER ); + + if( bState == sal_False ) + { + eFactory = SvtModuleOptions::E_WRITERWEB ; + bState = ( sName == FACTORYNAME_WRITERWEB ); + } + // no else! + if( bState == sal_False ) + { + eFactory = SvtModuleOptions::E_WRITERGLOBAL ; + bState = ( sName == FACTORYNAME_WRITERGLOBAL ); + } + // no else! + if( bState == sal_False ) + { + eFactory = SvtModuleOptions::E_CALC ; + bState = ( sName == FACTORYNAME_CALC ); + } + // no else! + if( bState == sal_False ) + { + eFactory = SvtModuleOptions::E_DRAW ; + bState = ( sName == FACTORYNAME_DRAW ); + } + // no else! + if( bState == sal_False ) + { + eFactory = SvtModuleOptions::E_IMPRESS ; + bState = ( sName == FACTORYNAME_IMPRESS ); + } + // no else! + if( bState == sal_False ) + { + eFactory = SvtModuleOptions::E_MATH ; + bState = ( sName == FACTORYNAME_MATH ); + } + // no else! + if( bState == sal_False ) + { + eFactory = SvtModuleOptions::E_CHART ; + bState = ( sName == FACTORYNAME_CHART ); + } + // no else! + if( bState == sal_False ) + { + eFactory = SvtModuleOptions::E_DATABASE ; + bState = ( sName == FACTORYNAME_DATABASE ); + } + // no else! + if( bState == sal_False ) + { + eFactory = SvtModuleOptions::E_STARTMODULE ; + bState = ( sName == FACTORYNAME_STARTMODULE); + } + + 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 readed. + @return - + + @onerror We do nothing. + @threadsafe no +*//*-*************************************************************************************************************/ +void SvtModuleOptions_Impl::impl_Read( const css::uno::Sequence< ::rtl::OUString >& lFactories ) +{ + // Expand every set node name in lFactories to full qualified pathes to his properties + // and get right values from configuration. + const css::uno::Sequence< ::rtl::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!\n" ); + + // 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 informations 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 ; + sal_Int32 nNodeCount = lFactories.getLength(); + FactoryInfo* pInfo = NULL ; + SvtModuleOptions::EFactory eFactory ; + + for( sal_Int32 nSetNode=0; nSetNode<nNodeCount; ++nSetNode ) + { + const ::rtl::OUString& sFactoryName = lFactories[nSetNode]; + if( ClassifyFactoryByName( sFactoryName, eFactory ) == sal_True ) + { + ::rtl::OUString sTemp; + sal_Int32 nTemp = 0; + + pInfo = &(m_lFactories[eFactory]); + pInfo->free(); + + pInfo->initInstalled( sal_True ); + pInfo->initFactory ( sFactoryName ); + + if (lValues[nPropertyStart+PROPERTYHANDLE_SHORTNAME] >>= sTemp) + pInfo->initShortName( sTemp ); + if (lValues[nPropertyStart+PROPERTYHANDLE_TEMPLATEFILE] >>= sTemp) + pInfo->initTemplateFile( sTemp ); + if (lValues[nPropertyStart+PROPERTYHANDLE_WINDOWATTRIBUTES] >>= sTemp) + pInfo->initWindowAttributes( sTemp ); + if (lValues[nPropertyStart+PROPERTYHANDLE_EMPTYDOCUMENTURL] >>= sTemp) + pInfo->initEmptyDocumentURL( 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< ::rtl::OUString > lFactories = GetNodeNames(::rtl::OUString()); + sal_Int32 c = lFactories.getLength(); + sal_Int32 i = 0; + for (i=0; i<c; ++i) + { + ::rtl::OUStringBuffer sPath(256); + sPath.append(lFactories[i] ); + sPath.append(PATHSEPERATOR ); + sPath.append(PROPERTYNAME_DEFAULTFILTER); + + lFactories[i] = sPath.makeStringAndClear(); + } + + css::uno::Sequence< sal_Bool > lReadonlyStates = GetReadOnlyStates(lFactories); + for (i=0; i<c; ++i) + { + ::rtl::OUString& rFactoryName = lFactories[i]; + SvtModuleOptions::EFactory eFactory ; + + if (!ClassifyFactoryByName(rFactoryName, eFactory)) + continue; + + FactoryInfo& rInfo = m_lFactories[eFactory]; + rInfo.setDefaultFilterReadonly(lReadonlyStates[i]); + } + + m_bReadOnlyStatesWellKnown = sal_True; +} + +//***************************************************************************************************************** +// initialize static member +// DON'T DO IT IN YOUR HEADER! +// see definition for further informations +//***************************************************************************************************************** +SvtModuleOptions_Impl* SvtModuleOptions::m_pDataContainer = NULL ; +sal_Int32 SvtModuleOptions::m_nRefCount = 0 ; + +/*-************************************************************************************************************//** + @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() + + @param - + @return - + + @onerror - + @threadsafe yes +*//*-*************************************************************************************************************/ +SvtModuleOptions::SvtModuleOptions() +{ + ::osl::MutexGuard aGuard( impl_GetOwnStaticMutex() ); + ++m_nRefCount; + if( m_nRefCount == 1 ) + { + RTL_LOGFILE_CONTEXT(aLog, "unotools ( ??? ) ::SvtModuleOptions_Impl::ctor()"); + m_pDataContainer = new SvtModuleOptions_Impl(this); + + ItemHolder1::holdConfigItem(E_MODULEOPTIONS); + } +} + +//***************************************************************************************************************** +SvtModuleOptions::~SvtModuleOptions() +{ + ::osl::MutexGuard aGuard( impl_GetOwnStaticMutex() ); + --m_nRefCount; + if( m_nRefCount == 0 ) + { + delete m_pDataContainer; + m_pDataContainer = NULL; + } +} + +/*-************************************************************************************************************//** + @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 informations! + + @seealso method impl_GetOwnStaticMutex() + + @param - + @return - + + @onerror - + @threadsafe yes +*//*-*************************************************************************************************************/ +sal_Bool SvtModuleOptions::IsModuleInstalled( EModule eModule ) const +{ + ::osl::MutexGuard aGuard( impl_GetOwnStaticMutex() ); + return m_pDataContainer->IsModuleInstalled( eModule ); +} + +//***************************************************************************************************************** +::rtl::OUString SvtModuleOptions::GetFactoryName( EFactory eFactory ) const +{ + ::osl::MutexGuard aGuard( impl_GetOwnStaticMutex() ); + return m_pDataContainer->GetFactoryName( eFactory ); +} + +//***************************************************************************************************************** +::rtl::OUString SvtModuleOptions::GetFactoryShortName( EFactory eFactory ) const +{ + ::osl::MutexGuard aGuard( impl_GetOwnStaticMutex() ); + return m_pDataContainer->GetFactoryShortName( eFactory ); +} + +//***************************************************************************************************************** +::rtl::OUString SvtModuleOptions::GetFactoryStandardTemplate( EFactory eFactory ) const +{ + ::osl::MutexGuard aGuard( impl_GetOwnStaticMutex() ); + return m_pDataContainer->GetFactoryStandardTemplate( eFactory ); +} + +//***************************************************************************************************************** +::rtl::OUString SvtModuleOptions::GetFactoryWindowAttributes( EFactory eFactory ) const +{ + ::osl::MutexGuard aGuard( impl_GetOwnStaticMutex() ); + return m_pDataContainer->GetFactoryWindowAttributes( eFactory ); +} + +//***************************************************************************************************************** +::rtl::OUString SvtModuleOptions::GetFactoryEmptyDocumentURL( EFactory eFactory ) const +{ + ::osl::MutexGuard aGuard( impl_GetOwnStaticMutex() ); + return m_pDataContainer->GetFactoryEmptyDocumentURL( eFactory ); +} + +//***************************************************************************************************************** +::rtl::OUString SvtModuleOptions::GetFactoryDefaultFilter( EFactory eFactory ) const +{ + ::osl::MutexGuard aGuard( impl_GetOwnStaticMutex() ); + return m_pDataContainer->GetFactoryDefaultFilter( eFactory ); +} +//***************************************************************************************************************** +sal_Bool SvtModuleOptions::IsDefaultFilterReadonly( EFactory eFactory ) const +{ + ::osl::MutexGuard aGuard( impl_GetOwnStaticMutex() ); + m_pDataContainer->MakeReadonlyStatesAvailable(); + return m_pDataContainer->IsDefaultFilterReadonly( eFactory ); +} +//***************************************************************************************************************** +sal_Int32 SvtModuleOptions::GetFactoryIcon( EFactory eFactory ) const +{ + ::osl::MutexGuard aGuard( impl_GetOwnStaticMutex() ); + return m_pDataContainer->GetFactoryIcon( eFactory ); +} + +//***************************************************************************************************************** +sal_Bool SvtModuleOptions::ClassifyFactoryByName( const ::rtl::OUString& 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 ::rtl::OUString& sTemplate ) +{ + ::osl::MutexGuard aGuard( impl_GetOwnStaticMutex() ); + m_pDataContainer->SetFactoryStandardTemplate( eFactory, sTemplate ); +} + +//***************************************************************************************************************** +void SvtModuleOptions::SetFactoryWindowAttributes( EFactory eFactory , + const ::rtl::OUString& sAttributes) +{ + ::osl::MutexGuard aGuard( impl_GetOwnStaticMutex() ); + m_pDataContainer->SetFactoryWindowAttributes( eFactory, sAttributes ); +} + +//***************************************************************************************************************** +void SvtModuleOptions::SetFactoryDefaultFilter( EFactory eFactory, + const ::rtl::OUString& sFilter ) +{ + ::osl::MutexGuard aGuard( impl_GetOwnStaticMutex() ); + m_pDataContainer->SetFactoryDefaultFilter( eFactory, sFilter ); +} + +//***************************************************************************************************************** +sal_Bool SvtModuleOptions::IsMath() const +{ + ::osl::MutexGuard aGuard( impl_GetOwnStaticMutex() ); + return m_pDataContainer->IsModuleInstalled( E_SMATH ); +} + +//***************************************************************************************************************** +sal_Bool SvtModuleOptions::IsChart() const +{ + ::osl::MutexGuard aGuard( impl_GetOwnStaticMutex() ); + return m_pDataContainer->IsModuleInstalled( E_SCHART ); +} + +//***************************************************************************************************************** +sal_Bool SvtModuleOptions::IsCalc() const +{ + ::osl::MutexGuard aGuard( impl_GetOwnStaticMutex() ); + return m_pDataContainer->IsModuleInstalled( E_SCALC ); +} + +//***************************************************************************************************************** +sal_Bool SvtModuleOptions::IsDraw() const +{ + ::osl::MutexGuard aGuard( impl_GetOwnStaticMutex() ); + return m_pDataContainer->IsModuleInstalled( E_SDRAW ); +} + +//***************************************************************************************************************** +sal_Bool SvtModuleOptions::IsWriter() const +{ + ::osl::MutexGuard aGuard( impl_GetOwnStaticMutex() ); + return m_pDataContainer->IsModuleInstalled( E_SWRITER ); +} + +//***************************************************************************************************************** +sal_Bool SvtModuleOptions::IsImpress() const +{ + ::osl::MutexGuard aGuard( impl_GetOwnStaticMutex() ); + return m_pDataContainer->IsModuleInstalled( E_SIMPRESS ); +} + +//***************************************************************************************************************** +sal_Bool SvtModuleOptions::IsBasicIDE() const +{ + return sal_True; +} +//***************************************************************************************************************** +sal_Bool SvtModuleOptions::IsDataBase() const +{ + ::osl::MutexGuard aGuard( impl_GetOwnStaticMutex() ); + return m_pDataContainer->IsModuleInstalled( E_SDATABASE ); +} +//***************************************************************************************************************** +sal_uInt32 SvtModuleOptions::GetFeatures() const +{ + ::osl::MutexGuard aGuard( impl_GetOwnStaticMutex() ); + + sal_uInt32 nFeature = 0; + + if( m_pDataContainer->IsModuleInstalled( E_SWRITER ) == sal_True ) + nFeature |= FEATUREFLAG_WRITER; + if( m_pDataContainer->IsModuleInstalled( E_SCALC ) == sal_True ) + nFeature |= FEATUREFLAG_CALC; + if( m_pDataContainer->IsModuleInstalled( E_SDRAW ) == sal_True ) + nFeature |= FEATUREFLAG_DRAW; + if( m_pDataContainer->IsModuleInstalled( E_SIMPRESS ) == sal_True ) + nFeature |= FEATUREFLAG_IMPRESS; + if( m_pDataContainer->IsModuleInstalled( E_SCHART ) == sal_True ) + nFeature |= FEATUREFLAG_CHART; + if( m_pDataContainer->IsModuleInstalled( E_SMATH ) == sal_True ) + nFeature |= FEATUREFLAG_MATH; + if( m_pDataContainer->IsModuleInstalled( E_SBASIC ) == sal_True ) + nFeature |= FEATUREFLAG_BASICIDE; + if( m_pDataContainer->IsModuleInstalled( E_SDATABASE ) == sal_True ) + nFeature |= FEATUREFLAG_INSIGHT; + + return nFeature; +} + +/*-****************************************************************************************************//** + @short return a reference to a static mutex + @descr These class is threadsafe. + We create a static mutex only for one time and use it to protect our refcount and container + member! + + @seealso - + + @param - + @return A reference to a static mutex member. + + @onerror - + @threadsafe yes +*//*-*****************************************************************************************************/ +::osl::Mutex& SvtModuleOptions::impl_GetOwnStaticMutex() +{ + // Initialize static mutex only for one time! + static ::osl::Mutex* pMutex = NULL; + // If these method first called (Mutex not already exist!) ... + if( pMutex == NULL ) + { + // ... we must create a new one. Protect follow code with the global mutex - + // It must be - we create a static variable! + ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); + // We must check our pointer again - because it can be that another instance of ouer class will be fastr then these! + if( pMutex == NULL ) + { + // Create the new mutex and set it for return on static variable. + static ::osl::Mutex aMutex; + pMutex = &aMutex; + } + } + // Return new created or already existing mutex object. + return *pMutex; +} + +::rtl::OUString SvtModuleOptions::GetModuleName( EModule eModule ) const +{ + switch( eModule ) + { + case SvtModuleOptions::E_SWRITER : { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Writer")); } + case SvtModuleOptions::E_SWEB : { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Web")); } + case SvtModuleOptions::E_SGLOBAL : { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Global")); } + case SvtModuleOptions::E_SCALC : { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Calc")); } + case SvtModuleOptions::E_SDRAW : { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Draw")); } + case SvtModuleOptions::E_SIMPRESS : { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Impress")); } + case SvtModuleOptions::E_SMATH : { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Math")); } + case SvtModuleOptions::E_SCHART : { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Chart")); } + case SvtModuleOptions::E_SBASIC : { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Basic")); } + case SvtModuleOptions::E_SDATABASE : { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Database")); } + default: + OSL_ASSERT( "unknown module" ); + break; + } + + return ::rtl::OUString(); +} + +::rtl::OUString SvtModuleOptions::GetModuleName( EFactory eFactory ) const +{ + switch( eFactory ) + { + case SvtModuleOptions::E_WRITER : { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Writer")); } + case SvtModuleOptions::E_WRITERWEB : { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Writer")); } + case SvtModuleOptions::E_WRITERGLOBAL : { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Writer")); } + case SvtModuleOptions::E_CALC : { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Calc")); } + case SvtModuleOptions::E_DRAW : { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Draw")); } + case SvtModuleOptions::E_IMPRESS : { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Impress")); } + case SvtModuleOptions::E_MATH : { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Math")); } + case SvtModuleOptions::E_CHART : { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Chart")); } + case SvtModuleOptions::E_BASIC : { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Basic")); } + case SvtModuleOptions::E_DATABASE : { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Database")); } + default: + OSL_ASSERT( "unknown factory" ); + break; + } + + return ::rtl::OUString(); +} + +/*----------------------------------------------- + 07.03.2004 15:03 +-----------------------------------------------*/ +SvtModuleOptions::EFactory SvtModuleOptions::ClassifyFactoryByShortName(const ::rtl::OUString& sName) +{ + if (sName.equalsAscii("swriter")) + return E_WRITER; + if (sName.equalsIgnoreAsciiCaseAscii("swriter/Web")) // sometimes they are registerd for swriter/web :-( + return E_WRITERWEB; + if (sName.equalsIgnoreAsciiCaseAscii("swriter/GlobalDocument")) // sometimes they are registerd for swriter/globaldocument :-( + return E_WRITERGLOBAL; + if (sName.equalsAscii("scalc")) + return E_CALC; + if (sName.equalsAscii("sdraw")) + return E_DRAW; + if (sName.equalsAscii("simpress")) + return E_IMPRESS; + if (sName.equalsAscii("schart")) + return E_CHART; + if (sName.equalsAscii("smath")) + return E_MATH; + if (sName.equalsAscii("sbasic")) + return E_BASIC; + if (sName.equalsAscii("sdatabase")) + return E_DATABASE; + + return E_UNKNOWN_FACTORY; +} + +/*----------------------------------------------- + 31.07.2003 10:41 +-----------------------------------------------*/ +SvtModuleOptions::EFactory SvtModuleOptions::ClassifyFactoryByServiceName(const ::rtl::OUString& sName) +{ + if (sName.equals(FACTORYNAME_WRITERGLOBAL)) + return E_WRITERGLOBAL; + if (sName.equals(FACTORYNAME_WRITERWEB)) + return E_WRITERWEB; + if (sName.equals(FACTORYNAME_WRITER)) + return E_WRITER; + if (sName.equals(FACTORYNAME_CALC)) + return E_CALC; + if (sName.equals(FACTORYNAME_DRAW)) + return E_DRAW; + if (sName.equals(FACTORYNAME_IMPRESS)) + return E_IMPRESS; + if (sName.equals(FACTORYNAME_MATH)) + return E_MATH; + if (sName.equals(FACTORYNAME_CHART)) + return E_CHART; + if (sName.equals(FACTORYNAME_DATABASE)) + return E_DATABASE; + + return E_UNKNOWN_FACTORY; +} + +/*----------------------------------------------- + 31.07.2003 14:39 +-----------------------------------------------*/ +SvtModuleOptions::EFactory SvtModuleOptions::ClassifyFactoryByURL(const ::rtl::OUString& sURL , + const css::uno::Sequence< css::beans::PropertyValue >& lMediaDescriptor) +{ + css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = ::utl::getProcessServiceFactory(); + if (!xSMGR.is()) + return E_UNKNOWN_FACTORY; + + css::uno::Reference< css::container::XNameAccess > xFilterCfg; + css::uno::Reference< css::container::XNameAccess > xTypeCfg ; + try + { + xFilterCfg = css::uno::Reference< css::container::XNameAccess >( + xSMGR->createInstance(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.document.FilterFactory"))), css::uno::UNO_QUERY); + xTypeCfg = css::uno::Reference< css::container::XNameAccess >( + xSMGR->createInstance(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.document.TypeDetection"))), css::uno::UNO_QUERY); + } + catch(const css::uno::RuntimeException&) + { throw; } + catch(const css::uno::Exception&) + { return E_UNKNOWN_FACTORY; } + + ::comphelper::SequenceAsHashMap stlDesc(lMediaDescriptor); + + // is there already a filter inside the descriptor? + ::rtl::OUString sFilterName = stlDesc.getUnpackedValueOrDefault(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("FilterName")), ::rtl::OUString()); + if (sFilterName.getLength()) + { + try + { + ::comphelper::SequenceAsHashMap stlFilterProps (xFilterCfg->getByName(sFilterName)); + ::rtl::OUString sDocumentService = stlFilterProps.getUnpackedValueOrDefault(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("DocumentService")), ::rtl::OUString()); + SvtModuleOptions::EFactory eApp = SvtModuleOptions::ClassifyFactoryByServiceName(sDocumentService); + + if (eApp != E_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? + ::rtl::OUString sTypeName = stlDesc.getUnpackedValueOrDefault(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("TypeName")), ::rtl::OUString()); + if (!sTypeName.getLength()) + { + // no :-( + // start flat detection of URL + css::uno::Reference< css::document::XTypeDetection > xDetect(xTypeCfg, css::uno::UNO_QUERY); + sTypeName = xDetect->queryTypeByURL(sURL); + } + + if (!sTypeName.getLength()) + return E_UNKNOWN_FACTORY; + + // yes - there is a type info + // Try to find the preferred filter. + try + { + ::comphelper::SequenceAsHashMap stlTypeProps (xTypeCfg->getByName(sTypeName)); + ::rtl::OUString sPreferredFilter = stlTypeProps.getUnpackedValueOrDefault(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("PreferredFilter")), ::rtl::OUString()); + ::comphelper::SequenceAsHashMap stlFilterProps (xFilterCfg->getByName(sPreferredFilter)); + ::rtl::OUString sDocumentService = stlFilterProps.getUnpackedValueOrDefault(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("DocumentService")), ::rtl::OUString()); + SvtModuleOptions::EFactory eApp = SvtModuleOptions::ClassifyFactoryByServiceName(sDocumentService); + + if (eApp != E_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 E_UNKNOWN_FACTORY; +} + +/*----------------------------------------------- + 31.07.2003 10:41 +-----------------------------------------------*/ +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 E_UNKNOWN_FACTORY; + + const css::uno::Sequence< ::rtl::OUString > lServices = xInfo->getSupportedServiceNames(); + const ::rtl::OUString* pServices = lServices.getConstArray(); + + for (sal_Int32 i=0; i<lServices.getLength() ; ++i) + { + SvtModuleOptions::EFactory eApp = SvtModuleOptions::ClassifyFactoryByServiceName(pServices[i]); + if (eApp != E_UNKNOWN_FACTORY) + return eApp; + } + + return E_UNKNOWN_FACTORY; +} + +::com::sun::star::uno::Sequence < ::rtl::OUString > SvtModuleOptions::GetAllServiceNames() +{ + ::osl::MutexGuard aGuard( impl_GetOwnStaticMutex() ); + return m_pDataContainer->GetAllServiceNames(); +} + +::rtl::OUString SvtModuleOptions::GetDefaultModuleName() +{ + ::rtl::OUString aModule; + if (m_pDataContainer->IsModuleInstalled(SvtModuleOptions::E_SWRITER)) + aModule = m_pDataContainer->GetFactoryShortName(SvtModuleOptions::E_WRITER); + else + if (m_pDataContainer->IsModuleInstalled(SvtModuleOptions::E_SCALC)) + aModule = m_pDataContainer->GetFactoryShortName(SvtModuleOptions::E_CALC); + else + if (m_pDataContainer->IsModuleInstalled(SvtModuleOptions::E_SIMPRESS)) + aModule = m_pDataContainer->GetFactoryShortName(SvtModuleOptions::E_IMPRESS); + else + if (m_pDataContainer->IsModuleInstalled(SvtModuleOptions::E_SDATABASE)) + aModule = m_pDataContainer->GetFactoryShortName(SvtModuleOptions::E_DATABASE); + else + if (m_pDataContainer->IsModuleInstalled(SvtModuleOptions::E_SDRAW)) + aModule = m_pDataContainer->GetFactoryShortName(SvtModuleOptions::E_DRAW); + else + if (m_pDataContainer->IsModuleInstalled(SvtModuleOptions::E_SWEB)) + aModule = m_pDataContainer->GetFactoryShortName(SvtModuleOptions::E_WRITERWEB); + else + if (m_pDataContainer->IsModuleInstalled(SvtModuleOptions::E_SGLOBAL)) + aModule = m_pDataContainer->GetFactoryShortName(SvtModuleOptions::E_WRITERGLOBAL); + else + if (m_pDataContainer->IsModuleInstalled(SvtModuleOptions::E_SMATH)) + aModule = m_pDataContainer->GetFactoryShortName(SvtModuleOptions::E_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 000000000000..e8b5ad40bebd --- /dev/null +++ b/unotools/source/config/options.cxx @@ -0,0 +1,108 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" + +#include "sal/config.h" +#include <tools/list.hxx> +#include <unotools/options.hxx> + +namespace utl +{ + DECLARE_LIST( IMPL_ConfigurationListenerList, ConfigurationListener* ) +} + +using utl::detail::Options; +using utl::ConfigurationBroadcaster; + +ConfigurationBroadcaster::ConfigurationBroadcaster() +: mpList(0) +, m_nBroadcastBlocked( 0 ) +, m_nBlockedHint( 0 ) +{ +} + +ConfigurationBroadcaster::~ConfigurationBroadcaster() +{ + delete mpList; +} + +void ConfigurationBroadcaster::AddListener( utl::ConfigurationListener* pListener ) +{ + if ( !mpList ) + mpList = new IMPL_ConfigurationListenerList; + mpList->Insert( pListener ); +} + +void ConfigurationBroadcaster::RemoveListener( utl::ConfigurationListener* pListener ) +{ + if ( mpList ) + mpList->Remove( pListener ); +} + +void ConfigurationBroadcaster::NotifyListeners( sal_uInt32 nHint ) +{ + if ( m_nBroadcastBlocked ) + m_nBlockedHint |= nHint; + else + { + nHint |= m_nBlockedHint; + m_nBlockedHint = 0; + if ( mpList ) + for ( sal_uInt32 n=0; n<mpList->Count(); n++ ) + mpList->GetObject(n)->ConfigurationChanged( this, nHint ); + } +} + +void ConfigurationBroadcaster::BlockBroadcasts( bool bBlock ) +{ + if ( bBlock ) + ++m_nBroadcastBlocked; + else if ( m_nBroadcastBlocked ) + { + if ( --m_nBroadcastBlocked == 0 ) + NotifyListeners( 0 ); + } +} + +Options::Options() +{ +} + +Options::~Options() +{ +} + +void Options::ConfigurationChanged( ConfigurationBroadcaster*, sal_uInt32 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 000000000000..c922b1f2353b --- /dev/null +++ b/unotools/source/config/optionsdlg.cxx @@ -0,0 +1,292 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" + +#include <unotools/optionsdlg.hxx> +#include <unotools/configmgr.hxx> +#include <unotools/configitem.hxx> +#include <tools/debug.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> +#include <osl/mutex.hxx> +#include <comphelper/stl_types.hxx> + +#include <hash_map> +#include "itemholder1.hxx" + +using namespace utl; +using namespace rtl; +using namespace com::sun::star::beans ; +using namespace com::sun::star::uno; + +#define CFG_FILENAME OUString( RTL_CONSTASCII_USTRINGPARAM( "Office.OptionsDialog" ) ) +#define ROOT_NODE OUString( RTL_CONSTASCII_USTRINGPARAM( "OptionsDialogGroups" ) ) +#define PAGES_NODE OUString( RTL_CONSTASCII_USTRINGPARAM( "Pages" ) ) +#define OPTIONS_NODE OUString( RTL_CONSTASCII_USTRINGPARAM( "Options" ) ) +#define PROPERTY_HIDE OUString( RTL_CONSTASCII_USTRINGPARAM( "Hide" ) ) + +static SvtOptionsDlgOptions_Impl* pOptions = NULL; +static sal_Int32 nRefCount = 0; + +class SvtOptionsDlgOptions_Impl : public utl::ConfigItem +{ +private: + struct OUStringHashCode + { + size_t operator()( const ::rtl::OUString& sString ) const + { + return sString.hashCode(); + } + }; + + typedef std::hash_map< OUString, sal_Bool, OUStringHashCode, ::std::equal_to< OUString > > OptionNodeList; + + OUString m_sPathDelimiter; + OptionNodeList m_aOptionNodeList; + + enum NodeType{ NT_Group, NT_Page, NT_Option }; + void ReadNode( const OUString& _rNode, NodeType _eType ); + sal_Bool IsHidden( const OUString& _rPath ) const; + +public: + SvtOptionsDlgOptions_Impl(); + + virtual void Notify( const com::sun::star::uno::Sequence< rtl::OUString >& aPropertyNames ); + virtual void Commit(); + + static ::osl::Mutex & getInitMutex(); + + sal_Bool IsGroupHidden ( const OUString& _rGroup ) const; + sal_Bool IsPageHidden ( const OUString& _rPage, + const OUString& _rGroup ) const; + sal_Bool IsOptionHidden ( const OUString& _rOption, + const OUString& _rPage, + const OUString& _rGroup ) const; +}; + +::osl::Mutex & SvtOptionsDlgOptions_Impl::getInitMutex() +{ + static ::osl::Mutex *pMutex = 0; + + if( ! pMutex ) + { + ::osl::MutexGuard guard( ::osl::Mutex::getGlobalMutex() ); + if( ! pMutex ) + { + static ::osl::Mutex mutex; + pMutex = &mutex; + } + } + return *pMutex; +} + +// ----------------------------------------------------------------------- + +SvtOptionsDlgOptions_Impl::SvtOptionsDlgOptions_Impl() + : ConfigItem( OUString( CFG_FILENAME ) ), + + m_sPathDelimiter( RTL_CONSTASCII_USTRINGPARAM( "/" ) ), + m_aOptionNodeList( OptionNodeList() ) + +{ + OUString sRootNode( ROOT_NODE ); + Sequence< OUString > aNodeSeq = GetNodeNames( sRootNode ); + OUString sNode( sRootNode + m_sPathDelimiter ); + sal_uInt32 nCount = aNodeSeq.getLength(); + for ( sal_uInt32 n = 0; n < nCount; n++ ) + { + OUString sSubNode( sNode + aNodeSeq[n] ); + ReadNode( sSubNode, NT_Group ); + } +} + +// ----------------------------------------------------------------------- + +void SvtOptionsDlgOptions_Impl::Commit() +{ + // nothing to commit +} + +// ----------------------------------------------------------------------- + +void SvtOptionsDlgOptions_Impl::Notify( const Sequence< rtl::OUString >& ) +{ + // nothing to notify +} + +void SvtOptionsDlgOptions_Impl::ReadNode( const OUString& _rNode, NodeType _eType ) +{ + OUString sNode( _rNode + m_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; + } + } + + Sequence< OUString > lResult( nLen ); + lResult[0] = OUString( sNode + PROPERTY_HIDE ); + if ( _eType != NT_Option ) + lResult[1] = OUString( sNode + sSet ); + + Sequence< Any > aValues; + aValues = GetProperties( lResult ); + sal_Bool bHide = sal_False; + if ( aValues[0] >>= bHide ) + m_aOptionNodeList.insert( OptionNodeList::value_type( sNode, bHide ) ); + + if ( _eType != NT_Option ) + { + OUString sNodes( sNode + sSet ); + Sequence< OUString > aNodes = GetNodeNames( sNodes ); + if ( aNodes.getLength() > 0 ) + { + for ( sal_uInt32 n = 0; n < (sal_uInt32)aNodes.getLength(); ++n ) + { + OUString sSubNodeName( sNodes + m_sPathDelimiter + aNodes[n] ); + ReadNode( sSubNodeName, _eType == NT_Group ? NT_Page : NT_Option ); + } + } + } +} + +// ----------------------------------------------------------------------- + +OUString getGroupPath( const OUString& _rGroup ) +{ + return OUString( ROOT_NODE + OUString('/') + _rGroup + OUString('/') ); +} +OUString getPagePath( const OUString& _rPage ) +{ + return OUString( PAGES_NODE + OUString('/') + _rPage + OUString('/') ); +} +OUString getOptionPath( const OUString& _rOption ) +{ + return OUString( OPTIONS_NODE + OUString('/') + _rOption + OUString('/') ); +} + +// ----------------------------------------------------------------------- + +sal_Bool SvtOptionsDlgOptions_Impl::IsHidden( const OUString& _rPath ) const +{ + sal_Bool bRet = sal_False; + OptionNodeList::const_iterator pIter = m_aOptionNodeList.find( _rPath ); + if ( pIter != m_aOptionNodeList.end() ) + bRet = pIter->second; + return bRet; +} + +// ----------------------------------------------------------------------- + +sal_Bool SvtOptionsDlgOptions_Impl::IsGroupHidden( const OUString& _rGroup ) const +{ + return IsHidden( getGroupPath( _rGroup ) ); +} + +// ----------------------------------------------------------------------- + +sal_Bool SvtOptionsDlgOptions_Impl::IsPageHidden( const OUString& _rPage, const OUString& _rGroup ) const +{ + return IsHidden( getGroupPath( _rGroup ) + getPagePath( _rPage ) ); +} + +// ----------------------------------------------------------------------- + +sal_Bool SvtOptionsDlgOptions_Impl::IsOptionHidden( + const OUString& _rOption, const OUString& _rPage, const OUString& _rGroup ) const +{ + return IsHidden( getGroupPath( _rGroup ) + getPagePath( _rPage ) + getOptionPath( _rOption ) ); +} + +// ----------------------------------------------------------------------- + +SvtOptionsDialogOptions::SvtOptionsDialogOptions() +{ + // Global access, must be guarded (multithreading) + ::osl::MutexGuard aGuard( SvtOptionsDlgOptions_Impl::getInitMutex() ); + ++nRefCount; + if ( !pOptions ) + { + pOptions = new SvtOptionsDlgOptions_Impl; + + ItemHolder1::holdConfigItem( E_OPTIONSDLGOPTIONS ); + } + m_pImp = pOptions; +} + +// ----------------------------------------------------------------------- + +SvtOptionsDialogOptions::~SvtOptionsDialogOptions() +{ + // Global access, must be guarded (multithreading) + ::osl::MutexGuard aGuard( SvtOptionsDlgOptions_Impl::getInitMutex() ); + if ( !--nRefCount ) + { + if ( pOptions->IsModified() ) + pOptions->Commit(); + DELETEZ( pOptions ); + } +} + +sal_Bool SvtOptionsDialogOptions::IsGroupHidden( const String& _rGroup ) const +{ + return m_pImp->IsGroupHidden( _rGroup ); +} + +sal_Bool SvtOptionsDialogOptions::IsPageHidden( const String& _rPage, const String& _rGroup ) const +{ + return m_pImp->IsPageHidden( _rPage, _rGroup ); +} + +sal_Bool SvtOptionsDialogOptions::IsOptionHidden( + const String& _rOption, const String& _rPage, const String& _rGroup ) const +{ + return m_pImp->IsOptionHidden( _rOption, _rPage, _rGroup ); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/optionsdrawinglayer.cxx b/unotools/source/config/optionsdrawinglayer.cxx new file mode 100644 index 000000000000..c7fbad4a6db6 --- /dev/null +++ b/unotools/source/config/optionsdrawinglayer.cxx @@ -0,0 +1,1707 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +#ifdef _MSC_VER +#pragma hdrstop +#endif + +//_________________________________________________________________________________________________________________ +// includes +//_________________________________________________________________________________________________________________ + +#include <unotools/optionsdrawinglayer.hxx> +#include <unotools/configmgr.hxx> +#include <unotools/configitem.hxx> +#include <tools/debug.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> +#include <vcl/svapp.hxx> +#include <vcl/outdev.hxx> + +//_________________________________________________________________________________________________________________ +// namespaces +//_________________________________________________________________________________________________________________ + +using namespace ::utl ; +using namespace ::rtl ; +using namespace ::osl ; +using namespace ::com::sun::star::uno ; + +//_________________________________________________________________________________________________________________ +// const +//_________________________________________________________________________________________________________________ + +#define ROOTNODE_START OUString(RTL_CONSTASCII_USTRINGPARAM("Office.Common/Drawinglayer" )) +#define DEFAULT_OVERLAYBUFFER sal_True +#define DEFAULT_PAINTBUFFER sal_True +#define DEFAULT_STRIPE_COLOR_A 0 +#define DEFAULT_STRIPE_COLOR_B 16581375 +#define DEFAULT_STRIPE_LENGTH 4 + +// #i73602# +// #i74769#, #i75172# : Change default for Calc and Writer to True +#define DEFAULT_OVERLAYBUFFER_CALC sal_True +#define DEFAULT_OVERLAYBUFFER_WRITER sal_True +#define DEFAULT_OVERLAYBUFFER_DRAWIMPRESS sal_True + +// #i74769#, #i75172# +#define DEFAULT_PAINTBUFFER_CALC sal_True +#define DEFAULT_PAINTBUFFER_WRITER sal_True +#define DEFAULT_PAINTBUFFER_DRAWIMPRESS sal_True + +// #i4219# +#define DEFAULT_MAXIMUMPAPERWIDTH 300 +#define DEFAULT_MAXIMUMPAPERHEIGHT 300 +#define DEFAULT_MAXIMUMPAPERLEFTMARGIN 9999 +#define DEFAULT_MAXIMUMPAPERRIGHTMARGIN 9999 +#define DEFAULT_MAXIMUMPAPERTOPMARGIN 9999 +#define DEFAULT_MAXIMUMPAPERBOTTOMMARGIN 9999 + +// primitives +#define DEFAULT_ANTIALIASING sal_True +#define DEFAULT_SNAPHORVERLINESTODISCRETE sal_True +#define DEFAULT_SOLIDDRAGCREATE sal_True +#define DEFAULT_RENDERDECORATEDTEXTDIRECT sal_True +#define DEFAULT_RENDERSIMPLETEXTDIRECT sal_True +#define DEFAULT_QUADRATIC3DRENDERLIMIT 1000000 +#define DEFAULT_QUADRATICFORMCONTROLRENDERLIMIT 45000 + +// #i97672# selection settings +#define DEFAULT_TRANSPARENTSELECTION sal_True +#define DEFAULT_TRANSPARENTSELECTIONPERCENT 75 +#define DEFAULT_SELECTIONMAXIMUMLUMINANCEPERCENT 70 + +#define PROPERTYNAME_OVERLAYBUFFER OUString(RTL_CONSTASCII_USTRINGPARAM("OverlayBuffer" )) +#define PROPERTYNAME_PAINTBUFFER OUString(RTL_CONSTASCII_USTRINGPARAM("PaintBuffer" )) +#define PROPERTYNAME_STRIPE_COLOR_A OUString(RTL_CONSTASCII_USTRINGPARAM("StripeColorA" )) +#define PROPERTYNAME_STRIPE_COLOR_B OUString(RTL_CONSTASCII_USTRINGPARAM("StripeColorB" )) +#define PROPERTYNAME_STRIPE_LENGTH OUString(RTL_CONSTASCII_USTRINGPARAM("StripeLength" )) + +// #i73602# +#define PROPERTYNAME_OVERLAYBUFFER_CALC OUString(RTL_CONSTASCII_USTRINGPARAM("OverlayBuffer_Calc")) +#define PROPERTYNAME_OVERLAYBUFFER_WRITER OUString(RTL_CONSTASCII_USTRINGPARAM("OverlayBuffer_Writer")) +#define PROPERTYNAME_OVERLAYBUFFER_DRAWIMPRESS OUString(RTL_CONSTASCII_USTRINGPARAM("OverlayBuffer_DrawImpress")) + +// #i74769#, #i75172# +#define PROPERTYNAME_PAINTBUFFER_CALC OUString(RTL_CONSTASCII_USTRINGPARAM("PaintBuffer_Calc")) +#define PROPERTYNAME_PAINTBUFFER_WRITER OUString(RTL_CONSTASCII_USTRINGPARAM("PaintBuffer_Writer")) +#define PROPERTYNAME_PAINTBUFFER_DRAWIMPRESS OUString(RTL_CONSTASCII_USTRINGPARAM("PaintBuffer_DrawImpress")) + +// #i4219# +#define PROPERTYNAME_MAXIMUMPAPERWIDTH OUString(RTL_CONSTASCII_USTRINGPARAM("MaximumPaperWidth")) +#define PROPERTYNAME_MAXIMUMPAPERHEIGHT OUString(RTL_CONSTASCII_USTRINGPARAM("MaximumPaperHeight")) +#define PROPERTYNAME_MAXIMUMPAPERLEFTMARGIN OUString(RTL_CONSTASCII_USTRINGPARAM("MaximumPaperLeftMargin")) +#define PROPERTYNAME_MAXIMUMPAPERRIGHTMARGIN OUString(RTL_CONSTASCII_USTRINGPARAM("MaximumPaperRightMargin")) +#define PROPERTYNAME_MAXIMUMPAPERTOPMARGIN OUString(RTL_CONSTASCII_USTRINGPARAM("MaximumPaperTopMargin")) +#define PROPERTYNAME_MAXIMUMPAPERBOTTOMMARGIN OUString(RTL_CONSTASCII_USTRINGPARAM("MaximumPaperBottomMargin")) + +// primitives +#define PROPERTYNAME_ANTIALIASING OUString(RTL_CONSTASCII_USTRINGPARAM("AntiAliasing")) +#define PROPERTYNAME_SNAPHORVERLINESTODISCRETE OUString(RTL_CONSTASCII_USTRINGPARAM("SnapHorVerLinesToDiscrete")) +#define PROPERTYNAME_SOLIDDRAGCREATE OUString(RTL_CONSTASCII_USTRINGPARAM("SolidDragCreate")) +#define PROPERTYNAME_RENDERDECORATEDTEXTDIRECT OUString(RTL_CONSTASCII_USTRINGPARAM("RenderDecoratedTextDirect")) +#define PROPERTYNAME_RENDERSIMPLETEXTDIRECT OUString(RTL_CONSTASCII_USTRINGPARAM("RenderSimpleTextDirect")) +#define PROPERTYNAME_QUADRATIC3DRENDERLIMIT OUString(RTL_CONSTASCII_USTRINGPARAM("Quadratic3DRenderLimit")) +#define PROPERTYNAME_QUADRATICFORMCONTROLRENDERLIMIT OUString(RTL_CONSTASCII_USTRINGPARAM("QuadraticFormControlRenderLimit")) + +// #i97672# selection settings +#define PROPERTYNAME_TRANSPARENTSELECTION OUString(RTL_CONSTASCII_USTRINGPARAM("TransparentSelection")) +#define PROPERTYNAME_TRANSPARENTSELECTIONPERCENT OUString(RTL_CONSTASCII_USTRINGPARAM("TransparentSelectionPercent")) +#define PROPERTYNAME_SELECTIONMAXIMUMLUMINANCEPERCENT OUString(RTL_CONSTASCII_USTRINGPARAM("SelectionMaximumLuminancePercent")) + +#define PROPERTYHANDLE_OVERLAYBUFFER 0 +#define PROPERTYHANDLE_PAINTBUFFER 1 +#define PROPERTYHANDLE_STRIPE_COLOR_A 2 +#define PROPERTYHANDLE_STRIPE_COLOR_B 3 +#define PROPERTYHANDLE_STRIPE_LENGTH 4 + +// #i73602# +#define PROPERTYHANDLE_OVERLAYBUFFER_CALC 5 +#define PROPERTYHANDLE_OVERLAYBUFFER_WRITER 6 +#define PROPERTYHANDLE_OVERLAYBUFFER_DRAWIMPRESS 7 + +// #i74769#, #i75172# +#define PROPERTYHANDLE_PAINTBUFFER_CALC 8 +#define PROPERTYHANDLE_PAINTBUFFER_WRITER 9 +#define PROPERTYHANDLE_PAINTBUFFER_DRAWIMPRESS 10 + +// #i4219# +#define PROPERTYHANDLE_MAXIMUMPAPERWIDTH 11 +#define PROPERTYHANDLE_MAXIMUMPAPERHEIGHT 12 +#define PROPERTYHANDLE_MAXIMUMPAPERLEFTMARGIN 13 +#define PROPERTYHANDLE_MAXIMUMPAPERRIGHTMARGIN 14 +#define PROPERTYHANDLE_MAXIMUMPAPERTOPMARGIN 15 +#define PROPERTYHANDLE_MAXIMUMPAPERBOTTOMMARGIN 16 + +// primitives +#define PROPERTYHANDLE_ANTIALIASING 17 +#define PROPERTYHANDLE_SNAPHORVERLINESTODISCRETE 18 +#define PROPERTYHANDLE_SOLIDDRAGCREATE 19 +#define PROPERTYHANDLE_RENDERDECORATEDTEXTDIRECT 20 +#define PROPERTYHANDLE_RENDERSIMPLETEXTDIRECT 21 +#define PROPERTYHANDLE_QUADRATIC3DRENDERLIMIT 22 +#define PROPERTYHANDLE_QUADRATICFORMCONTROLRENDERLIMIT 23 + +// #i97672# selection settings +#define PROPERTYHANDLE_TRANSPARENTSELECTION 24 +#define PROPERTYHANDLE_TRANSPARENTSELECTIONPERCENT 25 +#define PROPERTYHANDLE_SELECTIONMAXIMUMLUMINANCEPERCENT 26 + +#define PROPERTYCOUNT 27 + +class SvtOptionsDrawinglayer_Impl : public ConfigItem +{ +public: + +//--------------------------------------------------------------------------------------------------------- +// constructor / destructor +//--------------------------------------------------------------------------------------------------------- + + SvtOptionsDrawinglayer_Impl(); + ~SvtOptionsDrawinglayer_Impl(); + +//--------------------------------------------------------------------------------------------------------- +// overloaded methods of baseclass +//--------------------------------------------------------------------------------------------------------- + + virtual void Commit(); + +//--------------------------------------------------------------------------------------------------------- +// public interface +//--------------------------------------------------------------------------------------------------------- + + sal_Bool IsOverlayBuffer() const; + sal_Bool IsPaintBuffer() const; + Color GetStripeColorA() const; + Color GetStripeColorB() const; + sal_uInt16 GetStripeLength() const; + + // #i73602# + sal_Bool IsOverlayBuffer_Calc() const; + sal_Bool IsOverlayBuffer_Writer() const; + sal_Bool IsOverlayBuffer_DrawImpress() const; + + // #i74769#, #i75172# + sal_Bool IsPaintBuffer_Calc() const; + sal_Bool IsPaintBuffer_Writer() const; + sal_Bool IsPaintBuffer_DrawImpress() const; + + void SetOverlayBuffer( sal_Bool bState ); + void SetPaintBuffer( sal_Bool bState ); + void SetStripeColorA( Color aColor ); + void SetStripeColorB( Color aColor ); + void SetStripeLength( sal_uInt16 nLength ); + + // #i73602# + void SetOverlayBuffer_Calc( sal_Bool bState ); + void SetOverlayBuffer_Writer( sal_Bool bState ); + void SetOverlayBuffer_DrawImpress( sal_Bool bState ); + + // #i74769#, #i75172# + void SetPaintBuffer_Calc( sal_Bool bState ); + void SetPaintBuffer_Writer( sal_Bool bState ); + void SetPaintBuffer_DrawImpress( sal_Bool bState ); + + // #i4219# + sal_uInt32 GetMaximumPaperWidth() const; + sal_uInt32 GetMaximumPaperHeight() const; + sal_uInt32 GetMaximumPaperLeftMargin() const; + sal_uInt32 GetMaximumPaperRightMargin() const; + sal_uInt32 GetMaximumPaperTopMargin() const; + sal_uInt32 GetMaximumPaperBottomMargin() const; + + void SetMaximumPaperWidth(sal_uInt32 nNew); + void SetMaximumPaperHeight(sal_uInt32 nNew); + void SetMaximumPaperLeftMargin(sal_uInt32 nNew); + void SetMaximumPaperRightMargin(sal_uInt32 nNew); + void SetMaximumPaperTopMargin(sal_uInt32 nNew); + void SetMaximumPaperBottomMargin(sal_uInt32 nNew); + + // helper + sal_Bool IsAAPossibleOnThisSystem() const; + + // primitives + sal_Bool IsAntiAliasing() const; + sal_Bool IsSnapHorVerLinesToDiscrete() const; + sal_Bool IsSolidDragCreate() const; + sal_Bool IsRenderDecoratedTextDirect() const; + sal_Bool IsRenderSimpleTextDirect() const; + sal_uInt32 GetQuadratic3DRenderLimit() const; + sal_uInt32 GetQuadraticFormControlRenderLimit() const; + + void SetAntiAliasing( sal_Bool bState ); + void SetSnapHorVerLinesToDiscrete( sal_Bool bState ); + void SetSolidDragCreate( sal_Bool bState ); + void SetRenderDecoratedTextDirect( sal_Bool bState ); + void SetRenderSimpleTextDirect( sal_Bool bState ); + void SetQuadratic3DRenderLimit(sal_uInt32 nNew); + void SetQuadraticFormControlRenderLimit(sal_uInt32 nNew); + + // #i97672# selection settings + sal_Bool IsTransparentSelection() const; + sal_uInt16 GetTransparentSelectionPercent() const; + sal_uInt16 GetSelectionMaximumLuminancePercent() const; + + void SetTransparentSelection( sal_Bool bState ); + void SetTransparentSelectionPercent( sal_uInt16 nPercent ); + void SetSelectionMaximumLuminancePercent( sal_uInt16 nPercent ); + +//------------------------------------------------------------------------------------------------------------- +// private methods +//------------------------------------------------------------------------------------------------------------- + +private: + + static Sequence< OUString > impl_GetPropertyNames(); + +//------------------------------------------------------------------------------------------------------------- +// private member +//------------------------------------------------------------------------------------------------------------- + +private: + + sal_Bool m_bOverlayBuffer; + sal_Bool m_bPaintBuffer; + Color m_bStripeColorA; + Color m_bStripeColorB; + sal_uInt16 m_nStripeLength; + + // #i73602# + sal_Bool m_bOverlayBuffer_Calc; + sal_Bool m_bOverlayBuffer_Writer; + sal_Bool m_bOverlayBuffer_DrawImpress; + + // #i74769#, #i75172# + sal_Bool m_bPaintBuffer_Calc; + sal_Bool m_bPaintBuffer_Writer; + sal_Bool m_bPaintBuffer_DrawImpress; + + // #i4219# + sal_uInt32 m_nMaximumPaperWidth; + sal_uInt32 m_nMaximumPaperHeight; + sal_uInt32 m_nMaximumPaperLeftMargin; + sal_uInt32 m_nMaximumPaperRightMargin; + sal_uInt32 m_nMaximumPaperTopMargin; + sal_uInt32 m_nMaximumPaperBottomMargin; + + // primitives + sal_Bool m_bAntiAliasing; + sal_Bool m_bSnapHorVerLinesToDiscrete; + sal_Bool m_bSolidDragCreate; + sal_Bool m_bRenderDecoratedTextDirect; + sal_Bool m_bRenderSimpleTextDirect; + sal_uInt32 m_nQuadratic3DRenderLimit; + sal_uInt32 m_nQuadraticFormControlRenderLimit; + + // #i97672# selection settings + sal_uInt16 m_nTransparentSelectionPercent; + sal_uInt16 m_nSelectionMaximumLuminancePercent; + sal_Bool m_bTransparentSelection; + + // local values + bool m_bAllowAA : 1; + bool m_bAllowAAChecked : 1; +}; + +//_________________________________________________________________________________________________________________ +// definitions +//_________________________________________________________________________________________________________________ + +//***************************************************************************************************************** +// constructor +//***************************************************************************************************************** +SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl() : + ConfigItem( ROOTNODE_START ), + m_bOverlayBuffer( DEFAULT_OVERLAYBUFFER ), + m_bPaintBuffer( DEFAULT_PAINTBUFFER ), + m_bStripeColorA(Color(DEFAULT_STRIPE_COLOR_A)), + m_bStripeColorB(Color(DEFAULT_STRIPE_COLOR_B)), + m_nStripeLength(DEFAULT_STRIPE_LENGTH), + + // #i73602# + m_bOverlayBuffer_Calc( DEFAULT_OVERLAYBUFFER_CALC ), + m_bOverlayBuffer_Writer( DEFAULT_OVERLAYBUFFER_WRITER ), + m_bOverlayBuffer_DrawImpress( DEFAULT_OVERLAYBUFFER_DRAWIMPRESS ), + + // #i74769#, #i75172# + m_bPaintBuffer_Calc( DEFAULT_PAINTBUFFER_CALC ), + m_bPaintBuffer_Writer( DEFAULT_PAINTBUFFER_WRITER ), + m_bPaintBuffer_DrawImpress( DEFAULT_PAINTBUFFER_DRAWIMPRESS ), + + // #i4219# + m_nMaximumPaperWidth(DEFAULT_MAXIMUMPAPERWIDTH), + m_nMaximumPaperHeight(DEFAULT_MAXIMUMPAPERHEIGHT), + m_nMaximumPaperLeftMargin(DEFAULT_MAXIMUMPAPERLEFTMARGIN), + m_nMaximumPaperRightMargin(DEFAULT_MAXIMUMPAPERRIGHTMARGIN), + m_nMaximumPaperTopMargin(DEFAULT_MAXIMUMPAPERTOPMARGIN), + m_nMaximumPaperBottomMargin(DEFAULT_MAXIMUMPAPERBOTTOMMARGIN), + + // primitives + m_bAntiAliasing(DEFAULT_ANTIALIASING), + m_bSnapHorVerLinesToDiscrete(DEFAULT_SNAPHORVERLINESTODISCRETE), + m_bSolidDragCreate(DEFAULT_SOLIDDRAGCREATE), + m_bRenderDecoratedTextDirect(DEFAULT_RENDERDECORATEDTEXTDIRECT), + m_bRenderSimpleTextDirect(DEFAULT_RENDERSIMPLETEXTDIRECT), + m_nQuadratic3DRenderLimit(DEFAULT_QUADRATIC3DRENDERLIMIT), + m_nQuadraticFormControlRenderLimit(DEFAULT_QUADRATICFORMCONTROLRENDERLIMIT), + + // #i97672# selection settings + m_nTransparentSelectionPercent(DEFAULT_TRANSPARENTSELECTIONPERCENT), + m_nSelectionMaximumLuminancePercent(DEFAULT_SELECTIONMAXIMUMLUMINANCEPERCENT), + m_bTransparentSelection(DEFAULT_TRANSPARENTSELECTION), + + // local values + m_bAllowAA(true), + m_bAllowAAChecked(false) +{ + Sequence< OUString > seqNames( impl_GetPropertyNames() ); + Sequence< Any > seqValues = GetProperties( seqNames ) ; + + DBG_ASSERT( !(seqNames.getLength()!=seqValues.getLength()), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nI miss some values of configuration keys!\n" ); + + // Copy values from list in right order to ouer internal member. + sal_Int32 nPropertyCount = seqValues.getLength(); + sal_Int32 nProperty = 0; + + for( nProperty=0; nProperty<nPropertyCount; ++nProperty ) + { + DBG_ASSERT( !(seqValues[nProperty].hasValue()==sal_False), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nInvalid property value for property detected!\n" ); + + switch( nProperty ) + { + case PROPERTYHANDLE_OVERLAYBUFFER: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\OverlayBuffer\"?" ); + seqValues[nProperty] >>= m_bOverlayBuffer; + } + break; + + case PROPERTYHANDLE_PAINTBUFFER: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\PaintBuffer\"?" ); + seqValues[nProperty] >>= m_bPaintBuffer; + } + break; + + case PROPERTYHANDLE_STRIPE_COLOR_A: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_LONG), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\StripeColorA\"?" ); + sal_Int32 nValue = 0; + seqValues[nProperty] >>= nValue; + m_bStripeColorA = nValue; + } + break; + + case PROPERTYHANDLE_STRIPE_COLOR_B: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_LONG), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\StripeColorB\"?" ); + sal_Int32 nValue = 0; + seqValues[nProperty] >>= nValue; + m_bStripeColorB = nValue; + } + break; + + case PROPERTYHANDLE_STRIPE_LENGTH: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_SHORT), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\StripeLength\"?" ); + seqValues[nProperty] >>= m_nStripeLength; + } + break; + + // #i73602# + case PROPERTYHANDLE_OVERLAYBUFFER_CALC: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\OverlayBuffer_Calc\"?" ); + seqValues[nProperty] >>= m_bOverlayBuffer_Calc; + } + break; + + case PROPERTYHANDLE_OVERLAYBUFFER_WRITER: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\OverlayBuffer_Writer\"?" ); + seqValues[nProperty] >>= m_bOverlayBuffer_Writer; + } + break; + + case PROPERTYHANDLE_OVERLAYBUFFER_DRAWIMPRESS: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\OverlayBuffer_DrawImpress\"?" ); + seqValues[nProperty] >>= m_bOverlayBuffer_DrawImpress; + } + break; + + // #i74769#, #i75172# + case PROPERTYHANDLE_PAINTBUFFER_CALC: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\PaintBuffer_Calc\"?" ); + seqValues[nProperty] >>= m_bPaintBuffer_Calc; + } + break; + + case PROPERTYHANDLE_PAINTBUFFER_WRITER: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\PaintBuffer_Writer\"?" ); + seqValues[nProperty] >>= m_bPaintBuffer_Writer; + } + break; + + case PROPERTYHANDLE_PAINTBUFFER_DRAWIMPRESS: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\PaintBuffer_DrawImpress\"?" ); + seqValues[nProperty] >>= m_bPaintBuffer_DrawImpress; + } + break; + + // #i4219# + case PROPERTYHANDLE_MAXIMUMPAPERWIDTH: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_LONG), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\MaximumPaperWidth\"?" ); + seqValues[nProperty] >>= m_nMaximumPaperWidth; + } + break; + + case PROPERTYHANDLE_MAXIMUMPAPERHEIGHT: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_LONG), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\MaximumPaperHeight\"?" ); + seqValues[nProperty] >>= m_nMaximumPaperHeight; + } + break; + + case PROPERTYHANDLE_MAXIMUMPAPERLEFTMARGIN: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_LONG), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\MaximumPaperLeftMargin\"?" ); + seqValues[nProperty] >>= m_nMaximumPaperLeftMargin; + } + break; + + case PROPERTYHANDLE_MAXIMUMPAPERRIGHTMARGIN: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_LONG), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\MaximumPaperRightMargin\"?" ); + seqValues[nProperty] >>= m_nMaximumPaperRightMargin; + } + break; + + case PROPERTYHANDLE_MAXIMUMPAPERTOPMARGIN: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_LONG), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\MaximumPaperTopMargin\"?" ); + seqValues[nProperty] >>= m_nMaximumPaperTopMargin; + } + break; + + case PROPERTYHANDLE_MAXIMUMPAPERBOTTOMMARGIN: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_LONG), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\MaximumPaperBottomMargin\"?" ); + seqValues[nProperty] >>= m_nMaximumPaperBottomMargin; + } + break; + + // primitives + case PROPERTYHANDLE_ANTIALIASING: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\AntiAliasing\"?" ); + seqValues[nProperty] >>= m_bAntiAliasing; + } + break; + + // primitives + case PROPERTYHANDLE_SNAPHORVERLINESTODISCRETE: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\SnapHorVerLinesToDiscrete\"?" ); + seqValues[nProperty] >>= m_bSnapHorVerLinesToDiscrete; + } + break; + + case PROPERTYHANDLE_SOLIDDRAGCREATE: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\SolidDragCreate\"?" ); + seqValues[nProperty] >>= m_bSolidDragCreate; + } + break; + + case PROPERTYHANDLE_RENDERDECORATEDTEXTDIRECT: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\RenderDecoratedTextDirect\"?" ); + seqValues[nProperty] >>= m_bRenderDecoratedTextDirect; + } + break; + + case PROPERTYHANDLE_RENDERSIMPLETEXTDIRECT: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\RenderSimpleTextDirect\"?" ); + seqValues[nProperty] >>= m_bRenderSimpleTextDirect; + } + break; + + case PROPERTYHANDLE_QUADRATIC3DRENDERLIMIT: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_LONG), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\Quadratic3DRenderLimit\"?" ); + seqValues[nProperty] >>= m_nQuadratic3DRenderLimit; + } + break; + + case PROPERTYHANDLE_QUADRATICFORMCONTROLRENDERLIMIT: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_LONG), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\QuadraticFormControlRenderLimit\"?" ); + seqValues[nProperty] >>= m_nQuadraticFormControlRenderLimit; + } + break; + + // #i97672# selection settings + case PROPERTYHANDLE_TRANSPARENTSELECTION: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\TransparentSelection\"?" ); + seqValues[nProperty] >>= m_bTransparentSelection; + } + break; + + case PROPERTYHANDLE_TRANSPARENTSELECTIONPERCENT: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_SHORT), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\TransparentSelectionPercent\"?" ); + seqValues[nProperty] >>= m_nTransparentSelectionPercent; + } + + case PROPERTYHANDLE_SELECTIONMAXIMUMLUMINANCEPERCENT: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_SHORT), "SvtOptionsDrawinglayer_Impl::SvtOptionsDrawinglayer_Impl()\nWho has changed the value type of \"Office.Common\\Drawinglayer\\SelectionMaximumLuminancePercent\"?" ); + seqValues[nProperty] >>= m_nSelectionMaximumLuminancePercent; + } + break; + } + } +} + +//***************************************************************************************************************** +// destructor +//***************************************************************************************************************** +SvtOptionsDrawinglayer_Impl::~SvtOptionsDrawinglayer_Impl() +{ + if( IsModified() ) + Commit(); +} + +//***************************************************************************************************************** +// Commit +//***************************************************************************************************************** +void SvtOptionsDrawinglayer_Impl::Commit() +{ + Sequence< OUString > aSeqNames( impl_GetPropertyNames() ); + Sequence< Any > aSeqValues( aSeqNames.getLength() ); + + for( sal_Int32 nProperty = 0, nCount = aSeqNames.getLength(); nProperty < nCount; ++nProperty ) + { + switch( nProperty ) + { + case PROPERTYHANDLE_OVERLAYBUFFER: + aSeqValues[nProperty] <<= m_bOverlayBuffer; + break; + + case PROPERTYHANDLE_PAINTBUFFER: + aSeqValues[nProperty] <<= m_bPaintBuffer; + break; + + case PROPERTYHANDLE_STRIPE_COLOR_A: + aSeqValues[nProperty] <<= m_bStripeColorA.GetColor(); + break; + + case PROPERTYHANDLE_STRIPE_COLOR_B: + aSeqValues[nProperty] <<= m_bStripeColorB.GetColor(); + break; + + case PROPERTYHANDLE_STRIPE_LENGTH: + aSeqValues[nProperty] <<= m_nStripeLength; + break; + + // #i73602# + case PROPERTYHANDLE_OVERLAYBUFFER_CALC: + aSeqValues[nProperty] <<= m_bOverlayBuffer_Calc; + break; + + case PROPERTYHANDLE_OVERLAYBUFFER_WRITER: + aSeqValues[nProperty] <<= m_bOverlayBuffer_Writer; + break; + + case PROPERTYHANDLE_OVERLAYBUFFER_DRAWIMPRESS: + aSeqValues[nProperty] <<= m_bOverlayBuffer_DrawImpress; + break; + + // #i74769#, #i75172# + case PROPERTYHANDLE_PAINTBUFFER_CALC: + aSeqValues[nProperty] <<= m_bPaintBuffer_Calc; + break; + + case PROPERTYHANDLE_PAINTBUFFER_WRITER: + aSeqValues[nProperty] <<= m_bPaintBuffer_Writer; + break; + + case PROPERTYHANDLE_PAINTBUFFER_DRAWIMPRESS: + aSeqValues[nProperty] <<= m_bPaintBuffer_DrawImpress; + break; + + // #i4219# + case PROPERTYHANDLE_MAXIMUMPAPERWIDTH: + aSeqValues[nProperty] <<= m_nMaximumPaperWidth; + break; + + case PROPERTYHANDLE_MAXIMUMPAPERHEIGHT: + aSeqValues[nProperty] <<= m_nMaximumPaperHeight; + break; + + case PROPERTYHANDLE_MAXIMUMPAPERLEFTMARGIN: + aSeqValues[nProperty] <<= m_nMaximumPaperLeftMargin; + break; + + case PROPERTYHANDLE_MAXIMUMPAPERRIGHTMARGIN: + aSeqValues[nProperty] <<= m_nMaximumPaperRightMargin; + break; + + case PROPERTYHANDLE_MAXIMUMPAPERTOPMARGIN: + aSeqValues[nProperty] <<= m_nMaximumPaperTopMargin; + break; + + case PROPERTYHANDLE_MAXIMUMPAPERBOTTOMMARGIN: + aSeqValues[nProperty] <<= m_nMaximumPaperBottomMargin; + break; + + // primitives + case PROPERTYHANDLE_ANTIALIASING: + aSeqValues[nProperty] <<= m_bAntiAliasing; + break; + + case PROPERTYHANDLE_SNAPHORVERLINESTODISCRETE: + aSeqValues[nProperty] <<= m_bSnapHorVerLinesToDiscrete; + break; + + case PROPERTYHANDLE_SOLIDDRAGCREATE: + aSeqValues[nProperty] <<= m_bSolidDragCreate; + break; + + case PROPERTYHANDLE_RENDERDECORATEDTEXTDIRECT: + aSeqValues[nProperty] <<= m_bRenderDecoratedTextDirect; + break; + + case PROPERTYHANDLE_RENDERSIMPLETEXTDIRECT: + aSeqValues[nProperty] <<= m_bRenderSimpleTextDirect; + break; + + case PROPERTYHANDLE_QUADRATIC3DRENDERLIMIT: + aSeqValues[nProperty] <<= m_nQuadratic3DRenderLimit; + break; + + case PROPERTYHANDLE_QUADRATICFORMCONTROLRENDERLIMIT: + aSeqValues[nProperty] <<= m_nQuadraticFormControlRenderLimit; + break; + + // #i97672# selection settings + case PROPERTYHANDLE_TRANSPARENTSELECTION: + aSeqValues[nProperty] <<= m_bTransparentSelection; + break; + + case PROPERTYHANDLE_TRANSPARENTSELECTIONPERCENT: + aSeqValues[nProperty] <<= m_nTransparentSelectionPercent; + break; + + case PROPERTYHANDLE_SELECTIONMAXIMUMLUMINANCEPERCENT: + aSeqValues[nProperty] <<= m_nSelectionMaximumLuminancePercent; + break; + } + } + + PutProperties( aSeqNames, aSeqValues ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Bool SvtOptionsDrawinglayer_Impl::IsOverlayBuffer() const +{ + return m_bOverlayBuffer; +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Bool SvtOptionsDrawinglayer_Impl::IsPaintBuffer() const +{ + return m_bPaintBuffer; +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +Color SvtOptionsDrawinglayer_Impl::GetStripeColorA() const +{ + return m_bStripeColorA; +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +Color SvtOptionsDrawinglayer_Impl::GetStripeColorB() const +{ + return m_bStripeColorB; +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_uInt16 SvtOptionsDrawinglayer_Impl::GetStripeLength() const +{ + return m_nStripeLength; +} + +// #i73602# +sal_Bool SvtOptionsDrawinglayer_Impl::IsOverlayBuffer_Calc() const +{ + return m_bOverlayBuffer_Calc; +} + +sal_Bool SvtOptionsDrawinglayer_Impl::IsOverlayBuffer_Writer() const +{ + return m_bOverlayBuffer_Writer; +} + +sal_Bool SvtOptionsDrawinglayer_Impl::IsOverlayBuffer_DrawImpress() const +{ + return m_bOverlayBuffer_DrawImpress; +} + +// #i74769#, #i75172# +sal_Bool SvtOptionsDrawinglayer_Impl::IsPaintBuffer_Calc() const +{ + return m_bPaintBuffer_Calc; +} + +sal_Bool SvtOptionsDrawinglayer_Impl::IsPaintBuffer_Writer() const +{ + return m_bPaintBuffer_Writer; +} + +sal_Bool SvtOptionsDrawinglayer_Impl::IsPaintBuffer_DrawImpress() const +{ + return m_bPaintBuffer_DrawImpress; +} + +// #i4219# +sal_uInt32 SvtOptionsDrawinglayer_Impl::GetMaximumPaperWidth() const +{ + return m_nMaximumPaperWidth; +} + +sal_uInt32 SvtOptionsDrawinglayer_Impl::GetMaximumPaperHeight() const +{ + return m_nMaximumPaperHeight; +} + +sal_uInt32 SvtOptionsDrawinglayer_Impl::GetMaximumPaperLeftMargin() const +{ + return m_nMaximumPaperLeftMargin; +} + +sal_uInt32 SvtOptionsDrawinglayer_Impl::GetMaximumPaperRightMargin() const +{ + return m_nMaximumPaperRightMargin; +} + +sal_uInt32 SvtOptionsDrawinglayer_Impl::GetMaximumPaperTopMargin() const +{ + return m_nMaximumPaperTopMargin; +} + +sal_uInt32 SvtOptionsDrawinglayer_Impl::GetMaximumPaperBottomMargin() const +{ + return m_nMaximumPaperBottomMargin; +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtOptionsDrawinglayer_Impl::SetOverlayBuffer( sal_Bool bState ) +{ + if(m_bOverlayBuffer != bState) + { + m_bOverlayBuffer = bState; + SetModified(); + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtOptionsDrawinglayer_Impl::SetPaintBuffer( sal_Bool bState ) +{ + if(m_bPaintBuffer != bState) + { + m_bPaintBuffer = bState; + SetModified(); + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtOptionsDrawinglayer_Impl::SetStripeColorA( Color aColor ) +{ + if(m_bStripeColorA != aColor) + { + m_bStripeColorA = aColor; + SetModified(); + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtOptionsDrawinglayer_Impl::SetStripeColorB( Color aColor ) +{ + if(m_bStripeColorB != aColor) + { + m_bStripeColorB = aColor; + SetModified(); + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtOptionsDrawinglayer_Impl::SetStripeLength( sal_uInt16 nLength ) +{ + if(m_nStripeLength != nLength) + { + m_nStripeLength = nLength; + SetModified(); + } +} + +// #i73602# +void SvtOptionsDrawinglayer_Impl::SetOverlayBuffer_Calc( sal_Bool bState ) +{ + if(m_bOverlayBuffer_Calc != bState) + { + m_bOverlayBuffer_Calc = bState; + SetModified(); + } +} + +void SvtOptionsDrawinglayer_Impl::SetOverlayBuffer_Writer( sal_Bool bState ) +{ + if(m_bOverlayBuffer_Writer != bState) + { + m_bOverlayBuffer_Writer = bState; + SetModified(); + } +} + +void SvtOptionsDrawinglayer_Impl::SetOverlayBuffer_DrawImpress( sal_Bool bState ) +{ + if(m_bOverlayBuffer_DrawImpress != bState) + { + m_bOverlayBuffer_DrawImpress = bState; + SetModified(); + } +} + +// #i74769#, #i75172# +void SvtOptionsDrawinglayer_Impl::SetPaintBuffer_Calc( sal_Bool bState ) +{ + if(m_bPaintBuffer_Calc != bState) + { + m_bPaintBuffer_Calc = bState; + SetModified(); + } +} + +void SvtOptionsDrawinglayer_Impl::SetPaintBuffer_Writer( sal_Bool bState ) +{ + if(m_bPaintBuffer_Writer != bState) + { + m_bPaintBuffer_Writer = bState; + SetModified(); + } +} + +void SvtOptionsDrawinglayer_Impl::SetPaintBuffer_DrawImpress( sal_Bool bState ) +{ + if(m_bPaintBuffer_DrawImpress != bState) + { + m_bPaintBuffer_DrawImpress = bState; + SetModified(); + } +} + +// #i4219# +void SvtOptionsDrawinglayer_Impl::SetMaximumPaperWidth( sal_uInt32 nNew ) +{ + if(m_nMaximumPaperWidth != nNew) + { + m_nMaximumPaperWidth = nNew; + SetModified(); + } +} + +void SvtOptionsDrawinglayer_Impl::SetMaximumPaperHeight( sal_uInt32 nNew ) +{ + if(m_nMaximumPaperHeight != nNew) + { + m_nMaximumPaperHeight = nNew; + SetModified(); + } +} + +void SvtOptionsDrawinglayer_Impl::SetMaximumPaperLeftMargin( sal_uInt32 nNew ) +{ + if(m_nMaximumPaperLeftMargin != nNew) + { + m_nMaximumPaperLeftMargin = nNew; + SetModified(); + } +} + +void SvtOptionsDrawinglayer_Impl::SetMaximumPaperRightMargin( sal_uInt32 nNew ) +{ + if(m_nMaximumPaperRightMargin != nNew) + { + m_nMaximumPaperRightMargin = nNew; + SetModified(); + } +} + +void SvtOptionsDrawinglayer_Impl::SetMaximumPaperTopMargin( sal_uInt32 nNew ) +{ + if(m_nMaximumPaperTopMargin != nNew) + { + m_nMaximumPaperTopMargin = nNew; + SetModified(); + } +} + +void SvtOptionsDrawinglayer_Impl::SetMaximumPaperBottomMargin( sal_uInt32 nNew ) +{ + if(m_nMaximumPaperBottomMargin != nNew) + { + m_nMaximumPaperBottomMargin = nNew; + SetModified(); + } +} + +// helper +sal_Bool SvtOptionsDrawinglayer_Impl::IsAAPossibleOnThisSystem() const +{ + if(!m_bAllowAAChecked) + { + SvtOptionsDrawinglayer_Impl* pThat = const_cast< SvtOptionsDrawinglayer_Impl* >(this); + pThat->m_bAllowAAChecked = true; + +#ifdef WIN32 + // WIN32 uses GDIPlus with VCL forthe first incarnation; this will be enhanced + // in the future to use canvases and the canvas renderer, thus a AA-abled + // canvas needs to be checked here in the future. + // Currently, just allow AA for WIN32 +#endif + + // check XRenderExtension + if(m_bAllowAA && !Application::GetDefaultDevice()->supportsOperation( OutDevSupport_TransparentRect )) + { + pThat->m_bAllowAA = false; + } + } + + return m_bAllowAA; +} + +// primitives +sal_Bool SvtOptionsDrawinglayer_Impl::IsAntiAliasing() const +{ + return m_bAntiAliasing; +} + +sal_Bool SvtOptionsDrawinglayer_Impl::IsSnapHorVerLinesToDiscrete() const +{ + return m_bSnapHorVerLinesToDiscrete; +} + +sal_Bool SvtOptionsDrawinglayer_Impl::IsSolidDragCreate() const +{ + return m_bSolidDragCreate; +} + +sal_Bool SvtOptionsDrawinglayer_Impl::IsRenderDecoratedTextDirect() const +{ + return m_bRenderDecoratedTextDirect; +} + +sal_Bool SvtOptionsDrawinglayer_Impl::IsRenderSimpleTextDirect() const +{ + return m_bRenderSimpleTextDirect; +} + +sal_uInt32 SvtOptionsDrawinglayer_Impl::GetQuadratic3DRenderLimit() const +{ + return m_nQuadratic3DRenderLimit; +} + +sal_uInt32 SvtOptionsDrawinglayer_Impl::GetQuadraticFormControlRenderLimit() const +{ + return m_nQuadraticFormControlRenderLimit; +} + +void SvtOptionsDrawinglayer_Impl::SetAntiAliasing( sal_Bool bState ) +{ + if(m_bAntiAliasing != bState) + { + m_bAntiAliasing = bState; + SetModified(); + } +} + +void SvtOptionsDrawinglayer_Impl::SetSnapHorVerLinesToDiscrete( sal_Bool bState ) +{ + if(m_bSnapHorVerLinesToDiscrete != bState) + { + m_bSnapHorVerLinesToDiscrete = bState; + SetModified(); + } +} + +void SvtOptionsDrawinglayer_Impl::SetSolidDragCreate( sal_Bool bState ) +{ + if(m_bSolidDragCreate != bState) + { + m_bSolidDragCreate = bState; + SetModified(); + } +} + +void SvtOptionsDrawinglayer_Impl::SetRenderDecoratedTextDirect( sal_Bool bState ) +{ + if(m_bRenderDecoratedTextDirect != bState) + { + m_bRenderDecoratedTextDirect = bState; + SetModified(); + } +} + +void SvtOptionsDrawinglayer_Impl::SetRenderSimpleTextDirect( sal_Bool bState ) +{ + if(m_bRenderSimpleTextDirect != bState) + { + m_bRenderSimpleTextDirect = bState; + SetModified(); + } +} + +void SvtOptionsDrawinglayer_Impl::SetQuadratic3DRenderLimit(sal_uInt32 nNew) +{ + if(m_nQuadratic3DRenderLimit != nNew) + { + m_nQuadratic3DRenderLimit = nNew; + SetModified(); + } +} + +void SvtOptionsDrawinglayer_Impl::SetQuadraticFormControlRenderLimit(sal_uInt32 nNew) +{ + if(m_nQuadraticFormControlRenderLimit != nNew) + { + m_nQuadraticFormControlRenderLimit = nNew; + SetModified(); + } +} + +// #i97672# selection settings +sal_Bool SvtOptionsDrawinglayer_Impl::IsTransparentSelection() const +{ + return m_bTransparentSelection; +} + +void SvtOptionsDrawinglayer_Impl::SetTransparentSelection( sal_Bool bState ) +{ + if(m_bTransparentSelection != bState) + { + m_bTransparentSelection = bState; + SetModified(); + } +} + +void SvtOptionsDrawinglayer_Impl::SetTransparentSelectionPercent( sal_uInt16 nPercent ) +{ + if(m_nTransparentSelectionPercent != nPercent) + { + m_nTransparentSelectionPercent = nPercent; + SetModified(); + } +} + +sal_uInt16 SvtOptionsDrawinglayer_Impl::GetTransparentSelectionPercent() const +{ + return m_nTransparentSelectionPercent; +} + +void SvtOptionsDrawinglayer_Impl::SetSelectionMaximumLuminancePercent( sal_uInt16 nPercent ) +{ + if(m_nSelectionMaximumLuminancePercent != nPercent) + { + m_nSelectionMaximumLuminancePercent = nPercent; + SetModified(); + } +} + +sal_uInt16 SvtOptionsDrawinglayer_Impl::GetSelectionMaximumLuminancePercent() const +{ + return m_nSelectionMaximumLuminancePercent; +} + +//***************************************************************************************************************** +// private method +//***************************************************************************************************************** +Sequence< OUString > SvtOptionsDrawinglayer_Impl::impl_GetPropertyNames() +{ + // Build static list of configuration key names. + static const OUString pProperties[] = + { + PROPERTYNAME_OVERLAYBUFFER , + PROPERTYNAME_PAINTBUFFER , + PROPERTYNAME_STRIPE_COLOR_A , + PROPERTYNAME_STRIPE_COLOR_B , + PROPERTYNAME_STRIPE_LENGTH , + + // #i73602# + PROPERTYNAME_OVERLAYBUFFER_CALC, + PROPERTYNAME_OVERLAYBUFFER_WRITER, + PROPERTYNAME_OVERLAYBUFFER_DRAWIMPRESS, + + // #i74769#, #i75172# + PROPERTYNAME_PAINTBUFFER_CALC, + PROPERTYNAME_PAINTBUFFER_WRITER, + PROPERTYNAME_PAINTBUFFER_DRAWIMPRESS, + + // #i4219# + PROPERTYNAME_MAXIMUMPAPERWIDTH, + PROPERTYNAME_MAXIMUMPAPERHEIGHT, + PROPERTYNAME_MAXIMUMPAPERLEFTMARGIN, + PROPERTYNAME_MAXIMUMPAPERRIGHTMARGIN, + PROPERTYNAME_MAXIMUMPAPERTOPMARGIN, + PROPERTYNAME_MAXIMUMPAPERBOTTOMMARGIN, + + // primitives + PROPERTYNAME_ANTIALIASING, + PROPERTYNAME_SNAPHORVERLINESTODISCRETE, + PROPERTYNAME_SOLIDDRAGCREATE, + PROPERTYNAME_RENDERDECORATEDTEXTDIRECT, + PROPERTYNAME_RENDERSIMPLETEXTDIRECT, + PROPERTYNAME_QUADRATIC3DRENDERLIMIT, + PROPERTYNAME_QUADRATICFORMCONTROLRENDERLIMIT, + + // #i97672# selection settings + PROPERTYNAME_TRANSPARENTSELECTION, + PROPERTYNAME_TRANSPARENTSELECTIONPERCENT, + PROPERTYNAME_SELECTIONMAXIMUMLUMINANCEPERCENT + }; + + // Initialize return sequence with these list ... + static const Sequence< OUString > seqPropertyNames( pProperties, PROPERTYCOUNT ); + // ... and return it. + return seqPropertyNames; +} + +//***************************************************************************************************************** +// initialize static member +// DON'T DO IT IN YOUR HEADER! +// see definition for further informations +//***************************************************************************************************************** +SvtOptionsDrawinglayer_Impl* SvtOptionsDrawinglayer::m_pDataContainer = NULL; +sal_Int32 SvtOptionsDrawinglayer::m_nRefCount = 0; + +//***************************************************************************************************************** +// constructor +//***************************************************************************************************************** +SvtOptionsDrawinglayer::SvtOptionsDrawinglayer() +{ + // Global access, must be guarded (multithreading!). + MutexGuard aGuard( GetOwnStaticMutex() ); + // Increase ouer refcount ... + ++m_nRefCount; + // ... and initialize ouer data container only if it not already! + if( m_pDataContainer == NULL ) + { + m_pDataContainer = new SvtOptionsDrawinglayer_Impl(); + } +} + +//***************************************************************************************************************** +// destructor +//***************************************************************************************************************** +SvtOptionsDrawinglayer::~SvtOptionsDrawinglayer() +{ + // Global access, must be guarded (multithreading!) + MutexGuard aGuard( GetOwnStaticMutex() ); + // Decrease ouer refcount. + --m_nRefCount; + // If last instance was deleted ... + // we must destroy ouer static data container! + if( m_nRefCount <= 0 ) + { + delete m_pDataContainer; + m_pDataContainer = NULL; + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Bool SvtOptionsDrawinglayer::IsOverlayBuffer() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsOverlayBuffer(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Bool SvtOptionsDrawinglayer::IsPaintBuffer() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsPaintBuffer(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +Color SvtOptionsDrawinglayer::GetStripeColorA() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->GetStripeColorA(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +Color SvtOptionsDrawinglayer::GetStripeColorB() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->GetStripeColorB(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_uInt16 SvtOptionsDrawinglayer::GetStripeLength() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->GetStripeLength(); +} + +// #i73602# +sal_Bool SvtOptionsDrawinglayer::IsOverlayBuffer_Calc() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsOverlayBuffer_Calc(); +} + +sal_Bool SvtOptionsDrawinglayer::IsOverlayBuffer_Writer() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsOverlayBuffer_Writer(); +} + +sal_Bool SvtOptionsDrawinglayer::IsOverlayBuffer_DrawImpress() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsOverlayBuffer_DrawImpress(); +} + +// #i74769#, #i75172# +sal_Bool SvtOptionsDrawinglayer::IsPaintBuffer_Calc() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsPaintBuffer_Calc(); +} + +sal_Bool SvtOptionsDrawinglayer::IsPaintBuffer_Writer() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsPaintBuffer_Writer(); +} + +sal_Bool SvtOptionsDrawinglayer::IsPaintBuffer_DrawImpress() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsPaintBuffer_DrawImpress(); +} + +// #i4219# +sal_uInt32 SvtOptionsDrawinglayer::GetMaximumPaperWidth() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->GetMaximumPaperWidth(); +} + +sal_uInt32 SvtOptionsDrawinglayer::GetMaximumPaperHeight() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->GetMaximumPaperHeight(); +} + +sal_uInt32 SvtOptionsDrawinglayer::GetMaximumPaperLeftMargin() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->GetMaximumPaperLeftMargin(); +} + +sal_uInt32 SvtOptionsDrawinglayer::GetMaximumPaperRightMargin() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->GetMaximumPaperRightMargin(); +} + +sal_uInt32 SvtOptionsDrawinglayer::GetMaximumPaperTopMargin() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->GetMaximumPaperTopMargin(); +} + +sal_uInt32 SvtOptionsDrawinglayer::GetMaximumPaperBottomMargin() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->GetMaximumPaperBottomMargin(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtOptionsDrawinglayer::SetOverlayBuffer( sal_Bool bState ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetOverlayBuffer( bState ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtOptionsDrawinglayer::SetPaintBuffer( sal_Bool bState ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetPaintBuffer( bState ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtOptionsDrawinglayer::SetStripeColorA( Color aColor ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetStripeColorA( aColor ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtOptionsDrawinglayer::SetStripeColorB( Color aColor ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetStripeColorB( aColor ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtOptionsDrawinglayer::SetStripeLength( sal_uInt16 nLength ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetStripeLength( nLength ); +} + +// #i73602# +void SvtOptionsDrawinglayer::SetOverlayBuffer_Calc( sal_Bool bState ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetOverlayBuffer_Calc( bState ); +} + +void SvtOptionsDrawinglayer::SetOverlayBuffer_Writer( sal_Bool bState ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetOverlayBuffer_Writer( bState ); +} + +void SvtOptionsDrawinglayer::SetOverlayBuffer_DrawImpress( sal_Bool bState ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetOverlayBuffer_DrawImpress( bState ); +} + +// #i74769#, #i75172# +void SvtOptionsDrawinglayer::SetPaintBuffer_Calc( sal_Bool bState ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetPaintBuffer_Calc( bState ); +} + +void SvtOptionsDrawinglayer::SetPaintBuffer_Writer( sal_Bool bState ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetPaintBuffer_Writer( bState ); +} + +void SvtOptionsDrawinglayer::SetPaintBuffer_DrawImpress( sal_Bool bState ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetPaintBuffer_DrawImpress( bState ); +} + +// #i4219# +void SvtOptionsDrawinglayer::SetMaximumPaperWidth( sal_uInt32 nNew ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetMaximumPaperWidth( nNew ); +} + +void SvtOptionsDrawinglayer::SetMaximumPaperHeight( sal_uInt32 nNew ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetMaximumPaperHeight( nNew ); +} + +void SvtOptionsDrawinglayer::SetMaximumPaperLeftMargin( sal_uInt32 nNew ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetMaximumPaperLeftMargin( nNew ); +} + +void SvtOptionsDrawinglayer::SetMaximumPaperRightMargin( sal_uInt32 nNew ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetMaximumPaperRightMargin( nNew ); +} + +void SvtOptionsDrawinglayer::SetMaximumPaperTopMargin( sal_uInt32 nNew ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetMaximumPaperTopMargin( nNew ); +} + +void SvtOptionsDrawinglayer::SetMaximumPaperBottomMargin( sal_uInt32 nNew ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetMaximumPaperBottomMargin( nNew ); +} + +// helper +sal_Bool SvtOptionsDrawinglayer::IsAAPossibleOnThisSystem() const +{ + return m_pDataContainer->IsAAPossibleOnThisSystem(); +} + +// primitives +sal_Bool SvtOptionsDrawinglayer::IsAntiAliasing() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsAntiAliasing() && IsAAPossibleOnThisSystem(); +} + +sal_Bool SvtOptionsDrawinglayer::IsSnapHorVerLinesToDiscrete() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsAntiAliasing() && m_pDataContainer->IsSnapHorVerLinesToDiscrete(); +} + +sal_Bool SvtOptionsDrawinglayer::IsSolidDragCreate() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsSolidDragCreate(); +} + +sal_Bool SvtOptionsDrawinglayer::IsRenderDecoratedTextDirect() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsRenderDecoratedTextDirect(); +} + +sal_Bool SvtOptionsDrawinglayer::IsRenderSimpleTextDirect() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsRenderSimpleTextDirect(); +} + +sal_uInt32 SvtOptionsDrawinglayer::GetQuadratic3DRenderLimit() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->GetQuadratic3DRenderLimit(); +} + +sal_uInt32 SvtOptionsDrawinglayer::GetQuadraticFormControlRenderLimit() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->GetQuadraticFormControlRenderLimit(); +} + +void SvtOptionsDrawinglayer::SetAntiAliasing( sal_Bool bState ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetAntiAliasing( bState ); +} + +void SvtOptionsDrawinglayer::SetSnapHorVerLinesToDiscrete( sal_Bool bState ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetSnapHorVerLinesToDiscrete( bState ); +} + +void SvtOptionsDrawinglayer::SetSolidDragCreate( sal_Bool bState ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetSolidDragCreate( bState ); +} + +void SvtOptionsDrawinglayer::SetRenderDecoratedTextDirect( sal_Bool bState ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetRenderDecoratedTextDirect( bState ); +} + +void SvtOptionsDrawinglayer::SetRenderSimpleTextDirect( sal_Bool bState ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetRenderSimpleTextDirect( bState ); +} + +void SvtOptionsDrawinglayer::SetQuadratic3DRenderLimit(sal_uInt32 nNew) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetQuadratic3DRenderLimit( nNew ); +} + +void SvtOptionsDrawinglayer::SetQuadraticFormControlRenderLimit(sal_uInt32 nNew) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetQuadraticFormControlRenderLimit( nNew ); +} + +// #i97672# selection settings +sal_Bool SvtOptionsDrawinglayer::IsTransparentSelection() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsTransparentSelection(); +} + +void SvtOptionsDrawinglayer::SetTransparentSelection( sal_Bool bState ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetTransparentSelection( bState ); +} + +sal_uInt16 SvtOptionsDrawinglayer::GetTransparentSelectionPercent() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + sal_uInt16 aRetval(m_pDataContainer->GetTransparentSelectionPercent()); + + // crop to range [10% .. 90%] + if(aRetval < 10) + { + aRetval = 10; + } + + if(aRetval > 90) + { + aRetval = 90; + } + + return aRetval; +} + +void SvtOptionsDrawinglayer::SetTransparentSelectionPercent( sal_uInt16 nPercent ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + + // crop to range [10% .. 90%] + if(nPercent < 10) + { + nPercent = 10; + } + + if(nPercent > 90) + { + nPercent = 90; + } + + m_pDataContainer->SetTransparentSelectionPercent( nPercent ); +} + +sal_uInt16 SvtOptionsDrawinglayer::GetSelectionMaximumLuminancePercent() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + sal_uInt16 aRetval(m_pDataContainer->GetSelectionMaximumLuminancePercent()); + + // crop to range [0% .. 100%] + if(aRetval > 90) + { + aRetval = 90; + } + + return aRetval; +} + +void SvtOptionsDrawinglayer::SetSelectionMaximumLuminancePercent( sal_uInt16 nPercent ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + + // crop to range [0% .. 100%] + if(nPercent > 90) + { + nPercent = 90; + } + + m_pDataContainer->SetSelectionMaximumLuminancePercent( nPercent ); +} + +//***************************************************************************************************************** +// private method +//***************************************************************************************************************** +Mutex& SvtOptionsDrawinglayer::GetOwnStaticMutex() +{ + // Initialize static mutex only for one time! + static Mutex* pMutex = NULL; + // If these method first called (Mutex not already exist!) ... + if( pMutex == NULL ) + { + // ... we must create a new one. Protect follow code with the global mutex - + // It must be - we create a static variable! + MutexGuard aGuard( Mutex::getGlobalMutex() ); + // We must check our pointer again - because it can be that another instance of ouer class will be fastr then these! + if( pMutex == NULL ) + { + // Create the new mutex and set it for return on static variable. + static Mutex aMutex; + pMutex = &aMutex; + } + } + // Return new created or already existing mutex object. + return *pMutex; +} + +// eof + +/* 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 000000000000..cb1e790bb82b --- /dev/null +++ b/unotools/source/config/pathoptions.cxx @@ -0,0 +1,1083 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" + +#include <unotools/pathoptions.hxx> +#include <unotools/configitem.hxx> +#include <unotools/configmgr.hxx> +#include <tools/debug.hxx> +#include <tools/resmgr.hxx> +#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/localfilehelper.hxx> +#include <unotools/bootstrap.hxx> + +#include <unotools/ucbhelper.hxx> +#include <comphelper/processfactory.hxx> +#include <com/sun/star/beans/XFastPropertySet.hpp> +#include <com/sun/star/beans/XPropertySet.hpp> +#include <com/sun/star/beans/PropertyAttribute.hpp> +#include <com/sun/star/beans/XPropertySetInfo.hpp> +#include <com/sun/star/util/XStringSubstitution.hpp> +#include <com/sun/star/lang/XMultiServiceFactory.hpp> +#include <rtl/instance.hxx> + +#include <itemholder1.hxx> + +#include <vector> +#include <hash_map> + +using namespace osl; +using namespace utl; +using namespace rtl; +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 ---------------------------------------------------------------- + +#define SEARCHPATH_DELIMITER ';' + +#define ASCII_STR(s) OUString( RTL_CONSTASCII_USTRINGPARAM(s) ) + +#define SIGN_STARTVARIABLE ASCII_STR("$(") +#define SIGN_ENDVARIABLE ASCII_STR(")") + +// Supported variables by the old SvtPathOptions implementation +#define SUBSTITUTE_INST "$(inst)" +#define SUBSTITUTE_PROG "$(prog)" +#define SUBSTITUTE_USER "$(user)" +#define SUBSTITUTE_INSTPATH "$(instpath)" +#define SUBSTITUTE_PROGPATH "$(progpath)" +#define SUBSTITUTE_USERPATH "$(userpath)" +#define SUBSTITUTE_INSTURL "$(insturl)" +#define SUBSTITUTE_PROGURL "$(progurl)" +#define SUBSTITUTE_USERURL "$(userurl)" +#define SUBSTITUTE_PATH "$(path)" +//#define SUBSTITUTE_LANG "$(lang)" +#define SUBSTITUTE_LANGID "$(langid)" +#define SUBSTITUTE_VLANG "$(vlang)" +#define SUBSTITUTE_WORKDIRURL "$(workdirurl)" + +#define STRPOS_NOTFOUND -1 + +struct OUStringHashCode +{ + size_t operator()( const ::rtl::OUString& sString ) const + { + return sString.hashCode(); + } +}; + +enum VarNameProperty +{ + VAR_NEEDS_SYSTEM_PATH, + VAR_NEEDS_FILEURL +}; + +class NameToHandleMap : public ::std::hash_map< ::rtl::OUString, sal_Int32, OUStringHashCode, ::std::equal_to< ::rtl::OUString > > +{ + public: + inline void free() { NameToHandleMap().swap( *this ); } +}; + +class EnumToHandleMap : public ::std::hash_map< sal_Int32, sal_Int32, std::hash< sal_Int32 >, std::equal_to< sal_Int32 > > +{ + public: + inline void free() { EnumToHandleMap().swap( *this ); } +}; + +class VarNameToEnumMap : public ::std::hash_map< OUString, VarNameProperty, OUStringHashCode, ::std::equal_to< OUString > > +{ + public: + inline void free() { VarNameToEnumMap().swap( *this ); } +}; + + +// class SvtPathOptions_Impl --------------------------------------------- +class SvtPathOptions_Impl +{ + private: + // Local variables to return const references + std::vector< String > m_aPathArray; + Reference< XFastPropertySet > m_xPathSettings; + Reference< XStringSubstitution > m_xSubstVariables; + mutable EnumToHandleMap m_aMapEnumToPropHandle; + VarNameToEnumMap m_aMapVarNamesToEnum; + + ::com::sun::star::lang::Locale m_aLocale; + String m_aEmptyString; + mutable ::osl::Mutex m_aMutex; + + public: + SvtPathOptions_Impl(); + + // get the pathes, not const because of using a mutex + const String& GetPath( SvtPathOptions::Pathes ); + const String& GetAddinPath() { return GetPath( SvtPathOptions::PATH_ADDIN ); } + const String& GetAutoCorrectPath() { return GetPath( SvtPathOptions::PATH_AUTOCORRECT ); } + const String& GetAutoTextPath() { return GetPath( SvtPathOptions::PATH_AUTOTEXT ); } + const String& GetBackupPath() { return GetPath( SvtPathOptions::PATH_BACKUP ); } + const String& GetBasicPath() { return GetPath( SvtPathOptions::PATH_BASIC ); } + const String& GetBitmapPath() { return GetPath( SvtPathOptions::PATH_BITMAP ); } + const String& GetConfigPath() { return GetPath( SvtPathOptions::PATH_CONFIG ); } + const String& GetDictionaryPath() { return GetPath( SvtPathOptions::PATH_DICTIONARY ); } + const String& GetFavoritesPath() { return GetPath( SvtPathOptions::PATH_FAVORITES ); } + const String& GetFilterPath() { return GetPath( SvtPathOptions::PATH_FILTER ); } + const String& GetGalleryPath() { return GetPath( SvtPathOptions::PATH_GALLERY ); } + const String& GetGraphicPath() { return GetPath( SvtPathOptions::PATH_GRAPHIC ); } + const String& GetHelpPath() { return GetPath( SvtPathOptions::PATH_HELP ); } + const String& GetLinguisticPath() { return GetPath( SvtPathOptions::PATH_LINGUISTIC ); } + const String& GetModulePath() { return GetPath( SvtPathOptions::PATH_MODULE ); } + const String& GetPalettePath() { return GetPath( SvtPathOptions::PATH_PALETTE ); } + const String& GetPluginPath() { return GetPath( SvtPathOptions::PATH_PLUGIN ); } + const String& GetStoragePath() { return GetPath( SvtPathOptions::PATH_STORAGE ); } + const String& GetTempPath() { return GetPath( SvtPathOptions::PATH_TEMP ); } + const String& GetTemplatePath() { return GetPath( SvtPathOptions::PATH_TEMPLATE ); } + const String& GetUserConfigPath() { return GetPath( SvtPathOptions::PATH_USERCONFIG ); } + const String& GetWorkPath() { return GetPath( SvtPathOptions::PATH_WORK ); } + const String& GetUIConfigPath() { return GetPath( SvtPathOptions::PATH_UICONFIG ); } + const String& GetFingerprintPath() { return GetPath( SvtPathOptions::PATH_FINGERPRINT ); } + + // set the pathes + void SetPath( SvtPathOptions::Pathes, const String& rNewPath ); + void SetAddinPath( const String& rPath ) { SetPath( SvtPathOptions::PATH_ADDIN, rPath ); } + void SetAutoCorrectPath( const String& rPath ) { SetPath( SvtPathOptions::PATH_AUTOCORRECT, rPath ); } + void SetAutoTextPath( const String& rPath ) { SetPath( SvtPathOptions::PATH_AUTOTEXT, rPath ); } + void SetBackupPath( const String& rPath ) { SetPath( SvtPathOptions::PATH_BACKUP, rPath ); } + void SetBasicPath( const String& rPath ) { SetPath( SvtPathOptions::PATH_BASIC, rPath ); } + void SetBitmapPath( const String& rPath ) { SetPath( SvtPathOptions::PATH_BITMAP, rPath ); } + void SetConfigPath( const String& rPath ) { SetPath( SvtPathOptions::PATH_CONFIG, rPath ); } + void SetDictionaryPath( const String& rPath ) { SetPath( SvtPathOptions::PATH_DICTIONARY, rPath ); } + void SetFavoritesPath( const String& rPath ) { SetPath( SvtPathOptions::PATH_FAVORITES, rPath ); } + void SetFilterPath( const String& rPath ) { SetPath( SvtPathOptions::PATH_FILTER, rPath ); } + void SetGalleryPath( const String& rPath ) { SetPath( SvtPathOptions::PATH_GALLERY, rPath ); } + void SetGraphicPath( const String& rPath ) { SetPath( SvtPathOptions::PATH_GRAPHIC, rPath ); } + void SetHelpPath( const String& rPath ) { SetPath( SvtPathOptions::PATH_HELP, rPath ); } + void SetLinguisticPath( const String& rPath ) { SetPath( SvtPathOptions::PATH_LINGUISTIC, rPath ); } + void SetModulePath( const String& rPath ) { SetPath( SvtPathOptions::PATH_MODULE, rPath ); } + void SetPalettePath( const String& rPath ) { SetPath( SvtPathOptions::PATH_PALETTE, rPath ); } + void SetPluginPath( const String& rPath ) { SetPath( SvtPathOptions::PATH_PLUGIN, rPath ); } + void SetStoragePath( const String& rPath ) { SetPath( SvtPathOptions::PATH_STORAGE, rPath ); } + void SetTempPath( const String& rPath ) { SetPath( SvtPathOptions::PATH_TEMP, rPath ); } + void SetTemplatePath( const String& rPath ) { SetPath( SvtPathOptions::PATH_TEMPLATE, rPath ); } + void SetUserConfigPath( const String& rPath ) { SetPath( SvtPathOptions::PATH_USERCONFIG, rPath ); } + void SetWorkPath( const String& rPath ) { SetPath( SvtPathOptions::PATH_WORK, rPath ); } + + rtl::OUString SubstVar( const rtl::OUString& rVar ); + rtl::OUString SubstituteAndConvert( const rtl::OUString& rPath ); + rtl::OUString UsePathVariables( const rtl::OUString& rPath ); + + ::com::sun::star::lang::Locale GetLocale() const { return m_aLocale; } + + BOOL IsPathReadonly(SvtPathOptions::Pathes ePath)const; +}; + +// global ---------------------------------------------------------------- + +static SvtPathOptions_Impl* pOptions = NULL; +static sal_Int32 nRefCount = 0; + +// functions ------------------------------------------------------------- +struct PropertyStruct +{ + const char* pPropName; // The ascii name of the Office path + SvtPathOptions::Pathes ePath; // The enum value used by SvtPathOptions +}; + +struct VarNameAttribute +{ + const char* pVarName; // The name of the path variable + VarNameProperty eVarProperty; // Which return value is needed by this path variable +}; + +static PropertyStruct aPropNames[] = +{ + { "Addin", SvtPathOptions::PATH_ADDIN }, + { "AutoCorrect", SvtPathOptions::PATH_AUTOCORRECT }, + { "AutoText", SvtPathOptions::PATH_AUTOTEXT }, + { "Backup", SvtPathOptions::PATH_BACKUP }, + { "Basic", SvtPathOptions::PATH_BASIC }, + { "Bitmap", SvtPathOptions::PATH_BITMAP }, + { "Config", SvtPathOptions::PATH_CONFIG }, + { "Dictionary", SvtPathOptions::PATH_DICTIONARY }, + { "Favorite", SvtPathOptions::PATH_FAVORITES }, + { "Filter", SvtPathOptions::PATH_FILTER }, + { "Gallery", SvtPathOptions::PATH_GALLERY }, + { "Graphic", SvtPathOptions::PATH_GRAPHIC }, + { "Help", SvtPathOptions::PATH_HELP }, + { "Linguistic", SvtPathOptions::PATH_LINGUISTIC }, + { "Module", SvtPathOptions::PATH_MODULE }, + { "Palette", SvtPathOptions::PATH_PALETTE }, + { "Plugin", SvtPathOptions::PATH_PLUGIN }, + { "Storage", SvtPathOptions::PATH_STORAGE }, + { "Temp", SvtPathOptions::PATH_TEMP }, + { "Template", SvtPathOptions::PATH_TEMPLATE }, + { "UserConfig", SvtPathOptions::PATH_USERCONFIG }, + { "Work", SvtPathOptions::PATH_WORK }, + { "UIConfig", SvtPathOptions::PATH_UICONFIG }, + { "Fingerprint", SvtPathOptions::PATH_FINGERPRINT } +}; + +static VarNameAttribute aVarNameAttribute[] = +{ + { SUBSTITUTE_INSTPATH, VAR_NEEDS_SYSTEM_PATH }, // $(instpath) + { SUBSTITUTE_PROGPATH, VAR_NEEDS_SYSTEM_PATH }, // $(progpath) + { SUBSTITUTE_USERPATH, VAR_NEEDS_SYSTEM_PATH }, // $(userpath) + { SUBSTITUTE_PATH, VAR_NEEDS_SYSTEM_PATH }, // $(path) +}; + +// class SvtPathOptions_Impl --------------------------------------------- + +const String& SvtPathOptions_Impl::GetPath( SvtPathOptions::Pathes ePath ) +{ + if ( ePath >= SvtPathOptions::PATH_COUNT ) + return m_aEmptyString; + + ::osl::MutexGuard aGuard( m_aMutex ); + + try + { + OUString aPathValue; + String aResult; + sal_Int32 nHandle = m_aMapEnumToPropHandle[ (sal_Int32)ePath ]; + + // Substitution is done by the service itself using the substition service + Any a = m_xPathSettings->getFastPropertyValue( nHandle ); + a >>= aPathValue; + if( ePath == SvtPathOptions::PATH_ADDIN || + ePath == SvtPathOptions::PATH_FILTER || + ePath == SvtPathOptions::PATH_HELP || + ePath == SvtPathOptions::PATH_MODULE || + ePath == SvtPathOptions::PATH_PLUGIN || + ePath == SvtPathOptions::PATH_STORAGE + ) + { + // These office paths have to be converted to system pathes + utl::LocalFileHelper::ConvertURLToPhysicalName( aPathValue, aResult ); + aPathValue = aResult; + } + + m_aPathArray[ ePath ] = aPathValue; + return m_aPathArray[ ePath ]; + } + catch (UnknownPropertyException &) + { + } + + return m_aEmptyString; +} +// ----------------------------------------------------------------------- +BOOL SvtPathOptions_Impl::IsPathReadonly(SvtPathOptions::Pathes ePath)const +{ + ::osl::MutexGuard aGuard( m_aMutex ); + BOOL bReadonly = FALSE; + if ( ePath < SvtPathOptions::PATH_COUNT ) + { + Reference<XPropertySet> xPrSet(m_xPathSettings, UNO_QUERY); + if(xPrSet.is()) + { + Reference<XPropertySetInfo> xInfo = xPrSet->getPropertySetInfo(); + const char* pA = aPropNames[ePath].pPropName; + ::rtl::OUString sU = OUString::createFromAscii(pA); + Property aProperty = xInfo->getPropertyByName(sU); + bReadonly = 0 != (aProperty.Attributes & PropertyAttribute::READONLY); + } + } + return bReadonly; +} +// ----------------------------------------------------------------------- + +void SvtPathOptions_Impl::SetPath( SvtPathOptions::Pathes ePath, const String& rNewPath ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + + if ( ePath < SvtPathOptions::PATH_COUNT ) + { + String aResult; + OUString aNewValue; + Any a; + + switch ( ePath ) + { + case SvtPathOptions::PATH_ADDIN: + case SvtPathOptions::PATH_FILTER: + case SvtPathOptions::PATH_HELP: + case SvtPathOptions::PATH_MODULE: + case SvtPathOptions::PATH_PLUGIN: + case SvtPathOptions::PATH_STORAGE: + { + // These office paths have to be convert back to UCB-URL's + utl::LocalFileHelper::ConvertPhysicalNameToURL( rNewPath, aResult ); + aNewValue = aResult; + } + break; + + default: + aNewValue = rNewPath; + } + + // Resubstitution is done by the service itself using the substition service + a <<= aNewValue; + try + { + m_xPathSettings->setFastPropertyValue( m_aMapEnumToPropHandle[ (sal_Int32)ePath], a ); + } + catch (const Exception&) + { + } + } +} + +// ----------------------------------------------------------------------- + +OUString SvtPathOptions_Impl::SubstituteAndConvert( const rtl::OUString& rPath ) +{ + return SubstVar( rPath ); +} + +//------------------------------------------------------------------------- + +OUString SvtPathOptions_Impl::UsePathVariables( const OUString& rPath ) +{ + return m_xSubstVariables->reSubstituteVariables( rPath ); +} + +// ----------------------------------------------------------------------- + +OUString SvtPathOptions_Impl::SubstVar( const OUString& rVar ) +{ + // 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 occure 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 aReplacement; + OUString aSubString = aWorkText.copy( nPosition, nLength ); + aSubString = aSubString.toAsciiLowerCase(); + + // Look for special variable that needs a system path. + VarNameToEnumMap::const_iterator pIter = m_aMapVarNamesToEnum.find( aSubString ); + if ( pIter != m_aMapVarNamesToEnum.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, sal_False ); + + if ( bConvertLocal ) + { + // Convert the URL to a system path for special path variables + String aReturn; + utl::LocalFileHelper::ConvertURLToPhysicalName( aWorkText, aReturn ); + return aReturn; + } + + return aWorkText; +} + +// ----------------------------------------------------------------------- + +SvtPathOptions_Impl::SvtPathOptions_Impl() : + m_aPathArray( (sal_Int32)SvtPathOptions::PATH_COUNT ) +{ + Reference< XMultiServiceFactory > xSMgr = comphelper::getProcessServiceFactory(); + + // Create necessary services + m_xPathSettings = Reference< XFastPropertySet >( xSMgr->createInstance( + ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( + "com.sun.star.util.PathSettings" ))), + UNO_QUERY ); + if ( !m_xPathSettings.is() ) + { + // #112719#: check for existance + DBG_ERROR( "SvtPathOptions_Impl::SvtPathOptions_Impl(): #112719# happened again!" ); + throw RuntimeException( + ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Service com.sun.star.util.PathSettings cannot be created" )), + Reference< XInterface >() ); + } + + m_xSubstVariables = Reference< XStringSubstitution >( xSMgr->createInstance( + ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( + "com.sun.star.util.PathSubstitution" ))), + UNO_QUERY ); + if ( !m_xSubstVariables.is() ) + { + // #112719#: check for existance + DBG_ERROR( "SvtPathOptions_Impl::SvtPathOptions_Impl(): #112719# happened again!" ); + throw RuntimeException( + ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Service com.sun.star.util.PathSubstitution cannot be created" )), + Reference< XInterface >() ); + } + + // Create temporary hash map to have a mapping between property names and property handles + Reference< XPropertySet > xPropertySet = Reference< XPropertySet >( m_xPathSettings, UNO_QUERY ); + Reference< XPropertySetInfo > xPropSetInfo = xPropertySet->getPropertySetInfo(); + Sequence< Property > aPathPropSeq = xPropSetInfo->getProperties(); + + NameToHandleMap aTempHashMap; + for ( sal_Int32 n = 0; n < aPathPropSeq.getLength(); n++ ) + { + const com::sun::star::beans::Property& aProperty = aPathPropSeq[n]; + aTempHashMap.insert( NameToHandleMap::value_type( aProperty.Name, aProperty.Handle )); + } + + // Create mapping between internal enum (SvtPathOptions::Pathes) and property handle + sal_Int32 nCount = sizeof( aPropNames ) / sizeof( PropertyStruct ); + sal_Int32 i; + for ( i = 0; i < nCount; i++ ) + { + NameToHandleMap::const_iterator pIter = + aTempHashMap.find( rtl::OUString::createFromAscii( aPropNames[i].pPropName )); + + if ( pIter != aTempHashMap.end() ) + { + sal_Int32 nHandle = pIter->second; + sal_Int32 nEnum = aPropNames[i].ePath; + m_aMapEnumToPropHandle.insert( EnumToHandleMap::value_type( nEnum, nHandle )); + } + } + + // Create hash map for path variables that need a system path as a return value! + nCount = sizeof( aVarNameAttribute ) / sizeof( VarNameAttribute ); + for ( i = 0; i < nCount; i++ ) + { + m_aMapVarNamesToEnum.insert( VarNameToEnumMap::value_type( + OUString::createFromAscii( aVarNameAttribute[i].pVarName ), + aVarNameAttribute[i].eVarProperty )); + } + + // Set language type! + Any aLocale = ConfigManager::GetConfigManager().GetDirectConfigProperty( ConfigManager::LOCALE ); + OUString aLocaleStr; + if ( aLocale >>= aLocaleStr ) + { + sal_Int32 nIndex = 0; + m_aLocale.Language = aLocaleStr.getToken(0, '-', nIndex ); + m_aLocale.Country = aLocaleStr.getToken(0, '-', nIndex ); + m_aLocale.Variant = aLocaleStr.getToken(0, '-', nIndex ); + } + else + { + DBG_ERRORFILE( "wrong any type" ); + m_aLocale.Language = OStringToOUString(OString("en"), RTL_TEXTENCODING_UTF8); + m_aLocale.Country = OStringToOUString(OString("US"), RTL_TEXTENCODING_UTF8); + m_aLocale.Variant = OStringToOUString(OString(""), RTL_TEXTENCODING_UTF8); + } +} + +// ----------------------------------------------------------------------- + +// class SvtPathOptions -------------------------------------------------- + +namespace { struct lclMutex : public rtl::Static< ::osl::Mutex, lclMutex > {}; } + +SvtPathOptions::SvtPathOptions() +{ + // Global access, must be guarded (multithreading) + ::osl::MutexGuard aGuard( lclMutex::get() ); + if ( !pOptions ) + { + pOptions = new SvtPathOptions_Impl; + ItemHolder1::holdConfigItem(E_PATHOPTIONS); + } + ++nRefCount; + pImp = pOptions; +} + +// ----------------------------------------------------------------------- + +SvtPathOptions::~SvtPathOptions() +{ + // Global access, must be guarded (multithreading) + ::osl::MutexGuard aGuard( lclMutex::get() ); + if ( !--nRefCount ) + { + DELETEZ( pOptions ); + } +} + +// ----------------------------------------------------------------------- + +const String& SvtPathOptions::GetAddinPath() const +{ + return pImp->GetAddinPath(); +} + +// ----------------------------------------------------------------------- + +const String& SvtPathOptions::GetAutoCorrectPath() const +{ + return pImp->GetAutoCorrectPath(); +} + +// ----------------------------------------------------------------------- + +const String& SvtPathOptions::GetAutoTextPath() const +{ + return pImp->GetAutoTextPath(); +} + +// ----------------------------------------------------------------------- + +const String& SvtPathOptions::GetBackupPath() const +{ + return pImp->GetBackupPath(); +} + +// ----------------------------------------------------------------------- + +const String& SvtPathOptions::GetBasicPath() const +{ + return pImp->GetBasicPath(); +} + +// ----------------------------------------------------------------------- + +const String& SvtPathOptions::GetBitmapPath() const +{ + return pImp->GetBitmapPath(); +} + +// ----------------------------------------------------------------------- + +const String& SvtPathOptions::GetConfigPath() const +{ + return pImp->GetConfigPath(); +} + +// ----------------------------------------------------------------------- + +const String& SvtPathOptions::GetDictionaryPath() const +{ + return pImp->GetDictionaryPath(); +} + +// ----------------------------------------------------------------------- + +const String& SvtPathOptions::GetFavoritesPath() const +{ + return pImp->GetFavoritesPath(); +} + +// ----------------------------------------------------------------------- + +const String& SvtPathOptions::GetFilterPath() const +{ + return pImp->GetFilterPath(); +} + +// ----------------------------------------------------------------------- + +const String& SvtPathOptions::GetGalleryPath() const +{ + return pImp->GetGalleryPath(); +} + +// ----------------------------------------------------------------------- + +const String& SvtPathOptions::GetGraphicPath() const +{ + return pImp->GetGraphicPath(); +} + +// ----------------------------------------------------------------------- + +const String& SvtPathOptions::GetHelpPath() const +{ + return pImp->GetHelpPath(); +} + +// ----------------------------------------------------------------------- + +const String& SvtPathOptions::GetLinguisticPath() const +{ + return pImp->GetLinguisticPath(); +} + +// ----------------------------------------------------------------------- + +const String& SvtPathOptions::GetFingerprintPath() const +{ + return pImp->GetFingerprintPath(); +} + +// ----------------------------------------------------------------------- + +const String& SvtPathOptions::GetModulePath() const +{ + return pImp->GetModulePath(); +} + +// ----------------------------------------------------------------------- + +const String& SvtPathOptions::GetPalettePath() const +{ + return pImp->GetPalettePath(); +} + +// ----------------------------------------------------------------------- + +const String& SvtPathOptions::GetPluginPath() const +{ + return pImp->GetPluginPath(); +} + +// ----------------------------------------------------------------------- + +const String& SvtPathOptions::GetStoragePath() const +{ + return pImp->GetStoragePath(); +} + +// ----------------------------------------------------------------------- + +const String& SvtPathOptions::GetTempPath() const +{ + return pImp->GetTempPath(); +} + +// ----------------------------------------------------------------------- + +const String& SvtPathOptions::GetTemplatePath() const +{ + return pImp->GetTemplatePath(); +} + +// ----------------------------------------------------------------------- + +const String& SvtPathOptions::GetUserConfigPath() const +{ + return pImp->GetUserConfigPath(); +} + +const String& SvtPathOptions::GetUIConfigPath() const +{ + return pImp->GetUIConfigPath(); +} + +// ----------------------------------------------------------------------- + +const String& SvtPathOptions::GetWorkPath() const +{ + return pImp->GetWorkPath(); +} + +// ----------------------------------------------------------------------- + +void SvtPathOptions::SetAddinPath( const String& rPath ) +{ + pImp->SetAddinPath( rPath ); +} + +// ----------------------------------------------------------------------- + +void SvtPathOptions::SetAutoCorrectPath( const String& rPath ) +{ + pImp->SetAutoCorrectPath( rPath ); +} + +// ----------------------------------------------------------------------- + +void SvtPathOptions::SetAutoTextPath( const String& rPath ) +{ + pImp->SetAutoTextPath( rPath ); +} + +// ----------------------------------------------------------------------- + +void SvtPathOptions::SetBackupPath( const String& rPath ) +{ + pImp->SetBackupPath( rPath ); +} + +// ----------------------------------------------------------------------- + +void SvtPathOptions::SetBasicPath( const String& rPath ) +{ + pImp->SetBasicPath( rPath ); +} + +// ----------------------------------------------------------------------- + +void SvtPathOptions::SetBitmapPath( const String& rPath ) +{ + pImp->SetBitmapPath( rPath ); +} + +// ----------------------------------------------------------------------- + +void SvtPathOptions::SetConfigPath( const String& rPath ) +{ + pImp->SetConfigPath( rPath ); +} + +// ----------------------------------------------------------------------- + +void SvtPathOptions::SetDictionaryPath( const String& rPath ) +{ + pImp->SetDictionaryPath( rPath ); +} + +// ----------------------------------------------------------------------- + +void SvtPathOptions::SetFavoritesPath( const String& rPath ) +{ + pImp->SetFavoritesPath( rPath ); +} + +// ----------------------------------------------------------------------- + +void SvtPathOptions::SetFilterPath( const String& rPath ) +{ + pImp->SetFilterPath( rPath ); +} + +// ----------------------------------------------------------------------- + +void SvtPathOptions::SetGalleryPath( const String& rPath ) +{ + pImp->SetGalleryPath( rPath ); +} + +// ----------------------------------------------------------------------- + +void SvtPathOptions::SetGraphicPath( const String& rPath ) +{ + pImp->SetGraphicPath( rPath ); +} + +// ----------------------------------------------------------------------- + +void SvtPathOptions::SetHelpPath( const String& rPath ) +{ + pImp->SetHelpPath( rPath ); +} + +// ----------------------------------------------------------------------- + +void SvtPathOptions::SetLinguisticPath( const String& rPath ) +{ + pImp->SetLinguisticPath( rPath ); +} + +// ----------------------------------------------------------------------- + +void SvtPathOptions::SetModulePath( const String& rPath ) +{ + pImp->SetModulePath( rPath ); +} + +// ----------------------------------------------------------------------- + +void SvtPathOptions::SetPalettePath( const String& rPath ) +{ + pImp->SetPalettePath( rPath ); +} + +// ----------------------------------------------------------------------- + +void SvtPathOptions::SetPluginPath( const String& rPath ) +{ + pImp->SetPluginPath( rPath ); +} + +// ----------------------------------------------------------------------- + +void SvtPathOptions::SetStoragePath( const String& rPath ) +{ + pImp->SetStoragePath( rPath ); +} + +// ----------------------------------------------------------------------- + +void SvtPathOptions::SetTempPath( const String& rPath ) +{ + pImp->SetTempPath( rPath ); +} + +// ----------------------------------------------------------------------- + +void SvtPathOptions::SetTemplatePath( const String& rPath ) +{ + pImp->SetTemplatePath( rPath ); +} + +// ----------------------------------------------------------------------- + +void SvtPathOptions::SetUserConfigPath( const String& rPath ) +{ + pImp->SetUserConfigPath( rPath ); +} + +// ----------------------------------------------------------------------- + +void SvtPathOptions::SetWorkPath( const String& rPath ) +{ + pImp->SetWorkPath( rPath ); +} + +// ----------------------------------------------------------------------- + +String SvtPathOptions::SubstituteVariable( const String& rVar ) +{ + String aRet = pImp->SubstituteAndConvert( rVar ); + return aRet; +} + +String SvtPathOptions::UseVariable( const String& rPath ) +{ + String aRet = pImp->UsePathVariables( rPath ); + return aRet; +} + +// ----------------------------------------------------------------------- + +sal_Bool SvtPathOptions::SearchFile( String& rIniFile, Pathes ePath ) +{ + // check parameter: empty inifile name? + if ( !rIniFile.Len() ) + { + DBG_ERRORFILE( "SvtPathOptions::SearchFile(): invalid parameter" ); + return sal_False; + } + + String aIniFile = pImp->SubstVar( rIniFile ); + sal_Bool bRet = sal_False; + + switch ( ePath ) + { + case PATH_USERCONFIG: + { + // path is a URL + bRet = sal_True; + INetURLObject aObj( GetUserConfigPath() ); + xub_StrLen i, nCount = aIniFile.GetTokenCount( '/' ); + for ( i = 0; i < nCount; ++i ) + aObj.insertName( aIniFile.GetToken( i, '/' ) ); + + if ( !::utl::UCBContentHelper::Exists( aObj.GetMainURL( INetURLObject::NO_DECODE ) ) ) + { + aObj.SetSmartURL( GetConfigPath() ); + aObj.insertName( aIniFile ); + bRet = ::utl::UCBContentHelper::Exists( aObj.GetMainURL( INetURLObject::NO_DECODE ) ); + } + + if ( bRet ) + rIniFile = aObj.GetMainURL( INetURLObject::NO_DECODE ); + + break; + } + + default: + { + String aPath; + switch ( ePath ) + { + case PATH_ADDIN: aPath = GetAddinPath(); break; + case PATH_AUTOCORRECT: aPath = GetAutoCorrectPath(); break; + case PATH_AUTOTEXT: aPath = GetAutoTextPath(); break; + case PATH_BACKUP: aPath = GetBackupPath(); break; + case PATH_BASIC: aPath = GetBasicPath(); break; + case PATH_BITMAP: aPath = GetBitmapPath(); break; + case PATH_CONFIG: aPath = GetConfigPath(); break; + case PATH_DICTIONARY: aPath = GetDictionaryPath(); break; + case PATH_FAVORITES: aPath = GetFavoritesPath(); break; + case PATH_FILTER: aPath = GetFilterPath(); break; + case PATH_GALLERY: aPath = GetGalleryPath(); break; + case PATH_GRAPHIC: aPath = GetGraphicPath(); break; + case PATH_HELP: aPath = GetHelpPath(); break; + case PATH_LINGUISTIC: aPath = GetLinguisticPath(); break; + case PATH_MODULE: aPath = GetModulePath(); break; + case PATH_PALETTE: aPath = GetPalettePath(); break; + case PATH_PLUGIN: aPath = GetPluginPath(); break; + case PATH_STORAGE: aPath = GetStoragePath(); break; + case PATH_TEMP: aPath = GetTempPath(); break; + case PATH_TEMPLATE: aPath = GetTemplatePath(); break; + case PATH_WORK: aPath = GetWorkPath(); break; + case PATH_UICONFIG: aPath = GetUIConfigPath(); break; + case PATH_FINGERPRINT: aPath = GetFingerprintPath(); break; + case PATH_USERCONFIG:/*-Wall???*/ break; + case PATH_COUNT: /*-Wall???*/ break; + } + + sal_uInt16 j, nIdx = 0, nTokenCount = aPath.GetTokenCount( SEARCHPATH_DELIMITER ); + for ( j = 0; j < nTokenCount; ++j ) + { + BOOL bIsURL = TRUE; + String aPathToken = aPath.GetToken( 0, SEARCHPATH_DELIMITER, nIdx ); + INetURLObject aObj( aPathToken ); + if ( aObj.HasError() ) + { + bIsURL = FALSE; + String aURL; + if ( LocalFileHelper::ConvertPhysicalNameToURL( aPathToken, aURL ) ) + aObj.SetURL( aURL ); + } + + xub_StrLen i, nCount = aIniFile.GetTokenCount( '/' ); + for ( i = 0; i < nCount; ++i ) + aObj.insertName( aIniFile.GetToken( i, '/' ) ); + bRet = ::utl::UCBContentHelper::Exists( aObj.GetMainURL( INetURLObject::NO_DECODE ) ); + + if ( bRet ) + { + if ( !bIsURL ) + ::utl::LocalFileHelper::ConvertURLToPhysicalName( + aObj.GetMainURL( INetURLObject::NO_DECODE ), rIniFile ); + else + rIniFile = aObj.GetMainURL( INetURLObject::NO_DECODE ); + break; + } + } + } + } + + return bRet; +} + +// ----------------------------------------------------------------------- + +::com::sun::star::lang::Locale SvtPathOptions::GetLocale() const +{ + return pImp->GetLocale(); +} +// ----------------------------------------------------------------------- +BOOL SvtPathOptions::IsPathReadonly(Pathes ePath)const +{ + return pImp->IsPathReadonly(ePath); +} +// ----------------------------------------------------------------------- +const String& SvtPathOptions::GetPath(Pathes ePath)const +{ + return pImp->GetPath(ePath); +} +// ----------------------------------------------------------------------- +void SvtPathOptions::SetPath( SvtPathOptions::Pathes ePath, const String& rNewPath ) +{ + pImp->SetPath(ePath, rNewPath); +} + +// class PathService ----------------------------------------------------- +#include <com/sun/star/frame/XConfigManager.hpp> +#include <com/sun/star/lang/XServiceInfo.hpp> +#include <cppuhelper/implbase2.hxx> + +class PathService : public ::cppu::WeakImplHelper2< ::com::sun::star::frame::XConfigManager, ::com::sun::star::lang::XServiceInfo > +{ + virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw(::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL + getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException); + virtual ::rtl::OUString SAL_CALL substituteVariables( const ::rtl::OUString& sText ) throw(::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& sKeyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& xListener ) throw(::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& sKeyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& xListener ) throw(::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL flush( ) throw(::com::sun::star::uno::RuntimeException); +}; + +// class PathService ----------------------------------------------------- + +void SAL_CALL PathService::addPropertyChangeListener( const ::rtl::OUString&, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& ) throw(::com::sun::star::uno::RuntimeException) {} +void SAL_CALL PathService::removePropertyChangeListener( const ::rtl::OUString&, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& ) throw(::com::sun::star::uno::RuntimeException) {} +void SAL_CALL PathService::flush( ) throw(::com::sun::star::uno::RuntimeException) {} + +::rtl::OUString SAL_CALL PathService::substituteVariables( const ::rtl::OUString& sText ) throw(::com::sun::star::uno::RuntimeException) +{ + return SvtPathOptions().SubstituteVariable( sText ); +} + +::rtl::OUString SAL_CALL PathService::getImplementationName( ) throw(::com::sun::star::uno::RuntimeException) +{ + return OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.unotools.PathService")); +} + +sal_Bool SAL_CALL PathService::supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException) +{ + if ( ServiceName.compareToAscii("com.sun.star.config.SpecialConfigManager") == COMPARE_EQUAL ) + return sal_True; + else + return sal_False; +} + +::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL PathService::getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException) +{ + Sequence< OUString > aRet(1); + *aRet.getArray() = OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.config.SpecialConfigManager")); + return aRet; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/printwarningoptions.cxx b/unotools/source/config/printwarningoptions.cxx new file mode 100644 index 000000000000..6f867c6b669c --- /dev/null +++ b/unotools/source/config/printwarningoptions.cxx @@ -0,0 +1,418 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" + +#include <unotools/printwarningoptions.hxx> +#include <unotools/configmgr.hxx> +#include <unotools/configitem.hxx> +#include <tools/debug.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> + +#include <itemholder1.hxx> + +//_________________________________________________________________________________________________________________ +// namespaces +//_________________________________________________________________________________________________________________ + +using namespace ::utl ; +using namespace ::rtl ; +using namespace ::osl ; +using namespace ::com::sun::star::uno ; + +//_________________________________________________________________________________________________________________ +// const +//_________________________________________________________________________________________________________________ + +#define ROOTNODE_START OUString(RTL_CONSTASCII_USTRINGPARAM("Office.Common/Print")) + +#define PROPERTYNAME_PAPERSIZE OUString(RTL_CONSTASCII_USTRINGPARAM("Warning/PaperSize")) +#define PROPERTYNAME_PAPERORIENTATION OUString(RTL_CONSTASCII_USTRINGPARAM("Warning/PaperOrientation")) +#define PROPERTYNAME_NOTFOUND OUString(RTL_CONSTASCII_USTRINGPARAM("Warning/NotFound")) +#define PROPERTYNAME_TRANSPARENCY OUString(RTL_CONSTASCII_USTRINGPARAM("Warning/Transparency")) +#define PROPERTYNAME_PRINTINGMODIFIESDOCUMENT OUString(RTL_CONSTASCII_USTRINGPARAM("PrintingModifiesDocument")) + +#define PROPERTYHANDLE_PAPERSIZE 0 +#define PROPERTYHANDLE_PAPERORIENTATION 1 +#define PROPERTYHANDLE_NOTFOUND 2 +#define PROPERTYHANDLE_TRANSPARENCY 3 +#define PROPERTYHDL_PRINTINGMODIFIESDOCUMENT 4 + +#define PROPERTYCOUNT 5 + +class SvtPrintWarningOptions_Impl : public ConfigItem +{ +public: + +//--------------------------------------------------------------------------------------------------------- +// constructor / destructor +//--------------------------------------------------------------------------------------------------------- + + SvtPrintWarningOptions_Impl(); + ~SvtPrintWarningOptions_Impl(); + +//--------------------------------------------------------------------------------------------------------- +// overloaded methods of baseclass +//--------------------------------------------------------------------------------------------------------- + + virtual void Commit(); + virtual void Notify( const com::sun::star::uno::Sequence< rtl::OUString >& aPropertyNames ); + +//--------------------------------------------------------------------------------------------------------- +// public interface +//--------------------------------------------------------------------------------------------------------- + + sal_Bool IsPaperSize() const { return m_bPaperSize; } + sal_Bool IsPaperOrientation() const { return m_bPaperOrientation; } + sal_Bool IsNotFound() const { return m_bNotFound; } + sal_Bool IsTransparency() const { return m_bTransparency; } + sal_Bool IsModifyDocumentOnPrintingAllowed() const { return m_bModifyDocumentOnPrintingAllowed; } + + void SetPaperSize( sal_Bool bState ) { m_bPaperSize = bState; SetModified(); } + void SetPaperOrientation( sal_Bool bState ) { m_bPaperOrientation = bState; SetModified(); } + void SetNotFound( sal_Bool bState ) { m_bNotFound = bState; SetModified(); } + void SetTransparency( sal_Bool bState ) { m_bTransparency = bState; SetModified(); } + void SetModifyDocumentOnPrintingAllowed( sal_Bool bState ) { m_bModifyDocumentOnPrintingAllowed = bState; SetModified(); } + +//------------------------------------------------------------------------------------------------------------- +// private methods +//------------------------------------------------------------------------------------------------------------- + +private: + + static Sequence< OUString > impl_GetPropertyNames(); + +//------------------------------------------------------------------------------------------------------------- +// private member +//------------------------------------------------------------------------------------------------------------- + +private: + + sal_Bool m_bPaperSize; + sal_Bool m_bPaperOrientation; + sal_Bool m_bNotFound; + sal_Bool m_bTransparency; + sal_Bool m_bModifyDocumentOnPrintingAllowed; +}; + +//_________________________________________________________________________________________________________________ +// definitions +//_________________________________________________________________________________________________________________ + +//***************************************************************************************************************** +// constructor +//***************************************************************************************************************** +SvtPrintWarningOptions_Impl::SvtPrintWarningOptions_Impl() : + ConfigItem( ROOTNODE_START ), + m_bPaperSize( sal_False ), + m_bPaperOrientation( sal_False ), + m_bNotFound( sal_False ), + m_bTransparency( sal_True ), + m_bModifyDocumentOnPrintingAllowed( sal_True ) +{ + Sequence< OUString > seqNames( impl_GetPropertyNames() ); + Sequence< Any > seqValues( GetProperties( seqNames ) ); + + DBG_ASSERT( !(seqNames.getLength()!=seqValues.getLength()), "SvtPrintWarningOptions_Impl::SvtPrintWarningOptions_Impl()\nI miss some values of configuration keys!\n" ); + + // Copy values from list in right order to our internal member. + sal_Int32 nPropertyCount = seqValues.getLength(); + sal_Int32 nProperty = 0; + + for( nProperty=0; nProperty<nPropertyCount; ++nProperty ) + { + DBG_ASSERT( !(seqValues[nProperty].hasValue()==sal_False), "SvtPrintWarningOptions_Impl::SvtPrintWarningOptions_Impl()\nInvalid property value for property detected!\n" ); + + switch( nProperty ) + { + case PROPERTYHANDLE_PAPERSIZE: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "Invalid type" ); + seqValues[nProperty] >>= m_bPaperSize; + } + break; + + case PROPERTYHANDLE_PAPERORIENTATION: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "Invalid type" ); + seqValues[nProperty] >>= m_bPaperOrientation; + } + break; + + case PROPERTYHANDLE_NOTFOUND: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "Invalid type" ); + seqValues[nProperty] >>= m_bNotFound; + } + break; + + case PROPERTYHANDLE_TRANSPARENCY: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "Invalid type" ); + seqValues[nProperty] >>= m_bTransparency; + } + break; + case PROPERTYHDL_PRINTINGMODIFIESDOCUMENT: + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "Invalid type" ); + seqValues[nProperty] >>= m_bModifyDocumentOnPrintingAllowed; + } + break; + + } + } +} + +//***************************************************************************************************************** +// destructor +//***************************************************************************************************************** +SvtPrintWarningOptions_Impl::~SvtPrintWarningOptions_Impl() +{ + if( IsModified() ) + Commit(); +} + +//***************************************************************************************************************** +// Commit +//***************************************************************************************************************** +void SvtPrintWarningOptions_Impl::Commit() +{ + Sequence< OUString > aSeqNames( impl_GetPropertyNames() ); + Sequence< Any > aSeqValues( aSeqNames.getLength() ); + + for( sal_Int32 nProperty = 0, nCount = aSeqNames.getLength(); nProperty < nCount; ++nProperty ) + { + switch( nProperty ) + { + case PROPERTYHANDLE_PAPERSIZE: + aSeqValues[nProperty] <<= m_bPaperSize; + break; + + case PROPERTYHANDLE_PAPERORIENTATION: + aSeqValues[nProperty] <<= m_bPaperOrientation; + break; + + case PROPERTYHANDLE_NOTFOUND: + aSeqValues[nProperty] <<= m_bNotFound; + break; + + case PROPERTYHANDLE_TRANSPARENCY: + aSeqValues[nProperty] <<= m_bTransparency; + break; + case PROPERTYHDL_PRINTINGMODIFIESDOCUMENT: + aSeqValues[nProperty] <<= m_bModifyDocumentOnPrintingAllowed; + break; + } + } + + PutProperties( aSeqNames, aSeqValues ); +} + +void SvtPrintWarningOptions_Impl::Notify( const Sequence< rtl::OUString >& ) +{ +} + +//***************************************************************************************************************** +// private method +//***************************************************************************************************************** +Sequence< OUString > SvtPrintWarningOptions_Impl::impl_GetPropertyNames() +{ + // Build static list of configuration key names. + static const OUString pProperties[] = + { + PROPERTYNAME_PAPERSIZE, + PROPERTYNAME_PAPERORIENTATION, + PROPERTYNAME_NOTFOUND, + PROPERTYNAME_TRANSPARENCY, + PROPERTYNAME_PRINTINGMODIFIESDOCUMENT + }; + + // Initialize return sequence with these list ... + static const Sequence< OUString > seqPropertyNames( pProperties, PROPERTYCOUNT ); + + return seqPropertyNames; +} + +//***************************************************************************************************************** +// initialize static member +// DON'T DO IT IN YOUR HEADER! +// see definition for further informations +//***************************************************************************************************************** +SvtPrintWarningOptions_Impl* SvtPrintWarningOptions::m_pDataContainer = NULL; +sal_Int32 SvtPrintWarningOptions::m_nRefCount = 0; + +//***************************************************************************************************************** +// constructor +//***************************************************************************************************************** +SvtPrintWarningOptions::SvtPrintWarningOptions() +{ + // Global access, must be guarded (multithreading!). + MutexGuard aGuard( GetOwnStaticMutex() ); + // Increase ouer refcount ... + ++m_nRefCount; + // ... and initialize ouer data container only if it not already! + if( m_pDataContainer == NULL ) + { + m_pDataContainer = new SvtPrintWarningOptions_Impl(); + ItemHolder1::holdConfigItem(E_PRINTWARNINGOPTIONS); + } +} + +//***************************************************************************************************************** +// destructor +//***************************************************************************************************************** +SvtPrintWarningOptions::~SvtPrintWarningOptions() +{ + // Global access, must be guarded (multithreading!) + MutexGuard aGuard( GetOwnStaticMutex() ); + // Decrease ouer refcount. + --m_nRefCount; + // If last instance was deleted ... + // we must destroy ouer static data container! + if( m_nRefCount <= 0 ) + { + delete m_pDataContainer; + m_pDataContainer = NULL; + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Bool SvtPrintWarningOptions::IsPaperSize() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsPaperSize(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Bool SvtPrintWarningOptions::IsPaperOrientation() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsPaperOrientation(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Bool SvtPrintWarningOptions::IsNotFound() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsNotFound(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Bool SvtPrintWarningOptions::IsTransparency() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsTransparency(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtPrintWarningOptions::SetPaperSize( sal_Bool bState ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetPaperSize( bState ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtPrintWarningOptions::SetPaperOrientation( sal_Bool bState ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetPaperOrientation( bState ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtPrintWarningOptions::SetNotFound( sal_Bool bState ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetNotFound( bState ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtPrintWarningOptions::SetTransparency( sal_Bool bState ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetTransparency( bState ); +} +// ----------------------------------------------------------------------------- + +sal_Bool SvtPrintWarningOptions::IsModifyDocumentOnPrintingAllowed() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsModifyDocumentOnPrintingAllowed(); +} + +// ----------------------------------------------------------------------------- + +void SvtPrintWarningOptions::SetModifyDocumentOnPrintingAllowed( sal_Bool bState ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetModifyDocumentOnPrintingAllowed( bState ) ; +} + +//***************************************************************************************************************** +// private method +//***************************************************************************************************************** +Mutex& SvtPrintWarningOptions::GetOwnStaticMutex() +{ + // Initialize static mutex only for one time! + static Mutex* pMutex = NULL; + // If these method first called (Mutex not already exist!) ... + if( pMutex == NULL ) + { + // ... we must create a new one. Protect follow code with the global mutex - + // It must be - we create a static variable! + MutexGuard aGuard( Mutex::getGlobalMutex() ); + // We must check our pointer again - because it can be that another instance of ouer class will be fastr then these! + if( pMutex == NULL ) + { + // Create the new mutex and set it for return on static variable. + static Mutex aMutex; + pMutex = &aMutex; + } + } + // Return new created or already existing mutex object. + return *pMutex; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/regoptions.cxx b/unotools/source/config/regoptions.cxx new file mode 100644 index 000000000000..aad9dc205c3a --- /dev/null +++ b/unotools/source/config/regoptions.cxx @@ -0,0 +1,552 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" +#include <unotools/regoptions.hxx> +#include <unotools/confignode.hxx> +#include <tools/date.hxx> +#include <comphelper/processfactory.hxx> +#include <osl/mutex.hxx> +#include <unotools/bootstrap.hxx> +#include <rtl/ustring.hxx> + +//........................................................................ +namespace utl +{ +//........................................................................ + + using namespace ::com::sun::star::uno; + + //==================================================================== + //= local helpers + //==================================================================== + //-------------------------------------------------------------------- + /** converts a string representation of a date into a integer representation + <p>No semantic check is made, i.e. if the string describes the 40.12, this is not recognized. In opposite, + the string must have a valid structure (DD.MM.YYYY).</p> + @return + the integer representation of the date which can be used with the Date class, + or 0 if the given string was no valid date representation + */ + static sal_Int32 lcl_convertString2Date( const ::rtl::OUString& _rStringRep ) + { + sal_Int32 nDateIntRep = 0; + if ( _rStringRep.getLength() == 2 + 1 + 2 + 1 + 4 ) // DD.MM.YYYY + { + // validate the string + sal_Bool bValid = sal_True; + + const sal_Unicode* pStringRep = _rStringRep.getStr(); + sal_Int32 nLen = _rStringRep.getLength(); + for ( sal_Int32 nPos = 0; + bValid && ( nPos < nLen ); + ++nPos, ++pStringRep + ) + { + if ( ( 2 == nPos ) || ( 5 == nPos ) ) + bValid = '.' == *pStringRep; // the number separators + else + bValid = ( *pStringRep >= '0' ) && ( *pStringRep <= '9' ); + } + + // passed the test? + if ( bValid ) + { + Date aDate; + aDate.SetDay ( (USHORT)_rStringRep.copy( 0, 2 ).toInt32( ) ); + aDate.SetMonth ( (USHORT)_rStringRep.copy( 3, 2 ).toInt32( ) ); + aDate.SetYear ( (USHORT)_rStringRep.copy( 6, 4 ).toInt32( ) ); + nDateIntRep = aDate.GetDate(); + } + } + + return nDateIntRep; + } + + //-------------------------------------------------------------------- + static const ::rtl::OUString& lcl_fillToken( const sal_Int32 /* [in] */ _nToken, const sal_Int16 /* [in] */ _nDigits, ::rtl::OUString& /* [out] */ _rToken ) + { + // convert into string + ::rtl::OUString sLeanToken = ::rtl::OUString::valueOf( _nToken ); + // check length + if ( sLeanToken.getLength() < _nDigits ) + { // fill + OSL_ENSURE( _nDigits <= 4, "lcl_fillToken: invalid digit number!" ); + _rToken = ::rtl::OUString( "0000", _nDigits - sLeanToken.getLength(), RTL_TEXTENCODING_ASCII_US ); + _rToken += sLeanToken; + } + else + _rToken = sLeanToken; + + return _rToken; + } + + //-------------------------------------------------------------------- + /** converts a integer representation of a date into a string representation + */ + static ::rtl::OUString lcl_ConvertDate2String( const Date& _rDate ) + { + OSL_ENSURE( _rDate.IsValid(), "lcl_ConvertDate2String: invalid integer representation!" ); + + sal_Unicode cSeparator( '.' ); + ::rtl::OUString sSeparator( &cSeparator, 1 ); + + ::rtl::OUString sStringRep; + ::rtl::OUString sToken; + sStringRep += lcl_fillToken( (sal_Int32)_rDate.GetDay(), 2, sToken ); + sStringRep += sSeparator; + sStringRep += lcl_fillToken( (sal_Int32)_rDate.GetMonth(), 2, sToken ); + sStringRep += sSeparator; + sStringRep += lcl_fillToken( (sal_Int32)_rDate.GetYear(), 4, sToken ); + + return sStringRep; + } + + //-------------------------------------------------------------------- + /// checks whether a given trigger date is reached (i.e. is _before_ the current date) + static sal_Bool lcl_reachedTriggerDate( const Date& _rTriggerDate ) + { + return _rTriggerDate <= Date(); + } + + //-------------------------------------------------------------------- + #define DECLARE_STATIC_LAZY_USTRING( name ) \ + static const ::rtl::OUString& lcl_get##name##Name() \ + { \ + static const ::rtl::OUString sName = ::rtl::OUString::createFromAscii( #name ); \ + return sName; \ + } + + DECLARE_STATIC_LAZY_USTRING( ReminderDate ); + DECLARE_STATIC_LAZY_USTRING( RequestDialog ); + DECLARE_STATIC_LAZY_USTRING( ShowMenuItem ); + DECLARE_STATIC_LAZY_USTRING( Patch ); + + //==================================================================== + //= RegOptionsImpl + //==================================================================== + class RegOptionsImpl + { + private: + OConfigurationTreeRoot m_aRegistrationNode; // the configuration node we need to access our persistent data + + String m_sRegistrationURL; // the URL to use when doing an online registration + Date m_aReminderDate; // the reminder date as found in the configuration + sal_Int32 m_nDialogCounter; // the dialog counter - see getDialogPermission + sal_Bool m_bShowMenuItem; // the flag indicating if the registration menu item is allowed + + static RegOptionsImpl* s_pSingleInstance; // the one and only instance of this class + static sal_Int32 s_nInstanceCount; // reference counter for the instances + static sal_Bool s_bThisSessionDone; // the flag indicating if for this session, everything beeing relevant has already been done + + private: + RegOptionsImpl( ); + + static ::osl::Mutex& getStaticMutex(); // get the mutex used to protect the static members of this class + + void commit( ); + sal_Int32 getBuildId() const; + + private: + RegOptions::DialogPermission implGetDialogPermission( ) const; + + public: + static RegOptionsImpl* registerClient( ); + static void revokeClient( ); + + inline sal_Bool hasURL( ) const { return ( 0 != m_sRegistrationURL.Len() ); } + inline sal_Bool allowMenu( ) const { return hasURL() && m_bShowMenuItem; } + inline String getRegistrationURL( ) const { return m_sRegistrationURL; } + + RegOptions::DialogPermission getDialogPermission( ) const; + void markSessionDone( ); + void activateReminder( sal_Int32 _nDaysFromNow ); + void removeReminder(); + bool hasReminderDateCome() const; + }; + + //-------------------------------------------------------------------- + RegOptionsImpl* RegOptionsImpl::s_pSingleInstance = NULL; + sal_Bool RegOptionsImpl::s_bThisSessionDone = sal_False; + sal_Int32 RegOptionsImpl::s_nInstanceCount = 0; + + //-------------------------------------------------------------------- + ::osl::Mutex& RegOptionsImpl::getStaticMutex() + { + static ::osl::Mutex* s_pStaticMutex = NULL; + if ( !s_pStaticMutex ) + { + ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); + if ( !s_pStaticMutex ) + { + static ::osl::Mutex s_aStaticMutex; + s_pStaticMutex = &s_aStaticMutex; + } + } + return *s_pStaticMutex; + } + + //-------------------------------------------------------------------- + void RegOptionsImpl::commit( ) + { + m_aRegistrationNode.commit( ); + } + + //-------------------------------------------------------------------- + RegOptionsImpl* RegOptionsImpl::registerClient( ) + { + ::osl::MutexGuard aGuard( getStaticMutex() ); + + if ( !s_pSingleInstance ) + s_pSingleInstance = new RegOptionsImpl; + + ++s_nInstanceCount; + return s_pSingleInstance; + } + + //-------------------------------------------------------------------- + void RegOptionsImpl::revokeClient( ) + { + ::osl::MutexGuard aGuard( getStaticMutex() ); + OSL_ENSURE( s_nInstanceCount, "RegOptionsImpl::revokeClient: there are no clients alive!" ); + OSL_ENSURE( s_pSingleInstance || !s_nInstanceCount, "RegOptionsImpl::revokeClient: invalid instance pointer!" ); + + if ( s_nInstanceCount ) + { + if ( s_pSingleInstance ) + // commit the changes done by this client + s_pSingleInstance->commit(); + + if ( 0 == --s_nInstanceCount ) + { + delete s_pSingleInstance; + s_pSingleInstance = NULL; + } + } + } + + //-------------------------------------------------------------------- + RegOptionsImpl::RegOptionsImpl( ) + :m_nDialogCounter ( 0 ) + ,m_bShowMenuItem ( sal_False ) + { + // create the config node for all our registration information + m_aRegistrationNode = OConfigurationTreeRoot::createWithServiceFactory( + ::comphelper::getProcessServiceFactory(), + ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/org.openoffice.Office.Common/Help/Registration")) + ); + + // cache some data + //the URL to use for online registration + ::rtl::OUString sStringValue; + m_aRegistrationNode.getNodeValue( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("URL")) ) >>= sStringValue; + m_sRegistrationURL = sStringValue; + + // the state of the dialog + m_aRegistrationNode.getNodeValue( lcl_getRequestDialogName() ) >>= m_nDialogCounter; + + // the flag for showing the menu item + sal_Bool bBoolValue = sal_False; + m_aRegistrationNode.getNodeValue( lcl_getShowMenuItemName() ) >>= bBoolValue; + m_bShowMenuItem = bBoolValue; + + // the reminder date (if any) + sal_Int32 nIntDate = 0; + sStringValue = ::rtl::OUString(); + m_aRegistrationNode.getNodeValue( lcl_getReminderDateName() ) >>= sStringValue; + bool bIsPatchDate = ( sStringValue.equals( lcl_getPatchName() ) != sal_False ); + if ( !bIsPatchDate && sStringValue.getLength() ) + nIntDate = lcl_convertString2Date( sStringValue ); + m_aReminderDate.SetDate( nIntDate ); + } + + //-------------------------------------------------------------------- + RegOptions::DialogPermission RegOptionsImpl::implGetDialogPermission( ) const + { + RegOptions::DialogPermission eResult = RegOptions::dpDisabled; + // no URL or a counter already decreased to zero means the dialog is disabled + if ( hasURL() && ( m_nDialogCounter > 0 ) ) + { + // during every session, the counter will be decreased + // If it reaches zero, the dialog shall be executed + if ( 1 == m_nDialogCounter ) + { + if ( m_aReminderDate.IsValid( ) ) + { // valid reminder date + // assume remind later + eResult = RegOptions::dpRemindLater; + // and check if we reached the reminder date + if ( lcl_reachedTriggerDate( m_aReminderDate ) ) + eResult = RegOptions::dpThisSession; + } + else + eResult = RegOptions::dpThisSession; // execute in this session + } + else + eResult = RegOptions::dpNotThisSession; // first trigger session not reached + + // a last check .... + if ( ( s_bThisSessionDone ) // this session is already marked as "done" + && ( RegOptions::dpThisSession == eResult )// but without this, the state would be "now" + ) + eResult = RegOptions::dpDisabled; // -> change state to "disabled" + } + + return eResult; + } + + //-------------------------------------------------------------------- + RegOptions::DialogPermission RegOptionsImpl::getDialogPermission( ) const + { + OSL_ENSURE( !s_bThisSessionDone, "RegOptionsImpl::getDialogPermission: should never be asked in this session, again!" ); + // Somebody already marked this session as "everything relevant happened". So why sombody (else?) asks + // me again? + + return implGetDialogPermission( ); + } + + //-------------------------------------------------------------------- + void RegOptionsImpl::activateReminder( sal_Int32 _nDaysFromNow ) + { + OSL_ENSURE( s_bThisSessionDone || ( implGetDialogPermission( ) != RegOptions::dpDisabled ), "RegOptionsImpl::activateReminder: invalid call!" ); + OSL_ENSURE( _nDaysFromNow > 0, "RegOptionsImpl::activateReminder: invalid argument!" ); + + // calc the reminder + m_aReminderDate = Date() + _nDaysFromNow; // today (default ctor) + days + + // remember the date + m_aRegistrationNode.setNodeValue( + lcl_getReminderDateName(), + makeAny( lcl_ConvertDate2String( m_aReminderDate ) ) + ); + // to be on the save side, write the counter + m_aRegistrationNode.setNodeValue( + lcl_getRequestDialogName(), + makeAny( (sal_Int32)1 ) + ); + + // mark this session as done + if ( !s_bThisSessionDone ) + markSessionDone( ); + } + + //-------------------------------------------------------------------- + void RegOptionsImpl::removeReminder() + { + ::rtl::OUString aDefault; + ::rtl::OUString aReminderValue( lcl_getPatchName() ); + aReminderValue += ::rtl::OUString::valueOf(getBuildId()); + + m_aRegistrationNode.setNodeValue( + lcl_getReminderDateName(), + Any( aReminderValue ) + ); + } + + //-------------------------------------------------------------------- + sal_Int32 RegOptionsImpl::getBuildId() const + { + sal_Int32 nBuildId( 0 ); + ::rtl::OUString aDefault; + ::rtl::OUString aBuildIdData = utl::Bootstrap::getBuildIdData( aDefault ); + sal_Int32 nIndex1 = aBuildIdData.indexOf(':'); + sal_Int32 nIndex2 = aBuildIdData.indexOf(')'); + if (( nIndex1 > 0 ) && ( nIndex2 > 0 ) && ( nIndex2-1 > nIndex1+1 )) + { + ::rtl::OUString aBuildId = aBuildIdData.copy( nIndex1+1, nIndex2-nIndex1-1 ); + nBuildId = aBuildId.toInt32(); + } + + return nBuildId; + } + + //-------------------------------------------------------------------- + bool RegOptionsImpl::hasReminderDateCome() const + { + bool bRet = false; + sal_Int32 nDate = 0; + ::rtl::OUString sDate; + m_aRegistrationNode.getNodeValue( lcl_getReminderDateName() ) >>= sDate; + if ( sDate.getLength() ) + { + if ( sDate.indexOf( lcl_getPatchName() ) == 0) + { + if (sDate.equals( lcl_getPatchName() )) + bRet = true; + else if (sDate.getLength() > lcl_getPatchName().getLength() ) + { + // Check the build ID to determine if the registration + // dialog needs to be shown. + sal_Int32 nBuildId = getBuildId(); + ::rtl::OUString aStoredBuildId( sDate.copy(lcl_getPatchName().getLength())); + + // remind if the current build ID is not the same as the stored one + if ( nBuildId != aStoredBuildId.toInt32() ) + bRet = true; + } + } + else + { + nDate = lcl_convertString2Date( sDate ); + if ( nDate > 0 ) + { + Date aReminderDate; + aReminderDate.SetDate( nDate ); + bRet = aReminderDate <= Date(); + } + } + } + else + bRet = true; + + return bRet; + } + + //-------------------------------------------------------------------- + void RegOptionsImpl::markSessionDone( ) + { + OSL_ENSURE( !s_bThisSessionDone, "RegOptionsImpl::markSessionDone: already marked!" ); + OSL_ENSURE( implGetDialogPermission( ) != RegOptions::dpDisabled, "RegOptionsImpl::markSessionDone: invalid call!" ); + if ( !s_bThisSessionDone ) + { + RegOptions::DialogPermission eOldPermission = implGetDialogPermission( ); + + s_bThisSessionDone = sal_True; + + if ( RegOptions::dpRemindLater == eOldPermission ) + { // no action required. If we shall remind later, the counter is already at 1, we should not change this, + // as the next smaller number (which is 0 :) means that the dialog would be disabled + OSL_ENSURE( 1 == m_nDialogCounter, "RegOptionsImpl::markSessionDone: invalid session counter (1)!" ); + } + else + { + OSL_ENSURE( m_nDialogCounter > 0, "RegOptionsImpl::markSessionDone: invalid session counter (2)!" ); + --m_nDialogCounter; + + // decrease the session counter + m_aRegistrationNode.setNodeValue( + lcl_getRequestDialogName(), + makeAny( (sal_Int32)m_nDialogCounter ) + ); + + // and clear the reminder date + removeReminder(); + } + } + } + + //==================================================================== + //= RegOptions + //==================================================================== + //-------------------------------------------------------------------- + RegOptions::RegOptions() + :m_pImpl( NULL ) + { + } + + //-------------------------------------------------------------------- + void RegOptions::ensureImpl( ) + { + if ( !m_pImpl ) + m_pImpl = RegOptionsImpl::registerClient(); + } + + //-------------------------------------------------------------------- + RegOptions::~RegOptions() + { + if ( m_pImpl ) + { + RegOptionsImpl::revokeClient(); + m_pImpl = NULL; + } + } + + //-------------------------------------------------------------------- + String RegOptions::getRegistrationURL( ) const + { + const_cast< RegOptions* >( this )->ensureImpl( ); + return m_pImpl->getRegistrationURL(); + } + + //-------------------------------------------------------------------- + RegOptions::DialogPermission RegOptions::getDialogPermission( ) const + { + const_cast< RegOptions* >( this )->ensureImpl( ); + return m_pImpl->getDialogPermission(); + } + + //-------------------------------------------------------------------- + void RegOptions::markSessionDone( ) + { + const_cast< RegOptions* >( this )->ensureImpl( ); + m_pImpl->markSessionDone(); + } + + //-------------------------------------------------------------------- + void RegOptions::activateReminder( sal_Int32 _nDaysFromNow ) + { + const_cast< RegOptions* >( this )->ensureImpl( ); + m_pImpl->activateReminder( _nDaysFromNow ); + } + + //-------------------------------------------------------------------- + sal_Bool RegOptions::allowMenu( ) const + { + /// we cache this setting, 'cause it is needed very often + static sal_Bool bKnowMenuPermission = sal_False; + static sal_Bool bAllowMenu = sal_False; + + if ( !bKnowMenuPermission ) + { + const_cast< RegOptions* >( this )->ensureImpl( ); + bAllowMenu = m_pImpl->allowMenu(); + bKnowMenuPermission = sal_True; + } + return bAllowMenu; + } + + //-------------------------------------------------------------------- + void RegOptions::removeReminder() + { + const_cast< RegOptions* >( this )->ensureImpl( ); + m_pImpl->removeReminder(); + } + + //-------------------------------------------------------------------- + bool RegOptions::hasReminderDateCome() const + { + const_cast< RegOptions* >( this )->ensureImpl( ); + return m_pImpl->hasReminderDateCome(); + } + +//........................................................................ +} // namespace utl +//........................................................................ + +/* 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 000000000000..8f1ee3d4bd16 --- /dev/null +++ b/unotools/source/config/saveopt.cxx @@ -0,0 +1,1001 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" + +#include <unotools/saveopt.hxx> +#include "rtl/instance.hxx" +#include <unotools/configmgr.hxx> +#include <unotools/configitem.hxx> +#include <tools/debug.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> + +#include <osl/mutex.hxx> +#include <comphelper/configurationhelper.hxx> +#include <unotools/processfactory.hxx> +#include <rtl/logfile.hxx> +#include "itemholder1.hxx" + +using namespace utl; +using namespace rtl; +using namespace com::sun::star::uno; +namespace css = ::com::sun::star; + +class SvtSaveOptions_Impl; +class SvtLoadOptions_Impl; + +#define CFG_READONLY_DEFAULT sal_False + +struct SvtLoadSaveOptions_Impl +{ + SvtSaveOptions_Impl* pSaveOpt; + SvtLoadOptions_Impl* pLoadOpt; +}; + +static SvtLoadSaveOptions_Impl* pOptions = NULL; +static sal_Int32 nRefCount = 0; + +class SvtSaveOptions_Impl : public utl::ConfigItem +{ + sal_Int32 nAutoSaveTime; + sal_Bool bUseUserData, + bBackup, + bAutoSave, + bAutoSavePrompt, + bDocInfSave, + bSaveWorkingSet, + bSaveDocView, + bSaveRelINet, + bSaveRelFSys, + bSaveUnpacked, + bDoPrettyPrinting, + bWarnAlienFormat, + bLoadDocPrinter; + + sal_Bool bROAutoSaveTime, + bROUseUserData, + bROBackup, + bROAutoSave, + bROAutoSavePrompt, + bRODocInfSave, + bROSaveWorkingSet, + bROSaveDocView, + bROSaveRelINet, + bROSaveRelFSys, + bROSaveUnpacked, + bROWarnAlienFormat, + bRODoPrettyPrinting, + bROLoadDocPrinter, + bROODFDefaultVersion; + + SvtSaveOptions::ODFDefaultVersion eODFDefaultVersion; + +public: + SvtSaveOptions_Impl(); + ~SvtSaveOptions_Impl(); + + virtual void Notify( const com::sun::star::uno::Sequence< rtl::OUString >& aPropertyNames ); + virtual void Commit(); + + sal_Int32 GetAutoSaveTime() const { return nAutoSaveTime; } + BOOL IsUseUserData() const { return bUseUserData; } + BOOL IsBackup() const { return bBackup; } + BOOL IsAutoSave() const { return bAutoSave; } + BOOL IsAutoSavePrompt() const { return bAutoSavePrompt; } + BOOL IsDocInfoSave() const { return bDocInfSave; } + BOOL IsSaveWorkingSet() const { return bSaveWorkingSet; } + BOOL IsSaveDocView() const { return bSaveDocView; } + BOOL IsSaveRelINet() const { return bSaveRelINet; } + BOOL IsSaveRelFSys() const { return bSaveRelFSys; } + BOOL IsSaveUnpacked() const { return bSaveUnpacked; } + sal_Bool IsPrettyPrintingEnabled( ) const { return bDoPrettyPrinting; } + sal_Bool IsWarnAlienFormat() const { return bWarnAlienFormat; } + sal_Bool IsLoadDocPrinter() const { return bLoadDocPrinter; } + SvtSaveOptions::ODFDefaultVersion + GetODFDefaultVersion() const { return eODFDefaultVersion; } + + void SetAutoSaveTime( sal_Int32 n ); + void SetUseUserData( BOOL b ); + void SetBackup( BOOL b ); + void SetAutoSave( BOOL b ); + void SetAutoSavePrompt( BOOL b ); + void SetDocInfoSave( BOOL b ); + void SetSaveWorkingSet( BOOL b ); + void SetSaveDocView( BOOL b ); + void SetSaveRelINet( BOOL b ); + void SetSaveRelFSys( BOOL b ); + void SetSaveUnpacked( BOOL b ); + void EnablePrettyPrinting( sal_Bool _bDoPP ); + void SetWarnAlienFormat( sal_Bool _bDoPP ); + void SetLoadDocPrinter( sal_Bool bNew ); + void SetODFDefaultVersion( SvtSaveOptions::ODFDefaultVersion eNew ); + + sal_Bool IsReadOnly( SvtSaveOptions::EOption eOption ) const; +}; + +void SvtSaveOptions_Impl::SetAutoSaveTime( sal_Int32 n ) +{ + if (!bROAutoSaveTime && nAutoSaveTime!=n) + { + nAutoSaveTime = n; + SetModified(); + Commit(); + } +} + +void SvtSaveOptions_Impl::SetUseUserData( BOOL b ) +{ + if (!bROUseUserData && bUseUserData!=b) + { + bUseUserData = b; + SetModified(); + } +} + +void SvtSaveOptions_Impl::SetBackup( BOOL b ) +{ + if (!bROBackup && bBackup!=b) + { + bBackup = b; + SetModified(); + } +} + +void SvtSaveOptions_Impl::SetAutoSave( BOOL b ) +{ + if (!bROAutoSave && bAutoSave!=b) + { + bAutoSave = b; + SetModified(); + Commit(); + } +} + +void SvtSaveOptions_Impl::SetAutoSavePrompt( BOOL b ) +{ + if (!bROAutoSavePrompt && bAutoSavePrompt!=b) + { + bAutoSavePrompt = b; + SetModified(); + } +} + +void SvtSaveOptions_Impl::SetDocInfoSave(BOOL b) +{ + if (!bRODocInfSave && bDocInfSave!=b) + { + bDocInfSave = b; + SetModified(); + } +} + +void SvtSaveOptions_Impl::SetSaveWorkingSet( BOOL b ) +{ + if (!bROSaveWorkingSet && bSaveWorkingSet!=b) + { + bSaveWorkingSet = b; + SetModified(); + } +} + +void SvtSaveOptions_Impl::SetSaveDocView( BOOL b ) +{ + if (!bROSaveDocView && bSaveDocView!=b) + { + bSaveDocView = b; + SetModified(); + } +} + +void SvtSaveOptions_Impl::SetSaveRelINet( BOOL b ) +{ + if (!bROSaveRelINet && bSaveRelINet!=b) + { + bSaveRelINet = b; + SetModified(); + } +} + +void SvtSaveOptions_Impl::SetSaveRelFSys( BOOL b ) +{ + if (!bROSaveRelFSys && bSaveRelFSys!=b) + { + bSaveRelFSys = b; + SetModified(); + } +} + +void SvtSaveOptions_Impl::SetSaveUnpacked( BOOL b ) +{ + if (!bROSaveUnpacked && bSaveUnpacked!=b) + { + bSaveUnpacked = b; + SetModified(); + } +} + +void SvtSaveOptions_Impl::EnablePrettyPrinting( sal_Bool _bDoPP ) +{ + if (!bRODoPrettyPrinting && bDoPrettyPrinting!=_bDoPP) + { + bDoPrettyPrinting = _bDoPP; + SetModified(); + } +} + +void SvtSaveOptions_Impl::SetWarnAlienFormat( sal_Bool _bDoPP ) +{ + if (!bROWarnAlienFormat && bWarnAlienFormat!=_bDoPP) + { + bWarnAlienFormat = _bDoPP; + SetModified(); + } +} + +void SvtSaveOptions_Impl::SetLoadDocPrinter( sal_Bool bNew ) +{ + if ( !bROLoadDocPrinter && bLoadDocPrinter != bNew ) + { + bLoadDocPrinter = bNew; + SetModified(); + } +} + +void SvtSaveOptions_Impl::SetODFDefaultVersion( SvtSaveOptions::ODFDefaultVersion eNew ) +{ + if ( !bROODFDefaultVersion && eODFDefaultVersion != eNew ) + { + eODFDefaultVersion = eNew; + SetModified(); + } +} + +sal_Bool SvtSaveOptions_Impl::IsReadOnly( SvtSaveOptions::EOption eOption ) const +{ + sal_Bool bReadOnly = CFG_READONLY_DEFAULT; + switch(eOption) + { + case SvtSaveOptions::E_AUTOSAVETIME : + bReadOnly = bROAutoSaveTime; + break; + case SvtSaveOptions::E_USEUSERDATA : + bReadOnly = bROUseUserData; + break; + case SvtSaveOptions::E_BACKUP : + bReadOnly = bROBackup; + break; + case SvtSaveOptions::E_AUTOSAVE : + bReadOnly = bROAutoSave; + break; + case SvtSaveOptions::E_AUTOSAVEPROMPT : + bReadOnly = bROAutoSavePrompt; + break; + case SvtSaveOptions::E_DOCINFSAVE : + bReadOnly = bRODocInfSave; + break; + case SvtSaveOptions::E_SAVEWORKINGSET : + bReadOnly = bROSaveWorkingSet; + break; + case SvtSaveOptions::E_SAVEDOCVIEW : + bReadOnly = bROSaveDocView; + break; + case SvtSaveOptions::E_SAVERELINET : + bReadOnly = bROSaveRelINet; + break; + case SvtSaveOptions::E_SAVERELFSYS : + bReadOnly = bROSaveRelFSys; + break; + case SvtSaveOptions::E_SAVEUNPACKED : + bReadOnly = bROSaveUnpacked; + break; + case SvtSaveOptions::E_DOPRETTYPRINTING : + bReadOnly = bRODoPrettyPrinting; + break; + case SvtSaveOptions::E_WARNALIENFORMAT : + bReadOnly = bROWarnAlienFormat; + break; + case SvtSaveOptions::E_LOADDOCPRINTER : + bReadOnly = bROLoadDocPrinter; + break; + case SvtSaveOptions::E_ODFDEFAULTVERSION : + bReadOnly = bROLoadDocPrinter; + break; + } + return bReadOnly; +} + +#define FORMAT 0 +#define TIMEINTERVALL 1 +#define USEUSERDATA 2 +#define CREATEBACKUP 3 +#define AUTOSAVE 4 +#define PROMPT 5 +#define EDITPROPERTY 6 +#define SAVEVIEWINFO 7 +#define UNPACKED 8 +#define PRETTYPRINTING 9 +#define WARNALIENFORMAT 10 +#define LOADDOCPRINTER 11 +#define FILESYSTEM 12 +#define INTERNET 13 +#define SAVEWORKINGSET 14 +#define ODFDEFAULTVERSION 15 + +Sequence< OUString > GetPropertyNames() +{ + static const char* aPropNames[] = + { + "Graphic/Format", + "Document/AutoSaveTimeIntervall", + "Document/UseUserData", + "Document/CreateBackup", + "Document/AutoSave", + "Document/AutoSavePrompt", + "Document/EditProperty", + "Document/ViewInfo", + "Document/Unpacked", + "Document/PrettyPrinting", + "Document/WarnAlienFormat", + "Document/LoadPrinter", + "URL/FileSystem", + "URL/Internet", + "WorkingSet", + "ODF/DefaultVersion" + }; + + const int nCount = sizeof( aPropNames ) / sizeof( const char* ); + Sequence< OUString > aNames( nCount ); + OUString* pNames = aNames.getArray(); + for ( int i = 0; i < nCount; i++ ) + pNames[i] = OUString::createFromAscii( aPropNames[i] ); + + return aNames; +} + +// ----------------------------------------------------------------------- + +SvtSaveOptions_Impl::SvtSaveOptions_Impl() + : ConfigItem( OUString(RTL_CONSTASCII_USTRINGPARAM("Office.Common/Save")) ) + , nAutoSaveTime( 0 ) + , bUseUserData( sal_False ) + , bBackup( sal_False ) + , bAutoSave( sal_False ) + , bAutoSavePrompt( sal_False ) + , bDocInfSave( sal_False ) + , bSaveWorkingSet( sal_False ) + , bSaveDocView( sal_False ) + , bSaveRelINet( sal_False ) + , bSaveRelFSys( sal_False ) + , bSaveUnpacked( sal_False ) + , bDoPrettyPrinting( sal_False ) + , bWarnAlienFormat( sal_True ) + , bLoadDocPrinter( sal_True ) + , bROAutoSaveTime( CFG_READONLY_DEFAULT ) + , bROUseUserData( CFG_READONLY_DEFAULT ) + , bROBackup( CFG_READONLY_DEFAULT ) + , bROAutoSave( CFG_READONLY_DEFAULT ) + , bROAutoSavePrompt( CFG_READONLY_DEFAULT ) + , bRODocInfSave( CFG_READONLY_DEFAULT ) + , bROSaveWorkingSet( CFG_READONLY_DEFAULT ) + , bROSaveDocView( CFG_READONLY_DEFAULT ) + , bROSaveRelINet( CFG_READONLY_DEFAULT ) + , bROSaveRelFSys( CFG_READONLY_DEFAULT ) + , bROSaveUnpacked( CFG_READONLY_DEFAULT ) + , bROWarnAlienFormat( CFG_READONLY_DEFAULT ) + , bRODoPrettyPrinting( CFG_READONLY_DEFAULT ) + , bROLoadDocPrinter( CFG_READONLY_DEFAULT ) + , bROODFDefaultVersion( CFG_READONLY_DEFAULT ) + , eODFDefaultVersion( SvtSaveOptions::ODFVER_LATEST ) +{ + Sequence< OUString > aNames = GetPropertyNames(); + Sequence< Any > aValues = GetProperties( aNames ); + Sequence< sal_Bool > aROStates = GetReadOnlyStates( aNames ); + EnableNotification( 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 ( int nProp = 0; nProp < aNames.getLength(); nProp++ ) + { + DBG_ASSERT( pValues[nProp].hasValue(), "property value missing" ); + if ( pValues[nProp].hasValue() ) + { + sal_Int32 nTemp = 0; + switch ( nProp ) + { + case FORMAT: + // not supported anymore + break; + + case TIMEINTERVALL : + if ( pValues[nProp] >>= nTemp ) + nAutoSaveTime = nTemp; + else { + DBG_ERROR( "Wrong Type!" ); + }; + bROAutoSaveTime = pROStates[nProp]; + break; + + case ODFDEFAULTVERSION : + { + sal_Int16 nTmp = 0; + if ( pValues[nProp] >>= nTmp ) + { + if( nTmp == 3 ) + eODFDefaultVersion = SvtSaveOptions::ODFVER_LATEST; + else + eODFDefaultVersion = SvtSaveOptions::ODFDefaultVersion( nTmp ); + } + else { + DBG_ERRORFILE( "SvtSaveOptions_Impl::SvtSaveOptions_Impl(): Wrong Type!" ); + }; + bROODFDefaultVersion = pROStates[nProp]; + break; + } + + default: + { + sal_Bool bTemp = sal_Bool(); + if ( pValues[nProp] >>= bTemp ) + { + switch ( nProp ) + { + case USEUSERDATA : + bUseUserData = bTemp; + bROUseUserData = pROStates[nProp]; + break; + case CREATEBACKUP : + bBackup = bTemp; + bROBackup = pROStates[nProp]; + break; + case AUTOSAVE : + bAutoSave = bTemp; + bROAutoSave = pROStates[nProp]; + break; + case PROMPT : + bAutoSavePrompt = bTemp; + bROAutoSavePrompt = pROStates[nProp]; + break; + case EDITPROPERTY : + bDocInfSave = bTemp; + bRODocInfSave = pROStates[nProp]; + break; + case SAVEWORKINGSET : + bSaveWorkingSet = bTemp; + bROSaveWorkingSet = pROStates[nProp]; + break; + case SAVEVIEWINFO : + bSaveDocView = bTemp; + bROSaveDocView = pROStates[nProp]; + break; + case FILESYSTEM : + bSaveRelFSys = bTemp; + bROSaveRelFSys = pROStates[nProp]; + break; + case INTERNET : + bSaveRelINet = bTemp; + bROSaveRelINet = pROStates[nProp]; + break; + case UNPACKED : + bSaveUnpacked = bTemp; + bROSaveUnpacked = pROStates[nProp]; + break; + + case PRETTYPRINTING: + bDoPrettyPrinting = bTemp; + bRODoPrettyPrinting = pROStates[nProp]; + break; + + case WARNALIENFORMAT: + bWarnAlienFormat = bTemp; + bROWarnAlienFormat = pROStates[nProp]; + break; + + case LOADDOCPRINTER: + bLoadDocPrinter = bTemp; + bROLoadDocPrinter = pROStates[nProp]; + break; + + default : + DBG_ERRORFILE( "invalid index to load a path" ); + } + } + else + { + DBG_ERROR( "Wrong Type!" ); + } + } + } + } + } + } + + try + { + css::uno::Reference< css::uno::XInterface > xCFG = ::comphelper::ConfigurationHelper::openConfig( + ::utl::getProcessServiceFactory(), + ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("org.openoffice.Office.Recovery")), + ::comphelper::ConfigurationHelper::E_READONLY); + + ::comphelper::ConfigurationHelper::readRelativeKey( + xCFG, + ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("AutoSave")), + ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Enabled"))) >>= bAutoSave; + + ::comphelper::ConfigurationHelper::readRelativeKey( + xCFG, + ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("AutoSave")), + ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("TimeIntervall"))) >>= nAutoSaveTime; + } + catch(const css::uno::Exception&) + { DBG_ERROR("Could not find needed informations for AutoSave feature."); } +} + +SvtSaveOptions_Impl::~SvtSaveOptions_Impl() +{} + +void SvtSaveOptions_Impl::Commit() +{ + Sequence< OUString > aOrgNames = GetPropertyNames(); + OUString* pOrgNames = aOrgNames.getArray(); + 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 i=0; i<nOrgCount; ++i) + { + switch (i) + { + case FORMAT: + // not supported anymore + break; + case TIMEINTERVALL : + if (!bROAutoSaveTime) + { + pValues[nRealCount] <<= nAutoSaveTime; + pNames[nRealCount] = pOrgNames[i]; + ++nRealCount; + } + break; + case USEUSERDATA : + if (!bROUseUserData) + { + pValues[nRealCount] <<= bUseUserData; + pNames[nRealCount] = pOrgNames[i]; + ++nRealCount; + } + break; + case CREATEBACKUP : + if (!bROBackup) + { + pValues[nRealCount] <<= bBackup; + pNames[nRealCount] = pOrgNames[i]; + ++nRealCount; + } + break; + case AUTOSAVE : + if (!bROAutoSave) + { + pValues[nRealCount] <<= bAutoSave; + pNames[nRealCount] = pOrgNames[i]; + ++nRealCount; + } + break; + case PROMPT : + if (!bROAutoSavePrompt) + { + pValues[nRealCount] <<= bAutoSavePrompt; + pNames[nRealCount] = pOrgNames[i]; + ++nRealCount; + } + break; + case EDITPROPERTY : + if (!bRODocInfSave) + { + pValues[nRealCount] <<= bDocInfSave; + pNames[nRealCount] = pOrgNames[i]; + ++nRealCount; + } + break; + case SAVEWORKINGSET : + if (!bROSaveWorkingSet) + { + pValues[nRealCount] <<= bSaveWorkingSet; + pNames[nRealCount] = pOrgNames[i]; + ++nRealCount; + } + break; + case SAVEVIEWINFO : + if (!bROSaveDocView) + { + pValues[nRealCount] <<= bSaveDocView; + pNames[nRealCount] = pOrgNames[i]; + ++nRealCount; + } + break; + case FILESYSTEM : + if (!bROSaveRelFSys) + { + pValues[nRealCount] <<= bSaveRelFSys; + pNames[nRealCount] = pOrgNames[i]; + ++nRealCount; + } + break; + case INTERNET : + if (!bROSaveRelINet) + { + pValues[nRealCount] <<= bSaveRelINet; + pNames[nRealCount] = pOrgNames[i]; + ++nRealCount; + } + break; + case UNPACKED : + if (!bROSaveUnpacked) + { + pValues[nRealCount] <<= bSaveUnpacked; + pNames[nRealCount] = pOrgNames[i]; + ++nRealCount; + } + break; + case PRETTYPRINTING: + if (!bRODoPrettyPrinting) + { + pValues[nRealCount] <<= bDoPrettyPrinting; + pNames[nRealCount] = pOrgNames[i]; + ++nRealCount; + } + break; + case WARNALIENFORMAT: + if (!bROWarnAlienFormat) + { + pValues[nRealCount] <<= bWarnAlienFormat; + pNames[nRealCount] = pOrgNames[i]; + ++nRealCount; + } + break; + case LOADDOCPRINTER: + if (!bROLoadDocPrinter) + { + pValues[nRealCount] <<= bLoadDocPrinter; + pNames[nRealCount] = pOrgNames[i]; + ++nRealCount; + } + break; + case ODFDEFAULTVERSION: + if (!bROODFDefaultVersion) + { + pValues[nRealCount] <<= (eODFDefaultVersion == SvtSaveOptions::ODFVER_LATEST) ? sal_Int16( 3 ) : sal_Int16( eODFDefaultVersion ); + pNames[nRealCount] = pOrgNames[i]; + ++nRealCount; + } + break; + default: + DBG_ERRORFILE( "invalid index to save a path" ); + } + } + + aNames.realloc(nRealCount); + aValues.realloc(nRealCount); + PutProperties( aNames, aValues ); + + css::uno::Reference< css::uno::XInterface > xCFG = ::comphelper::ConfigurationHelper::openConfig( + ::utl::getProcessServiceFactory(), + ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("org.openoffice.Office.Recovery")), + ::comphelper::ConfigurationHelper::E_STANDARD); + + ::comphelper::ConfigurationHelper::writeRelativeKey( + xCFG, + ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("AutoSave")), + ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("TimeIntervall")), + css::uno::makeAny(nAutoSaveTime)); + + ::comphelper::ConfigurationHelper::writeRelativeKey( + xCFG, + ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("AutoSave")), + ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Enabled")), + css::uno::makeAny(bAutoSave)); + + ::comphelper::ConfigurationHelper::flush(xCFG); +} + +// ----------------------------------------------------------------------- + +void SvtSaveOptions_Impl::Notify( const Sequence<rtl::OUString>& ) +{ +} + + +class SvtLoadOptions_Impl : public utl::ConfigItem +{ + + sal_Bool bLoadUserDefinedSettings; + +public: + SvtLoadOptions_Impl(); + ~SvtLoadOptions_Impl(); + + virtual void Notify( const com::sun::star::uno::Sequence< rtl::OUString >& aPropertyNames ); + virtual void Commit(); + + void SetLoadUserSettings(sal_Bool b){bLoadUserDefinedSettings = b; SetModified();} + sal_Bool IsLoadUserSettings() const {return bLoadUserDefinedSettings;} +}; +// ----------------------------------------------------------------------- +const sal_Char cUserDefinedSettings[] = "UserDefinedSettings"; + +SvtLoadOptions_Impl::SvtLoadOptions_Impl() + : ConfigItem( OUString(RTL_CONSTASCII_USTRINGPARAM("Office.Common/Load")) ) + , bLoadUserDefinedSettings( sal_False ) +{ + Sequence< OUString > aNames(1); + aNames[0] = OUString::createFromAscii(cUserDefinedSettings); + Sequence< Any > aValues = GetProperties( aNames ); + EnableNotification( aNames ); + const Any* pValues = aValues.getConstArray(); + DBG_ASSERT( aValues.getLength() == aNames.getLength(), "GetProperties failed" ); + if (pValues[0].getValueTypeClass() == ::com::sun::star::uno::TypeClass_BOOLEAN) + bLoadUserDefinedSettings = *(sal_Bool *)pValues[0].getValue(); +} +// ----------------------------------------------------------------------- +SvtLoadOptions_Impl::~SvtLoadOptions_Impl() +{ +} +// ----------------------------------------------------------------------- +void SvtLoadOptions_Impl::Commit() +{ + Sequence< OUString > aNames(1); + aNames[0] = OUString::createFromAscii(cUserDefinedSettings); + Sequence< Any > aValues( 1 ); + aValues[0].setValue(&bLoadUserDefinedSettings, ::getBooleanCppuType()); + PutProperties( aNames, aValues ); +} +// ----------------------------------------------------------------------- +void SvtLoadOptions_Impl::Notify( const Sequence<rtl::OUString>& ) +{ + DBG_ERRORFILE( "properties have been changed" ); +} +// ----------------------------------------------------------------------- + +namespace +{ + class LocalSingleton : public rtl::Static< osl::Mutex, LocalSingleton > + { + }; +} + +// ----------------------------------------------------------------------- +SvtSaveOptions::SvtSaveOptions() +{ + // Global access, must be guarded (multithreading) + ::osl::MutexGuard aGuard( LocalSingleton::get() ); + if ( !pOptions ) + { + RTL_LOGFILE_CONTEXT(aLog, "unotools ( ??? ) ::SvtSaveOptions_Impl::ctor()"); + pOptions = new SvtLoadSaveOptions_Impl; + pOptions->pSaveOpt = new SvtSaveOptions_Impl; + pOptions->pLoadOpt = new SvtLoadOptions_Impl; + + ItemHolder1::holdConfigItem(E_SAVEOPTIONS); + } + ++nRefCount; + pImp = pOptions; +} + +// ----------------------------------------------------------------------- + +SvtSaveOptions::~SvtSaveOptions() +{ + // Global access, must be guarded (multithreading) + ::osl::MutexGuard aGuard( LocalSingleton::get() ); + if ( !--nRefCount ) + { + if ( pOptions->pSaveOpt->IsModified() ) + pOptions->pSaveOpt->Commit(); + if ( pOptions->pLoadOpt->IsModified() ) + pOptions->pLoadOpt->Commit(); + + DELETEZ( pOptions->pLoadOpt ); + DELETEZ( pOptions->pSaveOpt ); + DELETEZ( pOptions ); + } +} + +void SvtSaveOptions::SetAutoSaveTime( sal_Int32 n ) +{ + pImp->pSaveOpt->SetAutoSaveTime( n ); +} + +sal_Int32 SvtSaveOptions::GetAutoSaveTime() const +{ + return pImp->pSaveOpt->GetAutoSaveTime(); +} + +void SvtSaveOptions::SetUseUserData( sal_Bool b ) +{ + pImp->pSaveOpt->SetUseUserData( b ); +} + +sal_Bool SvtSaveOptions::IsUseUserData() const +{ + return pImp->pSaveOpt->IsUseUserData(); +} + +void SvtSaveOptions::SetBackup( sal_Bool b ) +{ + pImp->pSaveOpt->SetBackup( b ); +} + +sal_Bool SvtSaveOptions::IsBackup() const +{ + return pImp->pSaveOpt->IsBackup(); +} + +void SvtSaveOptions::SetAutoSave( sal_Bool b ) +{ + pImp->pSaveOpt->SetAutoSave( b ); +} + +sal_Bool SvtSaveOptions::IsAutoSave() const +{ + return pImp->pSaveOpt->IsAutoSave(); +} + +void SvtSaveOptions::SetAutoSavePrompt( sal_Bool b ) +{ + pImp->pSaveOpt->SetAutoSavePrompt( b ); +} + +sal_Bool SvtSaveOptions::IsAutoSavePrompt() const +{ + return pImp->pSaveOpt->IsAutoSavePrompt(); +} + +void SvtSaveOptions::SetDocInfoSave(sal_Bool b) +{ + pImp->pSaveOpt->SetDocInfoSave( b ); +} + +sal_Bool SvtSaveOptions::IsDocInfoSave() const +{ + return pImp->pSaveOpt->IsDocInfoSave(); +} + +void SvtSaveOptions::SetSaveWorkingSet( sal_Bool b ) +{ + pImp->pSaveOpt->SetSaveWorkingSet( b ); +} + +sal_Bool SvtSaveOptions::IsSaveWorkingSet() const +{ + return pImp->pSaveOpt->IsSaveWorkingSet(); +} + +void SvtSaveOptions::SetSaveDocView( sal_Bool b ) +{ + pImp->pSaveOpt->SetSaveDocView( b ); +} + +sal_Bool SvtSaveOptions::IsSaveDocView() const +{ + return pImp->pSaveOpt->IsSaveDocView(); +} + +void SvtSaveOptions::SetSaveRelINet( sal_Bool b ) +{ + pImp->pSaveOpt->SetSaveRelINet( b ); +} + +sal_Bool SvtSaveOptions::IsSaveRelINet() const +{ + return pImp->pSaveOpt->IsSaveRelINet(); +} + +void SvtSaveOptions::SetSaveRelFSys( sal_Bool b ) +{ + pImp->pSaveOpt->SetSaveRelFSys( b ); +} + +sal_Bool SvtSaveOptions::IsSaveRelFSys() const +{ + return pImp->pSaveOpt->IsSaveRelFSys(); +} + +void SvtSaveOptions::SetSaveUnpacked( sal_Bool b ) +{ + pImp->pSaveOpt->SetSaveUnpacked( b ); +} + +sal_Bool SvtSaveOptions::IsSaveUnpacked() const +{ + return pImp->pSaveOpt->IsSaveUnpacked(); +} + +void SvtSaveOptions::SetLoadUserSettings(sal_Bool b) +{ + pImp->pLoadOpt->SetLoadUserSettings(b); +} + +sal_Bool SvtSaveOptions::IsLoadUserSettings() const +{ + return pImp->pLoadOpt->IsLoadUserSettings(); +} + +void SvtSaveOptions::SetPrettyPrinting( sal_Bool _bEnable ) +{ + pImp->pSaveOpt->EnablePrettyPrinting( _bEnable ); +} + +sal_Bool SvtSaveOptions::IsPrettyPrinting() const +{ + return pImp->pSaveOpt->IsPrettyPrintingEnabled(); +} + +void SvtSaveOptions::SetWarnAlienFormat( sal_Bool _bEnable ) +{ + pImp->pSaveOpt->SetWarnAlienFormat( _bEnable ); +} + +sal_Bool SvtSaveOptions::IsWarnAlienFormat() const +{ + return pImp->pSaveOpt->IsWarnAlienFormat(); +} + +void SvtSaveOptions::SetLoadDocumentPrinter( sal_Bool _bEnable ) +{ + pImp->pSaveOpt->SetLoadDocPrinter( _bEnable ); +} + +sal_Bool SvtSaveOptions::IsLoadDocumentPrinter() const +{ + return pImp->pSaveOpt->IsLoadDocPrinter(); +} + +void SvtSaveOptions::SetODFDefaultVersion( SvtSaveOptions::ODFDefaultVersion eVersion ) +{ + pImp->pSaveOpt->SetODFDefaultVersion( eVersion ); +} + +SvtSaveOptions::ODFDefaultVersion SvtSaveOptions::GetODFDefaultVersion() const +{ + return pImp->pSaveOpt->GetODFDefaultVersion(); +} + +sal_Bool SvtSaveOptions::IsReadOnly( SvtSaveOptions::EOption eOption ) const +{ + return pImp->pSaveOpt->IsReadOnly(eOption); +} + +/* 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 000000000000..f7d6333afac0 --- /dev/null +++ b/unotools/source/config/searchopt.cxx @@ -0,0 +1,639 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" + +#include <unotools/searchopt.hxx> +#include <tools/solar.h> +#include <tools/debug.hxx> +#include <unotools/configitem.hxx> +#include <com/sun/star/i18n/TransliterationModules.hpp> +#include <com/sun/star/uno/Sequence.hxx> +#include <com/sun/star/uno/Any.h> +#include <rtl/logfile.hxx> +#include <sal/macros.h> + + +using namespace rtl; +using namespace utl; +using namespace com::sun::star::uno; +using namespace com::sun::star::i18n; + +#define MAX_FLAGS_OFFSET 25 + +////////////////////////////////////////////////////////////////////// + + +class SvtSearchOptions_Impl : public ConfigItem +{ + INT32 nFlags; + BOOL bModified; + + // disallow copy-constructor and assignment-operator for now + SvtSearchOptions_Impl( const SvtSearchOptions_Impl & ); + SvtSearchOptions_Impl & operator = ( const SvtSearchOptions_Impl & ); + +protected: + BOOL IsModified() const { return bModified; } + using ConfigItem::SetModified; + void SetModified( BOOL bVal ); + BOOL Load(); + BOOL Save(); + + Sequence< OUString > GetPropertyNames() const; + +public: + SvtSearchOptions_Impl(); + virtual ~SvtSearchOptions_Impl(); + + // ConfigItem + virtual void Commit(); + virtual void Notify( const com::sun::star::uno::Sequence< rtl::OUString >& aPropertyNames ); + + BOOL GetFlag( USHORT nOffset ) const; + void SetFlag( USHORT nOffset, BOOL bVal ); +}; + + + +SvtSearchOptions_Impl::SvtSearchOptions_Impl() : + ConfigItem( OUString(RTL_CONSTASCII_USTRINGPARAM("Office.Common/SearchOptions")) ) +{ + RTL_LOGFILE_CONTEXT(aLog, "unotools SvtSearchOptions_Impl::SvtSearchOptions_Impl()"); + nFlags = 0x0003FFFF; // set all options values to 'true' + Load(); + SetModified( FALSE ); +} + + +SvtSearchOptions_Impl::~SvtSearchOptions_Impl() +{ + Commit(); +} + + +void SvtSearchOptions_Impl::Commit() +{ + if (IsModified()) + Save(); +} + +void SvtSearchOptions_Impl::Notify( const Sequence< rtl::OUString >& ) +{ +} + + +BOOL SvtSearchOptions_Impl::GetFlag( USHORT nOffset ) const +{ + DBG_ASSERT( nOffset <= MAX_FLAGS_OFFSET, "offset out of range"); + return ((nFlags >> nOffset) & 0x01) ? TRUE : FALSE; +} + + +void SvtSearchOptions_Impl::SetFlag( USHORT nOffset, BOOL bVal ) +{ + DBG_ASSERT( nOffset <= MAX_FLAGS_OFFSET, "offset out of range"); + INT32 nOldFlags = nFlags; + INT32 nMask = ((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() const +{ + 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 + }; + + const int nCount = SAL_N_ELEMENTS( aPropNames ); + Sequence< OUString > aNames( nCount ); + OUString* pNames = aNames.getArray(); + for (INT32 i = 0; i < nCount; ++i) + pNames[i] = OUString::createFromAscii( aPropNames[i] ); + + return aNames; +} + + +BOOL SvtSearchOptions_Impl::Load() +{ + BOOL bSucc = FALSE; + + Sequence< OUString > aNames = GetPropertyNames(); + 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 (USHORT 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 { + DBG_ERROR( "unexpected index" ); + } + } + else + { + DBG_ERROR( "unexpected type" ); + bSucc = FALSE; + } + } + else + { + DBG_ERROR( "value missing" ); + bSucc = FALSE; + } + } + } + DBG_ASSERT( bSucc, "LoadConfig failed" ); + + return bSucc; +} + + +BOOL SvtSearchOptions_Impl::Save() +{ + BOOL bSucc = FALSE; + + const Sequence< OUString > aNames = GetPropertyNames(); + 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 && nProps == MAX_FLAGS_OFFSET + 1) + { + for (USHORT i = 0; i < nProps; ++i) + pValue[i] <<= (BOOL) GetFlag(i); + bSucc |= PutProperties( aNames, aValues ); + } + + if (bSucc) + SetModified( FALSE ); + + return bSucc; +} + + +////////////////////////////////////////////////////////////////////// + +SvtSearchOptions::SvtSearchOptions() +{ + pImpl = new SvtSearchOptions_Impl; +} + + +SvtSearchOptions::~SvtSearchOptions() +{ + delete pImpl; +} + + +INT32 SvtSearchOptions::GetTransliterationFlags() const +{ + INT32 nRes = 0; + + if (!IsMatchCase()) // 'IsMatchCase' means act case sensitive + nRes |= TransliterationModules_IGNORE_CASE; + if ( IsMatchFullHalfWidthForms()) + nRes |= TransliterationModules_IGNORE_WIDTH; + if ( IsMatchHiraganaKatakana()) + nRes |= TransliterationModules_IGNORE_KANA; + if ( IsMatchContractions()) + nRes |= TransliterationModules_ignoreSize_ja_JP; + if ( IsMatchMinusDashChoon()) + nRes |= TransliterationModules_ignoreMinusSign_ja_JP; + if ( IsMatchRepeatCharMarks()) + nRes |= TransliterationModules_ignoreIterationMark_ja_JP; + if ( IsMatchVariantFormKanji()) + nRes |= TransliterationModules_ignoreTraditionalKanji_ja_JP; + if ( IsMatchOldKanaForms()) + nRes |= TransliterationModules_ignoreTraditionalKana_ja_JP; + if ( IsMatchDiziDuzu()) + nRes |= TransliterationModules_ignoreZiZu_ja_JP; + if ( IsMatchBavaHafa()) + nRes |= TransliterationModules_ignoreBaFa_ja_JP; + if ( IsMatchTsithichiDhizi()) + nRes |= TransliterationModules_ignoreTiJi_ja_JP; + if ( IsMatchHyuiyuByuvyu()) + nRes |= TransliterationModules_ignoreHyuByu_ja_JP; + if ( IsMatchSesheZeje()) + nRes |= TransliterationModules_ignoreSeZe_ja_JP; + if ( IsMatchIaiya()) + nRes |= TransliterationModules_ignoreIandEfollowedByYa_ja_JP; + if ( IsMatchKiku()) + nRes |= TransliterationModules_ignoreKiKuFollowedBySa_ja_JP; + if ( IsIgnorePunctuation()) + nRes |= TransliterationModules_ignoreSeparator_ja_JP; + if ( IsIgnoreWhitespace()) + nRes |= TransliterationModules_ignoreSpace_ja_JP; + if ( IsIgnoreProlongedSoundMark()) + nRes |= TransliterationModules_ignoreProlongedSoundMark_ja_JP; + if ( IsIgnoreMiddleDot()) + nRes |= TransliterationModules_ignoreMiddleDot_ja_JP; + + 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->SetFlag( 2, bVal ); +} + + +BOOL SvtSearchOptions::IsSearchForStyles() const +{ + return pImpl->GetFlag( 3 ); +} + + +void SvtSearchOptions::SetSearchForStyles( BOOL bVal ) +{ + pImpl->SetFlag( 3, bVal ); +} + + +BOOL SvtSearchOptions::IsSimilaritySearch() const +{ + return pImpl->GetFlag( 4 ); +} + + +void SvtSearchOptions::SetSimilaritySearch( BOOL bVal ) +{ + pImpl->SetFlag( 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 ); +} + +////////////////////////////////////////////////////////////////////// + +/* 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 000000000000..fb0ea146b71c --- /dev/null +++ b/unotools/source/config/securityoptions.cxx @@ -0,0 +1,1305 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" + +#include <unotools/securityoptions.hxx> +#include <unotools/configmgr.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/beans/PropertyValue.hpp> +#include <tools/urlobj.hxx> +#include <tools/wldcrd.hxx> + +#include <unotools/pathoptions.hxx> + +#include <rtl/logfile.hxx> +#include "itemholder1.hxx" + +//_________________________________________________________________________________________________________________ +// namespaces +//_________________________________________________________________________________________________________________ + +using namespace ::utl ; +using namespace ::rtl ; +using namespace ::osl ; +using namespace ::com::sun::star::uno ; + +//_________________________________________________________________________________________________________________ +// const +//_________________________________________________________________________________________________________________ + +#define ROOTNODE_SECURITY OUString(RTL_CONSTASCII_USTRINGPARAM("Office.Common/Security/Scripting")) +#define DEFAULT_SECUREURL Sequence< OUString >() +#define DEFAULT_SECLEVEL 3 +#define DEFAULT_TRUSTEDAUTHORS Sequence< SvtSecurityOptions::Certificate >() + +// xmlsec05 depricated +#define DEFAULT_STAROFFICEBASIC eALWAYS_EXECUTE + +#define CSTR_SECUREURL "SecureURL" +#define CSTR_DOCWARN_SAVEORSEND "WarnSaveOrSendDoc" +#define CSTR_DOCWARN_SIGNING "WarnSignDoc" +#define CSTR_DOCWARN_PRINT "WarnPrintDoc" +#define CSTR_DOCWARN_CREATEPDF "WarnCreatePDF" +#define CSTR_DOCWARN_REMOVEPERSONALINFO "RemovePersonalInfoOnSaving" +#define CSTR_DOCWARN_RECOMMENDPASSWORD "RecommendPasswordProtection" +#define CSTR_CTRLCLICK_HYPERLINK "HyperlinksWithCtrlClick" +#define CSTR_MACRO_SECLEVEL "MacroSecurityLevel" +#define CSTR_MACRO_TRUSTEDAUTHORS "TrustedAuthors" +#define CSTR_MACRO_DISABLE "DisableMacrosExecution" +#define CSTR_TRUSTEDAUTHOR_SUBJECTNAME "SubjectName" +#define CSTR_TRUSTEDAUTHOR_SERIALNUMBER "SerialNumber" +#define CSTR_TRUSTEDAUTHOR_RAWDATA "RawData" + +#define PROPERTYNAME_SECUREURL OUString(RTL_CONSTASCII_USTRINGPARAM(CSTR_SECUREURL )) +#define PROPERTYNAME_DOCWARN_SAVEORSEND OUString(RTL_CONSTASCII_USTRINGPARAM(CSTR_DOCWARN_SAVEORSEND )) +#define PROPERTYNAME_DOCWARN_SIGNING OUString(RTL_CONSTASCII_USTRINGPARAM(CSTR_DOCWARN_SIGNING )) +#define PROPERTYNAME_DOCWARN_PRINT OUString(RTL_CONSTASCII_USTRINGPARAM(CSTR_DOCWARN_PRINT )) +#define PROPERTYNAME_DOCWARN_CREATEPDF OUString(RTL_CONSTASCII_USTRINGPARAM(CSTR_DOCWARN_CREATEPDF )) +#define PROPERTYNAME_DOCWARN_REMOVEPERSONALINFO OUString(RTL_CONSTASCII_USTRINGPARAM(CSTR_DOCWARN_REMOVEPERSONALINFO )) +#define PROPERTYNAME_DOCWARN_RECOMMENDPASSWORD OUString(RTL_CONSTASCII_USTRINGPARAM(CSTR_DOCWARN_RECOMMENDPASSWORD )) +#define PROPERTYNAME_CTRLCLICK_HYPERLINK OUString(RTL_CONSTASCII_USTRINGPARAM(CSTR_CTRLCLICK_HYPERLINK )) +#define PROPERTYNAME_MACRO_SECLEVEL OUString(RTL_CONSTASCII_USTRINGPARAM(CSTR_MACRO_SECLEVEL )) +#define PROPERTYNAME_MACRO_TRUSTEDAUTHORS OUString(RTL_CONSTASCII_USTRINGPARAM(CSTR_MACRO_TRUSTEDAUTHORS )) +#define PROPERTYNAME_MACRO_DISABLE OUString(RTL_CONSTASCII_USTRINGPARAM(CSTR_MACRO_DISABLE )) +#define PROPERTYNAME_TRUSTEDAUTHOR_SUBJECTNAME OUString(RTL_CONSTASCII_USTRINGPARAM(CSTR_TRUSTEDAUTHOR_SUBJECTNAME)) +#define PROPERTYNAME_TRUSTEDAUTHOR_SERIALNUMBER OUString(RTL_CONSTASCII_USTRINGPARAM(CSTR_TRUSTEDAUTHOR_SERIALNUMBER)) +#define PROPERTYNAME_TRUSTEDAUTHOR_RAWDATA OUString(RTL_CONSTASCII_USTRINGPARAM(CSTR_TRUSTEDAUTHOR_RAWDATA)) + +// xmlsec05 depricated +#define PROPERTYNAME_STAROFFICEBASIC OUString(RTL_CONSTASCII_USTRINGPARAM("OfficeBasic" )) +#define PROPERTYNAME_EXECUTEPLUGINS OUString(RTL_CONSTASCII_USTRINGPARAM("ExecutePlugins" )) +#define PROPERTYNAME_WARNINGENABLED OUString(RTL_CONSTASCII_USTRINGPARAM("Warning" )) +#define PROPERTYNAME_CONFIRMATIONENABLED OUString(RTL_CONSTASCII_USTRINGPARAM("Confirmation" )) +// xmlsec05 depricated + + +#define PROPERTYHANDLE_SECUREURL 0 + +// xmlsec05 depricated +#define PROPERTYHANDLE_STAROFFICEBASIC 1 +#define PROPERTYHANDLE_EXECUTEPLUGINS 2 +#define PROPERTYHANDLE_WARNINGENABLED 3 +#define PROPERTYHANDLE_CONFIRMATIONENABLED 4 +// xmlsec05 depricated + +#define PROPERTYHANDLE_DOCWARN_SAVEORSEND 5 +#define PROPERTYHANDLE_DOCWARN_SIGNING 6 +#define PROPERTYHANDLE_DOCWARN_PRINT 7 +#define PROPERTYHANDLE_DOCWARN_CREATEPDF 8 +#define PROPERTYHANDLE_DOCWARN_REMOVEPERSONALINFO 9 +#define PROPERTYHANDLE_DOCWARN_RECOMMENDPASSWORD 10 +#define PROPERTYHANDLE_CTRLCLICK_HYPERLINK 11 +#define PROPERTYHANDLE_MACRO_SECLEVEL 12 +#define PROPERTYHANDLE_MACRO_TRUSTEDAUTHORS 13 +#define PROPERTYHANDLE_MACRO_DISABLE 14 + +#define PROPERTYCOUNT 15 +#define PROPERTYHANDLE_INVALID -1 + +#define CFG_READONLY_DEFAULT sal_False + +//_________________________________________________________________________________________________________________ +// private declarations! +//_________________________________________________________________________________________________________________ + +class SvtSecurityOptions_Impl : public ConfigItem +{ + //------------------------------------------------------------------------------------------------------------- + // public methods + //------------------------------------------------------------------------------------------------------------- + + public: + + //--------------------------------------------------------------------------------------------------------- + // constructor / destructor + //--------------------------------------------------------------------------------------------------------- + + SvtSecurityOptions_Impl(); + ~SvtSecurityOptions_Impl(); + + //--------------------------------------------------------------------------------------------------------- + // overloaded methods of baseclass + //--------------------------------------------------------------------------------------------------------- + + /*-****************************************************************************************************//** + @short called for notify of configmanager + @descr These method is called from the ConfigManager before application ends or from the + PropertyChangeListener if the sub tree broadcasts changes. You must update your + internal values. + + @seealso baseclass ConfigItem + + @param "seqPropertyNames" is the list of properties which should be updated. + @return - + + @onerror - + *//*-*****************************************************************************************************/ + + virtual void Notify( const Sequence< OUString >& seqPropertyNames ); + + /*-****************************************************************************************************//** + @short write changes to configuration + @descr These method writes the changed values into the sub tree + and should always called in our destructor to guarantee consistency of config data. + + @seealso baseclass ConfigItem + + @param - + @return - + + @onerror - + *//*-*****************************************************************************************************/ + + virtual void Commit(); + + //--------------------------------------------------------------------------------------------------------- + // public interface + //--------------------------------------------------------------------------------------------------------- + + sal_Bool IsReadOnly ( SvtSecurityOptions::EOption eOption ) const ; + + Sequence< OUString > GetSecureURLs ( ) const ; + void SetSecureURLs ( const Sequence< OUString >& seqURLList ) ; + sal_Bool IsSecureURL ( const OUString& sURL, + const OUString& sReferer ) const ; + inline sal_Int32 GetMacroSecurityLevel ( ) const ; + void SetMacroSecurityLevel ( sal_Int32 _nLevel ) ; + + inline sal_Bool IsMacroDisabled ( ) const ; + + Sequence< SvtSecurityOptions::Certificate > GetTrustedAuthors ( ) const ; + void SetTrustedAuthors ( const Sequence< SvtSecurityOptions::Certificate >& rAuthors ) ; + sal_Bool IsTrustedAuthorsEnabled ( ) ; + + sal_Bool IsOptionSet ( SvtSecurityOptions::EOption eOption ) const ; + sal_Bool SetOption ( SvtSecurityOptions::EOption eOption, sal_Bool bValue ) ; + sal_Bool IsOptionEnabled ( SvtSecurityOptions::EOption eOption ) const ; +private: + + /*-****************************************************************************************************//** + @short return list of key names of ouer configuration management which represent our module tree + @descr These methods return a static const list of key names. We need it to get needed values from our + configuration management. + + @seealso - + + @param - + @return A list of needed configuration keys is returned. + + @onerror - + *//*-*****************************************************************************************************/ + + void SetProperty( sal_Int32 nHandle, const Any& rValue, sal_Bool bReadOnly ); + void LoadAuthors( void ); + static sal_Int32 GetHandle( const OUString& rPropertyName ); + bool GetOption( SvtSecurityOptions::EOption eOption, sal_Bool*& rpValue, sal_Bool*& rpRO ); + + static Sequence< OUString > GetPropertyNames(); + + Sequence< OUString > m_seqSecureURLs; + sal_Bool m_bSaveOrSend; + sal_Bool m_bSigning; + sal_Bool m_bPrint; + sal_Bool m_bCreatePDF; + sal_Bool m_bRemoveInfo; + sal_Bool m_bRecommendPwd; + sal_Bool m_bCtrlClickHyperlink; + sal_Int32 m_nSecLevel; + Sequence< SvtSecurityOptions::Certificate > m_seqTrustedAuthors; + sal_Bool m_bDisableMacros; + + sal_Bool m_bROSecureURLs; + sal_Bool m_bROSaveOrSend; + sal_Bool m_bROSigning; + sal_Bool m_bROPrint; + sal_Bool m_bROCreatePDF; + sal_Bool m_bRORemoveInfo; + sal_Bool m_bRORecommendPwd; + sal_Bool m_bROCtrlClickHyperlink; + sal_Bool m_bROSecLevel; + sal_Bool m_bROTrustedAuthors; + sal_Bool m_bRODisableMacros; + + + // xmlsec05 depricated + EBasicSecurityMode m_eBasicMode; + sal_Bool m_bExecutePlugins; + sal_Bool m_bWarning; + sal_Bool m_bConfirmation; + + sal_Bool m_bROConfirmation; + sal_Bool m_bROWarning; + sal_Bool m_bROExecutePlugins; + sal_Bool m_bROBasicMode; + public: + sal_Bool IsWarningEnabled() const; + void SetWarningEnabled( sal_Bool bSet ); + sal_Bool IsConfirmationEnabled() const; + void SetConfirmationEnabled( sal_Bool bSet ); + sal_Bool IsExecutePlugins() const; + void SetExecutePlugins( sal_Bool bSet ); + EBasicSecurityMode GetBasicMode ( ) const ; + void SetBasicMode ( EBasicSecurityMode eMode ) ; +}; + +//_________________________________________________________________________________________________________________ +// definitions +//_________________________________________________________________________________________________________________ + +//***************************************************************************************************************** +// constructor +//***************************************************************************************************************** +SvtSecurityOptions_Impl::SvtSecurityOptions_Impl() + :ConfigItem ( ROOTNODE_SECURITY ) + ,m_seqSecureURLs ( DEFAULT_SECUREURL ) + ,m_bSaveOrSend ( sal_True ) + ,m_bSigning ( sal_True ) + ,m_bPrint ( sal_True ) + ,m_bCreatePDF ( sal_True ) + ,m_bRemoveInfo ( sal_True ) + ,m_nSecLevel ( sal_True ) + ,m_seqTrustedAuthors ( DEFAULT_TRUSTEDAUTHORS ) + ,m_bDisableMacros ( sal_False ) + ,m_bROSecureURLs ( CFG_READONLY_DEFAULT ) + ,m_bROSaveOrSend ( CFG_READONLY_DEFAULT ) + ,m_bROSigning ( CFG_READONLY_DEFAULT ) + ,m_bROPrint ( CFG_READONLY_DEFAULT ) + ,m_bROCreatePDF ( CFG_READONLY_DEFAULT ) + ,m_bRORemoveInfo ( CFG_READONLY_DEFAULT ) + ,m_bROSecLevel ( CFG_READONLY_DEFAULT ) + ,m_bROTrustedAuthors ( CFG_READONLY_DEFAULT ) + ,m_bRODisableMacros ( sal_True ) // currently is not intended to be changed + + // xmlsec05 depricated + , m_eBasicMode ( DEFAULT_STAROFFICEBASIC ) + , m_bExecutePlugins ( sal_True ) + , m_bWarning ( sal_True ) + , m_bConfirmation ( sal_True ) + , m_bROConfirmation ( CFG_READONLY_DEFAULT ) + , m_bROWarning ( CFG_READONLY_DEFAULT ) + , m_bROExecutePlugins ( CFG_READONLY_DEFAULT ) + , m_bROBasicMode ( CFG_READONLY_DEFAULT ) + // xmlsec05 depricated + +{ + Sequence< OUString > seqNames = GetPropertyNames ( ); + Sequence< Any > seqValues = GetProperties ( seqNames ); + Sequence< sal_Bool > seqRO = GetReadOnlyStates ( seqNames ); + + // 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( !(seqNames.getLength()!=seqValues.getLength()), "SvtSecurityOptions_Impl::SvtSecurityOptions_Impl()\nI miss some values of configuration keys!\n" ); + + // Copy values from list in right order to our internal member. + sal_Int32 nPropertyCount = seqValues.getLength(); + for( sal_Int32 nProperty = 0 ; nProperty < nPropertyCount ; ++nProperty ) + SetProperty( nProperty, seqValues[ nProperty ], seqRO[ nProperty ] ); + + LoadAuthors(); + + // Enable notification mechanism of our baseclass. + // We need it to get information about changes outside these class on our used configuration keys!*/ + + EnableNotification( seqNames ); +} + +//***************************************************************************************************************** +// destructor +//***************************************************************************************************************** +SvtSecurityOptions_Impl::~SvtSecurityOptions_Impl() +{ + if( IsModified() ) + Commit(); +} + +void SvtSecurityOptions_Impl::SetProperty( sal_Int32 nProperty, const Any& rValue, sal_Bool bRO ) +{ + switch( nProperty ) + { + case PROPERTYHANDLE_SECUREURL: + { + m_seqSecureURLs.realloc( 0 ); + rValue >>= m_seqSecureURLs; + SvtPathOptions aOpt; + sal_uInt32 nCount = m_seqSecureURLs.getLength(); + for( sal_uInt32 nItem = 0 ; nItem < nCount ; ++nItem ) + m_seqSecureURLs[ nItem ] = aOpt.SubstituteVariable( m_seqSecureURLs[ nItem ] ); + m_bROSecureURLs = bRO; + } + break; + + case PROPERTYHANDLE_DOCWARN_SAVEORSEND: + { + rValue >>= m_bSaveOrSend; + m_bROSaveOrSend = bRO; + } + break; + + case PROPERTYHANDLE_DOCWARN_SIGNING: + { + rValue >>= m_bSigning; + m_bROSigning = bRO; + } + break; + + case PROPERTYHANDLE_DOCWARN_PRINT: + { + rValue >>= m_bPrint; + m_bROPrint = bRO; + } + break; + + case PROPERTYHANDLE_DOCWARN_CREATEPDF: + { + rValue >>= m_bCreatePDF; + m_bROCreatePDF = bRO; + } + break; + + case PROPERTYHANDLE_DOCWARN_REMOVEPERSONALINFO: + { + rValue >>= m_bRemoveInfo; + m_bRORemoveInfo = bRO; + } + break; + + case PROPERTYHANDLE_DOCWARN_RECOMMENDPASSWORD: + { + rValue >>= m_bRecommendPwd; + m_bRORecommendPwd = bRO; + } + break; + + case PROPERTYHANDLE_CTRLCLICK_HYPERLINK: + { + rValue >>= m_bCtrlClickHyperlink; + m_bROCtrlClickHyperlink = bRO; + } + break; + + case PROPERTYHANDLE_MACRO_SECLEVEL: + { + rValue >>= m_nSecLevel; + m_bROSecLevel = bRO; + } + break; + + case PROPERTYHANDLE_MACRO_TRUSTEDAUTHORS: + { + // don't care about value here... + m_bROTrustedAuthors = bRO; + } + break; + + case PROPERTYHANDLE_MACRO_DISABLE: + { + rValue >>= m_bDisableMacros; + m_bRODisableMacros = bRO; + } + break; + + + // xmlsec05 depricated + case PROPERTYHANDLE_STAROFFICEBASIC: + { + sal_Int32 nMode = 0; + rValue >>= nMode; + m_eBasicMode = (EBasicSecurityMode)nMode; + m_bROBasicMode = bRO; + } + break; + case PROPERTYHANDLE_EXECUTEPLUGINS: + { + rValue >>= m_bExecutePlugins; + m_bROExecutePlugins = bRO; + } + break; + case PROPERTYHANDLE_WARNINGENABLED: + { + rValue >>= m_bWarning; + m_bROWarning = bRO; + } + break; + case PROPERTYHANDLE_CONFIRMATIONENABLED: + { + rValue >>= m_bConfirmation; + m_bROConfirmation = bRO; + } + break; + // xmlsec05 depricated + + + #if OSL_DEBUG_LEVEL > 1 + default: + DBG_ASSERT( false, "SvtSecurityOptions_Impl::SetProperty()\nUnkown property!\n" ); + #endif + } +} + +void SvtSecurityOptions_Impl::LoadAuthors( void ) +{ + m_seqTrustedAuthors.realloc( 0 ); // first clear + Sequence< OUString > lAuthors = GetNodeNames( PROPERTYNAME_MACRO_TRUSTEDAUTHORS ); + sal_Int32 c1 = lAuthors.getLength(); + if( c1 ) + { + sal_Int32 c2 = c1 * 3; // 3 Properties inside Struct TrustedAuthor + Sequence< OUString > lAllAuthors( c2 ); + + sal_Int32 i1; + sal_Int32 i2; + OUString aSep( RTL_CONSTASCII_USTRINGPARAM( "/" ) ); + for( i1 = 0, i2 = 0 ; i1 < c1 ; ++i1 ) + { + lAllAuthors[ i2 ] = PROPERTYNAME_MACRO_TRUSTEDAUTHORS + aSep + lAuthors[ i1 ] + aSep + PROPERTYNAME_TRUSTEDAUTHOR_SUBJECTNAME; + ++i2; + lAllAuthors[ i2 ] = PROPERTYNAME_MACRO_TRUSTEDAUTHORS + aSep + lAuthors[ i1 ] + aSep + PROPERTYNAME_TRUSTEDAUTHOR_SERIALNUMBER; + ++i2; + lAllAuthors[ i2 ] = PROPERTYNAME_MACRO_TRUSTEDAUTHORS + aSep + lAuthors[ i1 ] + aSep + PROPERTYNAME_TRUSTEDAUTHOR_RAWDATA; + ++i2; + } + + Sequence< Any > lValues = GetProperties( lAllAuthors ); + if( lValues.getLength() == c2 ) + { + m_seqTrustedAuthors.realloc( c1 ); + SvtSecurityOptions::Certificate aCert( 3 ); + for( i1 = 0, i2 = 0 ; i1 < c1 ; ++i1 ) + { + lValues[ i2 ] >>= aCert[ 0 ]; + ++i2; + lValues[ i2 ] >>= aCert[ 1 ]; + ++i2; + lValues[ i2 ] >>= aCert[ 2 ]; + ++i2; + m_seqTrustedAuthors[ i1 ] = aCert; + } + } + } +} + +sal_Int32 SvtSecurityOptions_Impl::GetHandle( const OUString& rName ) +{ + sal_Int32 nHandle; + + if( rName.compareToAscii( CSTR_SECUREURL ) == 0 ) + nHandle = PROPERTYHANDLE_SECUREURL; + else if( rName.compareToAscii( CSTR_DOCWARN_SAVEORSEND ) == 0 ) + nHandle = PROPERTYHANDLE_DOCWARN_SAVEORSEND; + else if( rName.compareToAscii( CSTR_DOCWARN_SIGNING ) == 0 ) + nHandle = PROPERTYHANDLE_DOCWARN_SIGNING; + else if( rName.compareToAscii( CSTR_DOCWARN_PRINT ) == 0 ) + nHandle = PROPERTYHANDLE_DOCWARN_PRINT; + else if( rName.compareToAscii( CSTR_DOCWARN_CREATEPDF ) == 0 ) + nHandle = PROPERTYHANDLE_DOCWARN_CREATEPDF; + else if( rName.compareToAscii( CSTR_DOCWARN_REMOVEPERSONALINFO ) == 0 ) + nHandle = PROPERTYHANDLE_DOCWARN_REMOVEPERSONALINFO; + else if( rName.compareToAscii( CSTR_DOCWARN_RECOMMENDPASSWORD ) == 0 ) + nHandle = PROPERTYHANDLE_DOCWARN_RECOMMENDPASSWORD; + else if( rName.compareToAscii( CSTR_CTRLCLICK_HYPERLINK ) == 0 ) + nHandle = PROPERTYHANDLE_CTRLCLICK_HYPERLINK; + else if( rName.compareToAscii( CSTR_MACRO_SECLEVEL ) == 0 ) + nHandle = PROPERTYHANDLE_MACRO_SECLEVEL; + else if( rName.compareToAscii( CSTR_MACRO_TRUSTEDAUTHORS ) == 0 ) + nHandle = PROPERTYHANDLE_MACRO_TRUSTEDAUTHORS; + else if( rName.compareToAscii( CSTR_MACRO_DISABLE ) == 0 ) + nHandle = PROPERTYHANDLE_MACRO_DISABLE; + + // xmlsec05 depricated + else if( rName == PROPERTYNAME_STAROFFICEBASIC ) + nHandle = PROPERTYHANDLE_STAROFFICEBASIC; + else if( rName == PROPERTYNAME_EXECUTEPLUGINS ) + nHandle = PROPERTYHANDLE_EXECUTEPLUGINS; + else if( rName == PROPERTYNAME_WARNINGENABLED ) + nHandle = PROPERTYHANDLE_WARNINGENABLED; + else if( rName == PROPERTYNAME_CONFIRMATIONENABLED ) + nHandle = PROPERTYHANDLE_CONFIRMATIONENABLED; + // xmlsec05 depricated + + else + nHandle = PROPERTYHANDLE_INVALID; + + return nHandle; +} + +bool SvtSecurityOptions_Impl::GetOption( SvtSecurityOptions::EOption eOption, sal_Bool*& rpValue, sal_Bool*& rpRO ) +{ + switch( eOption ) + { + case SvtSecurityOptions::E_DOCWARN_SAVEORSEND: + rpValue = &m_bSaveOrSend; + rpRO = &m_bROSaveOrSend; + break; + case SvtSecurityOptions::E_DOCWARN_SIGNING: + rpValue = &m_bSigning; + rpRO = &m_bROSigning; + break; + case SvtSecurityOptions::E_DOCWARN_PRINT: + rpValue = &m_bPrint; + rpRO = &m_bROPrint; + break; + case SvtSecurityOptions::E_DOCWARN_CREATEPDF: + rpValue = &m_bCreatePDF; + rpRO = &m_bROCreatePDF; + break; + case SvtSecurityOptions::E_DOCWARN_REMOVEPERSONALINFO: + rpValue = &m_bRemoveInfo; + rpRO = &m_bRORemoveInfo; + break; + case SvtSecurityOptions::E_DOCWARN_RECOMMENDPASSWORD: + rpValue = &m_bRecommendPwd; + rpRO = &m_bRORecommendPwd; + break; + case SvtSecurityOptions::E_CTRLCLICK_HYPERLINK: + rpValue = &m_bCtrlClickHyperlink; + rpRO = &m_bROCtrlClickHyperlink; + break; + default: + rpValue = NULL; + rpRO = NULL; + break; + } + + return rpValue != NULL; +} + +void SvtSecurityOptions_Impl::Notify( const Sequence< OUString >& seqPropertyNames ) +{ + // Use given list of updated properties to get his values from configuration directly! + Sequence< Any > seqValues = GetProperties( seqPropertyNames ); + Sequence< sal_Bool > seqRO = GetReadOnlyStates( seqPropertyNames ); + // Safe impossible cases. + // We need values from ALL notified configuration keys. + DBG_ASSERT( !(seqPropertyNames.getLength()!=seqValues.getLength()), "SvtSecurityOptions_Impl::Notify()\nI miss some values of configuration keys!\n" ); + // Step over list of property names and get right value from coreesponding value list to set it on internal members! + sal_Int32 nCount = seqPropertyNames.getLength(); + for( sal_Int32 nProperty = 0 ; nProperty < nCount ; ++nProperty ) + SetProperty( GetHandle( seqPropertyNames[ nProperty ] ), seqValues[ nProperty ], seqRO[ nProperty ] ); + + // read set of trusted authors separately + LoadAuthors(); +} + +void SvtSecurityOptions_Impl::Commit() +{ + // Get names of supported properties, create a list for values and copy current values to it. + Sequence< OUString > lOrgNames = GetPropertyNames(); + sal_Int32 nOrgCount = lOrgNames.getLength(); + + Sequence< OUString > lNames(nOrgCount); + Sequence< Any > lValues(nOrgCount); + sal_Int32 nRealCount = 0; + bool bDone; + + ClearNodeSet( PROPERTYNAME_MACRO_TRUSTEDAUTHORS ); + + for( sal_Int32 nProperty = 0 ; nProperty < nOrgCount ; ++nProperty ) + { + switch( nProperty ) + { + case PROPERTYHANDLE_SECUREURL: + { + bDone = !m_bROSecureURLs; + if( bDone ) + { + Sequence< OUString > lURLs( m_seqSecureURLs ); + SvtPathOptions aOpt; + sal_Int32 nURLsCnt = lURLs.getLength(); + for( sal_Int32 nItem = 0 ; nItem < nURLsCnt ; ++nItem ) + lURLs[ nItem ] = aOpt.UseVariable( lURLs[ nItem ] ); + lValues[ nRealCount ] <<= lURLs; + } + } + break; + + case PROPERTYHANDLE_DOCWARN_SAVEORSEND: + { + bDone = !m_bROSaveOrSend; + if( bDone ) + lValues[ nRealCount ] <<= m_bSaveOrSend; + } + break; + + case PROPERTYHANDLE_DOCWARN_SIGNING: + { + bDone = !m_bROSigning; + if( bDone ) + lValues[ nRealCount ] <<= m_bSigning; + } + break; + + case PROPERTYHANDLE_DOCWARN_PRINT: + { + bDone = !m_bROPrint; + if( bDone ) + lValues[ nRealCount ] <<= m_bPrint; + } + break; + + case PROPERTYHANDLE_DOCWARN_CREATEPDF: + { + bDone = !m_bROCreatePDF; + if( bDone ) + lValues[ nRealCount ] <<= m_bCreatePDF; + } + break; + + case PROPERTYHANDLE_DOCWARN_REMOVEPERSONALINFO: + { + bDone = !m_bRORemoveInfo; + if( bDone ) + lValues[ nRealCount ] <<= m_bRemoveInfo; + } + break; + + case PROPERTYHANDLE_DOCWARN_RECOMMENDPASSWORD: + { + bDone = !m_bRORecommendPwd; + if( bDone ) + lValues[ nRealCount ] <<= m_bRecommendPwd; + } + break; + + case PROPERTYHANDLE_CTRLCLICK_HYPERLINK: + { + bDone = !m_bROCtrlClickHyperlink; + if( bDone ) + lValues[ nRealCount ] <<= m_bCtrlClickHyperlink; + } + break; + + case PROPERTYHANDLE_MACRO_SECLEVEL: + { + bDone = !m_bROSecLevel; + if( bDone ) + lValues[ nRealCount ] <<= m_nSecLevel; + } + break; + + case PROPERTYHANDLE_MACRO_TRUSTEDAUTHORS: + { + bDone = !m_bROTrustedAuthors; + if( bDone ) + { + sal_Int32 nCnt = m_seqTrustedAuthors.getLength(); + if( nCnt ) + { + String s; + s.AppendAscii( CSTR_MACRO_TRUSTEDAUTHORS ); + s.AppendAscii( "/a" ); + + Sequence< Sequence< com::sun::star::beans::PropertyValue > > lPropertyValuesSeq( nCnt ); + for( sal_Int32 i = 0 ; i < nCnt ; ++i ) + { + String aPrefix( s ); + aPrefix += String::CreateFromInt32( i ); + aPrefix.AppendAscii( "/" ); + Sequence< com::sun::star::beans::PropertyValue > lPropertyValues( 3 ); + lPropertyValues[ 0 ].Name = aPrefix + PROPERTYNAME_TRUSTEDAUTHOR_SUBJECTNAME; + lPropertyValues[ 0 ].Value <<= m_seqTrustedAuthors[ i ][0]; + lPropertyValues[ 1 ].Name = aPrefix + PROPERTYNAME_TRUSTEDAUTHOR_SERIALNUMBER; + lPropertyValues[ 1 ].Value <<= m_seqTrustedAuthors[ i ][1]; + lPropertyValues[ 2 ].Name = aPrefix + PROPERTYNAME_TRUSTEDAUTHOR_RAWDATA; + lPropertyValues[ 2 ].Value <<= m_seqTrustedAuthors[ i ][2]; + + + SetSetProperties( PROPERTYNAME_MACRO_TRUSTEDAUTHORS, lPropertyValues ); + } + + bDone = false; // because we save in loop above! + } + else + bDone = false; + } + } + break; + + case PROPERTYHANDLE_MACRO_DISABLE: + { + bDone = !m_bRODisableMacros; + if( bDone ) + lValues[ nRealCount ] <<= (sal_Bool)m_bDisableMacros; + } + break; + + + // xmlsec05 depricated + case PROPERTYHANDLE_STAROFFICEBASIC: + { + bDone = !m_bROBasicMode; + if( bDone ) + lValues[ nRealCount ] <<= (sal_Int32)m_eBasicMode; + } + break; + case PROPERTYHANDLE_EXECUTEPLUGINS: + { + bDone = !m_bROExecutePlugins; + if( bDone ) + lValues[ nRealCount ] <<= m_bExecutePlugins; + } + break; + case PROPERTYHANDLE_WARNINGENABLED: + { + bDone = !m_bROWarning; + if( bDone ) + lValues[ nRealCount ] <<= m_bWarning; + } + break; + case PROPERTYHANDLE_CONFIRMATIONENABLED: + { + bDone = !m_bROConfirmation; + if( bDone ) + lValues[ nRealCount ] <<= m_bConfirmation; + } + break; + // xmlsec05 depricated + + + default: + bDone = false; + } + + if( bDone ) + { + lNames[ nRealCount ] = lOrgNames[ nProperty ]; + ++nRealCount; + } + } + // Set properties in configuration. + lNames.realloc(nRealCount); + lValues.realloc(nRealCount); + PutProperties( lNames, lValues ); +} + +sal_Bool SvtSecurityOptions_Impl::IsReadOnly( SvtSecurityOptions::EOption eOption ) const +{ + sal_Bool bReadonly; + switch(eOption) + { + case SvtSecurityOptions::E_SECUREURLS : + bReadonly = m_bROSecureURLs; + break; + case SvtSecurityOptions::E_DOCWARN_SAVEORSEND: + bReadonly = m_bROSaveOrSend; + break; + case SvtSecurityOptions::E_DOCWARN_SIGNING: + bReadonly = m_bROSigning; + break; + case SvtSecurityOptions::E_DOCWARN_PRINT: + bReadonly = m_bROPrint; + break; + case SvtSecurityOptions::E_DOCWARN_CREATEPDF: + bReadonly = m_bROCreatePDF; + break; + case SvtSecurityOptions::E_DOCWARN_REMOVEPERSONALINFO: + bReadonly = m_bRORemoveInfo; + break; + case SvtSecurityOptions::E_DOCWARN_RECOMMENDPASSWORD: + bReadonly = m_bRORecommendPwd; + break; + case SvtSecurityOptions::E_MACRO_SECLEVEL: + bReadonly = m_bROSecLevel; + break; + case SvtSecurityOptions::E_MACRO_TRUSTEDAUTHORS: + bReadonly = m_bROTrustedAuthors; + break; + case SvtSecurityOptions::E_MACRO_DISABLE: + bReadonly = m_bRODisableMacros; + break; + case SvtSecurityOptions::E_CTRLCLICK_HYPERLINK: + bReadonly = m_bROCtrlClickHyperlink; + break; + + + // xmlsec05 depricated + case SvtSecurityOptions::E_BASICMODE: + bReadonly = m_bROBasicMode; + break; + case SvtSecurityOptions::E_EXECUTEPLUGINS: + bReadonly = m_bROExecutePlugins; + break; + case SvtSecurityOptions::E_WARNING: + bReadonly = m_bROWarning; + break; + case SvtSecurityOptions::E_CONFIRMATION: + bReadonly = m_bROConfirmation; + break; + // xmlsec05 depricated + + + default: + bReadonly = sal_True; + } + + return bReadonly; +} + +Sequence< OUString > SvtSecurityOptions_Impl::GetSecureURLs() const +{ + return m_seqSecureURLs; +} + +void SvtSecurityOptions_Impl::SetSecureURLs( const Sequence< OUString >& seqURLList ) +{ + DBG_ASSERT(!m_bROSecureURLs, "SvtSecurityOptions_Impl::SetSecureURLs()\nYou tried to write on a readonly value!\n"); + if (!m_bROSecureURLs && m_seqSecureURLs!=seqURLList) + { + m_seqSecureURLs = seqURLList; + SetModified(); + } +} + +sal_Bool SvtSecurityOptions_Impl::IsSecureURL( const OUString& sURL , + const OUString& sReferer) const +{ + sal_Bool bState = sal_False; + + // Check for uncritical protocols first + // All protocols different from "macro..." and "slot..." are secure per definition and must not be checked. + // "macro://#..." means AppBasic macros that are considered safe + INetURLObject aURL ( sURL ); + INetProtocol aProtocol = aURL.GetProtocol(); + + // All other URLs must checked in combination with referer and internal information about security + if ( (aProtocol != INET_PROT_MACRO && aProtocol != INET_PROT_SLOT) || + aURL.GetMainURL( INetURLObject::NO_DECODE ).matchIgnoreAsciiCaseAsciiL( "macro:///", 9 ) == 0) + { + // security check only for "macro" ( without app basic ) or "slot" protocols + bState = sal_True; + } + else + { + // check list of allowed URL patterns + // Trusted referer given? + // NO => bState will be false per default + // YES => search for it in our internal url list + if( sReferer.getLength() > 0 ) + { + // Search in internal list + ::rtl::OUString sRef = sReferer.toAsciiLowerCase(); + sal_uInt32 nCount = m_seqSecureURLs.getLength(); + for( sal_uInt32 nItem=0; nItem<nCount; ++nItem ) + { + OUString sCheckURL = m_seqSecureURLs[nItem].toAsciiLowerCase(); + sCheckURL += OUString(RTL_CONSTASCII_USTRINGPARAM("*")); + if( WildCard( sCheckURL ).Matches( sRef ) == sal_True ) + { + bState = sal_True; + break; + } + } + + if ( !bState ) + bState = sRef.compareToAscii("private:user") == COMPARE_EQUAL; + } + } + + // Return result of operation. + return bState; +} + +inline sal_Int32 SvtSecurityOptions_Impl::GetMacroSecurityLevel() const +{ + return m_nSecLevel; +} + +inline sal_Bool SvtSecurityOptions_Impl::IsMacroDisabled() const +{ + return m_bDisableMacros; +} + +void SvtSecurityOptions_Impl::SetMacroSecurityLevel( sal_Int32 _nLevel ) +{ + if( !m_bROSecLevel ) + { + if( _nLevel > 3 || _nLevel < 0 ) + _nLevel = 3; + + if( m_nSecLevel != _nLevel ) + { + m_nSecLevel = _nLevel; + SetModified(); + } + } +} + +Sequence< SvtSecurityOptions::Certificate > SvtSecurityOptions_Impl::GetTrustedAuthors() const +{ + return m_seqTrustedAuthors; +} + +void SvtSecurityOptions_Impl::SetTrustedAuthors( const Sequence< SvtSecurityOptions::Certificate >& rAuthors ) +{ + DBG_ASSERT(!m_bROTrustedAuthors, "SvtSecurityOptions_Impl::SetTrustedAuthors()\nYou tried to write on a readonly value!\n"); + if( !m_bROTrustedAuthors && rAuthors != m_seqTrustedAuthors ) + { + m_seqTrustedAuthors = rAuthors; + SetModified(); + } +} + +sal_Bool SvtSecurityOptions_Impl::IsTrustedAuthorsEnabled() +{ + return m_bROTrustedAuthors; +} + +sal_Bool SvtSecurityOptions_Impl::IsOptionSet( SvtSecurityOptions::EOption eOption ) const +{ + sal_Bool* pValue; + sal_Bool* pRO; + sal_Bool bRet = sal_False; + + if( ( const_cast< SvtSecurityOptions_Impl* >( this ) )->GetOption( eOption, pValue, pRO ) ) + bRet = *pValue; + + return bRet; +} + +sal_Bool SvtSecurityOptions_Impl::SetOption( SvtSecurityOptions::EOption eOption, sal_Bool bValue ) +{ + sal_Bool* pValue; + sal_Bool* pRO; + sal_Bool bRet = sal_False; + + if( GetOption( eOption, pValue, pRO ) ) + { + if( !*pRO ) + { + bRet = sal_True; + if( *pValue != bValue ) + { + *pValue = bValue; + SetModified(); + } + } + } + + return bRet; +} + +sal_Bool SvtSecurityOptions_Impl::IsOptionEnabled( SvtSecurityOptions::EOption eOption ) const +{ + sal_Bool* pValue; + sal_Bool* pRO; + sal_Bool bRet = sal_False; + + if( ( const_cast< SvtSecurityOptions_Impl* >( this ) )->GetOption( eOption, pValue, pRO ) ) + bRet = !*pRO; + + return bRet; +} + +Sequence< OUString > SvtSecurityOptions_Impl::GetPropertyNames() +{ + // Build static list of configuration key names. + static const OUString pProperties[] = + { + PROPERTYNAME_SECUREURL, + PROPERTYNAME_STAROFFICEBASIC, + PROPERTYNAME_EXECUTEPLUGINS, + PROPERTYNAME_WARNINGENABLED, + PROPERTYNAME_CONFIRMATIONENABLED, + PROPERTYNAME_DOCWARN_SAVEORSEND, + PROPERTYNAME_DOCWARN_SIGNING, + PROPERTYNAME_DOCWARN_PRINT, + PROPERTYNAME_DOCWARN_CREATEPDF, + PROPERTYNAME_DOCWARN_REMOVEPERSONALINFO, + PROPERTYNAME_DOCWARN_RECOMMENDPASSWORD, + PROPERTYNAME_CTRLCLICK_HYPERLINK, + PROPERTYNAME_MACRO_SECLEVEL, + PROPERTYNAME_MACRO_TRUSTEDAUTHORS, + PROPERTYNAME_MACRO_DISABLE + }; + // Initialize return sequence with these list ... + static const Sequence< OUString > seqPropertyNames( pProperties, PROPERTYCOUNT ); + // ... and return it. + return seqPropertyNames; +} + +//***************************************************************************************************************** +// initialize static member +// DON'T DO IT IN YOUR HEADER! +// see definition for further informations +//***************************************************************************************************************** +SvtSecurityOptions_Impl* SvtSecurityOptions::m_pDataContainer = NULL ; +sal_Int32 SvtSecurityOptions::m_nRefCount = 0 ; + +SvtSecurityOptions::SvtSecurityOptions() +{ + // Global access, must be guarded (multithreading!). + MutexGuard aGuard( GetInitMutex() ); + // Increase ouer refcount ... + ++m_nRefCount; + // ... and initialize ouer data container only if it not already exist! + if( m_pDataContainer == NULL ) + { + RTL_LOGFILE_CONTEXT(aLog, "unotools ( ??? ) ::SvtSecurityOptions_Impl::ctor()"); + m_pDataContainer = new SvtSecurityOptions_Impl; + + ItemHolder1::holdConfigItem(E_SECURITYOPTIONS); + } +} + +SvtSecurityOptions::~SvtSecurityOptions() +{ + // Global access, must be guarded (multithreading!) + MutexGuard aGuard( GetInitMutex() ); + // Decrease ouer refcount. + --m_nRefCount; + // If last instance was deleted ... + // we must destroy ouer static data container! + if( m_nRefCount <= 0 ) + { + delete m_pDataContainer; + m_pDataContainer = NULL; + } +} + +sal_Bool SvtSecurityOptions::IsReadOnly( EOption eOption ) const +{ + MutexGuard aGuard( GetInitMutex() ); + return m_pDataContainer->IsReadOnly(eOption); +} + +Sequence< OUString > SvtSecurityOptions::GetSecureURLs() const +{ + MutexGuard aGuard( GetInitMutex() ); + return m_pDataContainer->GetSecureURLs(); +} + +void SvtSecurityOptions::SetSecureURLs( const Sequence< OUString >& seqURLList ) +{ + MutexGuard aGuard( GetInitMutex() ); + m_pDataContainer->SetSecureURLs( seqURLList ); +} + +sal_Bool SvtSecurityOptions::IsSecureURL( const OUString& sURL , + const OUString& sReferer ) const +{ + MutexGuard aGuard( GetInitMutex() ); + return m_pDataContainer->IsSecureURL( sURL, sReferer ); +} + +sal_Int32 SvtSecurityOptions::GetMacroSecurityLevel() const +{ + MutexGuard aGuard( GetInitMutex() ); + return m_pDataContainer->GetMacroSecurityLevel(); +} + +void SvtSecurityOptions::SetMacroSecurityLevel( sal_Int32 _nLevel ) +{ + MutexGuard aGuard( GetInitMutex() ); + m_pDataContainer->SetMacroSecurityLevel( _nLevel ); +} + +sal_Bool SvtSecurityOptions::IsMacroDisabled() const +{ + MutexGuard aGuard( GetInitMutex() ); + return m_pDataContainer->IsMacroDisabled(); +} + +Sequence< SvtSecurityOptions::Certificate > SvtSecurityOptions::GetTrustedAuthors() const +{ + MutexGuard aGuard( GetInitMutex() ); + return m_pDataContainer->GetTrustedAuthors(); +} + +void SvtSecurityOptions::SetTrustedAuthors( const Sequence< Certificate >& rAuthors ) +{ + MutexGuard aGuard( GetInitMutex() ); + m_pDataContainer->SetTrustedAuthors( rAuthors ); +} + +sal_Bool SvtSecurityOptions::IsTrustedAuthorsEnabled() +{ + MutexGuard aGuard( GetInitMutex() ); + return m_pDataContainer->IsTrustedAuthorsEnabled(); +} + +bool SvtSecurityOptions::IsOptionSet( EOption eOption ) const +{ + MutexGuard aGuard( GetInitMutex() ); + return m_pDataContainer->IsOptionSet( eOption ); +} + +bool SvtSecurityOptions::SetOption( EOption eOption, bool bValue ) +{ + MutexGuard aGuard( GetInitMutex() ); + return m_pDataContainer->SetOption( eOption, bValue ); +} + +bool SvtSecurityOptions::IsOptionEnabled( EOption eOption ) const +{ + MutexGuard aGuard( GetInitMutex() ); + return m_pDataContainer->IsOptionEnabled( eOption ); +} + +Mutex& SvtSecurityOptions::GetInitMutex() +{ + // Initialize static mutex only for one time! + static Mutex* pMutex = NULL; + // If these method first called (Mutex not already exist!) ... + if( pMutex == NULL ) + { + // ... we must create a new one. Protect follow code with the global mutex - + // It must be - we create a static variable! + MutexGuard aGuard( Mutex::getGlobalMutex() ); + // We must check our pointer again - because it can be that another instance of ouer class will be faster then these! + if( pMutex == NULL ) + { + // Create the new mutex and set it for return on static variable. + static Mutex aMutex; + pMutex = &aMutex; + } + } + // Return new created or already existing mutex object. + return *pMutex; +} + + + + +// xmlsec05 depricated + +EBasicSecurityMode SvtSecurityOptions_Impl::GetBasicMode() const +{ + return m_eBasicMode; +} + +void SvtSecurityOptions_Impl::SetBasicMode( EBasicSecurityMode eMode ) +{ + DBG_ASSERT(!m_bROBasicMode, "SvtSecurityOptions_Impl::SetBasicMode()\nYou tried to write on a readonly value!\n"); + if (!m_bROBasicMode && m_eBasicMode!=eMode) + { + m_eBasicMode = eMode; + SetModified(); + } +} + +sal_Bool SvtSecurityOptions_Impl::IsExecutePlugins() const +{ + return m_bExecutePlugins; +} + +void SvtSecurityOptions_Impl::SetExecutePlugins( sal_Bool bSet ) +{ + DBG_ASSERT(!m_bROExecutePlugins, "SvtSecurityOptions_Impl::SetExecutePlugins()\nYou tried to write on a readonly value!\n"); + if (!m_bROExecutePlugins && m_bExecutePlugins!=bSet) + { + m_bExecutePlugins = bSet; + SetModified(); + } +} + +sal_Bool SvtSecurityOptions_Impl::IsWarningEnabled() const +{ + return m_bWarning; +} + +void SvtSecurityOptions_Impl::SetWarningEnabled( sal_Bool bSet ) +{ + DBG_ASSERT(!m_bROWarning, "SvtSecurityOptions_Impl::SetWarningEnabled()\nYou tried to write on a readonly value!\n"); + if (!m_bROWarning && m_bWarning!=bSet) + { + m_bWarning = bSet; + SetModified(); + } +} + +sal_Bool SvtSecurityOptions_Impl::IsConfirmationEnabled() const +{ + return m_bConfirmation; +} + +void SvtSecurityOptions_Impl::SetConfirmationEnabled( sal_Bool bSet ) +{ + DBG_ASSERT(!m_bROConfirmation, "SvtSecurityOptions_Impl::SetConfirmationEnabled()\nYou tried to write on a readonly value!\n"); + if (!m_bROConfirmation && m_bConfirmation!=bSet) + { + m_bConfirmation = bSet; + SetModified(); + } +} + + +sal_Bool SvtSecurityOptions::IsExecutePlugins() const +{ + MutexGuard aGuard( GetInitMutex() ); + return m_pDataContainer->IsExecutePlugins(); +} + +void SvtSecurityOptions::SetExecutePlugins( sal_Bool bSet ) +{ + MutexGuard aGuard( GetInitMutex() ); + m_pDataContainer->SetExecutePlugins( bSet ); +} + +sal_Bool SvtSecurityOptions::IsWarningEnabled() const +{ + MutexGuard aGuard( GetInitMutex() ); + return m_pDataContainer->IsWarningEnabled(); +} + +void SvtSecurityOptions::SetWarningEnabled( sal_Bool bSet ) +{ + MutexGuard aGuard( GetInitMutex() ); + m_pDataContainer->SetWarningEnabled( bSet ); +} + +sal_Bool SvtSecurityOptions::IsConfirmationEnabled() const +{ + MutexGuard aGuard( GetInitMutex() ); + return m_pDataContainer->IsConfirmationEnabled(); +} + +void SvtSecurityOptions::SetConfirmationEnabled( sal_Bool bSet ) +{ + MutexGuard aGuard( GetInitMutex() ); + m_pDataContainer->SetConfirmationEnabled( bSet ); +} + +void SvtSecurityOptions::SetBasicMode( EBasicSecurityMode eMode ) +{ + MutexGuard aGuard( GetInitMutex() ); + m_pDataContainer->SetBasicMode( eMode ); +} + +EBasicSecurityMode SvtSecurityOptions::GetBasicMode() const +{ + MutexGuard aGuard( GetInitMutex() ); + return m_pDataContainer->GetBasicMode(); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/sourceviewconfig.cxx b/unotools/source/config/sourceviewconfig.cxx new file mode 100644 index 000000000000..13978c99b53d --- /dev/null +++ b/unotools/source/config/sourceviewconfig.cxx @@ -0,0 +1,242 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" +#include <unotools/sourceviewconfig.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> +#include <unotools/configitem.hxx> +#include <tools/debug.hxx> +#include <rtl/instance.hxx> + +#include <itemholder1.hxx> + +using namespace utl; +using namespace rtl; +using namespace com::sun::star::uno; +namespace utl +{ +class SourceViewConfig_Impl : public utl::ConfigItem +{ +private: + OUString m_sFontName; + sal_Int16 m_nFontHeight; + sal_Bool m_bProportionalFontOnly; + + void Load(); + + static Sequence< OUString > GetPropertyNames(); + +public: + SourceViewConfig_Impl(); + ~SourceViewConfig_Impl(); + + virtual void Notify( const Sequence< rtl::OUString >& aPropertyNames ); + virtual void Commit(); + + const rtl::OUString& GetFontName() const + {return m_sFontName;} + void SetFontName(const rtl::OUString& rName) + { + if(rName != m_sFontName) + { + m_sFontName = rName; + SetModified(); + } + } + + sal_Int16 GetFontHeight() const + {return m_nFontHeight;} + void SetFontHeight(sal_Int16 nHeight) + { + if(m_nFontHeight != nHeight) + { + m_nFontHeight = nHeight; + SetModified(); + } + } + + sal_Bool IsShowProportionalFontsOnly() const + {return m_bProportionalFontOnly;} + void SetShowProportionalFontsOnly(sal_Bool bSet) + { + if(m_bProportionalFontOnly != bSet) + { + m_bProportionalFontOnly = bSet; + SetModified(); + } + } +}; +// initialization of static members -------------------------------------- +SourceViewConfig_Impl* SourceViewConfig::m_pImplConfig = 0; +sal_Int32 SourceViewConfig::m_nRefCount = 0; +namespace { struct lclMutex : public rtl::Static< ::osl::Mutex, lclMutex > {}; } + +SourceViewConfig_Impl::SourceViewConfig_Impl() : + ConfigItem(OUString(RTL_CONSTASCII_USTRINGPARAM("Office.Common/Font/SourceViewFont"))), + m_nFontHeight(12), + m_bProportionalFontOnly(sal_False) +{ + Load(); +} + +SourceViewConfig_Impl::~SourceViewConfig_Impl() +{ +} + +Sequence< OUString > SourceViewConfig_Impl::GetPropertyNames() +{ + //this list needs exactly to mach the enum PropertyNameIndex + static const char* aPropNames[] = + { + "FontName" // 0 + ,"FontHeight" // 1 + ,"NonProportionalFontsOnly" // 2 + }; + const int nCount = sizeof( aPropNames ) / sizeof( const char* ); + Sequence< OUString > aNames( nCount ); + OUString* pNames = aNames.getArray(); + for ( int i = 0; i < nCount; i++ ) + pNames[i] = OUString::createFromAscii( aPropNames[i] ); + + return aNames; +} + +void SourceViewConfig_Impl::Load() +{ + Sequence< OUString > aNames = GetPropertyNames(); + Sequence< Any > aValues = GetProperties( aNames ); + EnableNotification( aNames ); + const Any* pValues = aValues.getConstArray(); + DBG_ASSERT( aValues.getLength() == aNames.getLength(), "GetProperties failed" ); + if ( aValues.getLength() == aNames.getLength() ) + { + for ( int nProp = 0; nProp < aNames.getLength(); nProp++ ) + { + if ( pValues[nProp].hasValue() ) + { + switch( nProp ) + { + case 0: pValues[nProp] >>= m_sFontName; break; + case 1: pValues[nProp] >>= m_nFontHeight; break; + case 2: pValues[nProp] >>= m_bProportionalFontOnly; break; + } + } + } + } +} + +void SourceViewConfig_Impl::Notify( const Sequence< OUString >& ) +{ + Load(); +} + +void SourceViewConfig_Impl::Commit() +{ + ClearModified(); + Sequence< OUString > aNames = GetPropertyNames(); + Sequence< Any > aValues( aNames.getLength() ); + Any* pValues = aValues.getArray(); + for ( int nProp = 0; nProp < aNames.getLength(); nProp++ ) + { + switch( nProp ) + { + case 0: pValues[nProp] <<= m_sFontName; break; + case 1: pValues[nProp] <<= m_nFontHeight; break; + case 2: pValues[nProp] <<= m_bProportionalFontOnly; break; + default: + DBG_ERRORFILE( "invalid index to save a user token" ); + } + } + PutProperties( aNames, aValues ); + + NotifyListeners(0); +} + +SourceViewConfig::SourceViewConfig() +{ + { + ::osl::MutexGuard aGuard( lclMutex::get() ); + if(!m_pImplConfig) + { + m_pImplConfig = new SourceViewConfig_Impl; + ItemHolder1::holdConfigItem(E_SOURCEVIEWCONFIG); + } + + ++m_nRefCount; + } + + m_pImplConfig->AddListener( this ); +} + +SourceViewConfig::~SourceViewConfig() +{ + m_pImplConfig->RemoveListener( this ); + ::osl::MutexGuard aGuard( lclMutex::get() ); + if( !--m_nRefCount ) + { + if( m_pImplConfig->IsModified() ) + m_pImplConfig->Commit(); + DELETEZ( m_pImplConfig ); + } +} + +const OUString& SourceViewConfig::GetFontName() const +{ + return m_pImplConfig->GetFontName(); +} + +void SourceViewConfig::SetFontName(const OUString& rName) +{ + m_pImplConfig->SetFontName(rName); +} + +sal_Int16 SourceViewConfig::GetFontHeight() const +{ + return m_pImplConfig->GetFontHeight(); +} + +void SourceViewConfig::SetFontHeight(sal_Int16 nHeight) +{ + m_pImplConfig->SetFontHeight(nHeight); +} + +sal_Bool SourceViewConfig::IsShowProportionalFontsOnly() const +{ + return m_pImplConfig->IsShowProportionalFontsOnly(); +} + +void SourceViewConfig::SetShowProportionalFontsOnly(sal_Bool bSet) +{ + m_pImplConfig->SetShowProportionalFontsOnly(bSet); +} +} +// namespace utl + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/startoptions.cxx b/unotools/source/config/startoptions.cxx new file mode 100644 index 000000000000..98d17b9a739b --- /dev/null +++ b/unotools/source/config/startoptions.cxx @@ -0,0 +1,455 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" + +#include <unotools/startoptions.hxx> +#include <unotools/configmgr.hxx> +#include <unotools/configitem.hxx> +#include <tools/debug.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> + +#include <rtl/logfile.hxx> +#include "itemholder1.hxx" +//_________________________________________________________________________________________________________________ +// namespaces +//_________________________________________________________________________________________________________________ + +using namespace ::utl ; +using namespace ::rtl ; +using namespace ::osl ; +using namespace ::com::sun::star::uno ; + +//_________________________________________________________________________________________________________________ +// const +//_________________________________________________________________________________________________________________ + +#define DEFAULT_SHOWINTRO sal_True +#define DEFAULT_CONNECTIONURL OUString() + +#define ROOTNODE_START OUString(RTL_CONSTASCII_USTRINGPARAM("Setup/Office" )) +#define PROPERTYNAME_SHOWINTRO OUString(RTL_CONSTASCII_USTRINGPARAM("ooSetupShowIntro" )) +#define PROPERTYNAME_CONNECTIONURL OUString(RTL_CONSTASCII_USTRINGPARAM("ooSetupConnectionURL" )) + +#define PROPERTYHANDLE_SHOWINTRO 0 +#define PROPERTYHANDLE_CONNECTIONURL 1 + +#define PROPERTYCOUNT 2 + +//_________________________________________________________________________________________________________________ +// private declarations! +//_________________________________________________________________________________________________________________ + +class SvtStartOptions_Impl : public ConfigItem +{ + //------------------------------------------------------------------------------------------------------------- + // public methods + //------------------------------------------------------------------------------------------------------------- + + public: + + //--------------------------------------------------------------------------------------------------------- + // constructor / destructor + //--------------------------------------------------------------------------------------------------------- + + SvtStartOptions_Impl(); + ~SvtStartOptions_Impl(); + + //--------------------------------------------------------------------------------------------------------- + // overloaded methods of baseclass + //--------------------------------------------------------------------------------------------------------- + + /*-****************************************************************************************************//** + @short called for notify of configmanager + @descr These method is called from the ConfigManager before application ends or from the + PropertyChangeListener if the sub tree broadcasts changes. You must update your + internal values. + + @ATTENTION We don't implement these method - because we support readonly values at runtime only! + + @seealso baseclass ConfigItem + + @param "seqPropertyNames" is the list of properties which should be updated. + @return - + + @onerror - + *//*-*****************************************************************************************************/ + + virtual void Notify( const Sequence< OUString >& seqPropertyNames ); + + /*-****************************************************************************************************//** + @short write changes to configuration + @descr These method writes the changed values into the sub tree + and should always called in our destructor to guarantee consistency of config data. + + @ATTENTION We don't implement these method - because we support readonly values at runtime only! + + @seealso baseclass ConfigItem + + @param - + @return - + + @onerror - + *//*-*****************************************************************************************************/ + + virtual void Commit(); + + //--------------------------------------------------------------------------------------------------------- + // public interface + //--------------------------------------------------------------------------------------------------------- + + /*-****************************************************************************************************//** + @short access method to get internal values + @descr These method give us a chance to regulate acces to ouer internal values. + It's not used in the moment - but it's possible for the feature! + + @seealso - + + @param - + @return - + + @onerror - + *//*-*****************************************************************************************************/ + + sal_Bool IsIntroEnabled ( ) const ; + void EnableIntro ( sal_Bool bState ) ; + OUString GetConnectionURL( ) const ; + void SetConnectionURL( const OUString& sURL ) ; + + //------------------------------------------------------------------------------------------------------------- + // private methods + //------------------------------------------------------------------------------------------------------------- + + private: + + /*-****************************************************************************************************//** + @short return list of fix key names of ouer configuration management which represent oue module tree + @descr These methods return a static const list of key names. We need it to get needed values from our + configuration management. We return well known key names only - because the "UserData" node + is handled in a special way! + + @seealso - + + @param - + @return A list of needed configuration keys is returned. + + @onerror - + *//*-*****************************************************************************************************/ + + static Sequence< OUString > impl_GetPropertyNames(); + + //------------------------------------------------------------------------------------------------------------- + // private member + //------------------------------------------------------------------------------------------------------------- + + private: + + sal_Bool m_bShowIntro ; /// cache "ShowIntro" of Start section + OUString m_sConnectionURL ; /// cache "Connection" of Start section +}; + +//_________________________________________________________________________________________________________________ +// definitions +//_________________________________________________________________________________________________________________ + +//***************************************************************************************************************** +// constructor +//***************************************************************************************************************** +SvtStartOptions_Impl::SvtStartOptions_Impl() + // Init baseclasses first + : ConfigItem ( ROOTNODE_START ) + // Init member then. + , m_bShowIntro ( DEFAULT_SHOWINTRO ) +{ + // Use our static list of configuration keys to get his values. + Sequence< OUString > seqNames = impl_GetPropertyNames(); + Sequence< Any > seqValues = GetProperties( seqNames ) ; + + // 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( !(seqNames.getLength()!=seqValues.getLength()), "SvtStartOptions_Impl::SvtStartOptions_Impl()\nI miss some values of configuration keys!\n" ); + + // Copy values from list in right order to ouer internal member. + sal_Int32 nPropertyCount = seqValues.getLength() ; + sal_Int32 nProperty = 0 ; + for( nProperty=0; nProperty<nPropertyCount; ++nProperty ) + { + // Safe impossible cases. + // Check any for valid value. + DBG_ASSERT( !(seqValues[nProperty].hasValue()==sal_False), "SvtStartOptions_Impl::SvtStartOptions_Impl()\nInvalid property value for property detected!\n" ); + switch( nProperty ) + { + case PROPERTYHANDLE_SHOWINTRO : { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtStartOptions_Impl::SvtStartOptions_Impl()\nWho has changed the value type of \"Office.Common\\Start\\ShowIntro\"?" ); + seqValues[nProperty] >>= m_bShowIntro; + } + break; + + case PROPERTYHANDLE_CONNECTIONURL : { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_STRING), "SvtStartOptions_Impl::SvtStartOptions_Impl()\nWho has changed the value type of \"Office.Common\\Start\\Connection\"?" ); + seqValues[nProperty] >>= m_sConnectionURL; + } + break; + } + } + + // Don't enable notification mechanism of ouer baseclass! + // We support readonly variables in the moment. +} + +//***************************************************************************************************************** +// destructor +//***************************************************************************************************************** +SvtStartOptions_Impl::~SvtStartOptions_Impl() +{ + // We must save our current values .. if user forget it! + if( IsModified() == sal_True ) + { + Commit(); + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtStartOptions_Impl::Notify( const Sequence< OUString >& seqPropertyNames ) +{ + // Use given list of updated properties to get his values from configuration directly! + Sequence< Any > seqValues = GetProperties( seqPropertyNames ); + // Safe impossible cases. + // We need values from ALL notified configuration keys. + DBG_ASSERT( !(seqPropertyNames.getLength()!=seqValues.getLength()), "SvtStartOptions_Impl::Notify()\nI miss some values of configuration keys!\n" ); + // Step over list of property names and get right value from coreesponding value list to set it on internal members! + sal_Int32 nCount = seqPropertyNames.getLength(); + for( sal_Int32 nProperty=0; nProperty<nCount; ++nProperty ) + { + if( seqPropertyNames[nProperty] == PROPERTYNAME_SHOWINTRO ) + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtStartOptions_Impl::Notify()\nWho has changed the value type of \"Office.Common\\Start\\ShowIntro\"?" ); + seqValues[nProperty] >>= m_bShowIntro; + } + else + if( seqPropertyNames[nProperty] == PROPERTYNAME_CONNECTIONURL ) + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_STRING), "SvtStartOptions_Impl::Notify()\nWho has changed the value type of \"Office.Common\\Start\\Connection\"?" ); + seqValues[nProperty] >>= m_sConnectionURL; + } + #if OSL_DEBUG_LEVEL > 1 + else DBG_ASSERT( sal_False, "SvtStartOptions_Impl::Notify()\nUnkown property detected ... I can't handle these!\n" ); + #endif + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtStartOptions_Impl::Commit() +{ + // Get names of supported properties, create a list for values and copy current values to it. + Sequence< OUString > seqNames = impl_GetPropertyNames(); + sal_Int32 nCount = seqNames.getLength(); + Sequence< Any > seqValues ( nCount ); + for( sal_Int32 nProperty=0; nProperty<nCount; ++nProperty ) + { + switch( nProperty ) + { + case PROPERTYHANDLE_SHOWINTRO : { + seqValues[nProperty] <<= m_bShowIntro; + } + break; + case PROPERTYHANDLE_CONNECTIONURL : { + seqValues[nProperty] <<= m_sConnectionURL; + } + break; + } + } + // Set properties in configuration. + PutProperties( seqNames, seqValues ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Bool SvtStartOptions_Impl::IsIntroEnabled() const +{ + return m_bShowIntro; +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtStartOptions_Impl::EnableIntro( sal_Bool bState ) +{ + m_bShowIntro = bState; + SetModified(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +OUString SvtStartOptions_Impl::GetConnectionURL() const +{ + return m_sConnectionURL; +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtStartOptions_Impl::SetConnectionURL( const OUString& sURL ) +{ + m_sConnectionURL = sURL; + SetModified(); +} + +//***************************************************************************************************************** +// private method +//***************************************************************************************************************** +Sequence< OUString > SvtStartOptions_Impl::impl_GetPropertyNames() +{ + // Build static list of configuration key names. + static const OUString pProperties[] = + { + PROPERTYNAME_SHOWINTRO , + PROPERTYNAME_CONNECTIONURL , + }; + // Initialize return sequence with these list ... + static const Sequence< OUString > seqPropertyNames( pProperties, PROPERTYCOUNT ); + // ... and return it. + return seqPropertyNames; +} + +//***************************************************************************************************************** +// initialize static member +// DON'T DO IT IN YOUR HEADER! +// see definition for further informations +//***************************************************************************************************************** +SvtStartOptions_Impl* SvtStartOptions::m_pDataContainer = NULL ; +sal_Int32 SvtStartOptions::m_nRefCount = 0 ; + +//***************************************************************************************************************** +// constructor +//***************************************************************************************************************** +SvtStartOptions::SvtStartOptions() +{ + // Global access, must be guarded (multithreading!). + MutexGuard aGuard( GetOwnStaticMutex() ); + // Increase ouer refcount ... + ++m_nRefCount; + // ... and initialize ouer data container only if it not already! + if( m_pDataContainer == NULL ) + { + RTL_LOGFILE_CONTEXT(aLog, "unotools ( ??? ) ::SvtStartOptions_Impl::ctor()"); + m_pDataContainer = new SvtStartOptions_Impl(); + + ItemHolder1::holdConfigItem(E_STARTOPTIONS); + } +} + +//***************************************************************************************************************** +// destructor +//***************************************************************************************************************** +SvtStartOptions::~SvtStartOptions() +{ + // Global access, must be guarded (multithreading!) + MutexGuard aGuard( GetOwnStaticMutex() ); + // Decrease ouer refcount. + --m_nRefCount; + // If last instance was deleted ... + // we must destroy ouer static data container! + if( m_nRefCount <= 0 ) + { + delete m_pDataContainer; + m_pDataContainer = NULL; + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Bool SvtStartOptions::IsIntroEnabled() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->IsIntroEnabled(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtStartOptions::EnableIntro( sal_Bool bState ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->EnableIntro( bState ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +OUString SvtStartOptions::GetConnectionURL() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->GetConnectionURL(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtStartOptions::SetConnectionURL( const OUString& sURL ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetConnectionURL( sURL ); +} + +//***************************************************************************************************************** +// private method +//***************************************************************************************************************** +Mutex& SvtStartOptions::GetOwnStaticMutex() +{ + // Initialize static mutex only for one time! + static Mutex* pMutex = NULL; + // If these method first called (Mutex not already exist!) ... + if( pMutex == NULL ) + { + // ... we must create a new one. Protect follow code with the global mutex - + // It must be - we create a static variable! + MutexGuard aGuard( Mutex::getGlobalMutex() ); + // We must check our pointer again - because it can be that another instance of ouer class will be fastr then these! + if( pMutex == NULL ) + { + // Create the new mutex and set it for return on static variable. + static Mutex aMutex; + pMutex = &aMutex; + } + } + // Return new created or already existing mutex object. + return *pMutex; +} + +/* 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 000000000000..fdafb7228833 --- /dev/null +++ b/unotools/source/config/syslocaleoptions.cxx @@ -0,0 +1,697 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" + +#include <com/sun/star/uno/Sequence.hxx> +#include <rtl/ustrbuf.hxx> +#include <rtl/instance.hxx> +#include <rtl/logfile.hxx> +#include <i18npool/mslangid.hxx> +#include <tools/string.hxx> +#include <tools/debug.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 sal_False + +using namespace osl; +using namespace utl; +using namespace rtl; +using namespace com::sun::star::uno; +using namespace com::sun::star::lang; + + +SvtSysLocaleOptions_Impl* SvtSysLocaleOptions::pOptions = NULL; +sal_Int32 SvtSysLocaleOptions::nRefCount = 0; +namespace +{ + struct CurrencyChangeLink + : public rtl::Static<Link, CurrencyChangeLink> {}; +} + +com::sun::star::lang::Locale lcl_str_to_locale( const ::rtl::OUString rStr ) +{ + com::sun::star::lang::Locale aRet; + if ( rStr.getLength() ) + { + aRet = com::sun::star::lang::Locale(); + sal_Int32 nSep = rStr.indexOf('-'); + if (nSep < 0) + aRet.Language = rStr; + else + { + aRet.Language = rStr.copy(0, nSep); + if (nSep < rStr.getLength()) + aRet.Country = rStr.copy(nSep+1, rStr.getLength() - (nSep+1)); + } + } + + return aRet; +} + +class SvtSysLocaleOptions_Impl : public utl::ConfigItem +{ + Locale m_aRealLocale; + Locale m_aRealUILocale; + LanguageType m_eRealLanguage; + LanguageType m_eRealUILanguage; + 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 + ULONG m_nBlockedHint; // pending hints + sal_Bool m_bDecimalSeparator; //use decimal separator same as locale + + sal_Bool m_bROLocale; + sal_Bool m_bROUILocale; + sal_Bool m_bROCurrency; + sal_Bool m_bRODecimalSeparator; + + static const Sequence< /* const */ OUString > GetPropertyNames(); + void MakeRealLocale(); + void MakeRealUILocale(); + +public: + SvtSysLocaleOptions_Impl(); + virtual ~SvtSysLocaleOptions_Impl(); + + virtual void Notify( const com::sun::star::uno::Sequence< rtl::OUString >& aPropertyNames ); + virtual void Commit(); + + const OUString& GetLocaleString() const + { return m_aLocaleString; } + void SetLocaleString( const OUString& rStr ); + + const OUString& GetUILocaleString() const + { return m_aUILocaleString; } + void SetUILocaleString( const OUString& rStr ); + + const OUString& GetCurrencyString() const + { return m_aCurrencyString; } + void SetCurrencyString( const OUString& rStr ); + + sal_Bool IsDecimalSeparatorAsLocale() const { return m_bDecimalSeparator;} + void SetDecimalSeparatorAsLocale( sal_Bool bSet); + + sal_Bool IsReadOnly( SvtSysLocaleOptions::EOption eOption ) const; + const Locale& GetRealLocale() { return m_aRealLocale; } + const Locale& GetRealUILocale() { return m_aRealUILocale; } + LanguageType GetRealLanguage() { return m_eRealLanguage; } + LanguageType GetRealUILanguage() { return m_eRealUILanguage; } +}; + + +#define ROOTNODE_SYSLOCALE OUString(RTL_CONSTASCII_USTRINGPARAM("Setup/L10N")) + +#define PROPERTYNAME_LOCALE OUString(RTL_CONSTASCII_USTRINGPARAM("ooSetupSystemLocale")) +#define PROPERTYNAME_UILOCALE OUString(RTL_CONSTASCII_USTRINGPARAM("ooLocale")) +#define PROPERTYNAME_CURRENCY OUString(RTL_CONSTASCII_USTRINGPARAM("ooSetupCurrency")) +#define PROPERTYNAME_DECIMALSEPARATOR OUString(RTL_CONSTASCII_USTRINGPARAM("DecimalSeparatorAsLocale")) + +#define PROPERTYHANDLE_LOCALE 0 +#define PROPERTYHANDLE_UILOCALE 1 +#define PROPERTYHANDLE_CURRENCY 2 +#define PROPERTYHANDLE_DECIMALSEPARATOR 3 + +#define PROPERTYCOUNT 4 + +const Sequence< OUString > SvtSysLocaleOptions_Impl::GetPropertyNames() +{ + static const OUString pProperties[] = + { + PROPERTYNAME_LOCALE, + PROPERTYNAME_UILOCALE, + PROPERTYNAME_CURRENCY, + PROPERTYNAME_DECIMALSEPARATOR + }; + static const Sequence< OUString > seqPropertyNames( pProperties, PROPERTYCOUNT ); + return seqPropertyNames; +} + +// ----------------------------------------------------------------------- + +SvtSysLocaleOptions_Impl::SvtSysLocaleOptions_Impl() + : ConfigItem( ROOTNODE_SYSLOCALE ) + , m_nBlockedHint( 0 ) + , m_bDecimalSeparator( sal_True ) + , m_bROLocale(CFG_READONLY_DEFAULT) + , m_bROUILocale(CFG_READONLY_DEFAULT) + , m_bROCurrency(CFG_READONLY_DEFAULT) + , m_bRODecimalSeparator(sal_False) + +{ + if ( IsValidConfigMgr() ) + { + 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++ ) + { + DBG_ASSERT( pValues[nProp].hasValue(), "property value missing" ); + if ( pValues[nProp].hasValue() ) + { + switch ( nProp ) + { + case PROPERTYHANDLE_LOCALE : + { + OUString aStr; + if ( pValues[nProp] >>= aStr ) + m_aLocaleString = aStr; + else + { + DBG_ERRORFILE( "Wrong property type!" ); + } + m_bROLocale = pROStates[nProp]; + } + break; + case PROPERTYHANDLE_UILOCALE : + { + OUString aStr; + if ( pValues[nProp] >>= aStr ) + m_aUILocaleString = aStr; + else + { + DBG_ERRORFILE( "Wrong property type!" ); + } + m_bROUILocale = pROStates[nProp]; + } + break; + case PROPERTYHANDLE_CURRENCY : + { + OUString aStr; + if ( pValues[nProp] >>= aStr ) + m_aCurrencyString = aStr; + else + { + DBG_ERRORFILE( "Wrong property type!" ); + } + m_bROCurrency = pROStates[nProp]; + } + break; + case PROPERTYHANDLE_DECIMALSEPARATOR: + { + sal_Bool bValue = sal_Bool(); + if ( pValues[nProp] >>= bValue ) + m_bDecimalSeparator = bValue; + else + { + DBG_ERRORFILE( "Wrong property type!" ); + } + m_bRODecimalSeparator = pROStates[nProp]; + } + break; + default: + DBG_ERRORFILE( "Wrong property type!" ); + } + } + } + } +// UpdateMiscSettings_Impl(); + EnableNotification( aNames ); + } + + MakeRealLocale(); + MakeRealUILocale(); +} + + +SvtSysLocaleOptions_Impl::~SvtSysLocaleOptions_Impl() +{ + if ( IsModified() ) + Commit(); +} + +void SvtSysLocaleOptions_Impl::MakeRealLocale() +{ + m_aRealLocale = lcl_str_to_locale( m_aLocaleString ); + if ( m_aRealLocale.Language.getLength() ) + { + m_eRealLanguage = MsLangId::convertLocaleToLanguage( m_aRealLocale ); + } + else + { + m_eRealLanguage = MsLangId::getSystemLanguage(); + MsLangId::convertLanguageToLocale( m_eRealLanguage, m_aRealLocale ); + } +} + +void SvtSysLocaleOptions_Impl::MakeRealUILocale() +{ + if ( !m_aRealUILocale.Language.getLength() ) + { + // as we can't switch UILocale at runtime, we only store changes in the configuration + m_aRealUILocale = lcl_str_to_locale( m_aUILocaleString ); + if ( m_aRealUILocale.Language.getLength() ) + { + m_eRealUILanguage = MsLangId::convertLocaleToLanguage( m_aRealUILocale ); + } + else + { + m_eRealUILanguage = MsLangId::getSystemUILanguage(); + MsLangId::convertLanguageToLocale( m_eRealUILanguage, m_aRealUILocale ); + } + } +} + +sal_Bool SvtSysLocaleOptions_Impl::IsReadOnly( SvtSysLocaleOptions::EOption eOption ) const +{ + sal_Bool bReadOnly = CFG_READONLY_DEFAULT; + switch(eOption) + { + case SvtSysLocaleOptions::E_LOCALE : + { + bReadOnly = m_bROLocale; + break; + } + case SvtSysLocaleOptions::E_UILOCALE : + { + bReadOnly = m_bROUILocale; + break; + } + case SvtSysLocaleOptions::E_CURRENCY : + { + bReadOnly = m_bROCurrency; + break; + } + } + return bReadOnly; +} + + +void SvtSysLocaleOptions_Impl::Commit() +{ + 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; + default: + DBG_ERRORFILE( "invalid index to save a path" ); + } + } + aNames.realloc(nRealCount); + aValues.realloc(nRealCount); + PutProperties( aNames, aValues ); + ClearModified(); +} + + +void SvtSysLocaleOptions_Impl::SetLocaleString( const OUString& rStr ) +{ + if (!m_bROLocale && rStr != m_aLocaleString ) + { + m_aLocaleString = rStr; + MakeRealLocale(); + MsLangId::setConfiguredSystemLanguage( m_eRealLanguage ); + SetModified(); + ULONG nHint = SYSLOCALEOPTIONS_HINT_LOCALE; + if ( !m_aCurrencyString.getLength() ) + nHint |= SYSLOCALEOPTIONS_HINT_CURRENCY; + NotifyListeners( nHint ); + } +} + +void SvtSysLocaleOptions_Impl::SetUILocaleString( const OUString& rStr ) +{ + if (!m_bROUILocale && rStr != m_aUILocaleString ) + { + m_aUILocaleString = rStr; +/* + // as we can't switch UILocale at runtime, we only store changes in the configuration + MakeRealUILocale(); + MsLangId::setConfiguredSystemLanguage( m_eRealUILanguage ); + SetModified(); + NotifyListeners( SYSLOCALEOPTIONS_HINT_UILOCALE ); +*/ + } +} + +void SvtSysLocaleOptions_Impl::SetCurrencyString( const OUString& rStr ) +{ + if (!m_bROCurrency && rStr != m_aCurrencyString ) + { + m_aCurrencyString = rStr; + SetModified(); + NotifyListeners( SYSLOCALEOPTIONS_HINT_CURRENCY ); + } +} + +void SvtSysLocaleOptions_Impl::SetDecimalSeparatorAsLocale( sal_Bool bSet) +{ + if(bSet != m_bDecimalSeparator) + { + m_bDecimalSeparator = bSet; + SetModified(); + NotifyListeners( SYSLOCALEOPTIONS_HINT_DECSEP ); + } +} + +void SvtSysLocaleOptions_Impl::Notify( const Sequence< rtl::OUString >& seqPropertyNames ) +{ + ULONG nHint = 0; + 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 |= SYSLOCALEOPTIONS_HINT_LOCALE; + if ( !m_aCurrencyString.getLength() ) + nHint |= SYSLOCALEOPTIONS_HINT_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 |= SYSLOCALEOPTIONS_HINT_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 |= SYSLOCALEOPTIONS_HINT_CURRENCY; + } + else if( seqPropertyNames[nProp] == PROPERTYNAME_DECIMALSEPARATOR ) + { + seqValues[nProp] >>= m_bDecimalSeparator; + m_bRODecimalSeparator = seqROStates[nProp]; + } + } + if ( nHint ) + NotifyListeners( nHint ); +} + +// ==================================================================== + +SvtSysLocaleOptions::SvtSysLocaleOptions() +{ + MutexGuard aGuard( GetMutex() ); + if ( !pOptions ) + { + RTL_LOGFILE_CONTEXT(aLog, "svl ( ??? ) ::SvtSysLocaleOptions_Impl::ctor()"); + pOptions = new SvtSysLocaleOptions_Impl; + + ItemHolder1::holdConfigItem(E_SYSLOCALEOPTIONS); + } + ++nRefCount; + pOptions->AddListener(this); +} + + +SvtSysLocaleOptions::~SvtSysLocaleOptions() +{ + MutexGuard aGuard( GetMutex() ); + pOptions->RemoveListener(this); + if ( !--nRefCount ) + { + delete pOptions; + pOptions = NULL; + } +} + + +// static +Mutex& SvtSysLocaleOptions::GetMutex() +{ + static Mutex* pMutex = NULL; + if( !pMutex ) + { + MutexGuard aGuard( Mutex::getGlobalMutex() ); + if( !pMutex ) + { + // #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!! + pMutex = new Mutex; + } + } + return *pMutex; +} + + +sal_Bool SvtSysLocaleOptions::IsModified() +{ + MutexGuard aGuard( GetMutex() ); + return pOptions->IsModified(); +} + + +void SvtSysLocaleOptions::Commit() +{ + MutexGuard aGuard( GetMutex() ); + pOptions->Commit(); +} + + +void SvtSysLocaleOptions::BlockBroadcasts( bool bBlock ) +{ + MutexGuard aGuard( GetMutex() ); + pOptions->BlockBroadcasts( bBlock ); +} + + +const OUString& SvtSysLocaleOptions::GetLocaleConfigString() const +{ + MutexGuard aGuard( GetMutex() ); + return pOptions->GetLocaleString(); +} + +void SvtSysLocaleOptions::SetLocaleConfigString( const OUString& rStr ) +{ + MutexGuard aGuard( GetMutex() ); + pOptions->SetLocaleString( rStr ); +} + +const OUString& SvtSysLocaleOptions::GetUILocaleConfigString() const +{ + MutexGuard aGuard( GetMutex() ); + return pOptions->GetUILocaleString(); +} + +void SvtSysLocaleOptions::SetUILocaleConfigString( const OUString& rStr ) +{ + MutexGuard aGuard( GetMutex() ); + pOptions->SetUILocaleString( rStr ); +} + +const OUString& SvtSysLocaleOptions::GetCurrencyConfigString() const +{ + MutexGuard aGuard( GetMutex() ); + return pOptions->GetCurrencyString(); +} + + +void SvtSysLocaleOptions::SetCurrencyConfigString( const OUString& rStr ) +{ + MutexGuard aGuard( GetMutex() ); + pOptions->SetCurrencyString( rStr ); +} + +sal_Bool SvtSysLocaleOptions::IsDecimalSeparatorAsLocale() const +{ + MutexGuard aGuard( GetMutex() ); + return pOptions->IsDecimalSeparatorAsLocale(); +} + +void SvtSysLocaleOptions::SetDecimalSeparatorAsLocale( sal_Bool bSet) +{ + MutexGuard aGuard( GetMutex() ); + pOptions->SetDecimalSeparatorAsLocale(bSet); +} + + +sal_Bool SvtSysLocaleOptions::IsReadOnly( EOption eOption ) const +{ + MutexGuard aGuard( GetMutex() ); + return pOptions->IsReadOnly( eOption ); +} + +// static +void SvtSysLocaleOptions::GetCurrencyAbbrevAndLanguage( String& rAbbrev, + LanguageType& eLang, const ::rtl::OUString& rConfigString ) +{ + sal_Int32 nDelim = rConfigString.indexOf( '-' ); + if ( nDelim >= 0 ) + { + rAbbrev = rConfigString.copy( 0, nDelim ); + String aIsoStr( rConfigString.copy( nDelim+1 ) ); + eLang = MsLangId::convertIsoStringToLanguage( aIsoStr ); + } + else + { + rAbbrev = rConfigString; + eLang = (rAbbrev.Len() ? LANGUAGE_NONE : LANGUAGE_SYSTEM); + } +} + + +// static +::rtl::OUString SvtSysLocaleOptions::CreateCurrencyConfigString( + const String& rAbbrev, LanguageType eLang ) +{ + String aIsoStr( MsLangId::convertLanguageToIsoString( eLang ) ); + if ( aIsoStr.Len() ) + { + ::rtl::OUStringBuffer aStr( rAbbrev.Len() + 1 + aIsoStr.Len() ); + aStr.append( rAbbrev.GetBuffer(), rAbbrev.Len() ); + aStr.append( sal_Unicode('-') ); + aStr.append( aIsoStr.GetBuffer(), aIsoStr.Len() ); + return aStr.makeStringAndClear(); + } + else + return rAbbrev; +} + + +// static +void SvtSysLocaleOptions::SetCurrencyChangeLink( const Link& rLink ) +{ + MutexGuard aGuard( GetMutex() ); + DBG_ASSERT( !CurrencyChangeLink::get().IsSet(), "SvtSysLocaleOptions::SetCurrencyChangeLink: already set" ); + CurrencyChangeLink::get() = rLink; +} + + +// static +const Link& SvtSysLocaleOptions::GetCurrencyChangeLink() +{ + MutexGuard aGuard( GetMutex() ); + return CurrencyChangeLink::get(); +} + + +void SvtSysLocaleOptions::ConfigurationChanged( utl::ConfigurationBroadcaster* p, sal_uInt32 nHint ) +{ + if ( nHint & SYSLOCALEOPTIONS_HINT_CURRENCY ) + { + const Link& rLink = GetCurrencyChangeLink(); + if ( rLink.IsSet() ) + rLink.Call( NULL ); + } + + ::utl::detail::Options::ConfigurationChanged( p, nHint ); +} + +com::sun::star::lang::Locale SvtSysLocaleOptions::GetLocale() const +{ + return lcl_str_to_locale( GetLocaleConfigString() ); +} + +com::sun::star::lang::Locale SvtSysLocaleOptions::GetUILocale() const +{ + return lcl_str_to_locale( GetUILocaleConfigString() ); +} + +com::sun::star::lang::Locale SvtSysLocaleOptions::GetRealLocale() const +{ + return pOptions->GetRealLocale(); +} + +com::sun::star::lang::Locale SvtSysLocaleOptions::GetRealUILocale() const +{ + return pOptions->GetRealUILocale(); +} + +LanguageType SvtSysLocaleOptions::GetRealLanguage() const +{ + return pOptions->GetRealLanguage(); +} + +LanguageType SvtSysLocaleOptions::GetRealUILanguage() const +{ + return pOptions->GetRealUILanguage(); +} + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/undoopt.cxx b/unotools/source/config/undoopt.cxx new file mode 100644 index 000000000000..1e55eea775fe --- /dev/null +++ b/unotools/source/config/undoopt.cxx @@ -0,0 +1,204 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" + +#include <unotools/undoopt.hxx> +#include "rtl/instance.hxx" +#include <unotools/configmgr.hxx> +#include <unotools/configitem.hxx> +#include <tools/debug.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> +#include <osl/mutex.hxx> +#include <osl/mutex.hxx> +#include <rtl/logfile.hxx> +#include "itemholder1.hxx" + +using namespace utl; +using namespace rtl; +using namespace com::sun::star::uno; + +static SvtUndoOptions_Impl* pOptions = NULL; +static sal_Int32 nRefCount = 0; + +#define STEPS 0 + +class SvtUndoOptions_Impl : public utl::ConfigItem +{ + sal_Int32 nUndoCount; + Sequence< rtl::OUString > m_aPropertyNames; + +public: + SvtUndoOptions_Impl(); + + virtual void Notify( const com::sun::star::uno::Sequence< rtl::OUString >& aPropertyNames ); + virtual void Commit(); + void Load(); + + void SetUndoCount( sal_Int32 n ) { nUndoCount = n; SetModified(); } + sal_Int32 GetUndoCount() const { return nUndoCount; } +}; + +// ----------------------------------------------------------------------- + +SvtUndoOptions_Impl::SvtUndoOptions_Impl() + : ConfigItem( OUString(RTL_CONSTASCII_USTRINGPARAM("Office.Common/Undo")) ) + , nUndoCount( 20 ) +{ + Load(); +} + +void SvtUndoOptions_Impl::Commit() +{ + Sequence< Any > aValues( m_aPropertyNames.getLength() ); + Any* pValues = aValues.getArray(); + for ( int nProp = 0; nProp < m_aPropertyNames.getLength(); nProp++ ) + { + switch ( nProp ) + { + case STEPS : + pValues[nProp] <<= nUndoCount; + break; + default: + DBG_ERRORFILE( "invalid index to save a path" ); + } + } + + PutProperties( m_aPropertyNames, aValues ); + NotifyListeners(0); +} + +// ----------------------------------------------------------------------- +void SvtUndoOptions_Impl::Load() +{ + if(!m_aPropertyNames.getLength()) + { + static const char* aPropNames[] = + { + "Steps", + }; + + const int nCount = sizeof( aPropNames ) / sizeof( const char* ); + m_aPropertyNames.realloc(nCount); + OUString* pNames = m_aPropertyNames.getArray(); + for ( int i = 0; i < nCount; i++ ) + pNames[i] = OUString::createFromAscii( aPropNames[i] ); + EnableNotification( m_aPropertyNames ); + } + + Sequence< Any > aValues = GetProperties( m_aPropertyNames ); + const Any* pValues = aValues.getConstArray(); + DBG_ASSERT( aValues.getLength() == m_aPropertyNames.getLength(), "GetProperties failed" ); + if ( aValues.getLength() == m_aPropertyNames.getLength() ) + { + for ( int nProp = 0; nProp < m_aPropertyNames.getLength(); nProp++ ) + { + DBG_ASSERT( pValues[nProp].hasValue(), "property value missing" ); + if ( pValues[nProp].hasValue() ) + { + switch ( nProp ) + { + case STEPS : + { + sal_Int32 nTemp = 0; + if ( pValues[nProp] >>= nTemp ) + nUndoCount = nTemp; + else + { + DBG_ERROR( "Wrong Type!" ); + } + break; + } + + default: + DBG_ERROR( "Wrong Type!" ); + break; + } + } + } + } +} +// ----------------------------------------------------------------------- +void SvtUndoOptions_Impl::Notify( const Sequence<rtl::OUString>& ) +{ + Load(); +} + +// ----------------------------------------------------------------------- +namespace +{ + class LocalSingleton : public rtl::Static< osl::Mutex, LocalSingleton > + { + }; +} + +// ----------------------------------------------------------------------- +SvtUndoOptions::SvtUndoOptions() +{ + // Global access, must be guarded (multithreading) + ::osl::MutexGuard aGuard( LocalSingleton::get() ); + if ( !pOptions ) + { + RTL_LOGFILE_CONTEXT(aLog, "unotools ( ??? ) ::SvtUndoOptions_Impl::ctor()"); + pOptions = new SvtUndoOptions_Impl; + + ItemHolder1::holdConfigItem(E_UNDOOPTIONS); + } + ++nRefCount; + pImp = pOptions; + pImp->AddListener(this); +} + +// ----------------------------------------------------------------------- + +SvtUndoOptions::~SvtUndoOptions() +{ + // Global access, must be guarded (multithreading) + ::osl::MutexGuard aGuard( LocalSingleton::get() ); + pImp->RemoveListener(this); + if ( !--nRefCount ) + { + if ( pOptions->IsModified() ) + pOptions->Commit(); + DELETEZ( pOptions ); + } +} + +void SvtUndoOptions::SetUndoCount( sal_Int32 n ) +{ + pImp->SetUndoCount( n ); +} + +sal_Int32 SvtUndoOptions::GetUndoCount() const +{ + return pImp->GetUndoCount(); +} + +/* 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 000000000000..7019d5648921 --- /dev/null +++ b/unotools/source/config/useroptions.cxx @@ -0,0 +1,1291 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" + +#include <unotools/useroptions.hxx> +#include <unotools/useroptions_const.hxx> + +#include <unotools/configmgr.hxx> +#include <tools/debug.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> +#include <osl/mutex.hxx> +#include <rtl/instance.hxx> +#include <rtl/logfile.hxx> +#include "itemholder1.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/container/XNameContainer.hpp> +#include <com/sun/star/lang/XSingleServiceFactory.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 <unotools/processfactory.hxx> +#include <unotools/loghelper.hxx> + +using namespace utl; +using namespace rtl; +using namespace com::sun::star; +using namespace com::sun::star::uno; + +namespace css = ::com::sun::star; + +// class SvtUserOptions_Impl --------------------------------------------- +class SvtUserOptions_Impl; +class SvtUserConfigChangeListener_Impl : public cppu::WeakImplHelper1 +< + com::sun::star::util::XChangesListener +> +{ + SvtUserOptions_Impl& m_rParent; + public: + SvtUserConfigChangeListener_Impl(SvtUserOptions_Impl& rParent); + ~SvtUserConfigChangeListener_Impl(); + + //XChangesListener + virtual void SAL_CALL changesOccurred( const util::ChangesEvent& Event ) throw(RuntimeException); + //XEventListener + virtual void SAL_CALL disposing( const lang::EventObject& Source ) throw(RuntimeException); +}; + +class SvtUserOptions_Impl : public utl::ConfigurationBroadcaster +{ +public: + SvtUserOptions_Impl(); + ~SvtUserOptions_Impl(); + + // get the user token + ::rtl::OUString GetCompany() const; + ::rtl::OUString GetFirstName() const; + ::rtl::OUString GetLastName() const; + ::rtl::OUString GetID() const; + ::rtl::OUString GetStreet() const; + ::rtl::OUString GetCity() const; + ::rtl::OUString GetState() const; + ::rtl::OUString GetZip() const; + ::rtl::OUString GetCountry() const; + ::rtl::OUString GetPosition() const; + ::rtl::OUString GetTitle() const; + ::rtl::OUString GetTelephoneHome() const; + ::rtl::OUString GetTelephoneWork() const; + ::rtl::OUString GetFax() const; + ::rtl::OUString GetEmail() const; + ::rtl::OUString GetCustomerNumber() const; + ::rtl::OUString GetFathersName() const; + ::rtl::OUString GetApartment() const; + + ::rtl::OUString GetFullName() const; + ::rtl::OUString GetLocale() const { return m_aLocale; } + + // set the address token + void SetCompany( const ::rtl::OUString& rNewToken ); + void SetFirstName( const ::rtl::OUString& rNewToken ); + void SetLastName( const ::rtl::OUString& rNewToken ); + void SetID( const ::rtl::OUString& rNewToken ); + void SetStreet( const ::rtl::OUString& rNewToken ); + void SetCity( const ::rtl::OUString& rNewToken ); + void SetState( const ::rtl::OUString& rNewToken ); + void SetZip( const ::rtl::OUString& rNewToken ); + void SetCountry( const ::rtl::OUString& rNewToken ); + void SetPosition( const ::rtl::OUString& rNewToken ); + void SetTitle( const ::rtl::OUString& rNewToken ); + void SetTelephoneHome( const ::rtl::OUString& rNewToken ); + void SetTelephoneWork( const ::rtl::OUString& rNewToken ); + void SetFax( const ::rtl::OUString& rNewToken ); + void SetEmail( const ::rtl::OUString& rNewToken ); + void SetCustomerNumber( const ::rtl::OUString& rNewToken ); + void SetFathersName( const ::rtl::OUString& rNewToken ); + void SetApartment( const ::rtl::OUString& rNewToken ); + + sal_Bool IsTokenReadonly( USHORT nToken ) const; + ::rtl::OUString GetToken(USHORT nToken) const; + void Notify(); + +private: + uno::Reference< util::XChangesListener > m_xChangeListener; + css::uno::Reference< css::container::XNameAccess > m_xCfg; + css::uno::Reference< css::beans::XPropertySet > m_xData; + ::rtl::OUString m_aLocale; +}; + +// global ---------------------------------------------------------------- + +static SvtUserOptions_Impl* pOptions = NULL; +static sal_Int32 nRefCount = 0; + +#define READONLY_DEFAULT sal_False + +SvtUserConfigChangeListener_Impl::SvtUserConfigChangeListener_Impl(SvtUserOptions_Impl& rParent) : + m_rParent( rParent ) +{ +} + +SvtUserConfigChangeListener_Impl::~SvtUserConfigChangeListener_Impl() +{ +} + +void SvtUserConfigChangeListener_Impl::changesOccurred( const util::ChangesEvent& rEvent ) throw(RuntimeException) +{ + if(rEvent.Changes.getLength()) + m_rParent.Notify(); +} + +void SvtUserConfigChangeListener_Impl::disposing( const lang::EventObject& rSource ) throw(RuntimeException) +{ + try + { + uno::Reference< util::XChangesNotifier > xChgNot( rSource.Source, UNO_QUERY_THROW); + xChgNot->removeChangesListener(this); + } + catch(Exception& ) + { + } +} + +// class SvtUserOptions_Impl --------------------------------------------- + +// ----------------------------------------------------------------------- +SvtUserOptions_Impl::SvtUserOptions_Impl() : + m_xChangeListener( new SvtUserConfigChangeListener_Impl(*this) ) +{ + try + { + m_xCfg = Reference< css::container::XNameAccess > ( + ::comphelper::ConfigurationHelper::openConfig( + utl::getProcessServiceFactory(), + s_sData, + ::comphelper::ConfigurationHelper::E_STANDARD), + css::uno::UNO_QUERY ); + + m_xData = css::uno::Reference< css::beans::XPropertySet >(m_xCfg, css::uno::UNO_QUERY); + uno::Reference< util::XChangesNotifier > xChgNot( m_xCfg, UNO_QUERY); + try + { + xChgNot->addChangesListener( m_xChangeListener ); + } + catch(RuntimeException& ) + { + } + } + catch(const css::uno::Exception& ex) + { + m_xCfg.clear(); + LogHelper::logIt(ex); + } + + Any aAny = ConfigManager::GetConfigManager().GetDirectConfigProperty( ConfigManager::LOCALE ); + ::rtl::OUString aLocale; + if ( aAny >>= aLocale ) + m_aLocale = aLocale; + else + { + DBG_ERRORFILE( "SvtUserOptions_Impl::SvtUserOptions_Impl(): no locale found" ); + } +} + +// ----------------------------------------------------------------------- + +SvtUserOptions_Impl::~SvtUserOptions_Impl() +{ +} + +::rtl::OUString SvtUserOptions_Impl::GetCompany() const +{ + ::rtl::OUString sCompany; + + try + { + m_xData->getPropertyValue(s_so) >>= sCompany; + } + catch ( const css::uno::Exception& ex ) + { + LogHelper::logIt(ex); + } + + return sCompany; +} + +::rtl::OUString SvtUserOptions_Impl::GetFirstName() const +{ + ::rtl::OUString sFirstName; + + try + { + m_xData->getPropertyValue(s_sgivenname) >>= sFirstName; + } + catch ( const css::uno::Exception& ex ) + { + LogHelper::logIt(ex); + } + + return sFirstName; +} + +::rtl::OUString SvtUserOptions_Impl::GetLastName() const +{ + ::rtl::OUString sLastName; + + try + { + m_xData->getPropertyValue(s_ssn) >>= sLastName; + } + catch ( const css::uno::Exception& ex ) + { + LogHelper::logIt(ex); + } + + return sLastName; +} + +::rtl::OUString SvtUserOptions_Impl::GetID() const +{ + ::rtl::OUString sID; + + try + { + m_xData->getPropertyValue(s_sinitials) >>= sID; + } + catch ( const css::uno::Exception& ex ) + { + LogHelper::logIt(ex); + } + + return sID; +} + +::rtl::OUString SvtUserOptions_Impl::GetStreet() const +{ + ::rtl::OUString sStreet; + + try + { + m_xData->getPropertyValue(s_sstreet) >>= sStreet; + } + catch ( const css::uno::Exception& ex ) + { + LogHelper::logIt(ex); + } + + return sStreet; +} + +::rtl::OUString SvtUserOptions_Impl::GetCity() const +{ + ::rtl::OUString sCity; + + try + { + m_xData->getPropertyValue(s_sl) >>= sCity; + } + catch ( const css::uno::Exception& ex ) + { + LogHelper::logIt(ex); + } + + return sCity; +} + +::rtl::OUString SvtUserOptions_Impl::GetState() const +{ + ::rtl::OUString sState; + + try + { + m_xData->getPropertyValue(s_sst) >>= sState; + } + catch ( const css::uno::Exception& ex ) + { + LogHelper::logIt(ex); + } + + return sState; +} + +::rtl::OUString SvtUserOptions_Impl::GetZip() const +{ + ::rtl::OUString sZip; + + try + { + m_xData->getPropertyValue(s_spostalcode) >>= sZip; + } + catch ( const css::uno::Exception& ex ) + { + LogHelper::logIt(ex); + } + + return sZip; +} + +::rtl::OUString SvtUserOptions_Impl::GetCountry() const +{ + ::rtl::OUString sCountry; + + try + { + m_xData->getPropertyValue(s_sc) >>= sCountry; + } + catch ( const css::uno::Exception& ex ) + { + LogHelper::logIt(ex); + } + + return sCountry; +} + +::rtl::OUString SvtUserOptions_Impl::GetPosition() const +{ + ::rtl::OUString sPosition; + + try + { + m_xData->getPropertyValue(s_sposition) >>= sPosition; + } + catch ( const css::uno::Exception& ex ) + { + LogHelper::logIt(ex); + } + + return sPosition; +} + +::rtl::OUString SvtUserOptions_Impl::GetTitle() const +{ + ::rtl::OUString sTitle; + + try + { + m_xData->getPropertyValue(s_stitle) >>= sTitle; + } + catch ( const css::uno::Exception& ex ) + { + LogHelper::logIt(ex); + } + + return sTitle; +} + +::rtl::OUString SvtUserOptions_Impl::GetTelephoneHome() const +{ + ::rtl::OUString sTelephoneHome; + + try + { + m_xData->getPropertyValue(s_shomephone) >>= sTelephoneHome; + } + catch ( const css::uno::Exception& ex ) + { + LogHelper::logIt(ex); + } + + return sTelephoneHome; +} + +::rtl::OUString SvtUserOptions_Impl::GetTelephoneWork() const +{ + ::rtl::OUString sTelephoneWork; + + try + { + m_xData->getPropertyValue(s_stelephonenumber) >>= sTelephoneWork; + } + catch ( const css::uno::Exception& ex ) + { + LogHelper::logIt(ex); + } + + return sTelephoneWork; +} + +::rtl::OUString SvtUserOptions_Impl::GetFax() const +{ + ::rtl::OUString sFax; + + try + { + m_xData->getPropertyValue(s_sfacsimiletelephonenumber) >>= sFax; + } + catch ( const css::uno::Exception& ex ) + { + LogHelper::logIt(ex); + } + + return sFax; +} + +::rtl::OUString SvtUserOptions_Impl::GetEmail() const +{ + ::rtl::OUString sEmail; + + try + { + m_xData->getPropertyValue(s_smail) >>= sEmail; + } + catch ( const css::uno::Exception& ex ) + { + LogHelper::logIt(ex); + } + + return sEmail; +} + +::rtl::OUString SvtUserOptions_Impl::GetCustomerNumber() const +{ + ::rtl::OUString sCustomerNumber; + + try + { + m_xData->getPropertyValue(s_scustomernumber) >>= sCustomerNumber; + } + catch ( const css::uno::Exception& ex ) + { + LogHelper::logIt(ex); + } + + return sCustomerNumber; +} + +::rtl::OUString SvtUserOptions_Impl::GetFathersName() const +{ + ::rtl::OUString sFathersName; + + try + { + m_xData->getPropertyValue(s_sfathersname) >>= sFathersName; + } + catch ( const css::uno::Exception& ex ) + { + LogHelper::logIt(ex); + } + + return sFathersName; +} + +::rtl::OUString SvtUserOptions_Impl::GetApartment() const +{ + ::rtl::OUString sApartment; + + try + { + m_xData->getPropertyValue(s_sapartment) >>= sApartment; + } + catch ( const css::uno::Exception& ex ) + { + LogHelper::logIt(ex); + } + + return sApartment; +} + +void SvtUserOptions_Impl::SetCompany( const ::rtl::OUString& sCompany ) +{ + try + { + m_xData->setPropertyValue(s_so, css::uno::makeAny(::rtl::OUString(sCompany))); + ::comphelper::ConfigurationHelper::flush(m_xCfg); + } + catch ( const css::uno::Exception& ex) + { + LogHelper::logIt(ex); + } +} + +void SvtUserOptions_Impl::SetFirstName( const ::rtl::OUString& sFirstName ) +{ + try + { + m_xData->setPropertyValue(s_sgivenname, css::uno::makeAny(::rtl::OUString(sFirstName))); + ::comphelper::ConfigurationHelper::flush(m_xCfg); + } + catch ( const css::uno::Exception& ex) + { + LogHelper::logIt(ex); + } +} + +void SvtUserOptions_Impl::SetLastName( const ::rtl::OUString& sLastName ) +{ + try + { + m_xData->setPropertyValue(s_ssn, css::uno::makeAny(::rtl::OUString(sLastName))); + ::comphelper::ConfigurationHelper::flush(m_xCfg); + } + catch ( const css::uno::Exception& ex) + { + LogHelper::logIt(ex); + } +} +void SvtUserOptions_Impl::SetID( const ::rtl::OUString& sID ) +{ + try + { + m_xData->setPropertyValue(s_sinitials, css::uno::makeAny(::rtl::OUString(sID))); + ::comphelper::ConfigurationHelper::flush(m_xCfg); + } + catch ( const css::uno::Exception& ex) + { + LogHelper::logIt(ex); + } +} + +void SvtUserOptions_Impl::SetStreet( const ::rtl::OUString& sStreet ) +{ + try + { + m_xData->setPropertyValue(s_sstreet, css::uno::makeAny(::rtl::OUString(sStreet))); + ::comphelper::ConfigurationHelper::flush(m_xCfg); + } + catch ( const css::uno::Exception& ex) + { + LogHelper::logIt(ex); + } +} + +void SvtUserOptions_Impl::SetCity( const ::rtl::OUString& sCity ) +{ + try + { + m_xData->setPropertyValue(s_sl, css::uno::makeAny(::rtl::OUString(sCity))); + ::comphelper::ConfigurationHelper::flush(m_xCfg); + } + catch ( const css::uno::Exception& ex) + { + LogHelper::logIt(ex); + } +} + +void SvtUserOptions_Impl::SetState( const ::rtl::OUString& sState ) +{ + try + { + m_xData->setPropertyValue(s_sst, css::uno::makeAny(::rtl::OUString(sState))); + ::comphelper::ConfigurationHelper::flush(m_xCfg); + } + catch ( const css::uno::Exception& ex) + { + LogHelper::logIt(ex); + } +} + +void SvtUserOptions_Impl::SetZip( const ::rtl::OUString& sZip ) +{ + try + { + m_xData->setPropertyValue(s_spostalcode, css::uno::makeAny(::rtl::OUString(sZip))); + ::comphelper::ConfigurationHelper::flush(m_xCfg); + } + catch ( const css::uno::Exception& ex) + { + LogHelper::logIt(ex); + } +} + +void SvtUserOptions_Impl::SetCountry( const ::rtl::OUString& sCountry ) +{ + try + { + m_xData->setPropertyValue(s_sc, css::uno::makeAny(::rtl::OUString(sCountry))); + ::comphelper::ConfigurationHelper::flush(m_xCfg); + } + catch ( const css::uno::Exception& ex) + { + LogHelper::logIt(ex); + } +} + +void SvtUserOptions_Impl::SetPosition( const ::rtl::OUString& sPosition ) +{ + try + { + m_xData->setPropertyValue(s_sposition, css::uno::makeAny(::rtl::OUString(sPosition))); + ::comphelper::ConfigurationHelper::flush(m_xCfg); + } + catch ( const css::uno::Exception& ex) + { + LogHelper::logIt(ex); + } +} + +void SvtUserOptions_Impl::SetTitle( const ::rtl::OUString& sTitle ) +{ + try + { + m_xData->setPropertyValue(s_stitle, css::uno::makeAny(::rtl::OUString(sTitle))); + ::comphelper::ConfigurationHelper::flush(m_xCfg); + } + catch ( const css::uno::Exception& ex) + { + LogHelper::logIt(ex); + } +} + +void SvtUserOptions_Impl::SetTelephoneHome( const ::rtl::OUString& sTelephoneHome ) +{ + try + { + m_xData->setPropertyValue(s_shomephone, css::uno::makeAny(::rtl::OUString(sTelephoneHome))); + ::comphelper::ConfigurationHelper::flush(m_xCfg); + } + catch ( const css::uno::Exception& ex) + { + LogHelper::logIt(ex); + } +} + +void SvtUserOptions_Impl::SetTelephoneWork( const ::rtl::OUString& sTelephoneWork ) +{ + try + { + m_xData->setPropertyValue(s_stelephonenumber, css::uno::makeAny(::rtl::OUString(sTelephoneWork))); + ::comphelper::ConfigurationHelper::flush(m_xCfg); + } + catch ( const css::uno::Exception& ex) + { + LogHelper::logIt(ex); + } +} + +void SvtUserOptions_Impl::SetFax( const ::rtl::OUString& sFax ) +{ + try + { + m_xData->setPropertyValue(s_sfacsimiletelephonenumber, css::uno::makeAny(::rtl::OUString(sFax))); + ::comphelper::ConfigurationHelper::flush(m_xCfg); + } + catch ( const css::uno::Exception& ex) + { + LogHelper::logIt(ex); + } +} + +void SvtUserOptions_Impl::SetEmail( const ::rtl::OUString& sEmail ) +{ + try + { + m_xData->setPropertyValue(s_smail, css::uno::makeAny(::rtl::OUString(sEmail))); + ::comphelper::ConfigurationHelper::flush(m_xCfg); + } + catch ( const css::uno::Exception& ex) + { + LogHelper::logIt(ex); + } +} + +void SvtUserOptions_Impl::SetCustomerNumber( const ::rtl::OUString& sCustomerNumber ) +{ + try + { + m_xData->setPropertyValue(s_scustomernumber, css::uno::makeAny(::rtl::OUString(sCustomerNumber))); + ::comphelper::ConfigurationHelper::flush(m_xCfg); + } + catch ( const css::uno::Exception& ex) + { + LogHelper::logIt(ex); + } +} + +void SvtUserOptions_Impl::SetFathersName( const ::rtl::OUString& sFathersName ) +{ + try + { + m_xData->setPropertyValue(s_sfathersname, css::uno::makeAny(::rtl::OUString(sFathersName))); + ::comphelper::ConfigurationHelper::flush(m_xCfg); + } + catch ( const css::uno::Exception& ex) + { + LogHelper::logIt(ex); + } +} + +void SvtUserOptions_Impl::SetApartment( const ::rtl::OUString& sApartment ) +{ + try + { + m_xData->setPropertyValue(s_sapartment, css::uno::makeAny(::rtl::OUString(sApartment))); + ::comphelper::ConfigurationHelper::flush(m_xCfg); + } + catch ( const css::uno::Exception& ex) + { + LogHelper::logIt(ex); + } +} + +// ----------------------------------------------------------------------- + +::rtl::OUString SvtUserOptions_Impl::GetFullName() const +{ + ::rtl::OUString sFullName; + + sFullName = GetFirstName(); + sFullName.trim(); + if ( sFullName.getLength() ) + sFullName += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" ")); + sFullName += GetLastName(); + sFullName.trim(); + + return sFullName; +} + +// ----------------------------------------------------------------------- + +void SvtUserOptions_Impl::Notify() +{ + NotifyListeners(0); +} + +// ----------------------------------------------------------------------- + +sal_Bool SvtUserOptions_Impl::IsTokenReadonly( USHORT nToken ) const +{ + css::uno::Reference< css::beans::XPropertySet > xData(m_xCfg, css::uno::UNO_QUERY); + css::uno::Reference< css::beans::XPropertySetInfo > xInfo = xData->getPropertySetInfo(); + css::beans::Property aProp; + sal_Bool bRet = sal_False; + + switch ( nToken ) + { + case USER_OPT_COMPANY: + { + aProp = xInfo->getPropertyByName(s_so); + bRet = ((aProp.Attributes & css::beans::PropertyAttribute::READONLY) == css::beans::PropertyAttribute::READONLY); + break; + } + case USER_OPT_FIRSTNAME: + { + aProp = xInfo->getPropertyByName(s_sgivenname); + bRet = ((aProp.Attributes & css::beans::PropertyAttribute::READONLY) == css::beans::PropertyAttribute::READONLY); + break; + } + case USER_OPT_LASTNAME: + { + aProp = xInfo->getPropertyByName(s_ssn); + bRet = ((aProp.Attributes & css::beans::PropertyAttribute::READONLY) == css::beans::PropertyAttribute::READONLY); + break; + } + case USER_OPT_ID: + { + aProp = xInfo->getPropertyByName(s_sinitials); + bRet = ((aProp.Attributes & css::beans::PropertyAttribute::READONLY) == css::beans::PropertyAttribute::READONLY); + break; + } + case USER_OPT_STREET: + { + aProp = xInfo->getPropertyByName(s_sstreet); + bRet = ((aProp.Attributes & css::beans::PropertyAttribute::READONLY) == css::beans::PropertyAttribute::READONLY); + break; + } + case USER_OPT_CITY: + { + aProp = xInfo->getPropertyByName(s_sl); + bRet = ((aProp.Attributes & css::beans::PropertyAttribute::READONLY) == css::beans::PropertyAttribute::READONLY); + break; + } + case USER_OPT_STATE: + { + aProp = xInfo->getPropertyByName(s_sst); + bRet = ((aProp.Attributes & css::beans::PropertyAttribute::READONLY) == css::beans::PropertyAttribute::READONLY); + break; + } + case USER_OPT_ZIP: + { + aProp = xInfo->getPropertyByName(s_spostalcode); + bRet = ((aProp.Attributes & css::beans::PropertyAttribute::READONLY) == css::beans::PropertyAttribute::READONLY); + break; + } + case USER_OPT_COUNTRY: + { + aProp = xInfo->getPropertyByName(s_sc); + bRet = ((aProp.Attributes & css::beans::PropertyAttribute::READONLY) == css::beans::PropertyAttribute::READONLY); + break; + } + case USER_OPT_POSITION: + { + aProp = xInfo->getPropertyByName(s_sposition); + bRet = ((aProp.Attributes & css::beans::PropertyAttribute::READONLY) == css::beans::PropertyAttribute::READONLY); + break; + } + case USER_OPT_TITLE: + { + aProp = xInfo->getPropertyByName(s_stitle); + bRet = ((aProp.Attributes & css::beans::PropertyAttribute::READONLY) == css::beans::PropertyAttribute::READONLY); + break; + } + case USER_OPT_TELEPHONEHOME: + { + aProp = xInfo->getPropertyByName(s_shomephone); + bRet = ((aProp.Attributes & css::beans::PropertyAttribute::READONLY) == css::beans::PropertyAttribute::READONLY); + break; + } + case USER_OPT_TELEPHONEWORK: + { + aProp = xInfo->getPropertyByName(s_stelephonenumber); + bRet = ((aProp.Attributes & css::beans::PropertyAttribute::READONLY) == css::beans::PropertyAttribute::READONLY); + break; + } + case USER_OPT_FAX: + { + aProp = xInfo->getPropertyByName(s_sfacsimiletelephonenumber); + bRet = ((aProp.Attributes & css::beans::PropertyAttribute::READONLY) == css::beans::PropertyAttribute::READONLY); + break; + } + case USER_OPT_EMAIL: + { + aProp = xInfo->getPropertyByName(s_smail); + bRet = ((aProp.Attributes & css::beans::PropertyAttribute::READONLY) == css::beans::PropertyAttribute::READONLY); + break; + } + case USER_OPT_FATHERSNAME: + { + aProp = xInfo->getPropertyByName(s_sfathersname); + bRet = ((aProp.Attributes & css::beans::PropertyAttribute::READONLY) == css::beans::PropertyAttribute::READONLY); + break; + } + case USER_OPT_APARTMENT: + { + aProp = xInfo->getPropertyByName(s_sapartment); + bRet = ((aProp.Attributes & css::beans::PropertyAttribute::READONLY) == css::beans::PropertyAttribute::READONLY); + break; + } + default: + DBG_ERRORFILE( "SvtUserOptions_Impl::IsTokenReadonly(): invalid token" ); + } + + return bRet; +} + +//------------------------------------------------------------------------ +::rtl::OUString SvtUserOptions_Impl::GetToken(USHORT nToken) const +{ + ::rtl::OUString pRet; + switch(nToken) + { + case USER_OPT_COMPANY: pRet = GetCompany(); break; + case USER_OPT_FIRSTNAME: pRet = GetFirstName(); break; + case USER_OPT_LASTNAME: pRet = GetLastName(); break; + case USER_OPT_ID: pRet = GetID(); break; + case USER_OPT_STREET: pRet = GetStreet(); break; + case USER_OPT_CITY: pRet = GetCity(); break; + case USER_OPT_STATE: pRet = GetState(); break; + case USER_OPT_ZIP: pRet = GetZip(); break; + case USER_OPT_COUNTRY: pRet = GetCountry(); break; + case USER_OPT_POSITION: pRet = GetPosition(); break; + case USER_OPT_TITLE: pRet = GetTitle(); break; + case USER_OPT_TELEPHONEHOME: pRet = GetTelephoneHome(); break; + case USER_OPT_TELEPHONEWORK: pRet = GetTelephoneWork(); break; + case USER_OPT_FAX: pRet = GetFax(); break; + case USER_OPT_EMAIL: pRet = GetEmail(); break; + case USER_OPT_FATHERSNAME: pRet = GetFathersName(); break; + case USER_OPT_APARTMENT: pRet = GetApartment(); break; + default: + DBG_ERRORFILE( "SvtUserOptions_Impl::GetToken(): invalid token" ); + } + return pRet; +} + +// class SvtUserOptions -------------------------------------------------- + +SvtUserOptions::SvtUserOptions() +{ + // Global access, must be guarded (multithreading) + ::osl::MutexGuard aGuard( GetInitMutex() ); + + if ( !pOptions ) + { + RTL_LOGFILE_CONTEXT(aLog, "unotools ( ??? ) ::SvtUserOptions_Impl::ctor()"); + pOptions = new SvtUserOptions_Impl; + + ItemHolder1::holdConfigItem(E_USEROPTIONS); + } + ++nRefCount; + pImp = pOptions; + pImp->AddListener(this); +} + +// ----------------------------------------------------------------------- + +SvtUserOptions::~SvtUserOptions() +{ + // Global access, must be guarded (multithreading) + ::osl::MutexGuard aGuard( GetInitMutex() ); + pImp->RemoveListener(this); + if ( !--nRefCount ) + { + //if ( pOptions->IsModified() ) + // pOptions->Commit(); + DELETEZ( pOptions ); + } +} + +// ----------------------------------------------------------------------- + +::osl::Mutex& SvtUserOptions::GetInitMutex() +{ + // Initialize static mutex only for one time! + static ::osl::Mutex* pMutex = NULL; + // If these method first called (Mutex not already exist!) ... + if ( pMutex == NULL ) + { + // ... we must create a new one. Protect follow code with the global mutex - + // It must be - we create a static variable! + ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); + // We must check our pointer again - + // because another instance of our class will be faster then this instance! + if ( pMutex == NULL ) + { + // Create the new mutex and set it for return on static variable. + static ::osl::Mutex aMutex; + pMutex = &aMutex; + } + } + // Return new created or already existing mutex object. + return *pMutex; +} + +// ----------------------------------------------------------------------- + +::rtl::OUString SvtUserOptions::GetCompany() const +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + return pImp->GetCompany(); +} + +// ----------------------------------------------------------------------- + +::rtl::OUString SvtUserOptions::GetFirstName() const +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + return pImp->GetFirstName(); +} + +// ----------------------------------------------------------------------- + +::rtl::OUString SvtUserOptions::GetLastName() const +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + return pImp->GetLastName(); +} + +// ----------------------------------------------------------------------- + +::rtl::OUString SvtUserOptions::GetID() const +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + return pImp->GetID(); +} + +// ----------------------------------------------------------------------- + +::rtl::OUString SvtUserOptions::GetStreet() const +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + return pImp->GetStreet(); +} + +// ----------------------------------------------------------------------- + +::rtl::OUString SvtUserOptions::GetCity() const +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + return pImp->GetCity(); +} + +// ----------------------------------------------------------------------- + +::rtl::OUString SvtUserOptions::GetState() const +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + return pImp->GetState(); +} + +// ----------------------------------------------------------------------- + +::rtl::OUString SvtUserOptions::GetZip() const +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + return pImp->GetZip(); +} + +// ----------------------------------------------------------------------- + +::rtl::OUString SvtUserOptions::GetCountry() const +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + return pImp->GetCountry(); +} + +// ----------------------------------------------------------------------- + +::rtl::OUString SvtUserOptions::GetPosition() const +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + return pImp->GetPosition(); +} + +// ----------------------------------------------------------------------- + +::rtl::OUString SvtUserOptions::GetTitle() const +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + return pImp->GetTitle(); +} + +// ----------------------------------------------------------------------- + +::rtl::OUString SvtUserOptions::GetTelephoneHome() const +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + return pImp->GetTelephoneHome(); +} + +// ----------------------------------------------------------------------- + +::rtl::OUString SvtUserOptions::GetTelephoneWork() const +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + return pImp->GetTelephoneWork(); +} + +// ----------------------------------------------------------------------- + +::rtl::OUString SvtUserOptions::GetFax() const +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + return pImp->GetFax(); +} + +// ----------------------------------------------------------------------- + +::rtl::OUString SvtUserOptions::GetEmail() const +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + return pImp->GetEmail(); +} + +// ----------------------------------------------------------------------- + +::rtl::OUString SvtUserOptions::GetCustomerNumber() const +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + return pImp->GetCustomerNumber(); +} +// ----------------------------------------------------------------------- + +::rtl::OUString SvtUserOptions::GetFathersName() const +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + return pImp->GetFathersName() ; +} + +// ----------------------------------------------------------------------- + +::rtl::OUString SvtUserOptions::GetApartment() const +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + return pImp->GetApartment(); +} + +// ----------------------------------------------------------------------- + +::rtl::OUString SvtUserOptions::GetFullName() const +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + return pImp->GetFullName(); +} + +// ----------------------------------------------------------------------- + +::rtl::OUString SvtUserOptions::GetLocale() const +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + return pImp->GetLocale(); +} + +// ----------------------------------------------------------------------- + +void SvtUserOptions::SetCompany( const ::rtl::OUString& rNewToken ) +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + pImp->SetCompany( rNewToken ); +} + +// ----------------------------------------------------------------------- + +void SvtUserOptions::SetFirstName( const ::rtl::OUString& rNewToken ) +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + pImp->SetFirstName( rNewToken ); +} + +// ----------------------------------------------------------------------- + +void SvtUserOptions::SetLastName( const ::rtl::OUString& rNewToken ) +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + pImp->SetLastName( rNewToken ); +} + +// ----------------------------------------------------------------------- + +void SvtUserOptions::SetID( const ::rtl::OUString& rNewToken ) +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + pImp->SetID( rNewToken ); +} + +// ----------------------------------------------------------------------- + +void SvtUserOptions::SetStreet( const ::rtl::OUString& rNewToken ) +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + pImp->SetStreet( rNewToken ); +} + +// ----------------------------------------------------------------------- + +void SvtUserOptions::SetCity( const ::rtl::OUString& rNewToken ) +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + pImp->SetCity( rNewToken ); +} + +// ----------------------------------------------------------------------- + +void SvtUserOptions::SetState( const ::rtl::OUString& rNewToken ) +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + pImp->SetState( rNewToken ); +} + +// ----------------------------------------------------------------------- + +void SvtUserOptions::SetZip( const ::rtl::OUString& rNewToken ) +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + pImp->SetZip( rNewToken ); +} + +// ----------------------------------------------------------------------- + +void SvtUserOptions::SetCountry( const ::rtl::OUString& rNewToken ) +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + pImp->SetCountry( rNewToken ); +} + +// ----------------------------------------------------------------------- + +void SvtUserOptions::SetPosition( const ::rtl::OUString& rNewToken ) +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + pImp->SetPosition( rNewToken ); +} + +// ----------------------------------------------------------------------- + +void SvtUserOptions::SetTitle( const ::rtl::OUString& rNewToken ) +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + pImp->SetTitle( rNewToken ); +} + +// ----------------------------------------------------------------------- + +void SvtUserOptions::SetTelephoneHome( const ::rtl::OUString& rNewToken ) +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + pImp->SetTelephoneHome( rNewToken ); +} + +// ----------------------------------------------------------------------- + +void SvtUserOptions::SetTelephoneWork( const ::rtl::OUString& rNewToken ) +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + pImp->SetTelephoneWork( rNewToken ); +} + +// ----------------------------------------------------------------------- + +void SvtUserOptions::SetFax( const ::rtl::OUString& rNewToken ) +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + pImp->SetFax( rNewToken ); +} + +// ----------------------------------------------------------------------- + +void SvtUserOptions::SetEmail( const ::rtl::OUString& rNewToken ) +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + pImp->SetEmail( rNewToken ); +} + +// ----------------------------------------------------------------------- + +void SvtUserOptions::SetCustomerNumber( const ::rtl::OUString& rNewToken ) +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + pImp->SetCustomerNumber( rNewToken ); +} +// ----------------------------------------------------------------------- + +void SvtUserOptions::SetFathersName( const ::rtl::OUString& rNewToken ) +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + pImp->SetFathersName( rNewToken ); +} + +// ----------------------------------------------------------------------- + +void SvtUserOptions::SetApartment( const ::rtl::OUString& rNewToken ) +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + pImp->SetApartment( rNewToken ); +} + +// ----------------------------------------------------------------------- + +sal_Bool SvtUserOptions::IsTokenReadonly( USHORT nToken ) const +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + return pImp->IsTokenReadonly( nToken ); +} +//------------------------------------------------------------------------ +::rtl::OUString SvtUserOptions::GetToken(USHORT nToken) const +{ + ::osl::MutexGuard aGuard( GetInitMutex() ); + return pImp->GetToken( nToken ); +} + +/* 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 000000000000..f3b93da38189 --- /dev/null +++ b/unotools/source/config/viewoptions.cxx @@ -0,0 +1,1304 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" +//_________________________________________________________________________________________________________________ +// includes +//_________________________________________________________________________________________________________________ + +#include <unotools/viewoptions.hxx> +#include <com/sun/star/uno/Any.hxx> + +#include <hash_map> +#include <com/sun/star/beans/PropertyValue.hpp> +#include <com/sun/star/container/XNameContainer.hpp> +#include <com/sun/star/container/XNameAccess.hpp> +#include <com/sun/star/beans/XPropertySet.hpp> +#include <rtl/ustrbuf.hxx> +#include <unotools/configpathes.hxx> +#include <comphelper/configurationhelper.hxx> +#include <unotools/processfactory.hxx> + +#include <itemholder1.hxx> + +//_________________________________________________________________________________________________________________ +// namespaces +//_________________________________________________________________________________________________________________ + +namespace css = ::com::sun::star; + +//_________________________________________________________________________________________________________________ +// const +//_________________________________________________________________________________________________________________ + +#ifdef CONST_ASCII + #error "Who define CONST_ASCII before! I use it to create const ascii strings ..." +#else + #define CONST_ASCII(SASCIIVALUE) ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SASCIIVALUE)) +#endif + +#define PATHSEPERATOR CONST_ASCII("/") + +#define PACKAGE_VIEWS CONST_ASCII("org.openoffice.Office.Views") + +#define LIST_DIALOGS CONST_ASCII("Dialogs" ) +#define LIST_TABDIALOGS CONST_ASCII("TabDialogs") +#define LIST_TABPAGES CONST_ASCII("TabPages" ) +#define LIST_WINDOWS CONST_ASCII("Windows" ) + +#define PROPERTY_WINDOWSTATE CONST_ASCII("WindowState") +#define PROPERTY_PAGEID CONST_ASCII("PageID" ) +#define PROPERTY_VISIBLE CONST_ASCII("Visible" ) +#define PROPERTY_USERDATA CONST_ASCII("UserData" ) + +#define PROPCOUNT_DIALOGS 1 +#define PROPCOUNT_TABDIALOGS 2 +#define PROPCOUNT_TABPAGES 1 +#define PROPCOUNT_WINDOWS 2 + +#define DEFAULT_WINDOWSTATE ::rtl::OUString() +#define DEFAULT_USERDATA css::uno::Sequence< css::beans::NamedValue >() +#define DEFAULT_PAGEID 0 +#define DEFAULT_VISIBLE sal_False + +//#define DEBUG_VIEWOPTIONS + +#ifdef DEBUG_VIEWOPTIONS + #define _LOG_COUNTER_( _SVIEW_, _NREAD_, _NWRITE_ ) \ + { \ + FILE* pFile = fopen( "viewdbg.txt", "a" ); \ + fprintf( pFile, "%s[%d, %d]\n", ::rtl::OUStringToOString(_SVIEW_, RTL_TEXTENCODING_UTF8).getStr(), _NREAD_, _NWRITE_ ); \ + fclose( pFile ); \ + } +#endif // DEBUG_VIEWOPTIONS + +#define SVTVIEWOPTIONS_LOG_UNEXPECTED_EXCEPTION(SVTVIEWOPTIONS_LOG_UNEXPECTED_EXCEPTION_PARAM_EXCEPTION) \ + { \ + ::rtl::OUStringBuffer sMsg(256); \ + sMsg.appendAscii("Unexpected exception catched. Original message was:\n\"" ); \ + sMsg.append (SVTVIEWOPTIONS_LOG_UNEXPECTED_EXCEPTION_PARAM_EXCEPTION.Message); \ + sMsg.appendAscii("\"" ); \ + OSL_ENSURE(sal_False, ::rtl::OUStringToOString(sMsg.makeStringAndClear(), RTL_TEXTENCODING_UTF8).getStr()); \ + } + +//_________________________________________________________________________________________________________________ +// initialization! +//_________________________________________________________________________________________________________________ + +SvtViewOptionsBase_Impl* SvtViewOptions::m_pDataContainer_Dialogs = NULL ; +sal_Int32 SvtViewOptions::m_nRefCount_Dialogs = 0 ; +SvtViewOptionsBase_Impl* SvtViewOptions::m_pDataContainer_TabDialogs = NULL ; +sal_Int32 SvtViewOptions::m_nRefCount_TabDialogs = 0 ; +SvtViewOptionsBase_Impl* SvtViewOptions::m_pDataContainer_TabPages = NULL ; +sal_Int32 SvtViewOptions::m_nRefCount_TabPages = 0 ; +SvtViewOptionsBase_Impl* SvtViewOptions::m_pDataContainer_Windows = NULL ; +sal_Int32 SvtViewOptions::m_nRefCount_Windows = 0 ; + +//_________________________________________________________________________________________________________________ +// private declarations! +//_________________________________________________________________________________________________________________ + +/*-************************************************************************************************************//** + @descr declare one configuration item + These struct hold information about one view item. But not all member are used for all entries! + User must decide which information are usefull and which not. We are a container iztem only and doesnt + know anything about the context. + But; we support a feature: + decision between items with default values (should not realy exist in configuration!) + and items with real values - changed by user. So user can suppress saving of realy unused items + to disk - because; defaulted items could be restored on runtime without reading from disk!!! + And if only items with valid information was written to cfg - we mustn't read so much and save time. + So we start with an member m_bDefault=True and reset it to False after first set-call. + Deficiencies of these solution - we cant allow direct read/write access to our member. We must + support it by set/get-methods ... +*//*-*************************************************************************************************************/ +class IMPL_TViewData +{ + public: + //--------------------------------------------------------------------------------------------------------- + // create "default" item + IMPL_TViewData() + { + m_sWindowState = DEFAULT_WINDOWSTATE ; + m_lUserData = DEFAULT_USERDATA ; + m_nPageID = DEFAULT_PAGEID ; + m_bVisible = DEFAULT_VISIBLE ; + + m_bDefault = sal_True ; + } + + //--------------------------------------------------------------------------------------------------------- + // write access - with reseting of default state + void setWindowState( const ::rtl::OUString& sValue ) + { + m_bDefault = ( + ( m_bDefault == sal_True ) && + ( sValue == DEFAULT_WINDOWSTATE ) + ); + m_sWindowState = sValue; + } + + //--------------------------------------------------------------------------------------------------------- + void setUserData( const css::uno::Sequence< css::beans::NamedValue >& lValue ) + { + m_bDefault = ( + ( m_bDefault == sal_True ) && + ( lValue == DEFAULT_USERDATA ) + ); + m_lUserData = lValue; + } + + //--------------------------------------------------------------------------------------------------------- + void setPageID( sal_Int32 nValue ) + { + m_bDefault = ( + ( m_bDefault == sal_True ) && + ( nValue == DEFAULT_PAGEID ) + ); + m_nPageID = nValue; + } + + //--------------------------------------------------------------------------------------------------------- + void setVisible( sal_Bool bValue ) + { + m_bDefault = ( + ( m_bDefault == sal_True ) && + ( bValue == DEFAULT_VISIBLE ) + ); + m_bVisible = bValue; + } + + //--------------------------------------------------------------------------------------------------------- + // read access + ::rtl::OUString getWindowState() { return m_sWindowState; } + css::uno::Sequence< css::beans::NamedValue > getUserData () { return m_lUserData ; } + sal_Int32 getPageID () { return m_nPageID ; } + sal_Bool getVisible () { return m_bVisible ; } + + //--------------------------------------------------------------------------------------------------------- + // special operation for easy access on user data + void setUserItem( const ::rtl::OUString& sName , + const css::uno::Any& aValue ) + { + // we change UserData in every case! + // a) we change already existing item + // or b) we add a new one + m_bDefault = sal_False; + + sal_Bool bExist = sal_False; + sal_Int32 nCount = m_lUserData.getLength(); + + // change it, if it already exist ... + for( sal_Int32 nStep=0; nStep<nCount; ++nStep ) + { + if( m_lUserData[nStep].Name == sName ) + { + m_lUserData[nStep].Value = aValue ; + bExist = sal_True; + break; + } + } + + // ... or create new list item + if( bExist == sal_False ) + { + m_lUserData.realloc( nCount+1 ); + m_lUserData[nCount].Name = sName ; + m_lUserData[nCount].Value = aValue ; + } + } + + //--------------------------------------------------------------------------------------------------------- + css::uno::Any getUserItem( const ::rtl::OUString& sName ) + { + // default value - if item not exist! + css::uno::Any aValue; + + sal_Int32 nCount = m_lUserData.getLength(); + for( sal_Int32 nStep=0; nStep<nCount; ++nStep ) + { + if( m_lUserData[nStep].Name == sName ) + { + aValue = m_lUserData[nStep].Value; + break; + } + } + return aValue; + } + + //--------------------------------------------------------------------------------------------------------- + // check for default items + sal_Bool isDefault() { return m_bDefault; } + + private: + ::rtl::OUString m_sWindowState ; + css::uno::Sequence< css::beans::NamedValue > m_lUserData ; + sal_Int32 m_nPageID ; + sal_Bool m_bVisible ; + + sal_Bool m_bDefault ; +}; + +struct IMPL_TStringHashCode +{ + size_t operator()(const ::rtl::OUString& sString) const + { + return sString.hashCode(); + } +}; + +typedef ::std::hash_map< ::rtl::OUString , + IMPL_TViewData , + IMPL_TStringHashCode , + ::std::equal_to< ::rtl::OUString > > IMPL_TViewHash; + +/*-************************************************************************************************************//** + @descr Implement base data container for view options elements. + Every item support ALL possible configuration informations. + But not every superclass should use them! Because some view types don't + have it realy. + + @attention We implement a write-througt-cache! We use it for reading - but write all changes directly to + configuration. (changes are made on internal cache too!). So it's easier to distinguish + between added/changed/removed elements without any complex mask or bool flag informations. + Caches from configuration and our own one are synchronized every time - if we do so. +*//*-*************************************************************************************************************/ +class SvtViewOptionsBase_Impl +{ + //------------------------------------------------------------------------------------------------------------- + public: + SvtViewOptionsBase_Impl ( const ::rtl::OUString& sList ); + virtual ~SvtViewOptionsBase_Impl ( ); + sal_Bool Exists ( const ::rtl::OUString& sName ); + sal_Bool Delete ( const ::rtl::OUString& sName ); + ::rtl::OUString GetWindowState ( const ::rtl::OUString& sName ); + void SetWindowState ( const ::rtl::OUString& sName , + const ::rtl::OUString& sState ); + css::uno::Sequence< css::beans::NamedValue > GetUserData ( const ::rtl::OUString& sName ); + void SetUserData ( const ::rtl::OUString& sName , + const css::uno::Sequence< css::beans::NamedValue >& lData ); + sal_Int32 GetPageID ( const ::rtl::OUString& sName ); + void SetPageID ( const ::rtl::OUString& sName , + sal_Int32 nID ); + sal_Bool GetVisible ( const ::rtl::OUString& sName ); + void SetVisible ( const ::rtl::OUString& sName , + sal_Bool bVisible ); + css::uno::Any GetUserItem ( const ::rtl::OUString& sName , + const ::rtl::OUString& sItem ); + void SetUserItem ( const ::rtl::OUString& sName , + const ::rtl::OUString& sItem , + const css::uno::Any& aValue ); + + //------------------------------------------------------------------------------------------------------------- + private: + css::uno::Reference< css::uno::XInterface > impl_getSetNode( const ::rtl::OUString& sNode , + sal_Bool bCreateIfMissing); + + //------------------------------------------------------------------------------------------------------------- + private: + ::rtl::OUString m_sListName; + css::uno::Reference< css::container::XNameAccess > m_xRoot; + css::uno::Reference< css::container::XNameAccess > m_xSet; + + #ifdef DEBUG_VIEWOPTIONS + sal_Int32 m_nReadCount ; + sal_Int32 m_nWriteCount ; + #endif +}; + +/*-************************************************************************************************************//** + @descr Implement the base data container. +*//*-*************************************************************************************************************/ + +/*-************************************************************************************************************//** + @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. + Normaly 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() + + @param - + @return - + + @last change 19.10.2001 07:54 +*//*-*************************************************************************************************************/ +SvtViewOptionsBase_Impl::SvtViewOptionsBase_Impl( const ::rtl::OUString& sList ) + : m_sListName ( sList ) // we must know, which view type we must support + #ifdef DEBUG_VIEWOPTIONS + , m_nReadCount ( 0 ) + , m_nWriteCount( 0 ) + #endif +{ + try + { + m_xRoot = css::uno::Reference< css::container::XNameAccess >( + ::comphelper::ConfigurationHelper::openConfig( + ::utl::getProcessServiceFactory(), + PACKAGE_VIEWS, + ::comphelper::ConfigurationHelper::E_STANDARD), + css::uno::UNO_QUERY); + if (m_xRoot.is()) + m_xRoot->getByName(sList) >>= m_xSet; + } + catch(const css::uno::Exception& ex) + { + m_xRoot.clear(); + m_xSet.clear(); + + SVTVIEWOPTIONS_LOG_UNEXPECTED_EXCEPTION(ex) + } +} + +/*-************************************************************************************************************//** + @short dtor + @descr clean up something + + @attention We implement a write through cache! So we mustn't do it realy. All changes was written to cfg directly. + Commit isn't neccessary then. + + @seealso baseclass ::utl::ConfigItem + @seealso method IsModified() + @seealso method SetModified() + @seealso method Commit() + + @param - + @return - + + @last change 19.10.2001 08:02 +*//*-*************************************************************************************************************/ +SvtViewOptionsBase_Impl::~SvtViewOptionsBase_Impl() +{ + // dont flush configuration changes here to m_xRoot. + // That must be done inside every SetXXX() method already ! + // Here its to late - DisposedExceptions from used configuration access can occure otherwise. + + m_xRoot.clear(); + m_xSet.clear(); + + #ifdef DEBUG_VIEWOPTIONS + _LOG_COUNTER_( m_sListName, m_nReadCount, m_nWriteCount ) + #endif // DEBUG_VIEWOPTIONS +} + +/*-************************************************************************************************************//** + @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 +*//*-*************************************************************************************************************/ +sal_Bool SvtViewOptionsBase_Impl::Exists( const ::rtl::OUString& sName ) +{ + sal_Bool bExists = sal_False; + + try + { + if (m_xSet.is()) + bExists = m_xSet->hasByName(sName); + } + catch(const css::uno::Exception& ex) + { + bExists = sal_False; + SVTVIEWOPTIONS_LOG_UNEXPECTED_EXCEPTION(ex) + } + + return bExists; +} + +/*-************************************************************************************************************//** + @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 + @return true , if item not exist(!) or could be deleted (should be the same!) + false, otherwise +*//*-*************************************************************************************************************/ +sal_Bool SvtViewOptionsBase_Impl::Delete( const ::rtl::OUString& sName ) +{ + #ifdef DEBUG_VIEWOPTIONS + ++m_nWriteCount; + #endif + + sal_Bool bDeleted = sal_False; + try + { + css::uno::Reference< css::container::XNameContainer > xSet(m_xSet, css::uno::UNO_QUERY_THROW); + xSet->removeByName(sName); + bDeleted = sal_True; + ::comphelper::ConfigurationHelper::flush(m_xRoot); + } + catch(const css::container::NoSuchElementException&) + { bDeleted = sal_True; } + catch(const css::uno::Exception& ex) + { + bDeleted = sal_False; + SVTVIEWOPTIONS_LOG_UNEXPECTED_EXCEPTION(ex) + } + + return bDeleted; +} + +/*-************************************************************************************************************//** + @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 + + @param - + @return - +*//*-*************************************************************************************************************/ +::rtl::OUString SvtViewOptionsBase_Impl::GetWindowState( const ::rtl::OUString& sName ) +{ + #ifdef DEBUG_VIEWOPTIONS + ++m_nReadCount; + #endif + + ::rtl::OUString sWindowState; + try + { + css::uno::Reference< css::beans::XPropertySet > xNode( + impl_getSetNode(sName, sal_False), + css::uno::UNO_QUERY); + if (xNode.is()) + xNode->getPropertyValue(PROPERTY_WINDOWSTATE) >>= sWindowState; + } + catch(const css::uno::Exception& ex) + { + sWindowState = ::rtl::OUString(); + SVTVIEWOPTIONS_LOG_UNEXPECTED_EXCEPTION(ex) + } + + return sWindowState; +} + +//***************************************************************************************************************** +void SvtViewOptionsBase_Impl::SetWindowState( const ::rtl::OUString& sName , + const ::rtl::OUString& sState ) +{ + #ifdef DEBUG_VIEWOPTIONS + ++m_nWriteCount; + #endif + + try + { + css::uno::Reference< css::beans::XPropertySet > xNode( + impl_getSetNode(sName, sal_True), + css::uno::UNO_QUERY_THROW); + xNode->setPropertyValue(PROPERTY_WINDOWSTATE, css::uno::makeAny(sState)); + ::comphelper::ConfigurationHelper::flush(m_xRoot); + } + catch(const css::uno::Exception& ex) + { + SVTVIEWOPTIONS_LOG_UNEXPECTED_EXCEPTION(ex) + } +} + +//***************************************************************************************************************** +css::uno::Sequence< css::beans::NamedValue > SvtViewOptionsBase_Impl::GetUserData( const ::rtl::OUString& sName ) +{ + #ifdef DEBUG_VIEWOPTIONS + ++m_nReadCount; + #endif + + try + { + css::uno::Reference< css::container::XNameAccess > xNode( + impl_getSetNode(sName, sal_False), + css::uno::UNO_QUERY); // no _THROW ! because we dont 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< ::rtl::OUString > lNames = xUserData->getElementNames(); + const ::rtl::OUString* pNames = lNames.getConstArray(); + sal_Int32 c = lNames.getLength(); + sal_Int32 i = 0; + css::uno::Sequence< css::beans::NamedValue > lUserData(c); + + for (i=0; i<c; ++i) + { + lUserData[i].Name = pNames[i]; + lUserData[i].Value = xUserData->getByName(pNames[i]); + } + + return lUserData; + } + } + catch(const css::uno::Exception& ex) + { + SVTVIEWOPTIONS_LOG_UNEXPECTED_EXCEPTION(ex) + } + + return css::uno::Sequence< css::beans::NamedValue >(); +} + +//***************************************************************************************************************** +void SvtViewOptionsBase_Impl::SetUserData( const ::rtl::OUString& sName , + const css::uno::Sequence< css::beans::NamedValue >& lData ) +{ + #ifdef DEBUG_VIEWOPTIONS + ++m_nWriteCount; + #endif + + try + { + css::uno::Reference< css::container::XNameAccess > xNode( + impl_getSetNode(sName, sal_True), + css::uno::UNO_QUERY_THROW); + css::uno::Reference< css::container::XNameContainer > xUserData; + xNode->getByName(PROPERTY_USERDATA) >>= xUserData; + if (xUserData.is()) + { + const css::beans::NamedValue* pData = lData.getConstArray(); + sal_Int32 c = lData.getLength(); + sal_Int32 i = 0; + for (i=0; i<c; ++i) + { + if (xUserData->hasByName(pData[i].Name)) + xUserData->replaceByName(pData[i].Name, pData[i].Value); + else + xUserData->insertByName(pData[i].Name, pData[i].Value); + } + } + ::comphelper::ConfigurationHelper::flush(m_xRoot); + } + catch(const css::uno::Exception& ex) + { + SVTVIEWOPTIONS_LOG_UNEXPECTED_EXCEPTION(ex) + } +} + +//***************************************************************************************************************** +css::uno::Any SvtViewOptionsBase_Impl::GetUserItem( const ::rtl::OUString& sName , + const ::rtl::OUString& sItem ) +{ + #ifdef DEBUG_VIEWOPTIONS + ++m_nReadCount; + #endif + + css::uno::Any aItem; + try + { + css::uno::Reference< css::container::XNameAccess > xNode( + impl_getSetNode(sName, sal_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(sItem); + } + catch(const css::container::NoSuchElementException&) + { aItem.clear(); } + catch(const css::uno::Exception& ex) + { + aItem.clear(); + SVTVIEWOPTIONS_LOG_UNEXPECTED_EXCEPTION(ex) + } + + return aItem; +} + +//***************************************************************************************************************** +void SvtViewOptionsBase_Impl::SetUserItem( const ::rtl::OUString& sName , + const ::rtl::OUString& sItem , + const css::uno::Any& aValue ) +{ + #ifdef DEBUG_VIEWOPTIONS + ++m_nWriteCount; + #endif + + try + { + css::uno::Reference< css::container::XNameAccess > xNode( + impl_getSetNode(sName, sal_True), + css::uno::UNO_QUERY_THROW); + css::uno::Reference< css::container::XNameContainer > xUserData; + xNode->getByName(PROPERTY_USERDATA) >>= xUserData; + if (xUserData.is()) + { + if (xUserData->hasByName(sItem)) + xUserData->replaceByName(sItem, aValue); + else + xUserData->insertByName(sItem, aValue); + } + ::comphelper::ConfigurationHelper::flush(m_xRoot); + } + catch(const css::uno::Exception& ex) + { + SVTVIEWOPTIONS_LOG_UNEXPECTED_EXCEPTION(ex) + } +} + +//***************************************************************************************************************** +sal_Int32 SvtViewOptionsBase_Impl::GetPageID( const ::rtl::OUString& sName ) +{ + #ifdef DEBUG_VIEWOPTIONS + ++m_nReadCount; + #endif + + sal_Int32 nID = 0; + try + { + css::uno::Reference< css::beans::XPropertySet > xNode( + impl_getSetNode(sName, sal_False), + css::uno::UNO_QUERY); + if (xNode.is()) + xNode->getPropertyValue(PROPERTY_PAGEID) >>= nID; + } + catch(const css::uno::Exception& ex) + { + nID = 0; + SVTVIEWOPTIONS_LOG_UNEXPECTED_EXCEPTION(ex) + } + + return nID; +} + +//***************************************************************************************************************** +void SvtViewOptionsBase_Impl::SetPageID( const ::rtl::OUString& sName , + sal_Int32 nID ) +{ + #ifdef DEBUG_VIEWOPTIONS + ++m_nWriteCount; + #endif + + try + { + css::uno::Reference< css::beans::XPropertySet > xNode( + impl_getSetNode(sName, sal_True), + css::uno::UNO_QUERY_THROW); + xNode->setPropertyValue(PROPERTY_PAGEID, css::uno::makeAny(nID)); + ::comphelper::ConfigurationHelper::flush(m_xRoot); + } + catch(const css::uno::Exception& ex) + { + SVTVIEWOPTIONS_LOG_UNEXPECTED_EXCEPTION(ex) + } +} + +//***************************************************************************************************************** +sal_Bool SvtViewOptionsBase_Impl::GetVisible( const ::rtl::OUString& sName ) +{ + #ifdef DEBUG_VIEWOPTIONS + ++m_nReadCount; + #endif + + sal_Bool bVisible = sal_False; + try + { + css::uno::Reference< css::beans::XPropertySet > xNode( + impl_getSetNode(sName, sal_False), + css::uno::UNO_QUERY); + if (xNode.is()) + xNode->getPropertyValue(PROPERTY_VISIBLE) >>= bVisible; + } + catch(const css::uno::Exception& ex) + { + bVisible = sal_False; + SVTVIEWOPTIONS_LOG_UNEXPECTED_EXCEPTION(ex) + } + + return bVisible; +} + +//***************************************************************************************************************** +void SvtViewOptionsBase_Impl::SetVisible( const ::rtl::OUString& sName , + sal_Bool bVisible ) +{ + #ifdef DEBUG_VIEWOPTIONS + ++m_nWriteCount; + #endif + + try + { + css::uno::Reference< css::beans::XPropertySet > xNode( + impl_getSetNode(sName, sal_True), + css::uno::UNO_QUERY_THROW); + xNode->setPropertyValue(PROPERTY_VISIBLE, css::uno::makeAny(bVisible)); + ::comphelper::ConfigurationHelper::flush(m_xRoot); + } + catch(const css::uno::Exception& ex) + { + SVTVIEWOPTIONS_LOG_UNEXPECTED_EXCEPTION(ex) + } +} + +/*-************************************************************************************************************//** + @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 + @return - + + @last change 19.10.2001 08:42 +*//*-*************************************************************************************************************/ +css::uno::Reference< css::uno::XInterface > SvtViewOptionsBase_Impl::impl_getSetNode( const ::rtl::OUString& sNode , + sal_Bool bCreateIfMissing) +{ + 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->getByName(sNode) >>= xNode; + } + } + catch(const css::container::NoSuchElementException&) + { xNode.clear(); } + catch(const css::uno::Exception& ex) + { + xNode.clear(); + SVTVIEWOPTIONS_LOG_UNEXPECTED_EXCEPTION(ex) + } + + return xNode; +} + +//_________________________________________________________________________________________________________________ +// definitions +//_________________________________________________________________________________________________________________ + +//***************************************************************************************************************** +// constructor +//***************************************************************************************************************** +SvtViewOptions::SvtViewOptions( EViewType eType , + const ::rtl::OUString& sViewName ) + : m_eViewType ( eType ) + , m_sViewName ( sViewName ) +{ + // Global access, must be guarded (multithreading!) + ::osl::MutexGuard aGuard( GetOwnStaticMutex() ); + + // Search for right dat container for this view type and initialize right data container or set right ref count! + switch( eType ) + { + case E_DIALOG : { + // Increase ref count for dialog data container first. + ++m_nRefCount_Dialogs; + // If these instance the first user of the dialog data container - create these impl static container! + if( m_nRefCount_Dialogs == 1 ) + { + //m_pDataContainer_Dialogs = new SvtViewDialogOptions_Impl( LIST_DIALOGS ); + m_pDataContainer_Dialogs = new SvtViewOptionsBase_Impl( LIST_DIALOGS ); + ItemHolder1::holdConfigItem(E_VIEWOPTIONS_DIALOG); + } + } + break; + case E_TABDIALOG : { + // Increase ref count for tab-dialog data container first. + ++m_nRefCount_TabDialogs; + // If these instance the first user of the tab-dialog data container - create these impl static container! + if( m_nRefCount_TabDialogs == 1 ) + { + m_pDataContainer_TabDialogs = new SvtViewOptionsBase_Impl( LIST_TABDIALOGS ); + ItemHolder1::holdConfigItem(E_VIEWOPTIONS_TABDIALOG); + } + } + break; + case E_TABPAGE : { + // Increase ref count for tab-page data container first. + ++m_nRefCount_TabPages; + // If these instance the first user of the tab-page data container - create these impl static container! + if( m_nRefCount_TabPages == 1 ) + { + m_pDataContainer_TabPages = new SvtViewOptionsBase_Impl( LIST_TABPAGES ); + ItemHolder1::holdConfigItem(E_VIEWOPTIONS_TABPAGE); + } + } + break; + case E_WINDOW : { + // Increase ref count for window data container first. + ++m_nRefCount_Windows; + // If these instance the first user of the window data container - create these impl static container! + if( m_nRefCount_Windows == 1 ) + { + m_pDataContainer_Windows = new SvtViewOptionsBase_Impl( LIST_WINDOWS ); + ItemHolder1::holdConfigItem(E_VIEWOPTIONS_WINDOW); + } + } + break; + default : OSL_ENSURE( sal_False, "SvtViewOptions::SvtViewOptions()\nThese view type is unknown! All following calls at these instance will do nothing!\n" ); + } +} + +//***************************************************************************************************************** +// destructor +//***************************************************************************************************************** +SvtViewOptions::~SvtViewOptions() +{ + // Global access, must be guarded (multithreading!) + ::osl::MutexGuard aGuard( GetOwnStaticMutex() ); + + // Search for right dat container for this view type and deinitialize right data container or set right ref count! + switch( m_eViewType ) + { + case E_DIALOG : { + // Decrease ref count for dialog data container first. + --m_nRefCount_Dialogs; + // If these instance the last user of the dialog data container - delete these impl static container! + if( m_nRefCount_Dialogs == 0 ) + { + delete m_pDataContainer_Dialogs; + m_pDataContainer_Dialogs = NULL; + } + } + break; + case E_TABDIALOG : { + // Decrease ref count for tab-dialog data container first. + --m_nRefCount_TabDialogs; + // If these instance the last user of the tab-dialog data container - delete these impl static container! + if( m_nRefCount_TabDialogs == 0 ) + { + delete m_pDataContainer_TabDialogs; + m_pDataContainer_TabDialogs = NULL; + } + } + break; + case E_TABPAGE : { + // Decrease ref count for tab-page data container first. + --m_nRefCount_TabPages; + // If these instance the last user of the tab-page data container - delete these impl static container! + if( m_nRefCount_TabPages == 0 ) + { + delete m_pDataContainer_TabPages; + m_pDataContainer_TabPages = NULL; + } + } + break; + case E_WINDOW : { + // Decrease ref count for window data container first. + --m_nRefCount_Windows; + // If these instance the last user of the window data container - delete these impl static container! + if( m_nRefCount_Windows == 0 ) + { + delete m_pDataContainer_Windows; + m_pDataContainer_Windows = NULL; + } + } + break; + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Bool SvtViewOptions::Exists() const +{ + // Ready for multithreading + ::osl::MutexGuard aGuard( GetOwnStaticMutex() ); + + sal_Bool bExists = sal_False; + switch( m_eViewType ) + { + case E_DIALOG : { + bExists = m_pDataContainer_Dialogs->Exists( m_sViewName ); + } + break; + case E_TABDIALOG : { + bExists = m_pDataContainer_TabDialogs->Exists( m_sViewName ); + } + break; + case E_TABPAGE : { + bExists = m_pDataContainer_TabPages->Exists( m_sViewName ); + } + break; + case E_WINDOW : { + bExists = m_pDataContainer_Windows->Exists( m_sViewName ); + } + break; + } + return bExists; +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Bool SvtViewOptions::Delete() +{ + // Ready for multithreading + ::osl::MutexGuard aGuard( GetOwnStaticMutex() ); + + sal_Bool bState = sal_False; + switch( m_eViewType ) + { + case E_DIALOG : { + bState = m_pDataContainer_Dialogs->Delete( m_sViewName ); + } + break; + case E_TABDIALOG : { + bState = m_pDataContainer_TabDialogs->Delete( m_sViewName ); + } + break; + case E_TABPAGE : { + bState = m_pDataContainer_TabPages->Delete( m_sViewName ); + } + break; + case E_WINDOW : { + bState = m_pDataContainer_Windows->Delete( m_sViewName ); + } + break; + } + return bState; +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +::rtl::OUString SvtViewOptions::GetWindowState() const +{ + // Ready for multithreading + ::osl::MutexGuard aGuard( GetOwnStaticMutex() ); + + ::rtl::OUString sState; + switch( m_eViewType ) + { + case E_DIALOG : { + sState = m_pDataContainer_Dialogs->GetWindowState( m_sViewName ); + } + break; + case E_TABDIALOG : { + sState = m_pDataContainer_TabDialogs->GetWindowState( m_sViewName ); + } + break; + case E_TABPAGE : { + sState = m_pDataContainer_TabPages->GetWindowState( m_sViewName ); + } + break; + case E_WINDOW : { + sState = m_pDataContainer_Windows->GetWindowState( m_sViewName ); + } + break; + } + return sState; +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtViewOptions::SetWindowState( const ::rtl::OUString& sState ) +{ + // Ready for multithreading + ::osl::MutexGuard aGuard( GetOwnStaticMutex() ); + + switch( m_eViewType ) + { + case E_DIALOG : { + m_pDataContainer_Dialogs->SetWindowState( m_sViewName, sState ); + } + break; + case E_TABDIALOG : { + m_pDataContainer_TabDialogs->SetWindowState( m_sViewName, sState ); + } + break; + case E_TABPAGE : { + m_pDataContainer_TabPages->SetWindowState( m_sViewName, sState ); + } + break; + case E_WINDOW : { + m_pDataContainer_Windows->SetWindowState( m_sViewName, sState ); + } + break; + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Int32 SvtViewOptions::GetPageID() const +{ + // Ready for multithreading + ::osl::MutexGuard aGuard( GetOwnStaticMutex() ); + + // Safe impossible cases. + // These call isn't allowed for dialogs, tab-pages or windows! + OSL_ENSURE( !(m_eViewType==E_DIALOG||m_eViewType==E_TABPAGE||m_eViewType==E_WINDOW), "SvtViewOptions::GetPageID()\nCall not allowed for Dialogs, TabPages or Windows! I do nothing!\n" ); + + sal_Int32 nID = 0; + if( m_eViewType == E_TABDIALOG ) + nID = m_pDataContainer_TabDialogs->GetPageID( m_sViewName ); + return nID; +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtViewOptions::SetPageID( sal_Int32 nID ) +{ + // Ready for multithreading + ::osl::MutexGuard aGuard( GetOwnStaticMutex() ); + + // Safe impossible cases. + // These call isn't allowed for dialogs, tab-pages or windows! + OSL_ENSURE( !(m_eViewType==E_DIALOG||m_eViewType==E_TABPAGE||m_eViewType==E_WINDOW), "SvtViewOptions::SetPageID()\nCall not allowed for Dialogs, TabPages or Windows! I do nothing!\n" ); + + if( m_eViewType == E_TABDIALOG ) + m_pDataContainer_TabDialogs->SetPageID( m_sViewName, nID ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +sal_Bool SvtViewOptions::IsVisible() const +{ + // Ready for multithreading + ::osl::MutexGuard aGuard( GetOwnStaticMutex() ); + + // Safe impossible cases. + // These call isn't allowed for dialogs, tab-dialogs or tab-pages! + OSL_ENSURE( !(m_eViewType==E_DIALOG||m_eViewType==E_TABDIALOG||m_eViewType==E_TABPAGE), "SvtViewOptions::IsVisible()\nCall not allowed for Dialogs, TabDialogs or TabPages! I do nothing!\n" ); + + sal_Bool bState = sal_False; + if( m_eViewType == E_WINDOW ) + bState = m_pDataContainer_Windows->GetVisible( m_sViewName ); + + return bState; +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtViewOptions::SetVisible( sal_Bool bState ) +{ + // Ready for multithreading + ::osl::MutexGuard aGuard( GetOwnStaticMutex() ); + + // Safe impossible cases. + // These call isn't allowed for dialogs, tab-dialogs or tab-pages! + OSL_ENSURE( !(m_eViewType==E_DIALOG||m_eViewType==E_TABDIALOG||m_eViewType==E_TABPAGE), "SvtViewOptions::SetVisible()\nCall not allowed for Dialogs, TabDialogs or TabPages! I do nothing!\n" ); + + if( m_eViewType == E_WINDOW ) + m_pDataContainer_Windows->SetVisible( m_sViewName, bState ); +} + +//***************************************************************************************************************** +css::uno::Sequence< css::beans::NamedValue > SvtViewOptions::GetUserData() const +{ + // Ready for multithreading + ::osl::MutexGuard aGuard( GetOwnStaticMutex() ); + + css::uno::Sequence< css::beans::NamedValue > lData; + switch( m_eViewType ) + { + case E_DIALOG : { + lData = m_pDataContainer_Dialogs->GetUserData( m_sViewName ); + } + break; + case E_TABDIALOG : { + lData = m_pDataContainer_TabDialogs->GetUserData( m_sViewName ); + } + break; + case E_TABPAGE : { + lData = m_pDataContainer_TabPages->GetUserData( m_sViewName ); + } + break; + case E_WINDOW : { + lData = m_pDataContainer_Windows->GetUserData( m_sViewName ); + } + break; + } + return lData; +} + +//***************************************************************************************************************** +void SvtViewOptions::SetUserData( const css::uno::Sequence< css::beans::NamedValue >& lData ) +{ + // Ready for multithreading + ::osl::MutexGuard aGuard( GetOwnStaticMutex() ); + + switch( m_eViewType ) + { + case E_DIALOG : { + m_pDataContainer_Dialogs->SetUserData( m_sViewName, lData ); + } + break; + case E_TABDIALOG : { + m_pDataContainer_TabDialogs->SetUserData( m_sViewName, lData ); + } + break; + case E_TABPAGE : { + m_pDataContainer_TabPages->SetUserData( m_sViewName, lData ); + } + break; + case E_WINDOW : { + m_pDataContainer_Windows->SetUserData( m_sViewName, lData ); + } + break; + } +} + +//***************************************************************************************************************** +css::uno::Any SvtViewOptions::GetUserItem( const ::rtl::OUString& sName ) const +{ + // Ready for multithreading + ::osl::MutexGuard aGuard( GetOwnStaticMutex() ); + + css::uno::Any aItem; + switch( m_eViewType ) + { + case E_DIALOG : { + aItem = m_pDataContainer_Dialogs->GetUserItem( m_sViewName, sName ); + } + break; + case E_TABDIALOG : { + aItem = m_pDataContainer_TabDialogs->GetUserItem( m_sViewName, sName ); + } + break; + case E_TABPAGE : { + aItem = m_pDataContainer_TabPages->GetUserItem( m_sViewName, sName ); + } + break; + case E_WINDOW : { + aItem = m_pDataContainer_Windows->GetUserItem( m_sViewName, sName ); + } + break; + } + return aItem; +} + +//***************************************************************************************************************** +void SvtViewOptions::SetUserItem( const ::rtl::OUString& sName , + const css::uno::Any& aValue ) +{ + // Ready for multithreading + ::osl::MutexGuard aGuard( GetOwnStaticMutex() ); + + switch( m_eViewType ) + { + case E_DIALOG : { + m_pDataContainer_Dialogs->SetUserItem( m_sViewName, sName, aValue ); + } + break; + case E_TABDIALOG : { + m_pDataContainer_TabDialogs->SetUserItem( m_sViewName, sName, aValue ); + } + break; + case E_TABPAGE : { + m_pDataContainer_TabPages->SetUserItem( m_sViewName, sName, aValue ); + } + break; + case E_WINDOW : { + m_pDataContainer_Windows->SetUserItem( m_sViewName, sName, aValue ); + } + break; + } +} + +//***************************************************************************************************************** +// private method +//***************************************************************************************************************** +::osl::Mutex& SvtViewOptions::GetOwnStaticMutex() +{ + // Initialize static mutex only for one time! + static ::osl::Mutex* pMutex = NULL; + // If these method first called (Mutex not already exist!) ... + if( pMutex == NULL ) + { + // ... we must create a new one. Protect follow code with the global mutex - + // It must be - we create a static variable! + ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); + // We must check our pointer again - because it can be that another instance of ouer class will be fastr then these! + if( pMutex == NULL ) + { + // Create the new mutex and set it for return on static variable. + static ::osl::Mutex aMutex; + pMutex = &aMutex; + } + } + // Return new created or already existing mutex object. + return *pMutex; +} + +void SvtViewOptions::AcquireOptions() +{ + ::osl::MutexGuard aGuard( GetOwnStaticMutex() ); + if( ++m_nRefCount_Dialogs == 1 ) + { + m_pDataContainer_Dialogs = new SvtViewOptionsBase_Impl( LIST_DIALOGS ); + ItemHolder1::holdConfigItem(E_VIEWOPTIONS_DIALOG); + } + if( ++m_nRefCount_TabDialogs == 1 ) + { + m_pDataContainer_TabDialogs = new SvtViewOptionsBase_Impl( LIST_TABDIALOGS ); + ItemHolder1::holdConfigItem(E_VIEWOPTIONS_TABDIALOG); + } + if( ++m_nRefCount_TabPages == 1 ) + { + m_pDataContainer_TabPages = new SvtViewOptionsBase_Impl( LIST_TABPAGES ); + ItemHolder1::holdConfigItem(E_VIEWOPTIONS_TABPAGE); + } + if( ++m_nRefCount_Windows == 1 ) + { + m_pDataContainer_Windows = new SvtViewOptionsBase_Impl( LIST_WINDOWS ); + ItemHolder1::holdConfigItem(E_VIEWOPTIONS_WINDOW); + } +} + +void SvtViewOptions::ReleaseOptions() +{ + ::osl::MutexGuard aGuard( GetOwnStaticMutex() ); + if( --m_nRefCount_Dialogs == 0 ) + { + delete m_pDataContainer_Dialogs; + m_pDataContainer_Dialogs = NULL; + } + if( --m_nRefCount_TabDialogs == 0 ) + { + delete m_pDataContainer_TabDialogs; + m_pDataContainer_TabDialogs = NULL; + } + if( --m_nRefCount_TabPages == 0 ) + { + delete m_pDataContainer_TabPages; + m_pDataContainer_TabPages = NULL; + } + if( --m_nRefCount_Windows == 0 ) + { + delete m_pDataContainer_Windows; + m_pDataContainer_Windows = NULL; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/workingsetoptions.cxx b/unotools/source/config/workingsetoptions.cxx new file mode 100644 index 000000000000..fd498c7b7556 --- /dev/null +++ b/unotools/source/config/workingsetoptions.cxx @@ -0,0 +1,390 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" + +#include <unotools/workingsetoptions.hxx> +#include <unotools/configmgr.hxx> +#include <unotools/configitem.hxx> +#include <tools/debug.hxx> +#include <com/sun/star/uno/Any.hxx> +#include <com/sun/star/uno/Sequence.hxx> + +#include <itemholder1.hxx> + +//_________________________________________________________________________________________________________________ +// namespaces +//_________________________________________________________________________________________________________________ + +using namespace ::utl ; +using namespace ::rtl ; +using namespace ::osl ; +using namespace ::com::sun::star::uno ; + +//_________________________________________________________________________________________________________________ +// const +//_________________________________________________________________________________________________________________ + +#define ROOTNODE_WORKINGSET OUString(RTL_CONSTASCII_USTRINGPARAM("Office.Common/WorkingSet")) +#define DEFAULT_WINDOWLIST Sequence< OUString >() + +#define PROPERTYNAME_WINDOWLIST OUString(RTL_CONSTASCII_USTRINGPARAM("WindowList" )) + +#define PROPERTYHANDLE_WINDOWLIST 0 + +#define PROPERTYCOUNT 1 + +//_________________________________________________________________________________________________________________ +// private declarations! +//_________________________________________________________________________________________________________________ + +class SvtWorkingSetOptions_Impl : public ConfigItem +{ + //------------------------------------------------------------------------------------------------------------- + // public methods + //------------------------------------------------------------------------------------------------------------- + + public: + + //--------------------------------------------------------------------------------------------------------- + // constructor / destructor + //--------------------------------------------------------------------------------------------------------- + + SvtWorkingSetOptions_Impl(); + ~SvtWorkingSetOptions_Impl(); + + //--------------------------------------------------------------------------------------------------------- + // overloaded methods of baseclass + //--------------------------------------------------------------------------------------------------------- + + /*-****************************************************************************************************//** + @short called for notify of configmanager + @descr These method is called from the ConfigManager before application ends or from the + PropertyChangeListener if the sub tree broadcasts changes. You must update your + internal values. + + @seealso baseclass ConfigItem + + @param "seqPropertyNames" is the list of properties which should be updated. + @return - + + @onerror - + *//*-*****************************************************************************************************/ + + virtual void Notify( const Sequence< OUString >& seqPropertyNames ); + + /*-****************************************************************************************************//** + @short write changes to configuration + @descr These method writes the changed values into the sub tree + and should always called in our destructor to guarantee consistency of config data. + + @seealso baseclass ConfigItem + + @param - + @return - + + @onerror - + *//*-*****************************************************************************************************/ + + virtual void Commit(); + + //--------------------------------------------------------------------------------------------------------- + // public interface + //--------------------------------------------------------------------------------------------------------- + + /*-****************************************************************************************************//** + @short access method to get internal values + @descr These method give us a chance to regulate acces to ouer internal values. + It's not used in the moment - but it's possible for the feature! + + @seealso - + + @param - + @return - + + @onerror - + *//*-*****************************************************************************************************/ + + Sequence< OUString > GetWindowList( ) const ; + void SetWindowList( const Sequence< OUString >& seqWindowList ) ; + + //------------------------------------------------------------------------------------------------------------- + // private methods + //------------------------------------------------------------------------------------------------------------- + + private: + + /*-****************************************************************************************************//** + @short return list of key names of ouer configuration management which represent oue module tree + @descr These methods return a static const list of key names. We need it to get needed values from our + configuration management. + + @seealso - + + @param - + @return A list of needed configuration keys is returned. + + @onerror - + *//*-*****************************************************************************************************/ + + static Sequence< OUString > GetPropertyNames(); + + //------------------------------------------------------------------------------------------------------------- + // private member + //------------------------------------------------------------------------------------------------------------- + + private: + + Sequence< OUString > m_seqWindowList ; +}; + +//_________________________________________________________________________________________________________________ +// definitions +//_________________________________________________________________________________________________________________ + +//***************************************************************************************************************** +// constructor +//***************************************************************************************************************** +SvtWorkingSetOptions_Impl::SvtWorkingSetOptions_Impl() + // Init baseclasses first + : ConfigItem ( ROOTNODE_WORKINGSET ) + // Init member then. + , m_seqWindowList ( DEFAULT_WINDOWLIST ) +{ + // Use our static list of configuration keys to get his values. + Sequence< OUString > seqNames = GetPropertyNames ( ); + Sequence< Any > seqValues = GetProperties ( seqNames ); + + // 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( !(seqNames.getLength()!=seqValues.getLength()), "SvtWorkingSetOptions_Impl::SvtWorkingSetOptions_Impl()\nI miss some values of configuration keys!\n" ); + + // Copy values from list in right order to ouer internal member. + sal_Int32 nPropertyCount = seqValues.getLength(); + for( sal_Int32 nProperty=0; nProperty<nPropertyCount; ++nProperty ) + { + // Safe impossible cases. + // Check any for valid value. + DBG_ASSERT( !(seqValues[nProperty].hasValue()==sal_False), "SvtWorkingSetOptions_Impl::SvtWorkingSetOptions_Impl()\nInvalid property value detected!\n" ); + switch( nProperty ) + { + case PROPERTYHANDLE_WINDOWLIST : { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_SEQUENCE), "SvtWorkingSetOptions_Impl::SvtWorkingSetOptions_Impl()\nWho has changed the value type of \"Office.Common\\WorkingSet\\WindowList\"?" ); + seqValues[nProperty] >>= m_seqWindowList; + } + break; + } + } + + // Enable notification mechanism of ouer baseclass. + // We need it to get information about changes outside these class on ouer used configuration keys! + EnableNotification( seqNames ); +} + +//***************************************************************************************************************** +// destructor +//***************************************************************************************************************** +SvtWorkingSetOptions_Impl::~SvtWorkingSetOptions_Impl() +{ + // We must save our current values .. if user forget it! + if( IsModified() == sal_True ) + { + Commit(); + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtWorkingSetOptions_Impl::Notify( const Sequence< OUString >& seqPropertyNames ) +{ + // Use given list of updated properties to get his values from configuration directly! + Sequence< Any > seqValues = GetProperties( seqPropertyNames ); + // Safe impossible cases. + // We need values from ALL notified configuration keys. + DBG_ASSERT( !(seqPropertyNames.getLength()!=seqValues.getLength()), "SvtWorkingSetOptions_Impl::Notify()\nI miss some values of configuration keys!\n" ); + // Step over list of property names and get right value from coreesponding value list to set it on internal members! + sal_Int32 nCount = seqPropertyNames.getLength(); + for( sal_Int32 nProperty=0; nProperty<nCount; ++nProperty ) + { + if( seqPropertyNames[nProperty] == PROPERTYNAME_WINDOWLIST ) + { + DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_SEQUENCE), "SvtWorkingSetOptions_Impl::Notify()\nWho has changed the value type of \"Office.Common\\WorkingSet\\WindowList\"?" ); + seqValues[nProperty] >>= m_seqWindowList; + } + #if OSL_DEBUG_LEVEL > 1 + else DBG_ASSERT( sal_False, "SvtWorkingSetOptions_Impl::Notify()\nUnkown property detected ... I can't handle these!\n" ); + #endif + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtWorkingSetOptions_Impl::Commit() +{ + // Get names of supported properties, create a list for values and copy current values to it. + Sequence< OUString > seqNames = GetPropertyNames (); + sal_Int32 nCount = seqNames.getLength(); + Sequence< Any > seqValues ( nCount ); + for( sal_Int32 nProperty=0; nProperty<nCount; ++nProperty ) + { + switch( nProperty ) + { + case PROPERTYHANDLE_WINDOWLIST : { + seqValues[nProperty] <<= m_seqWindowList; + } + break; + } + } + // Set properties in configuration. + PutProperties( seqNames, seqValues ); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +Sequence< OUString > SvtWorkingSetOptions_Impl::GetWindowList() const +{ + return m_seqWindowList; +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtWorkingSetOptions_Impl::SetWindowList( const Sequence< OUString >& seqWindowList ) +{ + m_seqWindowList = seqWindowList; + SetModified(); +} + +//***************************************************************************************************************** +// private method +//***************************************************************************************************************** +Sequence< OUString > SvtWorkingSetOptions_Impl::GetPropertyNames() +{ + // Build static list of configuration key names. + static const OUString pProperties[] = + { + PROPERTYNAME_WINDOWLIST , + }; + // Initialize return sequence with these list ... + static const Sequence< OUString > seqPropertyNames( pProperties, PROPERTYCOUNT ); + // ... and return it. + return seqPropertyNames; +} + +//***************************************************************************************************************** +// initialize static member +// DON'T DO IT IN YOUR HEADER! +// see definition for further informations +//***************************************************************************************************************** +SvtWorkingSetOptions_Impl* SvtWorkingSetOptions::m_pDataContainer = NULL ; +sal_Int32 SvtWorkingSetOptions::m_nRefCount = 0 ; + +//***************************************************************************************************************** +// constructor +//***************************************************************************************************************** +SvtWorkingSetOptions::SvtWorkingSetOptions() +{ + // Global access, must be guarded (multithreading!). + MutexGuard aGuard( GetOwnStaticMutex() ); + // Increase ouer refcount ... + ++m_nRefCount; + // ... and initialize ouer data container only if it not already exist! + if( m_pDataContainer == NULL ) + { + m_pDataContainer = new SvtWorkingSetOptions_Impl; + ItemHolder1::holdConfigItem(E_WORKINGSETOPTIONS); + } +} + +//***************************************************************************************************************** +// destructor +//***************************************************************************************************************** +SvtWorkingSetOptions::~SvtWorkingSetOptions() +{ + // Global access, must be guarded (multithreading!) + MutexGuard aGuard( GetOwnStaticMutex() ); + // Decrease ouer refcount. + --m_nRefCount; + // If last instance was deleted ... + // we must destroy ouer static data container! + if( m_nRefCount <= 0 ) + { + delete m_pDataContainer; + m_pDataContainer = NULL; + } +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +Sequence< OUString > SvtWorkingSetOptions::GetWindowList() const +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + return m_pDataContainer->GetWindowList(); +} + +//***************************************************************************************************************** +// public method +//***************************************************************************************************************** +void SvtWorkingSetOptions::SetWindowList( const Sequence< OUString >& seqWindowList ) +{ + MutexGuard aGuard( GetOwnStaticMutex() ); + m_pDataContainer->SetWindowList( seqWindowList ); +} + +//***************************************************************************************************************** +// private method +//***************************************************************************************************************** +Mutex& SvtWorkingSetOptions::GetOwnStaticMutex() +{ + // Initialize static mutex only for one time! + static Mutex* pMutex = NULL; + // If these method first called (Mutex not already exist!) ... + if( pMutex == NULL ) + { + // ... we must create a new one. Protect follow code with the global mutex - + // It must be - we create a static variable! + MutexGuard aGuard( Mutex::getGlobalMutex() ); + // We must check our pointer again - because it can be that another instance of ouer class will be fastr then these! + if( pMutex == NULL ) + { + // Create the new mutex and set it for return on static variable. + static Mutex aMutex; + pMutex = &aMutex; + } + } + // Return new created or already existing mutex object. + return *pMutex; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/unotools/source/config/xmlaccelcfg.cxx b/unotools/source/config/xmlaccelcfg.cxx new file mode 100644 index 000000000000..bd8f14c0373a --- /dev/null +++ b/unotools/source/config/xmlaccelcfg.cxx @@ -0,0 +1,418 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_unotools.hxx" + +#include <unotools/xmlaccelcfg.hxx> + +#include <vector> +#include <com/sun/star/xml/sax/XAttributeList.hpp> +#include <cppuhelper/implbase1.hxx> + +using namespace rtl; +using namespace com::sun::star::uno; +using namespace com::sun::star::xml::sax; + +#define ELEMENT_ACCELERATORLIST "acceleratorlist" +#define ELEMENT_ACCELERATORITEM "item" + +#define ATTRIBUTE_KEYCODE "code" +#define ATTRIBUTE_MODIFIER "modifier" +#define ATTRIBUTE_URL "url" + +#define ATTRIBUTE_TYPE_CDATA "CDATA" + +// ------------------------------------------------------------------ + +struct AttributeListImpl_impl; +class AttributeListImpl : public ::cppu::WeakImplHelper1< ::com::sun::star::xml::sax::XAttributeList > +{ +protected: + ~AttributeListImpl(); + +public: + AttributeListImpl(); + AttributeListImpl( const AttributeListImpl & ); + +public: + virtual sal_Int16 SAL_CALL getLength(void) throw (::com::sun::star::uno::RuntimeException); + virtual ::rtl::OUString SAL_CALL getNameByIndex(sal_Int16 i) throw (::com::sun::star::uno::RuntimeException); + virtual ::rtl::OUString SAL_CALL getTypeByIndex(sal_Int16 i) throw (::com::sun::star::uno::RuntimeException); + virtual ::rtl::OUString SAL_CALL getTypeByName(const ::rtl::OUString& aName) throw (::com::sun::star::uno::RuntimeException); + virtual ::rtl::OUString SAL_CALL getValueByIndex(sal_Int16 i) throw (::com::sun::star::uno::RuntimeException); + virtual ::rtl::OUString SAL_CALL getValueByName(const ::rtl::OUString& aName) throw (::com::sun::star::uno::RuntimeException); + +public: + void addAttribute( const ::rtl::OUString &sName , const ::rtl::OUString &sType , const ::rtl::OUString &sValue ); + void clear(); + +private: + struct AttributeListImpl_impl *m_pImpl; +}; + +struct TagAttribute +{ + TagAttribute(){} + TagAttribute( const OUString &aName, const OUString &aType , const OUString &aValue ) + { + sName = aName; + sType = aType; + sValue = aValue; + } + + OUString sName; + OUString sType; + OUString sValue; +}; + +struct AttributeListImpl_impl +{ + AttributeListImpl_impl() + { + // performance improvement during adding + vecAttribute.reserve(20); + } + ::std::vector<struct TagAttribute> vecAttribute; +}; + + + +sal_Int16 SAL_CALL AttributeListImpl::getLength(void) throw (RuntimeException) +{ + return sal::static_int_cast< sal_Int16 >(m_pImpl->vecAttribute.size()); +} + + +AttributeListImpl::AttributeListImpl( const AttributeListImpl &r ) : + cppu::WeakImplHelper1<com::sun::star::xml::sax::XAttributeList>(r) +{ + m_pImpl = new AttributeListImpl_impl; + *m_pImpl = *(r.m_pImpl); +} + +OUString AttributeListImpl::getNameByIndex(sal_Int16 i) throw (RuntimeException) +{ + if( i < sal::static_int_cast<sal_Int16>(m_pImpl->vecAttribute.size()) ) { + return m_pImpl->vecAttribute[i].sName; + } + return OUString(); +} + + +OUString AttributeListImpl::getTypeByIndex(sal_Int16 i) throw (RuntimeException) +{ + if( i < sal::static_int_cast<sal_Int16>(m_pImpl->vecAttribute.size()) ) { + return m_pImpl->vecAttribute[i].sType; + } + return OUString(); +} + +OUString AttributeListImpl::getValueByIndex(sal_Int16 i) throw (RuntimeException) +{ + if( i < sal::static_int_cast<sal_Int16>(m_pImpl->vecAttribute.size()) ) { + return m_pImpl->vecAttribute[i].sValue; + } + return OUString(); + +} + +OUString AttributeListImpl::getTypeByName( const OUString& sName ) throw (RuntimeException) +{ + ::std::vector<struct TagAttribute>::iterator ii = m_pImpl->vecAttribute.begin(); + + for( ; ii != m_pImpl->vecAttribute.end() ; ii ++ ) { + if( (*ii).sName == sName ) { + return (*ii).sType; + } + } + return OUString(); +} + +OUString AttributeListImpl::getValueByName(const OUString& sName) throw (RuntimeException) +{ + ::std::vector<struct TagAttribute>::iterator ii = m_pImpl->vecAttribute.begin(); + + for( ; ii != m_pImpl->vecAttribute.end() ; ii ++ ) { + if( (*ii).sName == sName ) { + return (*ii).sValue; + } + } + return OUString(); +} + + +AttributeListImpl::AttributeListImpl() +{ + m_pImpl = new AttributeListImpl_impl; +} + + + +AttributeListImpl::~AttributeListImpl() +{ + delete m_pImpl; +} + + +void AttributeListImpl::addAttribute( const OUString &sName , + const OUString &sType , + const OUString &sValue ) +{ + m_pImpl->vecAttribute.push_back( TagAttribute( sName , sType , sValue ) ); +} + +void AttributeListImpl::clear() +{ + ::std::vector<struct TagAttribute> dummy; + m_pImpl->vecAttribute.swap( dummy ); + + OSL_ASSERT( ! getLength() ); +} + +// ------------------------------------------------------------------ + +Any SAL_CALL OReadAccelatorDocumentHandler::queryInterface( const Type & rType ) throw( RuntimeException ) +{ + Any a = ::cppu::queryInterface( rType ,SAL_STATIC_CAST( XDocumentHandler*, this )); + if ( a.hasValue() ) + return a; + else + return OWeakObject::queryInterface( rType ); +} + +void SAL_CALL OReadAccelatorDocumentHandler::ignorableWhitespace( + const OUString& ) +throw( SAXException, RuntimeException ) +{ +} + +void SAL_CALL OReadAccelatorDocumentHandler::processingInstruction( + const OUString&, const OUString& ) +throw( SAXException, RuntimeException ) +{ +} + +void SAL_CALL OReadAccelatorDocumentHandler::setDocumentLocator( + const Reference< XLocator > &xLocator) +throw( SAXException, RuntimeException ) +{ + m_xLocator = xLocator; +} + +::rtl::OUString OReadAccelatorDocumentHandler::getErrorLineString() +{ + char buffer[32]; + + if ( m_xLocator.is() ) + { + return OUString::createFromAscii( buffer ); + } + else + return OUString(); +} + +void SAL_CALL OReadAccelatorDocumentHandler::startDocument(void) + throw ( SAXException, RuntimeException ) +{ +} + +void SAL_CALL OReadAccelatorDocumentHandler::endDocument(void) + throw( SAXException, RuntimeException ) +{ + if ( m_nElementDepth > 0 ) + { + OUString aErrorMessage = getErrorLineString(); + aErrorMessage += OUString( RTL_CONSTASCII_USTRINGPARAM( "A closing element is missing!" )); + throw SAXException( aErrorMessage, Reference< XInterface >(), Any() ); + } +} + + +void SAL_CALL OReadAccelatorDocumentHandler::startElement( + const OUString& aElementName, const Reference< XAttributeList > &xAttrList ) +throw( SAXException, RuntimeException ) +{ + m_nElementDepth++; + + if ( aElementName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( ELEMENT_ACCELERATORLIST ))) + { + // acceleratorlist + if ( m_bAcceleratorMode ) + { + OUString aErrorMessage = getErrorLineString(); + aErrorMessage += OUString( RTL_CONSTASCII_USTRINGPARAM( "Accelerator list used twice!" )); + throw SAXException( aErrorMessage, Reference< XInterface >(), Any() ); + } + else + m_bAcceleratorMode = sal_True; + } + else if ( aElementName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( ELEMENT_ACCELERATORITEM ))) + { + // accelerator item + if ( !m_bAcceleratorMode ) + { + OUString aErrorMessage = getErrorLineString(); + aErrorMessage += OUString( RTL_CONSTASCII_USTRINGPARAM( "Accelerator list element has to be used before!" )); + throw SAXException( aErrorMessage, Reference< XInterface >(), Any() ); + } + else + { + // read accelerator item + m_bItemCloseExpected = sal_True; + + SvtAcceleratorConfigItem aItem; + + // read attributes for accelerator + for ( sal_Int16 i=0; i< xAttrList->getLength(); i++ ) + { + OUString aName = xAttrList->getNameByIndex( i ); + OUString aValue = xAttrList->getValueByIndex( i ); + + if ( aName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( ATTRIBUTE_URL ))) + aItem.aCommand = aValue; + else if ( aName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( ATTRIBUTE_MODIFIER ))) + aItem.nModifier = (sal_uInt16)aValue.toInt32(); + else if ( aName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( ATTRIBUTE_KEYCODE ))) + aItem.nCode = (sal_uInt16)aValue.toInt32(); + } + + m_aReadAcceleratorList.push_back( aItem ); + } + } + else + { + OUString aErrorMessage = getErrorLineString(); + aErrorMessage += OUString( RTL_CONSTASCII_USTRINGPARAM( "Unknown element found!" )); + throw SAXException( aErrorMessage, Reference< XInterface >(), Any() ); + } +} + + +void SAL_CALL OReadAccelatorDocumentHandler::characters(const rtl::OUString&) +throw( SAXException, RuntimeException ) +{ +} + + +void SAL_CALL OReadAccelatorDocumentHandler::endElement( const OUString& aName ) + throw( SAXException, RuntimeException ) +{ + m_nElementDepth--; + + if ( aName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( ELEMENT_ACCELERATORLIST ))) + { + // acceleratorlist + if ( !m_bAcceleratorMode ) + { + OUString aErrorMessage = getErrorLineString(); + aErrorMessage += OUString( RTL_CONSTASCII_USTRINGPARAM( "Accelerator list used twice!" )); + throw SAXException( aErrorMessage, Reference< XInterface >(), Any() ); + } + } + else if ( aName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( ELEMENT_ACCELERATORITEM ))) + { + if ( !m_bItemCloseExpected ) + { + OUString aErrorMessage = getErrorLineString(); + aErrorMessage += OUString( RTL_CONSTASCII_USTRINGPARAM( "Closing accelerator item element expected!" )); + throw SAXException( aErrorMessage, Reference< XInterface >(), Any() ); + } + } + else + { + OUString aErrorMessage = getErrorLineString(); + aErrorMessage += OUString( RTL_CONSTASCII_USTRINGPARAM( "Unknown closing element found!" )); + throw SAXException( aErrorMessage, Reference< XInterface >(), Any() ); + } +} + +// ------------------------------------------------------------------ + +OWriteAccelatorDocumentHandler::OWriteAccelatorDocumentHandler( + const SvtAcceleratorItemList& aWriteAcceleratorList, Reference< XDocumentHandler > xDocumentHandler ) : + m_xWriteDocumentHandler( xDocumentHandler ), + m_aWriteAcceleratorList( aWriteAcceleratorList ) +{ + m_aAttributeType = OUString( RTL_CONSTASCII_USTRINGPARAM( ATTRIBUTE_TYPE_CDATA )); +} + +OWriteAccelatorDocumentHandler::~OWriteAccelatorDocumentHandler() +{ +} + +void OWriteAccelatorDocumentHandler::WriteAcceleratorDocument() + throw ( SAXException, RuntimeException ) +{ + AttributeListImpl* pList = new AttributeListImpl; + Reference< XAttributeList > rList( (XAttributeList *)pList , UNO_QUERY ); + + m_xWriteDocumentHandler->startDocument(); + m_xWriteDocumentHandler->startElement( OUString( RTL_CONSTASCII_USTRINGPARAM( ELEMENT_ACCELERATORLIST )), rList ); + m_xWriteDocumentHandler->ignorableWhitespace( OUString() ); + + std::list< SvtAcceleratorConfigItem>::const_iterator p; + for ( p = m_aWriteAcceleratorList.begin(); p != m_aWriteAcceleratorList.end(); p++ ) + WriteAcceleratorItem( *p ); + + m_xWriteDocumentHandler->endElement( OUString( RTL_CONSTASCII_USTRINGPARAM( ELEMENT_ACCELERATORLIST )) ); + m_xWriteDocumentHandler->endDocument(); +} + +void OWriteAccelatorDocumentHandler::WriteAcceleratorItem( + const SvtAcceleratorConfigItem& aAcceleratorItem ) + throw( SAXException, RuntimeException ) +{ + AttributeListImpl* pAcceleratorAttributes = new AttributeListImpl; + Reference< XAttributeList > xAcceleratorAttrList( (XAttributeList *)pAcceleratorAttributes , UNO_QUERY ); + + // set attributes + pAcceleratorAttributes->addAttribute( + OUString( RTL_CONSTASCII_USTRINGPARAM( ATTRIBUTE_KEYCODE )), + m_aAttributeType, + OUString::valueOf( aAcceleratorItem.nCode )); + + pAcceleratorAttributes->addAttribute( + OUString( RTL_CONSTASCII_USTRINGPARAM( ATTRIBUTE_MODIFIER )), + m_aAttributeType, + OUString::valueOf( aAcceleratorItem.nModifier )); + + pAcceleratorAttributes->addAttribute( + OUString( RTL_CONSTASCII_USTRINGPARAM( ATTRIBUTE_URL )), + m_aAttributeType, + aAcceleratorItem.aCommand ); + + // write start element + m_xWriteDocumentHandler->startElement( + OUString( RTL_CONSTASCII_USTRINGPARAM( ELEMENT_ACCELERATORITEM )), + xAcceleratorAttrList ); + m_xWriteDocumentHandler->ignorableWhitespace( OUString() ); + m_xWriteDocumentHandler->endElement( OUString( RTL_CONSTASCII_USTRINGPARAM( ELEMENT_ACCELERATORITEM )) ); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ |