diff options
Diffstat (limited to 'comphelper/source/misc')
51 files changed, 2251 insertions, 1273 deletions
diff --git a/comphelper/source/misc/AccessibleImplementationHelper.cxx b/comphelper/source/misc/AccessibleImplementationHelper.cxx index a45b6e5f3cd7..a02f4380dd33 100644 --- a/comphelper/source/misc/AccessibleImplementationHelper.cxx +++ b/comphelper/source/misc/AccessibleImplementationHelper.cxx @@ -33,8 +33,7 @@ OUString GetkeyBindingStrByXkeyBinding(const Sequence<KeyStroke>& keySet) OUStringBuffer buf; for (const auto& k : keySet) { - buf.append('\n'); - buf.append(k.KeyChar); + buf.append("\n" + OUStringChar(k.KeyChar)); } return buf.makeStringAndClear(); } diff --git a/comphelper/source/misc/DirectoryHelper.cxx b/comphelper/source/misc/DirectoryHelper.cxx index 248e7af185b7..badfe9b62d80 100644 --- a/comphelper/source/misc/DirectoryHelper.cxx +++ b/comphelper/source/misc/DirectoryHelper.cxx @@ -19,24 +19,24 @@ namespace comphelper { typedef std::shared_ptr<osl::File> FileSharedPtr; -OUString DirectoryHelper::splitAtLastToken(const OUString& rSrc, sal_Unicode aToken, - OUString& rRight) +std::u16string_view DirectoryHelper::splitAtLastToken(std::u16string_view rSrc, sal_Unicode aToken, + OUString& rRight) { - const sal_Int32 nIndex(rSrc.lastIndexOf(aToken)); - OUString aRetval; + const size_t nIndex(rSrc.rfind(aToken)); + std::u16string_view aRetval; - if (-1 == nIndex) + if (std::u16string_view::npos == nIndex) { aRetval = rSrc; rRight.clear(); } else if (nIndex > 0) { - aRetval = rSrc.copy(0, nIndex); + aRetval = rSrc.substr(0, nIndex); - if (rSrc.getLength() > nIndex + 1) + if (rSrc.size() > nIndex + 1) { - rRight = rSrc.copy(nIndex + 1); + rRight = rSrc.substr(nIndex + 1); } } @@ -210,4 +210,4 @@ bool DirectoryHelper::moveDirContent(const OUString& rSourceDirURL, return bError; } -}
\ No newline at end of file +} diff --git a/comphelper/source/misc/SelectionMultiplex.cxx b/comphelper/source/misc/SelectionMultiplex.cxx index 267266388c71..37e4e30037b3 100644 --- a/comphelper/source/misc/SelectionMultiplex.cxx +++ b/comphelper/source/misc/SelectionMultiplex.cxx @@ -95,7 +95,20 @@ void SAL_CALL OSelectionChangeMultiplexer::selectionChanged( const EventObject& m_pListener->_selectionChanged(_rEvent); } +void OSelectionChangeMultiplexer::dispose() +{ + osl_atomic_increment(&m_refCount); + { + Reference< XSelectionChangeListener> xPreventDelete(this); + if(m_xSet.is()) + { + m_xSet->removeSelectionChangeListener(xPreventDelete); + m_xSet.clear(); + } + } + osl_atomic_decrement(&m_refCount); } +} /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/comphelper/source/misc/accessiblecomponenthelper.cxx b/comphelper/source/misc/accessiblecomponenthelper.cxx index 2962bbac95a8..3922812b92af 100644 --- a/comphelper/source/misc/accessiblecomponenthelper.cxx +++ b/comphelper/source/misc/accessiblecomponenthelper.cxx @@ -18,6 +18,11 @@ */ #include <comphelper/accessiblecomponenthelper.hxx> +#include <comphelper/accessiblecontexthelper.hxx> +#include <osl/diagnose.h> +#include <com/sun/star/accessibility/IllegalAccessibleComponentStateException.hpp> +#include <comphelper/accessibleeventnotifier.hxx> +#include <comphelper/solarmutex.hxx> namespace comphelper @@ -30,12 +35,209 @@ namespace comphelper using namespace ::com::sun::star::accessibility; OCommonAccessibleComponent::OCommonAccessibleComponent( ) + :OCommonAccessibleComponent_Base( GetMutex() ) + ,m_nClientId( 0 ) { } OCommonAccessibleComponent::~OCommonAccessibleComponent( ) { + // this ensures that the lock, which may be already destroyed as part of the derivee, + // is not used anymore + + ensureDisposed(); + } + + + void SAL_CALL OCommonAccessibleComponent::disposing() + { + // rhbz#1001768: de facto this class is locked by SolarMutex; + // do not lock m_Mutex because it may cause deadlock + osl::Guard<SolarMutex> aGuard(SolarMutex::get()); + + if ( m_nClientId ) + { + AccessibleEventNotifier::revokeClientNotifyDisposing( m_nClientId, *this ); + m_nClientId=0; + } + } + + + void SAL_CALL OCommonAccessibleComponent::addAccessibleEventListener( const Reference< XAccessibleEventListener >& _rxListener ) + { + osl::Guard<SolarMutex> aGuard(SolarMutex::get()); + // don't use the OContextEntryGuard - it will throw an exception if we're not alive + // anymore, while the most recent specification for XComponent states that we should + // silently ignore the call in such a situation + if ( !isAlive() ) + { + if ( _rxListener.is() ) + _rxListener->disposing( EventObject( *this ) ); + return; + } + + if ( _rxListener.is() ) + { + if ( !m_nClientId ) + m_nClientId = AccessibleEventNotifier::registerClient( ); + + AccessibleEventNotifier::addEventListener( m_nClientId, _rxListener ); + } + } + + + void SAL_CALL OCommonAccessibleComponent::removeAccessibleEventListener( const Reference< XAccessibleEventListener >& _rxListener ) + { + osl::Guard<SolarMutex> aGuard(SolarMutex::get()); + // don't use the OContextEntryGuard - it will throw an exception if we're not alive + // anymore, while the most recent specification for XComponent states that we should + // silently ignore the call in such a situation + if ( !isAlive() ) + return; + + if ( !(_rxListener.is() && m_nClientId) ) + return; + + sal_Int32 nListenerCount = AccessibleEventNotifier::removeEventListener( m_nClientId, _rxListener ); + if ( !nListenerCount ) + { + // no listeners anymore + // -> revoke ourself. This may lead to the notifier thread dying (if we were the last client), + // and at least to us not firing any events anymore, in case somebody calls + // NotifyAccessibleEvent, again + AccessibleEventNotifier::revokeClient( m_nClientId ); + m_nClientId = 0; + } + } + + + void OCommonAccessibleComponent::NotifyAccessibleEvent( const sal_Int16 _nEventId, + const Any& _rOldValue, const Any& _rNewValue, sal_Int32 nIndexHint ) + { + if ( !m_nClientId ) + // if we don't have a client id for the notifier, then we don't have listeners, then + // we don't need to notify anything + return; + + // build an event object + AccessibleEventObject aEvent(*this, _nEventId, _rNewValue, _rOldValue, nIndexHint); + + // let the notifier handle this event + AccessibleEventNotifier::addEvent( m_nClientId, aEvent ); + } + + + bool OCommonAccessibleComponent::isAlive() const + { + return !rBHelper.bDisposed && !rBHelper.bInDispose; + } + + + void OCommonAccessibleComponent::ensureAlive() const + { + if( !isAlive() ) + throw DisposedException(); + } + + + void OCommonAccessibleComponent::ensureDisposed( ) + { + if ( !rBHelper.bDisposed ) + { + OSL_ENSURE( 0 == m_refCount, "OCommonAccessibleComponent::ensureDisposed: this method _has_ to be called from without your dtor only!" ); + acquire(); + dispose(); + } + } + + + void OCommonAccessibleComponent::lateInit( const Reference< XAccessible >& _rxAccessible ) + { + m_aCreator = _rxAccessible; + } + + + Reference< XAccessible > OCommonAccessibleComponent::getAccessibleCreator( ) const + { + return m_aCreator; + } + + + OUString SAL_CALL OCommonAccessibleComponent::getAccessibleId( ) + { + return OUString(); + } + + + sal_Int64 SAL_CALL OCommonAccessibleComponent::getAccessibleIndexInParent( ) + { + OExternalLockGuard aGuard( this ); + + // -1 for child not found/no parent (according to specification) + sal_Int64 nRet = -1; + + try + { + + Reference< XAccessibleContext > xParentContext( implGetParentContext() ); + + // iterate over parent's children and search for this object + if ( xParentContext.is() ) + { + // our own XAccessible for comparing with the children of our parent + Reference< XAccessible > xCreator( m_aCreator); + + OSL_ENSURE( xCreator.is(), "OCommonAccessibleComponent::getAccessibleIndexInParent: invalid creator!" ); + // two ideas why this could be NULL: + // * nobody called our late ctor (init), so we never had a creator at all -> bad + // * the creator is already dead. In this case, we should have been disposed, and + // never survived the above OContextEntryGuard. + // in all other situations the creator should be non-NULL + + if ( xCreator.is() ) + { + sal_Int64 nChildCount = xParentContext->getAccessibleChildCount(); + for ( sal_Int64 nChild = 0; ( nChild < nChildCount ) && ( -1 == nRet ); ++nChild ) + { + Reference< XAccessible > xChild( xParentContext->getAccessibleChild( nChild ) ); + if ( xChild.get() == xCreator.get() ) + nRet = nChild; + } + } + } + } + catch( const Exception& ) + { + OSL_FAIL( "OCommonAccessibleComponent::getAccessibleIndexInParent: caught an exception!" ); + } + + return nRet; + } + + + Locale SAL_CALL OCommonAccessibleComponent::getLocale( ) + { + // simply ask the parent + Reference< XAccessible > xParent = getAccessibleParent(); + Reference< XAccessibleContext > xParentContext; + if ( xParent.is() ) + xParentContext = xParent->getAccessibleContext(); + + if ( !xParentContext.is() ) + throw IllegalAccessibleComponentStateException( OUString(), *this ); + + return xParentContext->getLocale(); + } + + + Reference< XAccessibleContext > OCommonAccessibleComponent::implGetParentContext() + { + Reference< XAccessible > xParent = getAccessibleParent(); + Reference< XAccessibleContext > xParentContext; + if ( xParent.is() ) + xParentContext = xParent->getAccessibleContext(); + return xParentContext; } @@ -97,11 +299,6 @@ namespace comphelper } - IMPLEMENT_FORWARD_XINTERFACE2( OAccessibleComponentHelper, OCommonAccessibleComponent, OAccessibleComponentHelper_Base ) - IMPLEMENT_FORWARD_XTYPEPROVIDER2( OAccessibleComponentHelper, OCommonAccessibleComponent, OAccessibleComponentHelper_Base ) - // (order matters: the first is the class name, the second is the class doing the ref counting) - - sal_Bool SAL_CALL OAccessibleComponentHelper::containsPoint( const awt::Point& _rPoint ) { return OCommonAccessibleComponent::containsPoint( _rPoint ); @@ -136,11 +333,6 @@ namespace comphelper } - IMPLEMENT_FORWARD_XINTERFACE2( OAccessibleExtendedComponentHelper, OCommonAccessibleComponent, OAccessibleExtendedComponentHelper_Base ) - IMPLEMENT_FORWARD_XTYPEPROVIDER2( OAccessibleExtendedComponentHelper, OCommonAccessibleComponent, OAccessibleExtendedComponentHelper_Base ) - // (order matters: the first is the class name, the second is the class doing the ref counting) - - sal_Bool SAL_CALL OAccessibleExtendedComponentHelper::containsPoint( const awt::Point& _rPoint ) { return OCommonAccessibleComponent::containsPoint( _rPoint ); diff --git a/comphelper/source/misc/accessiblecontexthelper.cxx b/comphelper/source/misc/accessiblecontexthelper.cxx deleted file mode 100644 index ad2c63b1a1c0..000000000000 --- a/comphelper/source/misc/accessiblecontexthelper.cxx +++ /dev/null @@ -1,248 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ -/* - * This file is part of the LibreOffice project. - * - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - * - * This file incorporates work covered by the following license notice: - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed - * with this work for additional information regarding copyright - * ownership. The ASF licenses this file to you under the Apache - * License, Version 2.0 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.apache.org/licenses/LICENSE-2.0 . - */ - -#include <comphelper/accessiblecontexthelper.hxx> -#include <osl/diagnose.h> -#include <cppuhelper/weakref.hxx> -#include <com/sun/star/accessibility/IllegalAccessibleComponentStateException.hpp> -#include <comphelper/accessibleeventnotifier.hxx> -#include <comphelper/solarmutex.hxx> - - -namespace comphelper -{ - using namespace ::com::sun::star::uno; - using namespace ::com::sun::star::lang; - using namespace ::com::sun::star::accessibility; - - OAccessibleContextHelper::OAccessibleContextHelper( ) - :OAccessibleContextHelper_Base( GetMutex() ) - ,m_nClientId( 0 ) - { - } - - - OAccessibleContextHelper::~OAccessibleContextHelper( ) - { - // this ensures that the lock, which may be already destroyed as part of the derivee, - // is not used anymore - - ensureDisposed(); - } - - - void SAL_CALL OAccessibleContextHelper::disposing() - { - // rhbz#1001768: de facto this class is locked by SolarMutex; - // do not lock m_Mutex because it may cause deadlock - osl::Guard<SolarMutex> aGuard(SolarMutex::get()); - - if ( m_nClientId ) - { - AccessibleEventNotifier::revokeClientNotifyDisposing( m_nClientId, *this ); - m_nClientId=0; - } - } - - - void SAL_CALL OAccessibleContextHelper::addAccessibleEventListener( const Reference< XAccessibleEventListener >& _rxListener ) - { - osl::Guard<SolarMutex> aGuard(SolarMutex::get()); - // don't use the OContextEntryGuard - it will throw an exception if we're not alive - // anymore, while the most recent specification for XComponent states that we should - // silently ignore the call in such a situation - if ( !isAlive() ) - { - if ( _rxListener.is() ) - _rxListener->disposing( EventObject( *this ) ); - return; - } - - if ( _rxListener.is() ) - { - if ( !m_nClientId ) - m_nClientId = AccessibleEventNotifier::registerClient( ); - - AccessibleEventNotifier::addEventListener( m_nClientId, _rxListener ); - } - } - - - void SAL_CALL OAccessibleContextHelper::removeAccessibleEventListener( const Reference< XAccessibleEventListener >& _rxListener ) - { - osl::Guard<SolarMutex> aGuard(SolarMutex::get()); - // don't use the OContextEntryGuard - it will throw an exception if we're not alive - // anymore, while the most recent specification for XComponent states that we should - // silently ignore the call in such a situation - if ( !isAlive() ) - return; - - if ( !(_rxListener.is() && m_nClientId) ) - return; - - sal_Int32 nListenerCount = AccessibleEventNotifier::removeEventListener( m_nClientId, _rxListener ); - if ( !nListenerCount ) - { - // no listeners anymore - // -> revoke ourself. This may lead to the notifier thread dying (if we were the last client), - // and at least to us not firing any events anymore, in case somebody calls - // NotifyAccessibleEvent, again - AccessibleEventNotifier::revokeClient( m_nClientId ); - m_nClientId = 0; - } - } - - - void OAccessibleContextHelper::NotifyAccessibleEvent( const sal_Int16 _nEventId, - const Any& _rOldValue, const Any& _rNewValue ) - { - if ( !m_nClientId ) - // if we don't have a client id for the notifier, then we don't have listeners, then - // we don't need to notify anything - return; - - // build an event object - AccessibleEventObject aEvent; - aEvent.Source = *this; - aEvent.EventId = _nEventId; - aEvent.OldValue = _rOldValue; - aEvent.NewValue = _rNewValue; - - // let the notifier handle this event - AccessibleEventNotifier::addEvent( m_nClientId, aEvent ); - } - - - bool OAccessibleContextHelper::isAlive() const - { - return !rBHelper.bDisposed && !rBHelper.bInDispose; - } - - - void OAccessibleContextHelper::ensureAlive() const - { - if( !isAlive() ) - throw DisposedException(); - } - - - void OAccessibleContextHelper::ensureDisposed( ) - { - if ( !rBHelper.bDisposed ) - { - OSL_ENSURE( 0 == m_refCount, "OAccessibleContextHelper::ensureDisposed: this method _has_ to be called from without your dtor only!" ); - acquire(); - dispose(); - } - } - - - void OAccessibleContextHelper::lateInit( const Reference< XAccessible >& _rxAccessible ) - { - m_aCreator = _rxAccessible; - } - - - Reference< XAccessible > OAccessibleContextHelper::getAccessibleCreator( ) const - { - return m_aCreator; - } - - - OUString SAL_CALL OAccessibleContextHelper::getAccessibleId( ) - { - return OUString(); - } - - - sal_Int32 SAL_CALL OAccessibleContextHelper::getAccessibleIndexInParent( ) - { - OExternalLockGuard aGuard( this ); - - // -1 for child not found/no parent (according to specification) - sal_Int32 nRet = -1; - - try - { - - Reference< XAccessibleContext > xParentContext( implGetParentContext() ); - - // iterate over parent's children and search for this object - if ( xParentContext.is() ) - { - // our own XAccessible for comparing with the children of our parent - Reference< XAccessible > xCreator( m_aCreator); - - OSL_ENSURE( xCreator.is(), "OAccessibleContextHelper::getAccessibleIndexInParent: invalid creator!" ); - // two ideas why this could be NULL: - // * nobody called our late ctor (init), so we never had a creator at all -> bad - // * the creator is already dead. In this case, we should have been disposed, and - // never survived the above OContextEntryGuard. - // in all other situations the creator should be non-NULL - - if ( xCreator.is() ) - { - sal_Int32 nChildCount = xParentContext->getAccessibleChildCount(); - for ( sal_Int32 nChild = 0; ( nChild < nChildCount ) && ( -1 == nRet ); ++nChild ) - { - Reference< XAccessible > xChild( xParentContext->getAccessibleChild( nChild ) ); - if ( xChild.get() == xCreator.get() ) - nRet = nChild; - } - } - } - } - catch( const Exception& ) - { - OSL_FAIL( "OAccessibleContextHelper::getAccessibleIndexInParent: caught an exception!" ); - } - - return nRet; - } - - - Locale SAL_CALL OAccessibleContextHelper::getLocale( ) - { - // simply ask the parent - Reference< XAccessible > xParent = getAccessibleParent(); - Reference< XAccessibleContext > xParentContext; - if ( xParent.is() ) - xParentContext = xParent->getAccessibleContext(); - - if ( !xParentContext.is() ) - throw IllegalAccessibleComponentStateException( OUString(), *this ); - - return xParentContext->getLocale(); - } - - - Reference< XAccessibleContext > OAccessibleContextHelper::implGetParentContext() - { - Reference< XAccessible > xParent = getAccessibleParent(); - Reference< XAccessibleContext > xParentContext; - if ( xParent.is() ) - xParentContext = xParent->getAccessibleContext(); - return xParentContext; - } - - -} // namespace comphelper - - -/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/comphelper/source/misc/accessibleeventnotifier.cxx b/comphelper/source/misc/accessibleeventnotifier.cxx index f8bd5a1170e8..9c3b55126bc6 100644 --- a/comphelper/source/misc/accessibleeventnotifier.cxx +++ b/comphelper/source/misc/accessibleeventnotifier.cxx @@ -21,9 +21,10 @@ #include <com/sun/star/accessibility/XAccessibleEventListener.hpp> #include <comphelper/interfacecontainer4.hxx> +#include <limits> #include <map> #include <memory> -#include <limits> +#include <unordered_map> using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; @@ -36,7 +37,7 @@ typedef std::pair< AccessibleEventNotifier::TClientId, AccessibleEventObject > ClientEvent; typedef ::comphelper::OInterfaceContainerHelper4<XAccessibleEventListener> ListenerContainer; -typedef std::map< AccessibleEventNotifier::TClientId, ListenerContainer* > ClientMap; +typedef std::unordered_map< AccessibleEventNotifier::TClientId, ListenerContainer > ClientMap; /// key is the end of the interval, value is the start of the interval typedef std::map<AccessibleEventNotifier::TClientId, @@ -154,10 +155,8 @@ AccessibleEventNotifier::TClientId AccessibleEventNotifier::registerClient() // generate a new client id TClientId nNewClientId = generateId( ); - // the event listeners for the new client - ListenerContainer * pNewListeners = new ListenerContainer(); // add the client - gaClients.emplace( nNewClientId, pNewListeners ); + gaClients.emplace( nNewClientId, ListenerContainer{} ); // outta here return nNewClientId; @@ -173,7 +172,6 @@ void AccessibleEventNotifier::revokeClient( const TClientId _nClient ) return; // remove it from the clients map - delete aClientPos->second; gaClients.erase( aClientPos ); releaseId(_nClient); } @@ -189,7 +187,7 @@ void AccessibleEventNotifier::revokeClientNotifyDisposing( return; // notify the listeners - std::unique_ptr<ListenerContainer> pListeners(aClientPos->second); + ListenerContainer aListeners(std::move(aClientPos->second)); // we do not need the entry in the clients map anymore // (do this before actually notifying, because some client @@ -203,7 +201,7 @@ void AccessibleEventNotifier::revokeClientNotifyDisposing( aDisposalEvent.Source = _rxEventSource; // now really do the notification - pListeners->disposeAndClear( aGuard, aDisposalEvent ); + aListeners.disposeAndClear( aGuard, aDisposalEvent ); } sal_Int32 AccessibleEventNotifier::addEventListener( @@ -217,9 +215,9 @@ sal_Int32 AccessibleEventNotifier::addEventListener( return 0; if ( _rxListener.is() ) - aClientPos->second->addInterface( aGuard, _rxListener ); + aClientPos->second.addInterface( aGuard, _rxListener ); - return aClientPos->second->getLength(aGuard); + return aClientPos->second.getLength(aGuard); } sal_Int32 AccessibleEventNotifier::removeEventListener( @@ -233,35 +231,31 @@ sal_Int32 AccessibleEventNotifier::removeEventListener( return 0; if ( _rxListener.is() ) - aClientPos->second->removeInterface( aGuard, _rxListener ); + aClientPos->second.removeInterface( aGuard, _rxListener ); - return aClientPos->second->getLength(aGuard); + return aClientPos->second.getLength(aGuard); } void AccessibleEventNotifier::addEvent( const TClientId _nClient, const AccessibleEventObject& _rEvent ) { - std::vector< Reference< XAccessibleEventListener > > aListeners; - - { - std::unique_lock aGuard( GetLocalMutex() ); - - ClientMap::iterator aClientPos; - if ( !implLookupClient( _nClient, aClientPos ) ) - // already asserted in implLookupClient - return; + std::unique_lock aGuard( GetLocalMutex() ); - // since we're synchronous, again, we want to notify immediately - aListeners = aClientPos->second->getElements(aGuard); - } + ClientMap::iterator aClientPos; + if ( !implLookupClient( _nClient, aClientPos ) ) + // already asserted in implLookupClient + return; - // default handling: loop through all listeners, and notify them - for ( const auto& rListener : aListeners ) + // since we're synchronous, again, we want to notify immediately + OInterfaceIteratorHelper4 aIt(aGuard, aClientPos->second); + // no need to hold lock here, and we don't want to hold lock while calling listeners + aGuard.unlock(); + while (aIt.hasMoreElements()) { try { - rListener->notifyEvent( _rEvent ); + aIt.next()->notifyEvent(_rEvent); } - catch( const Exception& ) + catch (Exception&) { // no assertion, because a broken access remote bridge or something like this // can cause this exception @@ -269,6 +263,11 @@ void AccessibleEventNotifier::addEvent( const TClientId _nClient, const Accessib } } +void AccessibleEventNotifier::shutdown() +{ + gaClients.clear(); +} + } // namespace comphelper /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/comphelper/source/misc/accessiblekeybindinghelper.cxx b/comphelper/source/misc/accessiblekeybindinghelper.cxx index cf16f157c5e3..d1db69b98fa8 100644 --- a/comphelper/source/misc/accessiblekeybindinghelper.cxx +++ b/comphelper/source/misc/accessiblekeybindinghelper.cxx @@ -21,6 +21,7 @@ #include <com/sun/star/lang/IndexOutOfBoundsException.hpp> #include <comphelper/accessiblekeybindinghelper.hxx> +#include <o3tl/safeint.hxx> namespace comphelper @@ -83,7 +84,7 @@ namespace comphelper { std::scoped_lock aGuard( m_aMutex ); - if ( nIndex < 0 || nIndex >= static_cast<sal_Int32>(m_aKeyBindings.size()) ) + if ( nIndex < 0 || o3tl::make_unsigned(nIndex) >= m_aKeyBindings.size() ) throw IndexOutOfBoundsException(); return m_aKeyBindings[nIndex]; diff --git a/comphelper/source/misc/accessibleselectionhelper.cxx b/comphelper/source/misc/accessibleselectionhelper.cxx index 967c1b079e48..ff880a76ee98 100644 --- a/comphelper/source/misc/accessibleselectionhelper.cxx +++ b/comphelper/source/misc/accessibleselectionhelper.cxx @@ -17,6 +17,7 @@ * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ +#include <comphelper/accessiblecontexthelper.hxx> #include <comphelper/accessibleselectionhelper.hxx> @@ -25,8 +26,6 @@ namespace comphelper using namespace ::com::sun::star::uno; - using namespace ::com::sun::star::awt; - using namespace ::com::sun::star::lang; using namespace ::com::sun::star::accessibility; OCommonAccessibleSelection::OCommonAccessibleSelection( ) @@ -36,13 +35,13 @@ namespace comphelper OCommonAccessibleSelection::~OCommonAccessibleSelection() {} - void OCommonAccessibleSelection::selectAccessibleChild( sal_Int32 nChildIndex ) + void OCommonAccessibleSelection::selectAccessibleChild( sal_Int64 nChildIndex ) { implSelect( nChildIndex, true ); } - bool OCommonAccessibleSelection::isAccessibleChildSelected( sal_Int32 nChildIndex ) + bool OCommonAccessibleSelection::isAccessibleChildSelected( sal_Int64 nChildIndex ) { return implIsSelected( nChildIndex ); } @@ -60,16 +59,16 @@ namespace comphelper } - sal_Int32 OCommonAccessibleSelection::getSelectedAccessibleChildCount( ) + sal_Int64 OCommonAccessibleSelection::getSelectedAccessibleChildCount( ) { - sal_Int32 nRet = 0; + sal_Int64 nRet = 0; Reference< XAccessibleContext > xParentContext( implGetAccessibleContext() ); OSL_ENSURE( xParentContext.is(), "OCommonAccessibleSelection::getSelectedAccessibleChildCount: no parent context!" ); if( xParentContext.is() ) { - for( sal_Int32 i = 0, nChildCount = xParentContext->getAccessibleChildCount(); i < nChildCount; i++ ) + for( sal_Int64 i = 0, nChildCount = xParentContext->getAccessibleChildCount(); i < nChildCount; i++ ) if( implIsSelected( i ) ) ++nRet; } @@ -78,7 +77,7 @@ namespace comphelper } - Reference< XAccessible > OCommonAccessibleSelection::getSelectedAccessibleChild( sal_Int32 nSelectedChildIndex ) + Reference< XAccessible > OCommonAccessibleSelection::getSelectedAccessibleChild( sal_Int64 nSelectedChildIndex ) { Reference< XAccessible > xRet; Reference< XAccessibleContext > xParentContext( implGetAccessibleContext() ); @@ -87,7 +86,7 @@ namespace comphelper if( xParentContext.is() ) { - for( sal_Int32 i = 0, nChildCount = xParentContext->getAccessibleChildCount(), nPos = 0; ( i < nChildCount ) && !xRet.is(); i++ ) + for( sal_Int64 i = 0, nChildCount = xParentContext->getAccessibleChildCount(), nPos = 0; ( i < nChildCount ) && !xRet.is(); i++ ) if( implIsSelected( i ) && ( nPos++ == nSelectedChildIndex ) ) xRet = xParentContext->getAccessibleChild( i ); } @@ -96,7 +95,7 @@ namespace comphelper } - void OCommonAccessibleSelection::deselectAccessibleChild( sal_Int32 nSelectedChildIndex ) + void OCommonAccessibleSelection::deselectAccessibleChild( sal_Int64 nSelectedChildIndex ) { implSelect( nSelectedChildIndex, false ); } @@ -106,25 +105,20 @@ namespace comphelper } - IMPLEMENT_FORWARD_XINTERFACE2( OAccessibleSelectionHelper, OAccessibleComponentHelper, OAccessibleSelectionHelper_Base ) - IMPLEMENT_FORWARD_XTYPEPROVIDER2( OAccessibleSelectionHelper, OAccessibleComponentHelper, OAccessibleSelectionHelper_Base ) - // (order matters: the first is the class name, the second is the class doing the ref counting) - - Reference< XAccessibleContext > OAccessibleSelectionHelper::implGetAccessibleContext() { return this; } - void SAL_CALL OAccessibleSelectionHelper::selectAccessibleChild( sal_Int32 nChildIndex ) + void SAL_CALL OAccessibleSelectionHelper::selectAccessibleChild( sal_Int64 nChildIndex ) { OExternalLockGuard aGuard( this ); OCommonAccessibleSelection::selectAccessibleChild( nChildIndex ); } - sal_Bool SAL_CALL OAccessibleSelectionHelper::isAccessibleChildSelected( sal_Int32 nChildIndex ) + sal_Bool SAL_CALL OAccessibleSelectionHelper::isAccessibleChildSelected( sal_Int64 nChildIndex ) { OExternalLockGuard aGuard( this ); return OCommonAccessibleSelection::isAccessibleChildSelected( nChildIndex ); @@ -145,21 +139,21 @@ namespace comphelper } - sal_Int32 SAL_CALL OAccessibleSelectionHelper::getSelectedAccessibleChildCount( ) + sal_Int64 SAL_CALL OAccessibleSelectionHelper::getSelectedAccessibleChildCount( ) { OExternalLockGuard aGuard( this ); return OCommonAccessibleSelection::getSelectedAccessibleChildCount(); } - Reference< XAccessible > SAL_CALL OAccessibleSelectionHelper::getSelectedAccessibleChild( sal_Int32 nSelectedChildIndex ) + Reference< XAccessible > SAL_CALL OAccessibleSelectionHelper::getSelectedAccessibleChild( sal_Int64 nSelectedChildIndex ) { OExternalLockGuard aGuard( this ); return OCommonAccessibleSelection::getSelectedAccessibleChild( nSelectedChildIndex ); } - void SAL_CALL OAccessibleSelectionHelper::deselectAccessibleChild( sal_Int32 nSelectedChildIndex ) + void SAL_CALL OAccessibleSelectionHelper::deselectAccessibleChild( sal_Int64 nSelectedChildIndex ) { OExternalLockGuard aGuard( this ); OCommonAccessibleSelection::deselectAccessibleChild( nSelectedChildIndex ); diff --git a/comphelper/source/misc/accessibletexthelper.cxx b/comphelper/source/misc/accessibletexthelper.cxx index 35fe769c1700..02cd77fc766d 100644 --- a/comphelper/source/misc/accessibletexthelper.cxx +++ b/comphelper/source/misc/accessibletexthelper.cxx @@ -17,6 +17,7 @@ * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ +#include <comphelper/accessiblecontexthelper.hxx> #include <comphelper/accessibletexthelper.hxx> #include <com/sun/star/accessibility/AccessibleTextType.hpp> #include <com/sun/star/i18n/BreakIterator.hpp> @@ -38,7 +39,6 @@ namespace comphelper using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; - using namespace ::com::sun::star::beans; using namespace ::com::sun::star::accessibility; @@ -215,9 +215,9 @@ namespace comphelper } - sal_Unicode OCommonAccessibleText::implGetCharacter( const OUString& rText, sal_Int32 nIndex ) + sal_Unicode OCommonAccessibleText::implGetCharacter( std::u16string_view rText, sal_Int32 nIndex ) { - if ( !implIsValidIndex( nIndex, rText.getLength() ) ) + if ( !implIsValidIndex( nIndex, rText.size() ) ) throw IndexOutOfBoundsException(); return rText[nIndex]; @@ -265,16 +265,16 @@ namespace comphelper } - OUString OCommonAccessibleText::implGetTextRange( const OUString& rText, sal_Int32 nStartIndex, sal_Int32 nEndIndex ) + OUString OCommonAccessibleText::implGetTextRange( std::u16string_view rText, sal_Int32 nStartIndex, sal_Int32 nEndIndex ) { - if ( !implIsValidRange( nStartIndex, nEndIndex, rText.getLength() ) ) + if ( !implIsValidRange( nStartIndex, nEndIndex, rText.size() ) ) throw IndexOutOfBoundsException(); sal_Int32 nMinIndex = std::min( nStartIndex, nEndIndex ); sal_Int32 nMaxIndex = std::max( nStartIndex, nEndIndex ); - return rText.copy( nMinIndex, nMaxIndex - nMinIndex ); + return OUString(rText.substr( nMinIndex, nMaxIndex - nMinIndex )); } TextSegment OCommonAccessibleText::getTextAtIndex( sal_Int32 nIndex, sal_Int16 aTextType ) @@ -296,9 +296,12 @@ namespace comphelper { if ( implIsValidIndex( nIndex, nLength ) ) { - aResult.SegmentText = sText.copy( nIndex, 1 ); + auto nIndexEnd = nIndex; + sText.iterateCodePoints(&nIndexEnd); + + aResult.SegmentText = sText.copy( nIndex, nIndexEnd - nIndex ); aResult.SegmentStart = nIndex; - aResult.SegmentEnd = nIndex+1; + aResult.SegmentEnd = nIndexEnd; } } break; @@ -400,9 +403,12 @@ namespace comphelper { if ( implIsValidIndex( nIndex - 1, nLength ) ) { - aResult.SegmentText = sText.copy( nIndex - 1, 1 ); - aResult.SegmentStart = nIndex-1; - aResult.SegmentEnd = nIndex; + sText.iterateCodePoints(&nIndex, -1); + auto nIndexEnd = nIndex; + sText.iterateCodePoints(&nIndexEnd); + aResult.SegmentText = sText.copy(nIndex, nIndexEnd - nIndex); + aResult.SegmentStart = nIndex; + aResult.SegmentEnd = nIndexEnd; } } break; @@ -524,9 +530,12 @@ namespace comphelper { if ( implIsValidIndex( nIndex + 1, nLength ) ) { - aResult.SegmentText = sText.copy( nIndex + 1, 1 ); - aResult.SegmentStart = nIndex+1; - aResult.SegmentEnd = nIndex+2; + sText.iterateCodePoints(&nIndex); + auto nIndexEnd = nIndex; + sText.iterateCodePoints(&nIndexEnd); + aResult.SegmentText = sText.copy(nIndex, nIndexEnd - nIndex); + aResult.SegmentStart = nIndex; + aResult.SegmentEnd = nIndexEnd; } } break; @@ -634,13 +643,13 @@ namespace comphelper bool OCommonAccessibleText::implInitTextChangedEvent( - const OUString& rOldString, - const OUString& rNewString, + std::u16string_view rOldString, + std::u16string_view rNewString, css::uno::Any& rDeleted, css::uno::Any& rInserted) // throw() { - sal_uInt32 nLenOld = rOldString.getLength(); - sal_uInt32 nLenNew = rNewString.getLength(); + size_t nLenOld = rOldString.size(); + size_t nLenNew = rNewString.size(); // equal if ((0 == nLenOld) && (0 == nLenNew)) @@ -659,7 +668,7 @@ namespace comphelper { aInsertedText.SegmentStart = 0; aInsertedText.SegmentEnd = nLenNew; - aInsertedText.SegmentText = rNewString.copy( aInsertedText.SegmentStart, aInsertedText.SegmentEnd - aInsertedText.SegmentStart ); + aInsertedText.SegmentText = rNewString.substr( aInsertedText.SegmentStart, aInsertedText.SegmentEnd - aInsertedText.SegmentStart ); rInserted <<= aInsertedText; return true; @@ -670,28 +679,27 @@ namespace comphelper { aDeletedText.SegmentStart = 0; aDeletedText.SegmentEnd = nLenOld; - aDeletedText.SegmentText = rOldString.copy( aDeletedText.SegmentStart, aDeletedText.SegmentEnd - aDeletedText.SegmentStart ); + aDeletedText.SegmentText = rOldString.substr( aDeletedText.SegmentStart, aDeletedText.SegmentEnd - aDeletedText.SegmentStart ); rDeleted <<= aDeletedText; return true; } - const sal_Unicode* pFirstDiffOld = rOldString.getStr(); - const sal_Unicode* pLastDiffOld = rOldString.getStr() + nLenOld; - const sal_Unicode* pFirstDiffNew = rNewString.getStr(); - const sal_Unicode* pLastDiffNew = rNewString.getStr() + nLenNew; + auto pFirstDiffOld = rOldString.begin(); + auto pLastDiffOld = rOldString.end(); + auto pFirstDiffNew = rNewString.begin(); + auto pLastDiffNew = rNewString.end(); // find first difference - while ((*pFirstDiffOld == *pFirstDiffNew) && - (pFirstDiffOld < pLastDiffOld) && - (pFirstDiffNew < pLastDiffNew)) + while ((pFirstDiffOld < pLastDiffOld) && (pFirstDiffNew < pLastDiffNew) + && (*pFirstDiffOld == *pFirstDiffNew)) { pFirstDiffOld++; pFirstDiffNew++; } // equality test - if ((0 == *pFirstDiffOld) && (0 == *pFirstDiffNew)) + if (pFirstDiffOld == pLastDiffOld && pFirstDiffNew == pLastDiffNew) return false; // find last difference @@ -705,18 +713,18 @@ namespace comphelper if (pFirstDiffOld < pLastDiffOld) { - aDeletedText.SegmentStart = pFirstDiffOld - rOldString.getStr(); - aDeletedText.SegmentEnd = pLastDiffOld - rOldString.getStr(); - aDeletedText.SegmentText = rOldString.copy( aDeletedText.SegmentStart, aDeletedText.SegmentEnd - aDeletedText.SegmentStart ); + aDeletedText.SegmentStart = pFirstDiffOld - rOldString.begin(); + aDeletedText.SegmentEnd = pLastDiffOld - rOldString.begin(); + aDeletedText.SegmentText = rOldString.substr( aDeletedText.SegmentStart, aDeletedText.SegmentEnd - aDeletedText.SegmentStart ); rDeleted <<= aDeletedText; } if (pFirstDiffNew < pLastDiffNew) { - aInsertedText.SegmentStart = pFirstDiffNew - rNewString.getStr(); - aInsertedText.SegmentEnd = pLastDiffNew - rNewString.getStr(); - aInsertedText.SegmentText = rNewString.copy( aInsertedText.SegmentStart, aInsertedText.SegmentEnd - aInsertedText.SegmentStart ); + aInsertedText.SegmentStart = pFirstDiffNew - rNewString.begin(); + aInsertedText.SegmentEnd = pLastDiffNew - rNewString.begin(); + aInsertedText.SegmentText = rNewString.substr( aInsertedText.SegmentStart, aInsertedText.SegmentEnd - aInsertedText.SegmentStart ); rInserted <<= aInsertedText; } @@ -732,18 +740,6 @@ namespace comphelper } - // XInterface - - - IMPLEMENT_FORWARD_XINTERFACE2( OAccessibleTextHelper, OAccessibleExtendedComponentHelper, OAccessibleTextHelper_Base ) - - - // XTypeProvider - - - IMPLEMENT_FORWARD_XTYPEPROVIDER2( OAccessibleTextHelper, OAccessibleExtendedComponentHelper, OAccessibleTextHelper_Base ) - - // XAccessibleText diff --git a/comphelper/source/misc/accessiblewrapper.cxx b/comphelper/source/misc/accessiblewrapper.cxx index 1167f56403c3..3e356f434faa 100644 --- a/comphelper/source/misc/accessiblewrapper.cxx +++ b/comphelper/source/misc/accessiblewrapper.cxx @@ -79,7 +79,7 @@ namespace comphelper xComp->removeEventListener( this ); } // clear the map - AccessibleMap().swap(m_aChildrenMap); + m_aChildrenMap.clear(); } @@ -147,7 +147,7 @@ namespace comphelper } // clear our children - AccessibleMap().swap(m_aChildrenMap); + m_aChildrenMap.clear(); } @@ -345,9 +345,8 @@ namespace comphelper ,m_xChildMapper( new OWrappedAccessibleChildrenManager( getComponentContext() ) ) { // determine if we're allowed to cache children - Reference< XAccessibleStateSet > xStates( m_xInnerContext->getAccessibleStateSet( ) ); - OSL_ENSURE( xStates.is(), "OAccessibleContextWrapperHelper::OAccessibleContextWrapperHelper: no inner state set!" ); - m_xChildMapper->setTransientChildren( !xStates.is() || xStates->contains( AccessibleStateType::MANAGES_DESCENDANTS) ); + sal_Int64 aStates = m_xInnerContext->getAccessibleStateSet( ); + m_xChildMapper->setTransientChildren( aStates & AccessibleStateType::MANAGES_DESCENDANTS ); m_xChildMapper->setOwningAccessible( m_xOwningAccessible ); } @@ -389,13 +388,13 @@ namespace comphelper IMPLEMENT_FORWARD_XTYPEPROVIDER2( OAccessibleContextWrapperHelper, OComponentProxyAggregationHelper, OAccessibleContextWrapperHelper_Base ) - sal_Int32 OAccessibleContextWrapperHelper::baseGetAccessibleChildCount( ) + sal_Int64 OAccessibleContextWrapperHelper::baseGetAccessibleChildCount( ) { return m_xInnerContext->getAccessibleChildCount(); } - Reference< XAccessible > OAccessibleContextWrapperHelper::baseGetAccessibleChild( sal_Int32 i ) + Reference< XAccessible > OAccessibleContextWrapperHelper::baseGetAccessibleChild( sal_Int64 i ) { // get the child of the wrapped component Reference< XAccessible > xInnerChild = m_xInnerContext->getAccessibleChild( i ); @@ -417,7 +416,7 @@ namespace comphelper if ( AccessibleEventId::STATE_CHANGED == _rEvent.EventId ) { bool bChildTransienceChanged = false; - sal_Int16 nChangeState = 0; + sal_Int64 nChangeState = 0; if ( _rEvent.OldValue >>= nChangeState ) bChildTransienceChanged = bChildTransienceChanged || AccessibleStateType::MANAGES_DESCENDANTS == nChangeState; if ( _rEvent.NewValue >>= nChangeState ) @@ -495,13 +494,13 @@ namespace comphelper } - sal_Int32 SAL_CALL OAccessibleContextWrapper::getAccessibleChildCount( ) + sal_Int64 SAL_CALL OAccessibleContextWrapper::getAccessibleChildCount( ) { return baseGetAccessibleChildCount(); } - Reference< XAccessible > SAL_CALL OAccessibleContextWrapper::getAccessibleChild( sal_Int32 i ) + Reference< XAccessible > SAL_CALL OAccessibleContextWrapper::getAccessibleChild( sal_Int64 i ) { return baseGetAccessibleChild( i ); } @@ -513,7 +512,7 @@ namespace comphelper } - sal_Int32 SAL_CALL OAccessibleContextWrapper::getAccessibleIndexInParent( ) + sal_Int64 SAL_CALL OAccessibleContextWrapper::getAccessibleIndexInParent( ) { return m_xInnerContext->getAccessibleIndexInParent(); } @@ -543,7 +542,7 @@ namespace comphelper } - Reference< XAccessibleStateSet > SAL_CALL OAccessibleContextWrapper::getAccessibleStateSet( ) + sal_Int64 SAL_CALL OAccessibleContextWrapper::getAccessibleStateSet( ) { return m_xInnerContext->getAccessibleStateSet(); } @@ -586,7 +585,7 @@ namespace comphelper } - void SAL_CALL OAccessibleContextWrapper::disposing() + void OAccessibleContextWrapper::implDisposing(const css::lang::EventObject* pEvent) { AccessibleEventNotifier::TClientId nClientId( 0 ); @@ -604,12 +603,29 @@ namespace comphelper // --- </mutex lock> ----------------------------------------- // let the base class do - OAccessibleContextWrapperHelper::dispose(); + if (pEvent) + OAccessibleContextWrapperHelper::disposing(*pEvent); + else + OAccessibleContextWrapperHelper::dispose(); // notify the disposal if ( nClientId ) AccessibleEventNotifier::revokeClientNotifyDisposing( nClientId, *this ); } + + void SAL_CALL OAccessibleContextWrapper::disposing() + { + implDisposing(nullptr); + } + + void SAL_CALL OAccessibleContextWrapper::disposing(const css::lang::EventObject& rEvent) + { + assert(rEvent.Source == Reference<XInterface>(m_xInnerContext, UNO_QUERY) + && "OAccessibleContextWrapper::disposing called with event source that's not the " + "wrapped a11y context"); + + implDisposing(&rEvent); + } } // namespace accessibility diff --git a/comphelper/source/misc/accimplaccess.cxx b/comphelper/source/misc/accimplaccess.cxx deleted file mode 100644 index 4c66d03ffd08..000000000000 --- a/comphelper/source/misc/accimplaccess.cxx +++ /dev/null @@ -1,54 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ -/* - * This file is part of the LibreOffice project. - * - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - * - * This file incorporates work covered by the following license notice: - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed - * with this work for additional information regarding copyright - * ownership. The ASF licenses this file to you under the Apache - * License, Version 2.0 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.apache.org/licenses/LICENSE-2.0 . - */ - -#include <comphelper/accimplaccess.hxx> -#include <comphelper/servicehelper.hxx> - - -namespace comphelper -{ - - - using ::com::sun::star::uno::Sequence; - - OAccessibleImplementationAccess::OAccessibleImplementationAccess( ) - { - } - - - OAccessibleImplementationAccess::~OAccessibleImplementationAccess( ) - { - } - - Sequence<sal_Int8> OAccessibleImplementationAccess::getUnoTunnelId() - { - static const comphelper::UnoIdInit implID; - return implID.getSeq(); - } - - - sal_Int64 SAL_CALL OAccessibleImplementationAccess::getSomething( const Sequence< sal_Int8 >& _rIdentifier ) - { - return comphelper::getSomethingImpl(_rIdentifier, this); - } - -} // namespace comphelper - - -/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/comphelper/source/misc/anycompare.cxx b/comphelper/source/misc/anycompare.cxx index 8a23877239be..79d3864535c0 100644 --- a/comphelper/source/misc/anycompare.cxx +++ b/comphelper/source/misc/anycompare.cxx @@ -66,7 +66,7 @@ namespace comphelper if ( !( _lhs >>= lhs ) || !( _rhs >>= rhs ) ) - throw css::lang::IllegalArgumentException("bad ordering", css::uno::Reference<css::uno::XInterface>(), -1); + throw css::lang::IllegalArgumentException(u"bad ordering"_ustr, css::uno::Reference<css::uno::XInterface>(), -1); // FIXME Timezone? if ( lhs.Year < rhs.Year ) @@ -94,7 +94,7 @@ namespace comphelper if ( !( _lhs >>= lhs ) || !( _rhs >>= rhs ) ) - throw css::lang::IllegalArgumentException("bad ordering", css::uno::Reference<css::uno::XInterface>(), -1); + throw css::lang::IllegalArgumentException(u"bad ordering"_ustr, css::uno::Reference<css::uno::XInterface>(), -1); // FIXME Timezone? if ( lhs.Hours < rhs.Hours ) @@ -127,7 +127,7 @@ namespace comphelper if ( !( _lhs >>= lhs ) || !( _rhs >>= rhs ) ) - throw css::lang::IllegalArgumentException("bad ordering", css::uno::Reference<css::uno::XInterface>(), -1); + throw css::lang::IllegalArgumentException(u"bad ordering"_ustr, css::uno::Reference<css::uno::XInterface>(), -1); // FIXME Timezone? if ( lhs.Year < rhs.Year ) @@ -216,12 +216,12 @@ namespace comphelper if (!lhsTypeDescr.is()) lhsTypeDescr.makeComplete(); if (!lhsTypeDescr.is()) - throw css::lang::IllegalArgumentException("bad ordering", css::uno::Reference<css::uno::XInterface>(), -1); + throw css::lang::IllegalArgumentException(u"bad ordering"_ustr, css::uno::Reference<css::uno::XInterface>(), -1); TypeDescription rhsTypeDescr( rhsType ); if (!rhsTypeDescr.is()) rhsTypeDescr.makeComplete(); if (!rhsTypeDescr.is()) - throw css::lang::IllegalArgumentException("bad ordering", css::uno::Reference<css::uno::XInterface>(), -1); + throw css::lang::IllegalArgumentException(u"bad ordering"_ustr, css::uno::Reference<css::uno::XInterface>(), -1); int compare = compareTypes( lhsTypeDescr.get(), rhsTypeDescr.get()); if( compare != 0 ) return compare < 0; @@ -251,7 +251,7 @@ namespace comphelper { TypeDescriptionRef memberType( ppTypeRefs[ nPos ] ); if (!memberType.is()) - throw css::lang::IllegalArgumentException("bad ordering", css::uno::Reference<css::uno::XInterface>(), -1); + throw css::lang::IllegalArgumentException(u"bad ordering"_ustr, css::uno::Reference<css::uno::XInterface>(), -1); std::optional<bool> subLess = anyCompare( static_cast< char const * >( lhs ) + memberOffsets[ nPos ], @@ -273,10 +273,10 @@ namespace comphelper TypeDescriptionRef lhsTypeDescr( lhsType ); if (!lhsTypeDescr.is()) - throw css::lang::IllegalArgumentException("bad ordering", css::uno::Reference<css::uno::XInterface>(), -1); + throw css::lang::IllegalArgumentException(u"bad ordering"_ustr, css::uno::Reference<css::uno::XInterface>(), -1); TypeDescriptionRef rhsTypeDescr( rhsType ); if (!rhsTypeDescr.is()) - throw css::lang::IllegalArgumentException("bad ordering", css::uno::Reference<css::uno::XInterface>(), -1); + throw css::lang::IllegalArgumentException(u"bad ordering"_ustr, css::uno::Reference<css::uno::XInterface>(), -1); int compare = compareTypes( lhsTypeDescr.get(), rhsTypeDescr.get()); if( compare != 0 ) return compare < 0; @@ -285,7 +285,7 @@ namespace comphelper reinterpret_cast< typelib_IndirectTypeDescription * >(lhsTypeDescr.get())->pType; TypeDescriptionRef elementTypeDescr( elementTypeRef ); if (!elementTypeDescr.is()) - throw css::lang::IllegalArgumentException("bad ordering", css::uno::Reference<css::uno::XInterface>(), -1); + throw css::lang::IllegalArgumentException(u"bad ordering"_ustr, css::uno::Reference<css::uno::XInterface>(), -1); assert( elementTypeDescr.equals( TypeDescriptionRef( reinterpret_cast< typelib_IndirectTypeDescription * >(lhsTypeDescr.get())->pType ))); @@ -331,12 +331,12 @@ namespace comphelper if (!lhsTypeDescr.is()) lhsTypeDescr.makeComplete(); if (!lhsTypeDescr.is()) - throw css::lang::IllegalArgumentException("bad ordering", css::uno::Reference<css::uno::XInterface>(), -1); + throw css::lang::IllegalArgumentException(u"bad ordering"_ustr, css::uno::Reference<css::uno::XInterface>(), -1); TypeDescription rhsTypeDescr( rhsType ); if (!rhsTypeDescr.is()) rhsTypeDescr.makeComplete(); if (!rhsTypeDescr.is()) - throw css::lang::IllegalArgumentException("bad ordering", css::uno::Reference<css::uno::XInterface>(), -1); + throw css::lang::IllegalArgumentException(u"bad ordering"_ustr, css::uno::Reference<css::uno::XInterface>(), -1); int compare = compareTypes( lhsTypeDescr.get(), rhsTypeDescr.get()); if( compare != 0 ) return compare < 0; diff --git a/comphelper/source/misc/asyncnotification.cxx b/comphelper/source/misc/asyncnotification.cxx index cb8a2f251164..72c6414e7281 100644 --- a/comphelper/source/misc/asyncnotification.cxx +++ b/comphelper/source/misc/asyncnotification.cxx @@ -91,7 +91,7 @@ namespace comphelper std::scoped_lock aGuard( m_xImpl->aMutex ); // remove all events for this processor - m_xImpl->aEvents.erase(std::remove_if( m_xImpl->aEvents.begin(), m_xImpl->aEvents.end(), EqualProcessor( _xProcessor ) ), m_xImpl->aEvents.end()); + std::erase_if( m_xImpl->aEvents, EqualProcessor( _xProcessor ) ); } diff --git a/comphelper/source/misc/backupfilehelper.cxx b/comphelper/source/misc/backupfilehelper.cxx index 22bd5c5a851f..11fa4239d2e9 100644 --- a/comphelper/source/misc/backupfilehelper.cxx +++ b/comphelper/source/misc/backupfilehelper.cxx @@ -19,6 +19,7 @@ #include <deque> #include <memory> #include <string_view> +#include <utility> #include <vector> #include <zlib.h> @@ -221,8 +222,8 @@ namespace { } - ExtensionInfoEntry(const OString& rName, bool bEnabled) - : maName(rName), + ExtensionInfoEntry(OString aName, bool bEnabled) + : maName(std::move(aName)), maRepository(USER), mbEnabled(bEnabled) { @@ -353,7 +354,7 @@ namespace typedef std::vector< ExtensionInfoEntry > ExtensionInfoEntryVector; - constexpr OUStringLiteral gaRegPath { u"/registry/com.sun.star.comp.deployment.bundle.PackageRegistryBackend/backenddb.xml" }; + constexpr OUString gaRegPath { u"/registry/com.sun.star.comp.deployment.bundle.PackageRegistryBackend/backenddb.xml"_ustr }; class ExtensionInfo { @@ -410,7 +411,7 @@ namespace e.Context, anyEx ); } - for (const uno::Sequence< uno::Reference< deployment::XPackage > > & xPackageList : std::as_const(xAllPackages)) + for (const uno::Sequence< uno::Reference< deployment::XPackage > > & xPackageList : xAllPackages) { for (const uno::Reference< deployment::XPackage > & xPackage : xPackageList) { @@ -438,8 +439,8 @@ namespace if (aTagName == "extension") { - OUString aAttrUrl(rElement->getAttribute("url")); - const OUString aAttrRevoked(rElement->getAttribute("revoked")); + OUString aAttrUrl(rElement->getAttribute(u"url"_ustr)); + const OUString aAttrRevoked(rElement->getAttribute(u"revoked"_ustr)); if (!aAttrUrl.isEmpty()) { @@ -536,8 +537,8 @@ namespace if (aTagName == rTagToSearch) { - const OString aAttrUrl(OUStringToOString(rElement->getAttribute("url"), RTL_TEXTENCODING_ASCII_US)); - const OUString aAttrRevoked(rElement->getAttribute("revoked")); + const OString aAttrUrl(OUStringToOString(rElement->getAttribute(u"url"_ustr), RTL_TEXTENCODING_ASCII_US)); + const OUString aAttrRevoked(rElement->getAttribute(u"revoked"_ustr)); const bool bEnabled(aAttrRevoked.isEmpty() || !aAttrRevoked.toBoolean()); if (!aAttrUrl.isEmpty()) @@ -549,7 +550,7 @@ namespace if (!bEnabled) { // needs to be enabled - rElement->removeAttribute("revoked"); + rElement->removeAttribute(u"revoked"_ustr); bChanged = true; } } @@ -562,7 +563,7 @@ namespace if (bEnabled) { // needs to be disabled - rElement->setAttribute("revoked", "true"); + rElement->setAttribute(u"revoked"_ustr, u"true"_ustr); bChanged = true; } } @@ -660,15 +661,15 @@ namespace const ExtensionInfoEntryVector& rToBeEnabled, const ExtensionInfoEntryVector& rToBeDisabled) { - static const OUStringLiteral aRegPathFront(u"/uno_packages/cache/registry/com.sun.star.comp.deployment."); - static const OUStringLiteral aRegPathBack(u".PackageRegistryBackend/backenddb.xml"); + static constexpr OUString aRegPathFront(u"/uno_packages/cache/registry/com.sun.star.comp.deployment."_ustr); + static constexpr OUString aRegPathBack(u".PackageRegistryBackend/backenddb.xml"_ustr); // first appearance to check { const OUString aUnoPackagReg(OUString::Concat(rUserConfigWorkURL) + aRegPathFront + "bundle" + aRegPathBack); visitNodesXMLChangeOneCase( aUnoPackagReg, - "extension", + u"extension"_ustr, rToBeEnabled, rToBeDisabled); } @@ -679,7 +680,7 @@ namespace visitNodesXMLChangeOneCase( aUnoPackagReg, - "configuration", + u"configuration"_ustr, rToBeEnabled, rToBeDisabled); } @@ -690,7 +691,7 @@ namespace visitNodesXMLChangeOneCase( aUnoPackagReg, - "script", + u"script"_ustr, rToBeEnabled, rToBeDisabled); } @@ -995,13 +996,13 @@ namespace PackedFileEntry( sal_uInt32 nFullFileSize, sal_uInt32 nCrc32, - FileSharedPtr const & rFile, + FileSharedPtr xFile, bool bDoCompress) : mnFullFileSize(nFullFileSize), mnPackFileSize(nFullFileSize), mnOffset(0), mnCrc32(nCrc32), - maFile(rFile), + maFile(std::move(xFile)), mbDoCompress(bDoCompress) { } @@ -1243,7 +1244,7 @@ namespace { // need to create a new pack file, do this in a temp file to which data // will be copied from local file (so keep it here until this is done) - oslFileHandle aHandle; + oslFileHandle aHandle = nullptr; OUString aTempURL; // open target temp file - it exists until deleted @@ -1464,9 +1465,9 @@ namespace comphelper { // try to access user layer configuration file URL, the one that // points to registrymodifications.xcu - OUString conf("${CONFIGURATION_LAYERS}"); + OUString conf(u"${CONFIGURATION_LAYERS}"_ustr); rtl::Bootstrap::expandMacros(conf); - static const OUStringLiteral aTokenUser(u"user:"); + static constexpr OUString aTokenUser(u"user:"_ustr); sal_Int32 nStart(conf.indexOf(aTokenUser)); if (-1 != nStart) @@ -1511,7 +1512,7 @@ namespace comphelper const OUString& BackupFileHelper::getSafeModeName() { - static const OUString aSafeMode("SafeMode"); + static constexpr OUString aSafeMode(u"SafeMode"_ustr); return aSafeMode; } @@ -1526,7 +1527,7 @@ namespace comphelper OUString sTokenOut; // read configuration item 'SecureUserConfig' -> bool on/off - if (rtl::Bootstrap::get("SecureUserConfig", sTokenOut)) + if (rtl::Bootstrap::get(u"SecureUserConfig"_ustr, sTokenOut)) { mbActive = sTokenOut.toBoolean(); } @@ -1540,7 +1541,7 @@ namespace comphelper mbActive = !maInitialBaseURL.isEmpty() && !maUserConfigBaseURL.isEmpty() && !maRegModName.isEmpty(); } - if (mbActive && rtl::Bootstrap::get("SecureUserConfigNumCopies", sTokenOut)) + if (mbActive && rtl::Bootstrap::get(u"SecureUserConfigNumCopies"_ustr, sTokenOut)) { const sal_uInt16 nConfigNumCopies(static_cast<sal_uInt16>(sTokenOut.toUInt32())); @@ -1548,7 +1549,7 @@ namespace comphelper mnNumBackups = std::clamp(mnNumBackups, nConfigNumCopies, mnMaxAllowedBackups); } - if (mbActive && rtl::Bootstrap::get("SecureUserConfigMode", sTokenOut)) + if (mbActive && rtl::Bootstrap::get(u"SecureUserConfigMode"_ustr, sTokenOut)) { const sal_uInt16 nMode(static_cast<sal_uInt16>(sTokenOut.toUInt32())); @@ -1556,12 +1557,12 @@ namespace comphelper mnMode = std::min(nMode, sal_uInt16(2)); } - if (mbActive && rtl::Bootstrap::get("SecureUserConfigExtensions", sTokenOut)) + if (mbActive && rtl::Bootstrap::get(u"SecureUserConfigExtensions"_ustr, sTokenOut)) { mbExtensions = sTokenOut.toBoolean(); } - if (mbActive && rtl::Bootstrap::get("SecureUserConfigCompress", sTokenOut)) + if (mbActive && rtl::Bootstrap::get(u"SecureUserConfigCompress"_ustr, sTokenOut)) { mbCompress = sTokenOut.toBoolean(); } @@ -1834,12 +1835,12 @@ namespace comphelper { static std::vector< OUString > aDirNames = { - "config", // UI config stuff - "registry", // most of the registry stuff - "psprint", // not really needed, can be abandoned - "store", // not really needed, can be abandoned - "temp", // not really needed, can be abandoned - "pack" // own backup dir + u"config"_ustr, // UI config stuff + u"registry"_ustr, // most of the registry stuff + u"psprint"_ustr, // not really needed, can be abandoned + u"store"_ustr, // not really needed, can be abandoned + u"temp"_ustr, // not really needed, can be abandoned + u"pack"_ustr // own backup dir }; return aDirNames; @@ -1849,7 +1850,7 @@ namespace comphelper { static std::vector< OUString > aFileNames = { - "registrymodifications.xcu" // personal registry stuff + u"registrymodifications.xcu"_ustr // personal registry stuff }; return aFileNames; @@ -1859,14 +1860,14 @@ namespace comphelper uno::Reference<XElement> lcl_getConfigElement(const uno::Reference<XDocument>& xDocument, const OUString& rPath, const OUString& rKey, const OUString& rValue) { - uno::Reference< XElement > itemElement = xDocument->createElement("item"); - itemElement->setAttribute("oor:path", rPath); + uno::Reference< XElement > itemElement = xDocument->createElement(u"item"_ustr); + itemElement->setAttribute(u"oor:path"_ustr, rPath); - uno::Reference< XElement > propElement = xDocument->createElement("prop"); - propElement->setAttribute("oor:name", rKey); - propElement->setAttribute("oor:op", "replace"); // Replace any other options + uno::Reference< XElement > propElement = xDocument->createElement(u"prop"_ustr); + propElement->setAttribute(u"oor:name"_ustr, rKey); + propElement->setAttribute(u"oor:op"_ustr, u"replace"_ustr); // Replace any other options - uno::Reference< XElement > valueElement = xDocument->createElement("value"); + uno::Reference< XElement > valueElement = xDocument->createElement(u"value"_ustr); uno::Reference< XText > textElement = xDocument->createTextNode(rValue); valueElement->appendChild(textElement); @@ -1888,15 +1889,15 @@ namespace comphelper uno::Reference< XDocument > xDocument = xBuilder->parseURI(aRegistryModifications); uno::Reference< XElement > xRootElement = xDocument->getDocumentElement(); - xRootElement->appendChild(lcl_getConfigElement(xDocument, "/org.openoffice.Office.Common/VCL", - "DisableOpenGL", "true")); - xRootElement->appendChild(lcl_getConfigElement(xDocument, "/org.openoffice.Office.Common/Misc", - "UseOpenCL", "false")); + xRootElement->appendChild(lcl_getConfigElement(xDocument, u"/org.openoffice.Office.Common/VCL"_ustr, + u"DisableOpenGL"_ustr, u"true"_ustr)); + xRootElement->appendChild(lcl_getConfigElement(xDocument, u"/org.openoffice.Office.Common/Misc"_ustr, + u"UseOpenCL"_ustr, u"false"_ustr)); // Do not disable Skia entirely, just force its CPU-based raster mode. - xRootElement->appendChild(lcl_getConfigElement(xDocument, "/org.openoffice.Office.Common/VCL", - "ForceSkia", "false")); - xRootElement->appendChild(lcl_getConfigElement(xDocument, "/org.openoffice.Office.Common/VCL", - "ForceSkiaRaster", "true")); + xRootElement->appendChild(lcl_getConfigElement(xDocument, u"/org.openoffice.Office.Common/VCL"_ustr, + u"ForceSkia"_ustr, u"false"_ustr)); + xRootElement->appendChild(lcl_getConfigElement(xDocument, u"/org.openoffice.Office.Common/VCL"_ustr, + u"ForceSkiaRaster"_ustr, u"true"_ustr)); OUString aTempURL; { @@ -2434,31 +2435,31 @@ namespace comphelper maFiles.insert(std::pair< OUString, OUString >(maRegModName, maExt)); // User-defined substitution table (Tools/AutoCorrect) - maDirs.insert("autocorr"); + maDirs.insert(u"autocorr"_ustr); // User-Defined AutoText (Edit/AutoText) - maDirs.insert("autotext"); + maDirs.insert(u"autotext"_ustr); // User-defined Macros - maDirs.insert("basic"); + maDirs.insert(u"basic"_ustr); // User-adapted toolbars for modules - maDirs.insert("config"); + maDirs.insert(u"config"_ustr); // Initial and User-defined Databases - maDirs.insert("database"); + maDirs.insert(u"database"_ustr); // most part of registry files - maDirs.insert("registry"); + maDirs.insert(u"registry"_ustr); // User-Defined Scripts - maDirs.insert("Scripts"); + maDirs.insert(u"Scripts"_ustr); // Template files - maDirs.insert("template"); + maDirs.insert(u"template"_ustr); // Custom Dictionaries - maDirs.insert("wordbook"); + maDirs.insert(u"wordbook"_ustr); // Questionable - where and how is Extension stuff held and how // does this interact with enabled/disabled states which are extra handled? @@ -2480,19 +2481,19 @@ namespace comphelper // should not exist, but for the case an error occurred and it got // copied somehow, avoid further recursive copying/saving - maDirs.erase("SafeMode"); + maDirs.erase(u"SafeMode"_ustr); // not really needed, can be abandoned - maDirs.erase("psprint"); + maDirs.erase(u"psprint"_ustr); // not really needed, can be abandoned - maDirs.erase("store"); + maDirs.erase(u"store"_ustr); // not really needed, can be abandoned - maDirs.erase("temp"); + maDirs.erase(u"temp"_ustr); // exclude own backup dir to avoid recursion - maDirs.erase("pack"); + maDirs.erase(u"pack"_ustr); break; } diff --git a/comphelper/source/misc/base64.cxx b/comphelper/source/misc/base64.cxx index d73465601adb..2646f297d7aa 100644 --- a/comphelper/source/misc/base64.cxx +++ b/comphelper/source/misc/base64.cxx @@ -17,10 +17,15 @@ * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ +#include <sal/config.h> + +#include <cstddef> + #include <comphelper/base64.hxx> #include <com/sun/star/uno/Sequence.hxx> +#include <o3tl/safeint.hxx> #include <osl/diagnose.h> using namespace com::sun::star; @@ -56,15 +61,11 @@ const // p q r s t u v w x y z -static void ThreeByteToFourByte(const sal_Int8* pBuffer, const sal_Int32 nStart, const sal_Int32 nFullLen, char* aCharBuffer) +template <typename C> +static void ThreeByteToFourByte(const sal_Int8* pBuffer, const sal_Int32 nStart, const sal_Int32 nFullLen, C* aCharBuffer) { - sal_Int32 nLen(nFullLen - nStart); - if (nLen > 3) - nLen = 3; - if (nLen == 0) - { - return; - } + const sal_Int32 nLen(std::min(nFullLen - nStart, sal_Int32(3))); + assert(nLen > 0); // We are never expected to leave the output buffer uninitialized sal_Int32 nBinaer; switch (nLen) @@ -89,7 +90,7 @@ static void ThreeByteToFourByte(const sal_Int8* pBuffer, const sal_Int32 nStart, break; } - aCharBuffer[0] = aCharBuffer[1] = aCharBuffer[2] = aCharBuffer[3] = '='; + aCharBuffer[2] = aCharBuffer[3] = '='; sal_uInt8 nIndex (static_cast<sal_uInt8>((nBinaer & 0xFC0000) >> 18)); aCharBuffer[0] = aBase64EncodeTable [nIndex]; @@ -108,56 +109,52 @@ static void ThreeByteToFourByte(const sal_Int8* pBuffer, const sal_Int32 nStart, } } -void Base64::encode(OStringBuffer& aStrBuffer, const uno::Sequence<sal_Int8>& aPass) +template <typename Buffer> +static void base64encode(Buffer& aStrBuffer, const uno::Sequence<sal_Int8>& aPass) { sal_Int32 i(0); sal_Int32 nBufferLength(aPass.getLength()); + aStrBuffer.ensureCapacity(aStrBuffer.getLength() + (nBufferLength * 4 + 2) / 3); const sal_Int8* pBuffer = aPass.getConstArray(); while (i < nBufferLength) { - char aCharBuffer[4]; - ThreeByteToFourByte(pBuffer, i, nBufferLength, aCharBuffer); - aStrBuffer.append(aCharBuffer, SAL_N_ELEMENTS(aCharBuffer)); + ThreeByteToFourByte(pBuffer, i, nBufferLength, aStrBuffer.appendUninitialized(4)); i += 3; } } +void Base64::encode(OStringBuffer& aStrBuffer, const uno::Sequence<sal_Int8>& aPass) +{ + base64encode(aStrBuffer, aPass); +} + void Base64::encode(OUStringBuffer& aStrBuffer, const uno::Sequence<sal_Int8>& aPass) { - sal_Int32 i(0); - sal_Int32 nBufferLength(aPass.getLength()); - const sal_Int8* pBuffer = aPass.getConstArray(); - while (i < nBufferLength) - { - char aCharBuffer[4]; - ThreeByteToFourByte(pBuffer, i, nBufferLength, aCharBuffer); - aStrBuffer.appendAscii(aCharBuffer, SAL_N_ELEMENTS(aCharBuffer)); - i += 3; - } + base64encode(aStrBuffer, aPass); } void Base64::decode(uno::Sequence<sal_Int8>& aBuffer, std::u16string_view sBuffer) { - sal_Int32 nCharsDecoded = decodeSomeChars( aBuffer, sBuffer ); - OSL_ENSURE( sal_uInt32(nCharsDecoded) == sBuffer.size(), "some bytes left in base64 decoding!" ); + std::size_t nCharsDecoded = decodeSomeChars( aBuffer, sBuffer ); + OSL_ENSURE( nCharsDecoded == sBuffer.size(), "some bytes left in base64 decoding!" ); } -sal_Int32 Base64::decodeSomeChars(uno::Sequence<sal_Int8>& rOutBuffer, std::u16string_view rInBuffer) +std::size_t Base64::decodeSomeChars(uno::Sequence<sal_Int8>& rOutBuffer, std::u16string_view rInBuffer) { - sal_Int32 nInBufferLen = rInBuffer.size(); - sal_Int32 nMinOutBufferLen = (nInBufferLen / 4) * 3; - if( rOutBuffer.getLength() < nMinOutBufferLen ) + std::size_t nInBufferLen = rInBuffer.size(); + std::size_t nMinOutBufferLen = (nInBufferLen / 4) * 3; + if( o3tl::make_unsigned(rOutBuffer.getLength()) < nMinOutBufferLen ) rOutBuffer.realloc( nMinOutBufferLen ); const sal_Unicode *pInBuffer = rInBuffer.data(); sal_Int8 *pOutBuffer = rOutBuffer.getArray(); sal_Int8 *pOutBufferStart = pOutBuffer; - sal_Int32 nCharsDecoded = 0; + std::size_t nCharsDecoded = 0; sal_uInt8 aDecodeBuffer[4]; sal_Int32 nBytesToDecode = 0; sal_Int32 nBytesGotFromDecoding = 3; - sal_Int32 nInBufferPos= 0; + std::size_t nInBufferPos= 0; while( nInBufferPos < nInBufferLen ) { sal_Unicode cChar = *pInBuffer; diff --git a/comphelper/source/misc/compbase.cxx b/comphelper/source/misc/compbase.cxx index f8a8897b7bb7..1827527d1d56 100644 --- a/comphelper/source/misc/compbase.cxx +++ b/comphelper/source/misc/compbase.cxx @@ -8,6 +8,7 @@ */ #include <comphelper/compbase.hxx> +#include <cppuhelper/queryinterface.hxx> #include <sal/log.hxx> #include <osl/diagnose.h> @@ -226,6 +227,34 @@ css::uno::Any WeakComponentImplHelper_query(css::uno::Type const& rType, cppu::c return pBase->comphelper::WeakComponentImplHelperBase::queryInterface(rType); } +WeakImplHelperBase::~WeakImplHelperBase() {} + +css::uno::Any SAL_CALL WeakImplHelperBase::queryInterface(css::uno::Type const& rType) +{ + css::uno::Any aReturn = ::cppu::queryInterface(rType, static_cast<css::uno::XWeak*>(this)); + if (aReturn.hasValue()) + return aReturn; + return OWeakObject::queryInterface(rType); +} + +css::uno::Any WeakImplHelper_query(css::uno::Type const& rType, cppu::class_data* cd, + WeakImplHelperBase* pBase) +{ + checkInterface(rType); + typelib_TypeDescriptionReference* pTDR = rType.getTypeLibType(); + + // shortcut XInterface to WeakComponentImplHelperBase + if (!isXInterface(pTDR->pTypeName)) + { + void* p = queryDeepNoXInterface(pTDR, cd, pBase); + if (p) + { + return css::uno::Any(&p, pTDR); + } + } + return pBase->comphelper::WeakImplHelperBase::queryInterface(rType); +} + } // namespace comphelper /* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/comphelper/source/misc/configuration.cxx b/comphelper/source/misc/configuration.cxx index 67009cd9f864..88e6a7c6f658 100644 --- a/comphelper/source/misc/configuration.cxx +++ b/comphelper/source/misc/configuration.cxx @@ -38,12 +38,6 @@ namespace com::sun::star::uno { class XComponentContext; } namespace { -comphelper::detail::ConfigurationWrapper& GetTheConfigurationWrapper(const css::uno::Reference< css::uno::XComponentContext >& xContext) -{ - static comphelper::detail::ConfigurationWrapper WRAPPER(xContext); - return WRAPPER; -} - OUString getDefaultLocale( css::uno::Reference< css::uno::XComponentContext > const & context) { @@ -68,9 +62,9 @@ OUString extendLocalizedPath(std::u16string_view path, OUString const & locale) std::shared_ptr< comphelper::ConfigurationChanges > comphelper::ConfigurationChanges::create( - css::uno::Reference< css::uno::XComponentContext > const & context) + css::uno::Reference<css::uno::XComponentContext> const & context) { - return GetTheConfigurationWrapper(context).createChanges(); + return detail::ConfigurationWrapper::get(context).createChanges(); } comphelper::ConfigurationChanges::~ConfigurationChanges() {} @@ -108,15 +102,16 @@ comphelper::ConfigurationChanges::getSet(OUString const & path) const comphelper::detail::ConfigurationWrapper const & comphelper::detail::ConfigurationWrapper::get( - css::uno::Reference< css::uno::XComponentContext > const & context) + css::uno::Reference<css::uno::XComponentContext> const & context) { - return GetTheConfigurationWrapper(context); + static comphelper::detail::ConfigurationWrapper WRAPPER(context); + return WRAPPER; } comphelper::detail::ConfigurationWrapper::ConfigurationWrapper( - css::uno::Reference< css::uno::XComponentContext > const & context): - context_(context), - access_(css::configuration::ReadWriteAccess::create(context, "*")) + css::uno::Reference<css::uno::XComponentContext> const & context): + context_(context.is() ? context : comphelper::getProcessComponentContext()), + access_(css::configuration::ReadWriteAccess::create(context_, u"*"_ustr)) {} comphelper::detail::ConfigurationWrapper::~ConfigurationWrapper() {} @@ -130,18 +125,21 @@ bool comphelper::detail::ConfigurationWrapper::isReadOnly(OUString const & path) != 0; } -css::uno::Any comphelper::detail::ConfigurationWrapper::getPropertyValue(OUString const& path) const +css::uno::Any comphelper::detail::ConfigurationWrapper::getPropertyValue(std::u16string_view path) const { + // should be short-circuited in ConfigurationProperty::get() + assert(!comphelper::IsFuzzing()); + // Cache the configuration access, since some of the keys are used in hot code. // Note that this cache is only used by the officecfg:: auto-generated code, using it for anything // else would be unwise because the cache could end up containing stale entries. static std::mutex gMutex; static std::map<OUString, css::uno::Reference< css::container::XNameAccess >> gAccessMap; - sal_Int32 idx = path.lastIndexOf("/"); + sal_Int32 idx = path.rfind('/'); assert(idx!=-1); - OUString parentPath = path.copy(0, idx); - OUString childName = path.copy(idx+1); + OUString parentPath(path.substr(0, idx)); + OUString childName(path.substr(idx+1)); std::scoped_lock aGuard(gMutex); @@ -252,6 +250,7 @@ void comphelper::ConfigurationListener::dispose() listener->dispose(); } maListeners.clear(); + mxConfig.clear(); mbDisposed = true; } @@ -284,4 +283,23 @@ void SAL_CALL comphelper::ConfigurationListener::propertyChange( } } +namespace comphelper { + +static bool bIsFuzzing = false; + +#if !defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) +bool IsFuzzing() +{ + return bIsFuzzing; +} +#endif + +void EnableFuzzing() +{ + bIsFuzzing = true; + LanguageTag::disable_lt_tag_parse(); +} + +} + /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/comphelper/source/misc/configurationhelper.cxx b/comphelper/source/misc/configurationhelper.cxx index f3853baeff81..228885e2ec5a 100644 --- a/comphelper/source/misc/configurationhelper.cxx +++ b/comphelper/source/misc/configurationhelper.cxx @@ -51,7 +51,7 @@ css::uno::Reference< css::uno::XInterface > ConfigurationHelper::openConfig(cons if (eMode & EConfigurationModes::AllLocales) { aParam.Name = "locale"; - aParam.Value <<= OUString("*"); + aParam.Value <<= u"*"_ustr; lParams.emplace_back(aParam); } @@ -61,11 +61,11 @@ css::uno::Reference< css::uno::XInterface > ConfigurationHelper::openConfig(cons bool bReadOnly(eMode & EConfigurationModes::ReadOnly); if (bReadOnly) xCFG = xConfigProvider->createInstanceWithArguments( - "com.sun.star.configuration.ConfigurationAccess", + u"com.sun.star.configuration.ConfigurationAccess"_ustr, comphelper::containerToSequence(lParams)); else xCFG = xConfigProvider->createInstanceWithArguments( - "com.sun.star.configuration.ConfigurationUpdateAccess", + u"com.sun.star.configuration.ConfigurationUpdateAccess"_ustr, comphelper::containerToSequence(lParams)); return xCFG; diff --git a/comphelper/source/misc/date.cxx b/comphelper/source/misc/date.cxx new file mode 100644 index 000000000000..b95f63f75c97 --- /dev/null +++ b/comphelper/source/misc/date.cxx @@ -0,0 +1,210 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <comphelper/date.hxx> + +#include <cassert> + +namespace comphelper::date +{ +// Once upon a time the number of days we internally handled in tools' class +// Date was limited to MAX_DAYS 3636532. That changed with a full 16-bit year. +// Assuming the first valid positive date in a proleptic Gregorian calendar is +// 0001-01-01, this resulted in an end date of 9957-06-26. +// Hence we documented that years up to and including 9956 are handled. +/* XXX: it is unclear history why this value was chosen, the representable + * 9999-12-31 would be 3652060 days from 0001-01-01. Even 9998-12-31 to + * distinguish from a maximum possible date would be 3651695. + * There is connectivity/source/commontools/dbconversion.cxx that still has the + * same value to calculate with css::util::Date */ +/* XXX can that dbconversion cope with years > 9999 or negative years at all? + * Database fields may be limited to positive 4 digits. */ + +constexpr sal_Int32 MIN_DAYS = -11968265; // -32768-01-01 +constexpr sal_Int32 MAX_DAYS = 11967900; // 32767-12-31 + +constexpr sal_Int16 kYearMax = SAL_MAX_INT16; +constexpr sal_Int16 kYearMin = SAL_MIN_INT16; + +constexpr sal_Int32 nNullDateDays = convertDateToDays(30, 12, 1899); +static_assert(nNullDateDays == 693594); + +sal_Int32 convertDateToDaysNormalizing(sal_uInt16 nDay, sal_uInt16 nMonth, sal_Int16 nYear) +{ + // Speed-up the common null-date 1899-12-30. + if (nYear == 1899 && nMonth == 12 && nDay == 30) + return nNullDateDays; + + normalize(nDay, nMonth, nYear); + return convertDateToDays(nDay, nMonth, nYear); +} + +bool isValidDate(sal_uInt16 nDay, sal_uInt16 nMonth, sal_Int16 nYear) +{ + if (nYear == 0) + return false; + if (nMonth < 1 || 12 < nMonth) + return false; + if (nDay < 1 || (nDay > comphelper::date::getDaysInMonth(nMonth, nYear))) + return false; + return true; +} + +void convertDaysToDate(sal_Int32 nDays, sal_uInt16& rDay, sal_uInt16& rMonth, sal_Int16& rYear) +{ + if (nDays <= MIN_DAYS) + { + rDay = 1; + rMonth = 1; + rYear = kYearMin; + return; + } + if (nDays >= MAX_DAYS) + { + rDay = 31; + rMonth = 12; + rYear = kYearMax; + return; + } + + // Day 0 is -0001-12-31, day 1 is 0001-01-01 + const sal_Int16 nSign = (nDays <= 0 ? -1 : 1); + sal_Int32 nTempDays; + sal_Int32 i = 0; + bool bCalc; + + do + { + rYear = static_cast<sal_Int16>((nDays / 365) - (i * nSign)); + if (rYear == 0) + rYear = nSign; + nTempDays = nDays - YearToDays(rYear); + bCalc = false; + if (nTempDays < 1) + { + i += nSign; + bCalc = true; + } + else + { + if (nTempDays > 365) + { + if ((nTempDays != 366) || !isLeapYear(rYear)) + { + i -= nSign; + bCalc = true; + } + } + } + } while (bCalc); + + rMonth = 1; + while (nTempDays > getDaysInMonth(rMonth, rYear)) + { + nTempDays -= getDaysInMonth(rMonth, rYear); + ++rMonth; + } + + rDay = static_cast<sal_uInt16>(nTempDays); +} + +bool normalize(sal_uInt16& rDay, sal_uInt16& rMonth, sal_Int16& rYear) +{ + if (isValidDate(rDay, rMonth, rYear)) + return false; + + if (rDay == 0 && rMonth == 0 && rYear == 0) + return false; // empty date + + if (rDay == 0) + { + if (rMonth == 0) + ; // nothing, handled below + else + --rMonth; + // Last day of month is determined at the end. + } + + if (rMonth > 12) + { + rYear += rMonth / 12; + rMonth = rMonth % 12; + if (rYear == 0) + rYear = 1; + } + if (rMonth == 0) + { + --rYear; + if (rYear == 0) + rYear = -1; + rMonth = 12; + } + + if (rYear < 0) + { + sal_uInt16 nDays; + while (rDay > (nDays = getDaysInMonth(rMonth, rYear))) + { + rDay -= nDays; + if (rMonth > 1) + --rMonth; + else + { + if (rYear == kYearMin) + { + rDay = 1; + rMonth = 1; + return true; + } + --rYear; + rMonth = 12; + } + } + } + else + { + sal_uInt16 nDays; + while (rDay > (nDays = getDaysInMonth(rMonth, rYear))) + { + rDay -= nDays; + if (rMonth < 12) + ++rMonth; + else + { + if (rYear == kYearMax) + { + rDay = 31; + rMonth = 12; + return true; + } + ++rYear; + rMonth = 1; + } + } + } + + if (rDay == 0) + rDay = getDaysInMonth(rMonth, rYear); + + return true; +} + +} // namespace comphelper::date + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/comphelper/source/misc/diagnose_ex.cxx b/comphelper/source/misc/diagnose_ex.cxx new file mode 100644 index 000000000000..487f98b637a0 --- /dev/null +++ b/comphelper/source/misc/diagnose_ex.cxx @@ -0,0 +1,392 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <com/sun/star/configuration/CorruptedConfigurationException.hpp> +#include <com/sun/star/configuration/backend/BackendSetupException.hpp> +#include <com/sun/star/configuration/backend/MalformedDataException.hpp> +#include <com/sun/star/configuration/InvalidBootstrapFileException.hpp> +#include <com/sun/star/configuration/MissingBootstrapFileException.hpp> +#include <com/sun/star/deployment/DependencyException.hpp> +#include <com/sun/star/deployment/DeploymentException.hpp> +#include <com/sun/star/document/CorruptedFilterConfigurationException.hpp> +#include <com/sun/star/document/UndoFailedException.hpp> +#include <com/sun/star/lang/IllegalArgumentException.hpp> +#include <com/sun/star/lang/WrappedTargetException.hpp> +#include <com/sun/star/lang/WrappedTargetRuntimeException.hpp> +#include <com/sun/star/ldap/LdapGenericException.hpp> +#include <com/sun/star/script/BasicErrorException.hpp> +#include <com/sun/star/script/CannotConvertException.hpp> +#include <com/sun/star/script/provider/ScriptExceptionRaisedException.hpp> +#include <com/sun/star/script/provider/ScriptFrameworkErrorException.hpp> +#include <com/sun/star/sdbc/SQLException.hpp> +#include <com/sun/star/system/SystemShellExecuteException.hpp> +#include <com/sun/star/task/ErrorCodeIOException.hpp> +#include <com/sun/star/ucb/CommandFailedException.hpp> +#include <com/sun/star/ucb/ContentCreationException.hpp> +#include <com/sun/star/ucb/MissingPropertiesException.hpp> +#include <com/sun/star/ucb/NameClashException.hpp> +#include <com/sun/star/ucb/InteractiveIOException.hpp> +#include <com/sun/star/util/MalformedNumberFormatException.hpp> +#include <com/sun/star/xml/dom/DOMException.hpp> +#include <com/sun/star/xml/sax/SAXException.hpp> +#include <com/sun/star/xml/sax/SAXParseException.hpp> +#include <comphelper/anytostring.hxx> +#include <sal/log.hxx> +#include <osl/thread.h> +#include <rtl/strbuf.hxx> + +#include <comphelper/diagnose_ex.hxx> + +#if defined __GLIBCXX__ +#include <cxxabi.h> +#endif + +static void exceptionToStringImpl(OStringBuffer& sMessage, const css::uno::Any & caught) +{ + auto toOString = [](OUString const & s) { + return OUStringToOString( s, osl_getThreadTextEncoding() ); + }; + // when called recursively, we might not have any exception to print + if (!caught.hasValue()) + return; + sMessage.append(toOString(caught.getValueTypeName())); + css::uno::Exception exception; + caught >>= exception; + if ( !exception.Message.isEmpty() ) + { + sMessage.append(" message: \""); + sMessage.append(toOString(exception.Message)); + sMessage.append("\""); + } + if ( exception.Context.is() ) + { + const char* pContext = typeid( *exception.Context ).name(); +#if defined __GLIBCXX__ + // demangle the type name, not necessary under windows, we already get demangled names there + int status; + pContext = abi::__cxa_demangle( pContext, nullptr, nullptr, &status); +#endif + sMessage.append(" context: "); + sMessage.append(pContext); +#if defined __GLIBCXX__ + std::free(const_cast<char *>(pContext)); +#endif + } + { + css::configuration::CorruptedConfigurationException specialized; + if ( caught >>= specialized ) + { + sMessage.append(" details: "); + sMessage.append(toOString(specialized.Details)); + } + } + { + css::configuration::InvalidBootstrapFileException specialized; + if ( caught >>= specialized ) + { + sMessage.append(" BootstrapFileURL: "); + sMessage.append(toOString(specialized.BootstrapFileURL)); + } + } + { + css::configuration::MissingBootstrapFileException specialized; + if ( caught >>= specialized ) + { + sMessage.append(" BootstrapFileURL: "); + sMessage.append(toOString(specialized.BootstrapFileURL)); + } + } + { + css::configuration::backend::MalformedDataException specialized; + if ( caught >>= specialized ) + { + sMessage.append("\n wrapped: "); + exceptionToStringImpl(sMessage, specialized.ErrorDetails); + } + } + { + css::configuration::backend::BackendSetupException specialized; + if ( caught >>= specialized ) + { + sMessage.append("\n wrapped: "); + exceptionToStringImpl(sMessage, specialized.BackendException); + } + } + { + css::deployment::DependencyException specialized; + if ( caught >>= specialized ) + { + sMessage.append(" UnsatisfiedDependencies: "); + sMessage.append(toOString(comphelper::anyToString(css::uno::Any(specialized.UnsatisfiedDependencies)))); + } + } + { + css::deployment::DeploymentException specialized; + if ( caught >>= specialized ) + { + sMessage.append("\n wrapped: "); + exceptionToStringImpl(sMessage, specialized.Cause); + } + } + { + css::document::CorruptedFilterConfigurationException specialized; + if ( caught >>= specialized ) + { + sMessage.append(" Details: "); + sMessage.append(toOString(specialized.Details)); + } + } + { + css::document::UndoFailedException specialized; + if ( caught >>= specialized ) + { + sMessage.append(" Reason: "); + sMessage.append(toOString(comphelper::anyToString(specialized.Reason))); + } + } + { + css::lang::IllegalArgumentException specialized; + if ( caught >>= specialized ) + { + sMessage.append(" ArgumentPosition: "); + sMessage.append(static_cast<sal_Int32>(specialized.ArgumentPosition)); + } + } + { + css::lang::WrappedTargetException specialized; + if ( caught >>= specialized ) + { + sMessage.append("\n wrapped: "); + exceptionToStringImpl(sMessage, specialized.TargetException); + } + } + { + css::lang::WrappedTargetRuntimeException specialized; + if ( caught >>= specialized ) + { + sMessage.append("\n wrapped: "); + exceptionToStringImpl(sMessage, specialized.TargetException); + } + } + { + css::ldap::LdapGenericException specialized; + if ( caught >>= specialized ) + { + sMessage.append(" ErrorCode: "); + sMessage.append(specialized.ErrorCode); + } + } + { + css::script::BasicErrorException specialized; + if ( caught >>= specialized ) + { + sMessage.append(" ErrorCode: "); + sMessage.append(specialized.ErrorCode); + sMessage.append(" ErrorMessageArgument: "); + sMessage.append(toOString(specialized.ErrorMessageArgument)); + } + } + { + css::script::CannotConvertException specialized; + if ( caught >>= specialized ) + { + sMessage.append(" DestinationTypeClass: "); + sMessage.append(toOString(comphelper::anyToString(css::uno::Any(specialized.DestinationTypeClass)))); + sMessage.append(" Reason: "); + sMessage.append(specialized.Reason); + sMessage.append(" ArgumentIndex: "); + sMessage.append(specialized.ArgumentIndex); + } + } + { + css::script::provider::ScriptErrorRaisedException specialized; + if ( caught >>= specialized ) + { + sMessage.append(" scriptName: "); + sMessage.append(toOString(specialized.scriptName)); + sMessage.append(" language: "); + sMessage.append(toOString(specialized.language)); + sMessage.append(" lineNum: "); + sMessage.append(specialized.lineNum); + } + } + { + css::script::provider::ScriptExceptionRaisedException specialized; + if ( caught >>= specialized ) + { + sMessage.append(" exceptionType: "); + sMessage.append(toOString(specialized.exceptionType)); + } + } + { + css::script::provider::ScriptFrameworkErrorException specialized; + if ( caught >>= specialized ) + { + sMessage.append(" scriptName: "); + sMessage.append(toOString(specialized.scriptName)); + sMessage.append(" language: "); + sMessage.append(toOString(specialized.language)); + sMessage.append(" errorType: "); + sMessage.append(specialized.errorType); + } + } + { + css::sdbc::SQLException specialized; + if ( caught >>= specialized ) + { + sMessage.append(" SQLState: "); + sMessage.append(toOString(specialized.SQLState)); + sMessage.append(" ErrorCode: "); + sMessage.append(specialized.ErrorCode); + sMessage.append("\n wrapped: "); + exceptionToStringImpl(sMessage, specialized.NextException); + } + } + { + css::system::SystemShellExecuteException specialized; + if ( caught >>= specialized ) + { + sMessage.append(" PosixError: "); + sMessage.append(specialized.PosixError); + } + } + { + css::task::ErrorCodeIOException specialized; + if ( caught >>= specialized ) + { + sMessage.append(" errcode: "); + sMessage.append( specialized.ErrCode ); + } + } + { + css::ucb::CommandFailedException specialized; + if ( caught >>= specialized ) + { + sMessage.append("\n Reason: "); + exceptionToStringImpl( sMessage, specialized.Reason ); + } + } + { + css::ucb::ContentCreationException specialized; + if ( caught >>= specialized ) + { + sMessage.append(" eError: "); + sMessage.append(toOString(comphelper::anyToString( css::uno::Any(specialized.eError) ))); + } + } + { + css::ucb::MissingPropertiesException specialized; + if ( caught >>= specialized ) + { + sMessage.append(" Properties: "); + sMessage.append(toOString(comphelper::anyToString( css::uno::Any(specialized.Properties) ))); + } + } + { + css::ucb::NameClashException specialized; + if ( caught >>= specialized ) + { + sMessage.append(" Name: "); + sMessage.append(toOString( specialized.Name )); + } + } + { + css::util::MalformedNumberFormatException specialized; + if ( caught >>= specialized ) + { + sMessage.append(" CheckPos: "); + sMessage.append( specialized.CheckPos ); + } + } + { + css::xml::dom::DOMException specialized; + if ( caught >>= specialized ) + { + sMessage.append(" Code: "); + sMessage.append(toOString(comphelper::anyToString( css::uno::Any(specialized.Code) ))); + } + } + { + css::xml::dom::DOMException specialized; + if ( caught >>= specialized ) + { + sMessage.append(" Code: "); + sMessage.append(toOString(comphelper::anyToString( css::uno::Any(specialized.Code) ))); + } + } + { + css::xml::sax::SAXException specialized; + if ( caught >>= specialized ) + { + sMessage.append("\n wrapped: "); + exceptionToStringImpl( sMessage, specialized.WrappedException ); + } + } + { + css::xml::sax::SAXParseException specialized; + if ( caught >>= specialized ) + { + sMessage.append(" PublicId: "); + sMessage.append(toOString( specialized.PublicId )); + sMessage.append(" SystemId: "); + sMessage.append(toOString( specialized.SystemId )); + sMessage.append(" LineNumber: "); + sMessage.append( specialized.LineNumber ); + sMessage.append(" ColumnNumber: "); + sMessage.append( specialized.ColumnNumber ); + } + } + { + css::ucb::InteractiveIOException specialized; + if ( caught >>= specialized ) + { + sMessage.append(" Code: "); + sMessage.append( static_cast<sal_Int32>(specialized.Code) ); + } + } +} + +OString exceptionToString(const css::uno::Any & caught) +{ + OStringBuffer sMessage(512); + exceptionToStringImpl(sMessage, caught); + return sMessage.makeStringAndClear(); +} + +void DbgUnhandledException(const css::uno::Any & caught, const char* currentFunction, const char* fileAndLineNo, + const char* area, const char* explanatory) +{ + OStringBuffer sMessage( 512 ); + sMessage.append( OString::Concat("DBG_UNHANDLED_EXCEPTION in ") + currentFunction); + if (explanatory) + { + sMessage.append(OString::Concat("\n when: ") + explanatory); + } + sMessage.append(" exception: "); + exceptionToStringImpl(sMessage, caught); + + if (area == nullptr) + area = "legacy.osl"; + + SAL_DETAIL_LOG_FORMAT( + SAL_DETAIL_ENABLE_LOG_WARN, SAL_DETAIL_LOG_LEVEL_WARN, + area, fileAndLineNo, "%s", sMessage.getStr()); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/comphelper/source/misc/docpasswordhelper.cxx b/comphelper/source/misc/docpasswordhelper.cxx index f0f13ad74f1c..e4327acb8e40 100644 --- a/comphelper/source/misc/docpasswordhelper.cxx +++ b/comphelper/source/misc/docpasswordhelper.cxx @@ -51,7 +51,6 @@ using ::com::sun::star::task::PasswordRequestMode; using ::com::sun::star::task::PasswordRequestMode_PASSWORD_ENTER; using ::com::sun::star::task::PasswordRequestMode_PASSWORD_REENTER; using ::com::sun::star::task::XInteractionHandler; -using ::com::sun::star::task::XInteractionRequest; using namespace ::com::sun::star; @@ -96,10 +95,10 @@ uno::Sequence< beans::PropertyValue > DocPasswordHelper::GenerateNewModifyPasswo uno::Sequence< sal_Int8 > aNewHash = GeneratePBKDF2Hash(aPassword, aSalt, nPBKDF2IterationCount, 16); if ( aNewHash.hasElements() ) { - aResult = { comphelper::makePropertyValue("algorithm-name", OUString( "PBKDF2" )), - comphelper::makePropertyValue("salt", aSalt), - comphelper::makePropertyValue("iteration-count", nPBKDF2IterationCount), - comphelper::makePropertyValue("hash", aNewHash) }; + aResult = { comphelper::makePropertyValue(u"algorithm-name"_ustr, u"PBKDF2"_ustr), + comphelper::makePropertyValue(u"salt"_ustr, aSalt), + comphelper::makePropertyValue(u"iteration-count"_ustr, nPBKDF2IterationCount), + comphelper::makePropertyValue(u"hash"_ustr, aNewHash) }; } return aResult; @@ -111,23 +110,83 @@ DocPasswordHelper::GenerateNewModifyPasswordInfoOOXML(std::u16string_view aPassw { uno::Sequence<beans::PropertyValue> aResult; - uno::Sequence<sal_Int8> aSalt = GenerateRandomByteSequence(16); - OUStringBuffer aBuffer; - comphelper::Base64::encode(aBuffer, aSalt); - OUString sSalt = aBuffer.makeStringAndClear(); + if (!aPassword.empty()) + { + uno::Sequence<sal_Int8> aSalt = GenerateRandomByteSequence(16); + OUStringBuffer aBuffer(22); + comphelper::Base64::encode(aBuffer, aSalt); + OUString sSalt = aBuffer.makeStringAndClear(); + + sal_Int32 const nIterationCount = 100000; + OUString sAlgorithm(u"SHA-512"_ustr); + + const OUString sHash(GetOoxHashAsBase64(OUString(aPassword), sSalt, nIterationCount, + comphelper::Hash::IterCount::APPEND, sAlgorithm)); + + if (!sHash.isEmpty()) + { + aResult = { comphelper::makePropertyValue(u"algorithm-name"_ustr, sAlgorithm), + comphelper::makePropertyValue(u"salt"_ustr, sSalt), + comphelper::makePropertyValue(u"iteration-count"_ustr, nIterationCount), + comphelper::makePropertyValue(u"hash"_ustr, sHash) }; + } + } + + return aResult; +} - sal_Int32 const nIterationCount = 100000; - OUString sAlgorithm("SHA-512"); - const OUString sHash(GetOoxHashAsBase64(OUString(aPassword), sSalt, nIterationCount, - comphelper::Hash::IterCount::APPEND, sAlgorithm)); +uno::Sequence< beans::PropertyValue > DocPasswordHelper::ConvertPasswordInfo( const uno::Sequence< beans::PropertyValue >& aInfo ) +{ + uno::Sequence< beans::PropertyValue > aResult; + OUString sAlgorithm, sHash, sSalt, sCount; + sal_Int32 nAlgorithm = 0; + + for ( const auto & prop : aInfo ) + { + if ( prop.Name == "cryptAlgorithmSid" ) + { + prop.Value >>= sAlgorithm; + nAlgorithm = sAlgorithm.toInt32(); + } + else if ( prop.Name == "salt" ) + prop.Value >>= sSalt; + else if ( prop.Name == "cryptSpinCount" ) + prop.Value >>= sCount; + else if ( prop.Name == "hash" ) + prop.Value >>= sHash; + } - if (!sHash.isEmpty()) + if (nAlgorithm == 1) + sAlgorithm = "MD2"; + else if (nAlgorithm == 2) + sAlgorithm = "MD4"; + else if (nAlgorithm == 3) + sAlgorithm = "MD5"; + else if (nAlgorithm == 4) + sAlgorithm = "SHA-1"; + else if (nAlgorithm == 5) + sAlgorithm = "MAC"; + else if (nAlgorithm == 6) + sAlgorithm = "RIPEMD"; + else if (nAlgorithm == 7) + sAlgorithm = "RIPEMD-160"; + else if (nAlgorithm == 9) + sAlgorithm = "HMAC"; + else if (nAlgorithm == 12) + sAlgorithm = "SHA-256"; + else if (nAlgorithm == 13) + sAlgorithm = "SHA-384"; + else if (nAlgorithm == 14) + sAlgorithm = "SHA-512"; + + if ( !sCount.isEmpty() ) { - aResult = { comphelper::makePropertyValue("algorithm-name", sAlgorithm), - comphelper::makePropertyValue("salt", sSalt), - comphelper::makePropertyValue("iteration-count", nIterationCount), - comphelper::makePropertyValue("hash", sHash) }; + sal_Int32 nCount = sCount.toInt32(); + aResult = { comphelper::makePropertyValue(u"algorithm-name"_ustr, sAlgorithm), + comphelper::makePropertyValue(u"salt"_ustr, sSalt), + comphelper::makePropertyValue(u"iteration-count"_ustr, nCount), + comphelper::makePropertyValue(u"hash"_ustr, sHash) }; } return aResult; @@ -194,7 +253,7 @@ bool DocPasswordHelper::IsModifyPasswordCorrect( std::u16string_view aPassword, sal_uInt32 DocPasswordHelper::GetWordHashAsUINT32( - const OUString& aUString ) + std::u16string_view aUString ) { static const sal_uInt16 pInitialCode[] = { 0xE1F0, // 1 @@ -233,7 +292,7 @@ sal_uInt32 DocPasswordHelper::GetWordHashAsUINT32( }; sal_uInt32 nResult = 0; - sal_uInt32 nLen = aUString.getLength(); + size_t nLen = aUString.size(); if ( nLen ) { @@ -243,7 +302,7 @@ sal_uInt32 DocPasswordHelper::GetWordHashAsUINT32( sal_uInt16 nHighResult = pInitialCode[nLen - 1]; sal_uInt16 nLowResult = 0; - for ( sal_uInt32 nInd = 0; nInd < nLen; nInd++ ) + for ( size_t nInd = 0; nInd < nLen; nInd++ ) { // NO Encoding during conversion! // The specification says that the low byte should be used in case it is not NULL @@ -314,6 +373,8 @@ std::vector<unsigned char> DocPasswordHelper::GetOoxHashAsVector( eType = comphelper::HashType::SHA512; else if (rAlgorithmName == u"SHA-256" || rAlgorithmName == u"SHA256") eType = comphelper::HashType::SHA256; + else if (rAlgorithmName == u"SHA-384" || rAlgorithmName == u"SHA384") + eType = comphelper::HashType::SHA384; else if (rAlgorithmName == u"SHA-1" || rAlgorithmName == u"SHA1") // "SHA1" might be in the wild eType = comphelper::HashType::SHA1; else if (rAlgorithmName == u"MD5") @@ -366,22 +427,25 @@ OUString DocPasswordHelper::GetOoxHashAsBase64( uno::Sequence< sal_Int8 > aResult( nLength ); rtlRandomPool aRandomPool = rtl_random_createPool (); - rtl_random_getBytes ( aRandomPool, aResult.getArray(), nLength ); + if (rtl_random_getBytes(aRandomPool, aResult.getArray(), nLength) != rtl_Random_E_None) + { + throw uno::RuntimeException(u"rtl_random_getBytes failed"_ustr); + } rtl_random_destroyPool ( aRandomPool ); return aResult; } -/*static*/ uno::Sequence< sal_Int8 > DocPasswordHelper::GenerateStd97Key( const OUString& aPassword, const uno::Sequence< sal_Int8 >& aDocId ) +/*static*/ uno::Sequence< sal_Int8 > DocPasswordHelper::GenerateStd97Key( std::u16string_view aPassword, const uno::Sequence< sal_Int8 >& aDocId ) { uno::Sequence< sal_Int8 > aResultKey; - if ( !aPassword.isEmpty() && aDocId.getLength() == 16 ) + if ( !aPassword.empty() && aDocId.getLength() == 16 ) { sal_uInt16 pPassData[16] = {}; - sal_Int32 nPassLen = std::min< sal_Int32 >( aPassword.getLength(), 15 ); - memcpy( pPassData, aPassword.getStr(), nPassLen * sizeof(pPassData[0]) ); + sal_Int32 nPassLen = std::min< sal_Int32 >( aPassword.size(), 15 ); + memcpy( pPassData, aPassword.data(), nPassLen * sizeof(pPassData[0]) ); aResultKey = GenerateStd97Key( pPassData, aDocId ); } @@ -562,11 +626,10 @@ OUString DocPasswordHelper::GetOoxHashAsBase64( if (eResult == DocPasswordVerifierResult::OK && !aPassword.isEmpty()) { - if (std::find_if(std::cbegin(aEncData), std::cend(aEncData), + if (std::none_of(std::cbegin(aEncData), std::cend(aEncData), [](const css::beans::NamedValue& val) { return val.Name == PACKAGE_ENCRYPTIONDATA_SHA256UTF8; - }) - == std::cend(aEncData)) + })) { // tdf#118639: We need ODF encryption data for autorecovery, where password // will already be unavailable, so generate and append it here @@ -584,9 +647,9 @@ OUString DocPasswordHelper::GetOoxHashAsBase64( // 2. Add MS binary and OOXML encryption data to result aEncData = comphelper::concatSequences( aEncData, std::initializer_list<beans::NamedValue>{ - { "STD97EncryptionKey", css::uno::Any(aEnc97Key) }, - { "STD97UniqueID", css::uno::Any(aUniqueID) }, - { "OOXPassword", css::uno::Any(aPassword) }, + { u"STD97EncryptionKey"_ustr, css::uno::Any(aEnc97Key) }, + { u"STD97UniqueID"_ustr, css::uno::Any(aUniqueID) }, + { u"OOXPassword"_ustr, css::uno::Any(aPassword) }, }); } } @@ -607,26 +670,23 @@ OUString DocPasswordHelper::GetOoxHashAsBase64( GpgME::initializeLibrary(); GpgME::Error err = GpgME::checkEngine(GpgME::OpenPGP); if (err) - throw uno::RuntimeException("The GpgME library failed to initialize for the OpenPGP protocol."); + throw uno::RuntimeException(u"The GpgME library failed to initialize for the OpenPGP protocol."_ustr); ctx.reset( GpgME::Context::createForProtocol(GpgME::OpenPGP) ); if (ctx == nullptr) - throw uno::RuntimeException("The GpgME library failed to initialize for the OpenPGP protocol."); + throw uno::RuntimeException(u"The GpgME library failed to initialize for the OpenPGP protocol."_ustr); ctx->setArmor(false); - const uno::Sequence < beans::NamedValue > *pSequence = rGpgProperties.getConstArray(); - const sal_Int32 nLength = rGpgProperties.getLength(); - for ( sal_Int32 i = 0; i < nLength ; i++, pSequence++ ) + for (auto& rSequence : rGpgProperties) { - const beans::NamedValue *pValues = pSequence->getConstArray(); - if ( pSequence->getLength() == 3 ) + if (rSequence.getLength() == 3) { // take CipherValue and try to decrypt that - stop after // the first successful decryption // ctx is setup now, let's decrypt the lot! uno::Sequence < sal_Int8 > aVector; - pValues[2].Value >>= aVector; + rSequence[2].Value >>= aVector; GpgME::Data cipher( reinterpret_cast<const char*>(aVector.getConstArray()), @@ -653,7 +713,7 @@ OUString DocPasswordHelper::GetOoxHashAsBase64( result = plain.seek(0,SEEK_SET); assert(result == 0); if( plain.read(aKeyValue.getArray(), len) != len ) - throw uno::RuntimeException("The GpgME library failed to read the encrypted value."); + throw uno::RuntimeException(u"The GpgME library failed to read the encrypted value."_ustr); SAL_INFO("comphelper.crypto", "Extracted gpg session key of length: " << len); @@ -665,7 +725,7 @@ OUString DocPasswordHelper::GetOoxHashAsBase64( if ( aEncryptionData.hasElements() ) { uno::Sequence< beans::NamedValue > aContainer{ - { "GpgInfos", uno::Any(rGpgProperties) }, { "EncryptionKey", uno::Any(aEncryptionData) } + { u"GpgInfos"_ustr, uno::Any(rGpgProperties) }, { u"EncryptionKey"_ustr, uno::Any(aEncryptionData) } }; return aContainer; diff --git a/comphelper/source/misc/documentinfo.cxx b/comphelper/source/misc/documentinfo.cxx index 0a1c04347c84..21425524e64e 100644 --- a/comphelper/source/misc/documentinfo.cxx +++ b/comphelper/source/misc/documentinfo.cxx @@ -106,8 +106,7 @@ namespace comphelper { } // 4. try model arguments - NamedValueCollection aModelArgs( _rxDocument->getArgs() ); - sTitle = aModelArgs.getOrDefault( "Title", sTitle ); + sTitle = NamedValueCollection::getOrDefault( _rxDocument->getArgs(), u"Title", sTitle ); if ( !sTitle.isEmpty() ) return sTitle; diff --git a/comphelper/source/misc/errcode.cxx b/comphelper/source/misc/errcode.cxx new file mode 100644 index 000000000000..716daab1793e --- /dev/null +++ b/comphelper/source/misc/errcode.cxx @@ -0,0 +1,174 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <comphelper/errcode.hxx> +#include <rtl/ustrbuf.hxx> +#include <o3tl/runtimetooustring.hxx> + +UNLESS_MERGELIBS(COMPHELPER_DLLPUBLIC) OUString ErrCode::toString() const +{ + std::u16string_view pWarningError; + if (IsWarning()) + pWarningError = u"Warning"; + else + pWarningError = u"Error"; + + std::u16string_view pArea; + switch (GetArea()) + { + case ErrCodeArea::Io: + pArea = u"Io"; + break; + case ErrCodeArea::Sfx: + pArea = u"Sfx"; + break; + case ErrCodeArea::Inet: + pArea = u"Inet"; + break; + case ErrCodeArea::Vcl: + pArea = u"Vcl"; + break; + case ErrCodeArea::Svx: + pArea = u"Svx"; + break; + case ErrCodeArea::So: + pArea = u"So"; + break; + case ErrCodeArea::Sbx: + pArea = u"Sbx"; + break; + case ErrCodeArea::Uui: + pArea = u"Uui"; + break; + case ErrCodeArea::Sc: + pArea = u"Sc"; + break; + case ErrCodeArea::Sd: + pArea = u"Sd"; + break; + case ErrCodeArea::Sw: + pArea = u"Sw"; + break; + } + + std::u16string_view pClass; + switch (GetClass()) + { + case ErrCodeClass::NONE: + pClass = u"NONE"; + break; + case ErrCodeClass::Abort: + pClass = u"Abort"; + break; + case ErrCodeClass::General: + pClass = u"General"; + break; + case ErrCodeClass::NotExists: + pClass = u"NotExists"; + break; + case ErrCodeClass::AlreadyExists: + pClass = u"AlreadyExists"; + break; + case ErrCodeClass::Access: + pClass = u"Access"; + break; + case ErrCodeClass::Path: + pClass = u"Path"; + break; + case ErrCodeClass::Locking: + pClass = u"Locking"; + break; + case ErrCodeClass::Parameter: + pClass = u"Parameter"; + break; + case ErrCodeClass::Space: + pClass = u"Space"; + break; + case ErrCodeClass::NotSupported: + pClass = u"NotSupported"; + break; + case ErrCodeClass::Read: + pClass = u"Read"; + break; + case ErrCodeClass::Write: + pClass = u"Write"; + break; + case ErrCodeClass::Unknown: + pClass = u"Unknown"; + break; + case ErrCodeClass::Version: + pClass = u"Version"; + break; + case ErrCodeClass::Format: + pClass = u"Format"; + break; + case ErrCodeClass::Create: + pClass = u"Create"; + break; + case ErrCodeClass::Import: + pClass = u"Import"; + break; + case ErrCodeClass::Export: + pClass = u"Export"; + break; + case ErrCodeClass::So: + pClass = u"So"; + break; + case ErrCodeClass::Sbx: + pClass = u"Sbx"; + break; + case ErrCodeClass::Runtime: + pClass = u"Runtime"; + break; + case ErrCodeClass::Compiler: + pClass = u"Compiler"; + break; + } + return toHexString() + "(" + pWarningError + " Area:" + pArea + " Class:" + pClass + + " Code:" + OUString::number(GetCode()) + ")"; +} + +COMPHELPER_DLLPUBLIC std::ostream& operator<<(std::ostream& os, const ErrCode& err) +{ + os << err.toString(); + return os; +} + +UNLESS_MERGELIBS(COMPHELPER_DLLPUBLIC) OUString ErrCodeMsg::toString() const +{ + OUString s = mnCode.toString(); + if (!maArg1.isEmpty()) + s += " arg1=" + maArg1; + if (!maArg2.isEmpty()) + s += " arg2=" + maArg2; +#ifdef LIBO_ERRMSG_USE_SOURCE_LOCATION + if (!moLoc) + s += OUString::Concat(" func=") + o3tl::runtimeToOUString(moLoc->function_name()) + " src=" + + o3tl::runtimeToOUString(moLoc->file_name()) + ":" + OUString::number(moLoc->line()); +#endif + return s; +} + +COMPHELPER_DLLPUBLIC std::ostream& operator<<(std::ostream& os, const ErrCodeMsg& err) +{ + os << err.toString(); + return os; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/comphelper/source/misc/fileurl.cxx b/comphelper/source/misc/fileurl.cxx index 4f361ab4ba7a..2515b28c5b30 100644 --- a/comphelper/source/misc/fileurl.cxx +++ b/comphelper/source/misc/fileurl.cxx @@ -21,7 +21,11 @@ #include <comphelper/fileurl.hxx> #include <rtl/ustring.hxx> +#include <o3tl/string_view.hxx> -bool comphelper::isFileUrl(OUString const& url) { return url.startsWithIgnoreAsciiCase("file:"); } +bool comphelper::isFileUrl(std::u16string_view url) +{ + return o3tl::matchIgnoreAsciiCase(url, "file:"); +} /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/comphelper/source/misc/graphicmimetype.cxx b/comphelper/source/misc/graphicmimetype.cxx index 4448c832971f..a9bc0e504ea5 100644 --- a/comphelper/source/misc/graphicmimetype.cxx +++ b/comphelper/source/misc/graphicmimetype.cxx @@ -18,6 +18,10 @@ */ #include <comphelper/graphicmimetype.hxx> +#include <comphelper/mediamimetype.hxx> + +#include <map> +#include <set> #include <com/sun/star/beans/PropertyValue.hpp> #include <com/sun/star/beans/XPropertySet.hpp> @@ -53,8 +57,8 @@ OUString GraphicMimeTypeHelper::GetMimeTypeForExtension(std::string_view rExt) OUString aMimeType; - tools::Long const nCount = SAL_N_ELEMENTS(aMapper); - for (tools::Long i = 0; (i < nCount) && aMimeType.isEmpty(); ++i) + size_t const nCount = std::size(aMapper); + for (size_t i = 0; (i < nCount) && aMimeType.isEmpty(); ++i) { if (rExt == aMapper[i].pExt) aMimeType = OUString(aMapper[i].pMimeType, strlen(aMapper[i].pMimeType), @@ -69,11 +73,11 @@ OUString GraphicMimeTypeHelper::GetMimeTypeForXGraphic(const Reference<XGraphic> OUString aSourceMimeType; Reference<XPropertySet> const xGraphicPropertySet(xGraphic, UNO_QUERY); if (xGraphicPropertySet.is() && // it's null if it's an external link - (xGraphicPropertySet->getPropertyValue("MimeType") >>= aSourceMimeType)) + (xGraphicPropertySet->getPropertyValue(u"MimeType"_ustr) >>= aSourceMimeType)) { return aSourceMimeType; } - return ""; + return u""_ustr; } OUString @@ -82,7 +86,7 @@ GraphicMimeTypeHelper::GetMimeTypeForImageStream(const Reference<XInputStream>& // Create the graphic to retrieve the mimetype from it Reference<XGraphicProvider> xProvider = css::graphic::GraphicProvider::create(comphelper::getProcessComponentContext()); - Sequence<PropertyValue> aMediaProperties{ comphelper::makePropertyValue("InputStream", + Sequence<PropertyValue> aMediaProperties{ comphelper::makePropertyValue(u"InputStream"_ustr, xInputStream) }; Reference<XGraphic> xGraphic(xProvider->queryGraphic(aMediaProperties)); @@ -94,29 +98,29 @@ OUString GraphicMimeTypeHelper::GetMimeTypeForConvertDataFormat(ConvertDataForma switch (convertDataFormat) { case ConvertDataFormat::BMP: - return "image/bmp"; + return u"image/bmp"_ustr; case ConvertDataFormat::GIF: - return "image/gif"; + return u"image/gif"_ustr; case ConvertDataFormat::JPG: - return "image/jpeg"; + return u"image/jpeg"_ustr; case ConvertDataFormat::PCT: - return "image/x-pict"; + return u"image/x-pict"_ustr; case ConvertDataFormat::PNG: - return "image/png"; + return u"image/png"_ustr; case ConvertDataFormat::SVM: - return "image/x-svm"; + return u"image/x-svm"_ustr; case ConvertDataFormat::TIF: - return "image/tiff"; + return u"image/tiff"_ustr; case ConvertDataFormat::WMF: - return "image/x-wmf"; + return u"image/x-wmf"_ustr; case ConvertDataFormat::EMF: - return "image/x-emf"; + return u"image/x-emf"_ustr; case ConvertDataFormat::SVG: - return "image/svg+xml"; + return u"image/svg+xml"_ustr; case ConvertDataFormat::MET: // What is this? case ConvertDataFormat::Unknown: default: - return ""; + return u""_ustr; } } @@ -166,6 +170,70 @@ char const* GraphicMimeTypeHelper::GetExtensionForConvertDataFormat(ConvertDataF } return pExt; } + +static auto GetMediaMimes() -> std::map<OString, OString> const& +{ + static std::map<OString, OString> const mimes = { + { "mp4", "video/mp4" }, + { "ts", "video/MP2T" }, + { "mpeg", "video/mpeg" }, + { "mpg", "video/mpeg" }, + { "mkv", "video/x-matroska" }, + { "webm", "video/webm" }, + { "ogv", "video/ogg" }, + { "mov", "video/quicktime" }, + { "wmv", "video/x-ms-wmv" }, + { "avi", "video/x-msvideo" }, + { "m4a", "audio/mp4" }, + { "aac", "audio/aac" }, + { "mp3", "audio/mpeg" }, // https://bugs.chromium.org/p/chromium/issues/detail?id=227004 + { "ogg", "audio/ogg" }, + { "oga", "audio/ogg" }, + { "opus", "audio/ogg" }, + { "flac", "audio/flac" }, // missing at IANA? + // note there is RFC 2631 but i got the impression that vnd.wave + // requires specifying the codec in the container; also this page + // says "Historic" whatever that means: + // https://www.iana.org/assignments/wave-avi-codec-registry/wave-avi-codec-registry.xhtml + { "wav", "audio/x-wav" }, + }; + return mimes; +} + +auto IsMediaMimeType(::std::string_view const rMimeType) -> bool +{ + return IsMediaMimeType(OStringToOUString(rMimeType, RTL_TEXTENCODING_UTF8)); +} + +auto IsMediaMimeType(OUString const& rMimeType) -> bool +{ + static std::set<OUString> mimes; + if (mimes.empty()) + { + auto const& rMap(GetMediaMimes()); + for (auto const& it : rMap) + { + mimes.insert(OStringToOUString(it.second, RTL_TEXTENCODING_UTF8)); + } + } + return rMimeType == AVMEDIA_MIMETYPE_COMMON || mimes.find(rMimeType) != mimes.end(); +} + +auto GuessMediaMimeType(::std::u16string_view rFileName) -> OUString +{ + if (auto const i = rFileName.rfind('.'); i != ::std::string_view::npos) + { + OString const ext(OUStringToOString(rFileName.substr(i + 1), RTL_TEXTENCODING_UTF8)); + auto const& rMap(GetMediaMimes()); + auto const it(rMap.find(ext)); + if (it != rMap.end()) + { + return OStringToOUString(it->second, RTL_TEXTENCODING_ASCII_US); + } + } + return OUString(); } +} // namespace comphelper + /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/comphelper/source/misc/hash.cxx b/comphelper/source/misc/hash.cxx index 50fd8cd0f961..25b93ad87e54 100644 --- a/comphelper/source/misc/hash.cxx +++ b/comphelper/source/misc/hash.cxx @@ -18,6 +18,7 @@ #if USE_TLS_NSS #include <nss.h> +#include <nspr.h> #include <sechash.h> #elif USE_TLS_OPENSSL #include <openssl/evp.h> @@ -42,6 +43,8 @@ struct HashImpl return HASH_AlgSHA1; case HashType::SHA256: return HASH_AlgSHA256; + case HashType::SHA384: + return HASH_AlgSHA384; case HashType::SHA512: return HASH_AlgSHA512; } @@ -61,6 +64,8 @@ struct HashImpl return EVP_sha1(); case HashType::SHA256: return EVP_sha256(); + case HashType::SHA384: + return EVP_sha384(); case HashType::SHA512: return EVP_sha512(); } @@ -76,9 +81,15 @@ struct HashImpl { #if USE_TLS_NSS - auto const e = NSS_NoDB_Init(nullptr); - if (e != SECSuccess) { - throw css::uno::RuntimeException("NSS_NoDB_Init failed with " + OUString::number(e)); + if (!NSS_IsInitialized()) + { + auto const e = NSS_NoDB_Init(nullptr); + if (e != SECSuccess) + { + PRErrorCode error = PR_GetError(); + const char* errorText = PR_ErrorToName(error); + throw css::uno::RuntimeException("NSS_NoDB_Init failed with " + OUString(errorText, strlen(errorText), RTL_TEXTENCODING_UTF8) + " (" + OUString::number(static_cast<int>(error)) + ")"); + } } mpContext = HASH_Create(getNSSType()); HASH_Begin(mpContext); @@ -144,6 +155,8 @@ size_t Hash::getLength() const return SHA1_HASH_LENGTH; case HashType::SHA256: return SHA256_HASH_LENGTH; + case HashType::SHA384: + return SHA384_HASH_LENGTH; case HashType::SHA512: return SHA512_HASH_LENGTH; } diff --git a/comphelper/source/misc/instancelocker.cxx b/comphelper/source/misc/instancelocker.cxx index 2b1e89604e6a..ebb0983ace17 100644 --- a/comphelper/source/misc/instancelocker.cxx +++ b/comphelper/source/misc/instancelocker.cxx @@ -30,6 +30,7 @@ #include <com/sun/star/frame/DoubleInitializationException.hpp> #include <com/sun/star/embed/Actions.hpp> #include <com/sun/star/embed/XActionsApproval.hpp> +#include <utility> #include "instancelocker.hxx" @@ -122,13 +123,13 @@ void SAL_CALL OInstanceLocker::initialize( const uno::Sequence< uno::Any >& aArg sal_Int32 nLen = aArguments.getLength(); if ( nLen < 2 || nLen > 3 ) throw lang::IllegalArgumentException( - "Wrong count of parameters!", + u"Wrong count of parameters!"_ustr, uno::Reference< uno::XInterface >(), 0 ); if ( !( aArguments[0] >>= xInstance ) || !xInstance.is() ) throw lang::IllegalArgumentException( - "Nonempty reference is expected as the first argument!", + u"Nonempty reference is expected as the first argument!"_ustr, uno::Reference< uno::XInterface >(), 0 ); @@ -142,14 +143,14 @@ void SAL_CALL OInstanceLocker::initialize( const uno::Sequence< uno::Any >& aArg ) { throw lang::IllegalArgumentException( - "The correct modes set is expected as the second argument!", + u"The correct modes set is expected as the second argument!"_ustr, uno::Reference< uno::XInterface >(), 0 ); } if ( nLen == 3 && !( aArguments[2] >>= xApproval ) ) throw lang::IllegalArgumentException( - "If the third argument is provided, it must be XActionsApproval implementation!", + u"If the third argument is provided, it must be XActionsApproval implementation!"_ustr, uno::Reference< uno::XInterface >(), 0 ); @@ -172,7 +173,7 @@ void SAL_CALL OInstanceLocker::initialize( const uno::Sequence< uno::Any >& aArg // XServiceInfo OUString SAL_CALL OInstanceLocker::getImplementationName( ) { - return "com.sun.star.comp.embed.InstanceLocker"; + return u"com.sun.star.comp.embed.InstanceLocker"_ustr; } sal_Bool SAL_CALL OInstanceLocker::supportsService( const OUString& ServiceName ) @@ -182,19 +183,19 @@ sal_Bool SAL_CALL OInstanceLocker::supportsService( const OUString& ServiceName uno::Sequence< OUString > SAL_CALL OInstanceLocker::getSupportedServiceNames() { - return { "com.sun.star.embed.InstanceLocker" }; + return { u"com.sun.star.embed.InstanceLocker"_ustr }; } // OLockListener -OLockListener::OLockListener( const uno::WeakReference< lang::XComponent >& xWrapper, - const uno::Reference< uno::XInterface >& xInstance, +OLockListener::OLockListener( uno::WeakReference< lang::XComponent > xWrapper, + uno::Reference< uno::XInterface > xInstance, sal_Int32 nMode, - const uno::Reference< embed::XActionsApproval >& rApproval ) -: m_xInstance( xInstance ) -, m_xApproval( rApproval ) -, m_xWrapper( xWrapper ) + uno::Reference< embed::XActionsApproval > xApproval ) +: m_xInstance(std::move( xInstance )) +, m_xApproval(std::move( xApproval )) +, m_xWrapper(std::move( xWrapper )) , m_bDisposed( false ) , m_bInitialized( false ) , m_nMode( nMode ) @@ -215,6 +216,7 @@ void OLockListener::Dispose() return; auto xInstance = std::move(m_xInstance); + auto xApproval = std::move(m_xApproval); auto nMode = m_nMode; m_bDisposed = true; aGuard.unlock(); diff --git a/comphelper/source/misc/instancelocker.hxx b/comphelper/source/misc/instancelocker.hxx index 7391c5d7d365..6a050c7f437c 100644 --- a/comphelper/source/misc/instancelocker.hxx +++ b/comphelper/source/misc/instancelocker.hxx @@ -85,10 +85,10 @@ class OLockListener : public ::cppu::WeakImplHelper< css::util::XCloseListener, sal_Int32 m_nMode; public: - OLockListener( const css::uno::WeakReference< css::lang::XComponent >& xWrapper, - const css::uno::Reference< css::uno::XInterface >& xInstance, + OLockListener( css::uno::WeakReference< css::lang::XComponent > xWrapper, + css::uno::Reference< css::uno::XInterface > xInstance, sal_Int32 nMode, - const css::uno::Reference< css::embed::XActionsApproval >& rApproval ); + css::uno::Reference< css::embed::XActionsApproval > xApproval ); virtual ~OLockListener() override; diff --git a/comphelper/source/misc/interaction.cxx b/comphelper/source/misc/interaction.cxx index e1fd64d9b04b..9e7b1706d111 100644 --- a/comphelper/source/misc/interaction.cxx +++ b/comphelper/source/misc/interaction.cxx @@ -20,6 +20,7 @@ #include <comphelper/interaction.hxx> #include <comphelper/sequence.hxx> +#include <utility> #include <osl/diagnose.h> @@ -30,14 +31,14 @@ namespace comphelper using namespace ::com::sun::star::uno; using namespace ::com::sun::star::task; - OInteractionRequest::OInteractionRequest(const Any& _rRequestDescription) - :m_aRequest(_rRequestDescription) + OInteractionRequest::OInteractionRequest(Any _aRequestDescription) + :m_aRequest(std::move(_aRequestDescription)) { } - OInteractionRequest::OInteractionRequest(const Any& rRequestDescription, + OInteractionRequest::OInteractionRequest(Any aRequestDescription, std::vector<Reference<XInteractionContinuation>>&& rContinuations) - : m_aRequest(rRequestDescription) + : m_aRequest(std::move(aRequestDescription)) , m_aContinuations(std::move(rContinuations)) { } diff --git a/comphelper/source/misc/logging.cxx b/comphelper/source/misc/logging.cxx index b656389def83..a7785d46a747 100644 --- a/comphelper/source/misc/logging.cxx +++ b/comphelper/source/misc/logging.cxx @@ -22,6 +22,7 @@ #include <com/sun/star/logging/LoggerPool.hpp> +#include <comphelper/diagnose_ex.hxx> #include <osl/diagnose.h> @@ -37,7 +38,6 @@ namespace comphelper class EventLogger_Impl { private: - Reference< XComponentContext > m_aContext; Reference< XLogger > m_xLogger; public: @@ -47,23 +47,32 @@ namespace comphelper const Reference< XLogger >& getLogger() const { return m_xLogger; } }; - EventLogger_Impl::EventLogger_Impl( const Reference< XComponentContext >& _rxContext, const OUString& _rLoggerName ) - :m_aContext( _rxContext ) + namespace { - try + Reference<XLogger> createLogger(const Reference<XComponentContext>& rxContext, const OUString& rLoggerName) { - Reference< XLoggerPool > xPool( LoggerPool::get( m_aContext ) ); - if ( !_rLoggerName.isEmpty() ) - m_xLogger = xPool->getNamedLogger( _rLoggerName ); - else - m_xLogger = xPool->getDefaultLogger(); - } - catch( const Exception& ) - { - OSL_FAIL( "EventLogger_Impl::impl_createLogger_nothrow: caught an exception!" ); + try + { + Reference<XLoggerPool> xPool(LoggerPool::get(rxContext)); + if (!rLoggerName.isEmpty()) + return xPool->getNamedLogger(rLoggerName); + else + return xPool->getDefaultLogger(); + } + catch( const Exception& ) + { + TOOLS_WARN_EXCEPTION( + "comphelper", "EventLogger_Impl::impl_createLogger_nothrow: caught an exception!" ); + } + return Reference<XLogger>(); } } + EventLogger_Impl::EventLogger_Impl(const Reference< XComponentContext >& _rxContext, const OUString& rLoggerName) + : m_xLogger(createLogger(_rxContext, rLoggerName)) + { + } + EventLogger::EventLogger( const Reference< XComponentContext >& _rxContext, const char* _pAsciiLoggerName ) :m_pImpl( std::make_shared<EventLogger_Impl>( _rxContext, OUString::createFromAscii( _pAsciiLoggerName ) ) ) { @@ -80,7 +89,7 @@ namespace comphelper } catch( const Exception& ) { - OSL_FAIL( "EventLogger::isLoggable: caught an exception!" ); + TOOLS_WARN_EXCEPTION( "comphelper", "EventLogger::isLoggable: caught an exception!" ); } return false; @@ -151,7 +160,7 @@ namespace comphelper } catch( const Exception& ) { - OSL_FAIL( "EventLogger::impl_log: caught an exception!" ); + TOOLS_WARN_EXCEPTION( "comphelper", "EventLogger::impl_log: caught an exception!" ); } } } // namespace comphelper diff --git a/comphelper/source/misc/lok.cxx b/comphelper/source/misc/lok.cxx index b11bf4e83582..36898debc22e 100644 --- a/comphelper/source/misc/lok.cxx +++ b/comphelper/source/misc/lok.cxx @@ -8,6 +8,7 @@ */ #include <comphelper/lok.hxx> +#include <osl/process.h> #include <i18nlangtag/languagetag.hxx> #include <sal/log.hxx> @@ -18,6 +19,8 @@ namespace comphelper::LibreOfficeKit static bool g_bActive(false); +static bool g_bForkedChild(false); + static bool g_bPartInInvalidation(false); static bool g_bTiledPainting(false); @@ -97,6 +100,16 @@ bool isActive() return g_bActive; } +void setForkedChild(bool bIsChild) +{ + g_bForkedChild = bIsChild; +} + +bool isForkedChild() +{ + return g_bForkedChild; +} + void setPartInInvalidation(bool bPartInInvalidation) { g_bPartInInvalidation = bPartInInvalidation; @@ -181,6 +194,8 @@ void setCompatFlag(Compat flag) { g_eCompatFlags = static_cast<Compat>(g_eCompat bool isCompatFlagSet(Compat flag) { return (g_eCompatFlags & flag) == flag; } +void resetCompatFlag() { g_eCompatFlags = Compat::none; } + void setLocale(const LanguageTag& rLanguageTag) { g_aLanguageAndLocale.setLocale(rLanguageTag); @@ -229,7 +244,7 @@ bool isAllowlistedLanguage(const OUString& lang) continue; std::cerr << s << " "; - aList.emplace_back(OStringToOUString(s.c_str(), RTL_TEXTENCODING_UTF8)); + aList.emplace_back(OStringToOUString(s, RTL_TEXTENCODING_UTF8)); } std::cerr << std::endl; } @@ -255,6 +270,24 @@ bool isAllowlistedLanguage(const OUString& lang) #endif } +void setTimezone(bool isSet, const OUString& rTimezone) +{ + if (isSet) + { + // Set the given timezone, even if empty. + osl_setEnvironment(u"TZ"_ustr.pData, rTimezone.pData); + } + else + { + // Unset and empty aren't the same. + // When unset, it means default to the system configured timezone. + osl_clearEnvironment(u"TZ"_ustr.pData); + } + + // Update the timezone data. + ::tzset(); +} + static void (*pStatusIndicatorCallback)(void *data, statusIndicatorCallbackType type, int percent, const char* pText)(nullptr); static void *pStatusIndicatorCallbackData(nullptr); diff --git a/comphelper/source/misc/mimeconfighelper.cxx b/comphelper/source/misc/mimeconfighelper.cxx index 8ec72e271f55..dfd7fa53f677 100644 --- a/comphelper/source/misc/mimeconfighelper.cxx +++ b/comphelper/source/misc/mimeconfighelper.cxx @@ -33,17 +33,18 @@ #include <comphelper/documentconstants.hxx> #include <comphelper/propertysequence.hxx> #include <rtl/ustrbuf.hxx> +#include <utility> using namespace ::com::sun::star; using namespace comphelper; -MimeConfigurationHelper::MimeConfigurationHelper( const uno::Reference< uno::XComponentContext >& rxContext ) -: m_xContext( rxContext ) +MimeConfigurationHelper::MimeConfigurationHelper( uno::Reference< uno::XComponentContext > xContext ) +: m_xContext(std::move( xContext )) { if ( !m_xContext.is() ) - throw uno::RuntimeException(); + throw uno::RuntimeException(u"MimeConfigurationHelper:: empty component context"_ustr); } @@ -81,18 +82,18 @@ static sal_uInt8 GetDigit_Impl( char aChar ) } -uno::Sequence< sal_Int8 > MimeConfigurationHelper::GetSequenceClassIDRepresentation( const OUString& aClassID ) +uno::Sequence< sal_Int8 > MimeConfigurationHelper::GetSequenceClassIDRepresentation( std::u16string_view aClassID ) { - sal_Int32 nLength = aClassID.getLength(); + size_t nLength = aClassID.size(); if ( nLength == 36 ) { OString aCharClassID = OUStringToOString( aClassID, RTL_TEXTENCODING_ASCII_US ); uno::Sequence< sal_Int8 > aResult( 16 ); auto pResult = aResult.getArray(); - sal_Int32 nStrPointer = 0; + size_t nStrPointer = 0; sal_Int32 nSeqInd = 0; - while( nSeqInd < 16 && nStrPointer + 1 < nLength ) + while( nSeqInd < 16 && nStrPointer + 1U < nLength ) { sal_uInt8 nDigit1 = GetDigit_Impl( aCharClassID[nStrPointer++] ); sal_uInt8 nDigit2 = GetDigit_Impl( aCharClassID[nStrPointer++] ); @@ -128,7 +129,7 @@ uno::Reference< container::XNameAccess > MimeConfigurationHelper::GetConfigurati {"nodepath", uno::Any(aPath)} })); xConfig.set( m_xConfigProvider->createInstanceWithArguments( - "com.sun.star.configuration.ConfigurationAccess", + u"com.sun.star.configuration.ConfigurationAccess"_ustr, aArgs ), uno::UNO_QUERY ); } @@ -145,7 +146,7 @@ uno::Reference< container::XNameAccess > MimeConfigurationHelper::GetObjConfigur if ( !m_xObjectConfig.is() ) m_xObjectConfig = GetConfigurationByPathImpl( - "/org.openoffice.Office.Embedding/Objects" ); + u"/org.openoffice.Office.Embedding/Objects"_ustr ); return m_xObjectConfig; } @@ -157,7 +158,7 @@ uno::Reference< container::XNameAccess > MimeConfigurationHelper::GetVerbsConfig if ( !m_xVerbsConfig.is() ) m_xVerbsConfig = GetConfigurationByPathImpl( - "/org.openoffice.Office.Embedding/Verbs"); + u"/org.openoffice.Office.Embedding/Verbs"_ustr); return m_xVerbsConfig; } @@ -169,7 +170,7 @@ uno::Reference< container::XNameAccess > MimeConfigurationHelper::GetMediaTypeCo if ( !m_xMediaTypeConfig.is() ) m_xMediaTypeConfig = GetConfigurationByPathImpl( - "/org.openoffice.Office.Embedding/MimeTypeClassIDRelations"); + u"/org.openoffice.Office.Embedding/MimeTypeClassIDRelations"_ustr); return m_xMediaTypeConfig; } @@ -181,7 +182,7 @@ uno::Reference< container::XNameAccess > MimeConfigurationHelper::GetFilterFacto if ( !m_xFilterFactory.is() ) m_xFilterFactory.set( - m_xContext->getServiceManager()->createInstanceWithContext("com.sun.star.document.FilterFactory", m_xContext), + m_xContext->getServiceManager()->createInstanceWithContext(u"com.sun.star.document.FilterFactory"_ustr, m_xContext), uno::UNO_QUERY ); return m_xFilterFactory; @@ -202,7 +203,7 @@ OUString MimeConfigurationHelper::GetDocServiceNameFromFilter( const OUString& a uno::Sequence< beans::PropertyValue > aFilterData; if ( aFilterAnyData >>= aFilterData ) { - for ( const auto & prop : std::as_const(aFilterData) ) + for (const auto& prop : aFilterData) if ( prop.Name == "DocumentService" ) prop.Value >>= aDocServiceName; } @@ -217,7 +218,7 @@ OUString MimeConfigurationHelper::GetDocServiceNameFromFilter( const OUString& a OUString MimeConfigurationHelper::GetDocServiceNameFromMediaType( const OUString& aMediaType ) { uno::Reference< container::XContainerQuery > xTypeCFG( - m_xContext->getServiceManager()->createInstanceWithContext("com.sun.star.document.TypeDetection", m_xContext), + m_xContext->getServiceManager()->createInstanceWithContext(u"com.sun.star.document.TypeDetection"_ustr, m_xContext), uno::UNO_QUERY ); if ( xTypeCFG.is() ) @@ -225,7 +226,7 @@ OUString MimeConfigurationHelper::GetDocServiceNameFromMediaType( const OUString try { // make query for all types matching the properties - uno::Sequence < beans::NamedValue > aSeq { { "MediaType", css::uno::Any(aMediaType) } }; + uno::Sequence < beans::NamedValue > aSeq { { u"MediaType"_ustr, css::uno::Any(aMediaType) } }; uno::Reference < container::XEnumeration > xEnum = xTypeCFG->createSubSetEnumerationByProperties( aSeq ); while ( xEnum->hasMoreElements() ) @@ -233,7 +234,7 @@ OUString MimeConfigurationHelper::GetDocServiceNameFromMediaType( const OUString uno::Sequence< beans::PropertyValue > aType; if ( xEnum->nextElement() >>= aType ) { - for ( const auto & prop : std::as_const(aType) ) + for (const auto& prop : aType) { OUString aFilterName; if ( prop.Name == "PreferredFilter" @@ -267,10 +268,14 @@ bool MimeConfigurationHelper::GetVerbByShortcut( const OUString& aVerbShortcut, if ( xVerbsConfig.is() && ( xVerbsConfig->getByName( aVerbShortcut ) >>= xVerbsProps ) && xVerbsProps.is() ) { embed::VerbDescriptor aTempDescr; - if ( ( xVerbsProps->getByName("VerbID") >>= aTempDescr.VerbID ) - && ( xVerbsProps->getByName("VerbUIName") >>= aTempDescr.VerbName ) - && ( xVerbsProps->getByName("VerbFlags") >>= aTempDescr.VerbFlags ) - && ( xVerbsProps->getByName("VerbAttributes") >>= aTempDescr.VerbAttributes ) ) + static constexpr OUStringLiteral sVerbID = u"VerbID"; + static constexpr OUStringLiteral sVerbUIName = u"VerbUIName"; + static constexpr OUStringLiteral sVerbFlags = u"VerbFlags"; + static constexpr OUStringLiteral sVerbAttributes = u"VerbAttributes"; + if ( ( xVerbsProps->getByName(sVerbID) >>= aTempDescr.VerbID ) + && ( xVerbsProps->getByName(sVerbUIName) >>= aTempDescr.VerbName ) + && ( xVerbsProps->getByName(sVerbFlags) >>= aTempDescr.VerbFlags ) + && ( xVerbsProps->getByName(sVerbAttributes) >>= aTempDescr.VerbAttributes ) ) { aDescriptor = aTempDescr; bResult = true; @@ -310,12 +315,12 @@ uno::Sequence< beans::NamedValue > MimeConfigurationHelper::GetObjPropsFromConfi { uno::Sequence< OUString > aVerbShortcuts; if ( !(xObjectProps->getByName( aObjPropNames[nInd] ) >>= aVerbShortcuts) ) - throw uno::RuntimeException(); + throw uno::RuntimeException(u"Failed to get verb shortcuts from object properties"_ustr); uno::Sequence< embed::VerbDescriptor > aVerbDescriptors( aVerbShortcuts.getLength() ); auto aVerbDescriptorsRange = asNonConstRange(aVerbDescriptors); for ( sal_Int32 nVerbI = 0; nVerbI < aVerbShortcuts.getLength(); nVerbI++ ) if ( !GetVerbByShortcut( aVerbShortcuts[nVerbI], aVerbDescriptorsRange[nVerbI] ) ) - throw uno::RuntimeException(); + throw uno::RuntimeException(u"Failed to get verb descriptor by shortcut"_ustr); pResult[nInd+1].Value <<= aVerbDescriptors; } @@ -360,9 +365,9 @@ uno::Sequence< beans::NamedValue > MimeConfigurationHelper::GetObjectPropsByStri uno::Sequence< sal_Int8 > aClassID = GetSequenceClassIDRepresentation( aStringClassID ); if ( ClassIDsEqual( aClassID, GetSequenceClassID( SO3_DUMMY_CLASSID ) ) ) { - aObjProps = { { "ObjectFactory", - uno::Any(OUString("com.sun.star.embed.OOoSpecialEmbeddedObjectFactory")) }, - { "ClassID", uno::Any(aClassID) } }; + aObjProps = { { u"ObjectFactory"_ustr, + uno::Any(u"com.sun.star.embed.OOoSpecialEmbeddedObjectFactory"_ustr) }, + { u"ClassID"_ustr, uno::Any(aClassID) } }; return aObjProps; } @@ -391,9 +396,9 @@ uno::Sequence< beans::NamedValue > MimeConfigurationHelper::GetObjectPropsByClas uno::Sequence< beans::NamedValue > aObjProps; if ( ClassIDsEqual( aClassID, GetSequenceClassID( SO3_DUMMY_CLASSID ) ) ) { - aObjProps = { { "ObjectFactory", - uno::Any(OUString("com.sun.star.embed.OOoSpecialEmbeddedObjectFactory")) }, - { "ClassID", uno::Any(aClassID) } }; + aObjProps = { { u"ObjectFactory"_ustr, + uno::Any(u"com.sun.star.embed.OOoSpecialEmbeddedObjectFactory"_ustr) }, + { u"ClassID"_ustr, uno::Any(aClassID) } }; } OUString aStringClassID = GetStringClassIDRepresentation( aClassID ); @@ -456,7 +461,7 @@ uno::Sequence< beans::NamedValue > MimeConfigurationHelper::GetObjectPropsByDocu OUString aEntryDocName; if ( ( xObjConfig->getByName( id ) >>= xObjectProps ) && xObjectProps.is() - && ( xObjectProps->getByName("ObjectDocumentServiceName") >>= aEntryDocName ) + && ( xObjectProps->getByName(u"ObjectDocumentServiceName"_ustr) >>= aEntryDocName ) && aEntryDocName == aDocName ) { return GetObjPropsFromConfigEntry( GetSequenceClassIDRepresentation( id ), @@ -490,13 +495,13 @@ OUString MimeConfigurationHelper::GetFactoryNameByStringClassID( const OUString& try { if ( xObjConfig.is() && ( xObjConfig->getByName( aStringClassID.toAsciiUpperCase() ) >>= xObjectProps ) && xObjectProps.is() ) - xObjectProps->getByName("ObjectFactory") >>= aResult; + xObjectProps->getByName(u"ObjectFactory"_ustr) >>= aResult; } catch( uno::Exception& ) { uno::Sequence< sal_Int8 > aClassID = GetSequenceClassIDRepresentation( aStringClassID ); if ( ClassIDsEqual( aClassID, GetSequenceClassID( SO3_DUMMY_CLASSID ) ) ) - return "com.sun.star.embed.OOoSpecialEmbeddedObjectFactory"; + return u"com.sun.star.embed.OOoSpecialEmbeddedObjectFactory"_ustr; } } @@ -522,10 +527,10 @@ OUString MimeConfigurationHelper::GetFactoryNameByDocumentName( std::u16string_v OUString aEntryDocName; if ( ( xObjConfig->getByName( id ) >>= xObjectProps ) && xObjectProps.is() - && ( xObjectProps->getByName( "ObjectDocumentServiceName" ) >>= aEntryDocName ) + && ( xObjectProps->getByName( u"ObjectDocumentServiceName"_ustr ) >>= aEntryDocName ) && aEntryDocName == aDocName ) { - xObjectProps->getByName("ObjectFactory") >>= aResult; + xObjectProps->getByName(u"ObjectFactory"_ustr) >>= aResult; break; } } @@ -560,7 +565,7 @@ OUString MimeConfigurationHelper::UpdateMediaDescriptorWithFilterName( { OUString aFilterName; - for ( const auto & prop : std::as_const(aMediaDescr) ) + for (const auto& prop : aMediaDescr) if ( prop.Name == "FilterName" ) prop.Value >>= aFilterName; @@ -569,17 +574,17 @@ OUString MimeConfigurationHelper::UpdateMediaDescriptorWithFilterName( // filter name is not specified, so type detection should be done uno::Reference< document::XTypeDetection > xTypeDetection( - m_xContext->getServiceManager()->createInstanceWithContext("com.sun.star.document.TypeDetection", m_xContext), + m_xContext->getServiceManager()->createInstanceWithContext(u"com.sun.star.document.TypeDetection"_ustr, m_xContext), uno::UNO_QUERY_THROW ); // typedetection can change the mode, add a stream and so on, thus a copy should be used uno::Sequence< beans::PropertyValue > aTempMD( aMediaDescr ); // get TypeName - OUString aTypeName = xTypeDetection->queryTypeByDescriptor( aTempMD, true ); + OUString aTypeName = xTypeDetection->queryTypeByDescriptor(aTempMD, /*bAllowDeepDetection*/true); // get FilterName - for ( const auto & prop : std::as_const(aTempMD) ) + for (const auto& prop : aTempMD) if ( prop.Name == "FilterName" ) prop.Value >>= aFilterName; @@ -599,7 +604,7 @@ OUString MimeConfigurationHelper::UpdateMediaDescriptorWithFilterName( if ( xNameAccess.is() && ( xNameAccess->getByName( aTypeName ) >>= aTypes ) ) { - for ( const auto & prop : std::as_const(aTypes) ) + for (const auto& prop : aTypes) { if ( prop.Name == "PreferredFilter" && ( prop.Value >>= aFilterName ) ) { @@ -623,7 +628,7 @@ OUString MimeConfigurationHelper::UpdateMediaDescriptorWithFilterName( uno::Sequence< beans::NamedValue >& aObject ) { OUString aDocName; - for ( const auto & nv : std::as_const(aObject) ) + for (const auto& nv : aObject) if ( nv.Name == "ObjectDocumentServiceName" ) { nv.Value >>= aDocName; @@ -710,8 +715,8 @@ OUString MimeConfigurationHelper::GetDefaultFilterFromServiceName( const OUStrin uno::Sequence< beans::NamedValue > aSearchRequest { - { "DocumentService", css::uno::Any(aServiceName) }, - { "FileFormatVersion", css::uno::Any(nVersion) } + { u"DocumentService"_ustr, css::uno::Any(aServiceName) }, + { u"FileFormatVersion"_ustr, css::uno::Any(nVersion) } }; uno::Reference< container::XEnumeration > xFilterEnum = @@ -724,8 +729,19 @@ OUString MimeConfigurationHelper::GetDefaultFilterFromServiceName( const OUStrin uno::Sequence< beans::PropertyValue > aProps; if ( xFilterEnum->nextElement() >>= aProps ) { - SequenceAsHashMap aPropsHM( aProps ); - SfxFilterFlags nFlags = static_cast<SfxFilterFlags>(aPropsHM.getUnpackedValueOrDefault( "Flags", sal_Int32(0) )); + SfxFilterFlags nFlags = SfxFilterFlags::NONE; + OUString sName; + for (const auto & rPropVal : aProps) + { + if (rPropVal.Name == "Flags") + { + sal_Int32 nTmp(0); + if (rPropVal.Value >>= nTmp) + nFlags = static_cast<SfxFilterFlags>(nTmp); + } + else if (rPropVal.Name == "Name") + rPropVal.Value >>= sName; + } // that should be import, export, own filter and not a template filter ( TemplatePath flag ) SfxFilterFlags const nRequired = SfxFilterFlags::OWN @@ -739,7 +755,7 @@ OUString MimeConfigurationHelper::GetDefaultFilterFromServiceName( const OUStrin // if there are more than one filter the preferred one should be used // if there is no preferred filter the first one will be used if ( aResult.isEmpty() || ( nFlags & SfxFilterFlags::PREFERED ) ) - aResult = aPropsHM.getUnpackedValueOrDefault( "Name", OUString() ); + aResult = sName; if ( nFlags & SfxFilterFlags::PREFERED ) break; // the preferred filter was found } @@ -770,12 +786,12 @@ OUString MimeConfigurationHelper::GetExportFilterFromImportFilter( const OUStrin if ( aImpFilterAny >>= aImpData ) { SequenceAsHashMap aImpFilterHM( aImpData ); - SfxFilterFlags nFlags = static_cast<SfxFilterFlags>(aImpFilterHM.getUnpackedValueOrDefault( "Flags", sal_Int32(0) )); + SfxFilterFlags nFlags = static_cast<SfxFilterFlags>(aImpFilterHM.getUnpackedValueOrDefault( u"Flags"_ustr, sal_Int32(0) )); if ( !( nFlags & SfxFilterFlags::IMPORT ) ) { OSL_FAIL( "This is no import filter!" ); - throw uno::Exception("this is no import filter", nullptr); + throw uno::Exception(u"this is no import filter"_ustr, nullptr); } if ( nFlags & SfxFilterFlags::EXPORT ) @@ -784,16 +800,16 @@ OUString MimeConfigurationHelper::GetExportFilterFromImportFilter( const OUStrin } else { - OUString aDocumentServiceName = aImpFilterHM.getUnpackedValueOrDefault( "DocumentService", OUString() ); - OUString aTypeName = aImpFilterHM.getUnpackedValueOrDefault( "Type", OUString() ); + OUString aDocumentServiceName = aImpFilterHM.getUnpackedValueOrDefault( u"DocumentService"_ustr, OUString() ); + OUString aTypeName = aImpFilterHM.getUnpackedValueOrDefault( u"Type"_ustr, OUString() ); OSL_ENSURE( !aDocumentServiceName.isEmpty() && !aTypeName.isEmpty(), "Incomplete filter data!" ); if ( !(aDocumentServiceName.isEmpty() || aTypeName.isEmpty()) ) { uno::Sequence< beans::NamedValue > aSearchRequest { - { "Type", css::uno::Any(aTypeName) }, - { "DocumentService", css::uno::Any(aDocumentServiceName) } + { u"Type"_ustr, css::uno::Any(aTypeName) }, + { u"DocumentService"_ustr, css::uno::Any(aDocumentServiceName) } }; uno::Sequence< beans::PropertyValue > aExportFilterProps = SearchForFilter( @@ -805,7 +821,7 @@ OUString MimeConfigurationHelper::GetExportFilterFromImportFilter( const OUStrin if ( aExportFilterProps.hasElements() ) { SequenceAsHashMap aExpPropsHM( aExportFilterProps ); - aExportFilterName = aExpPropsHM.getUnpackedValueOrDefault( "Name", OUString() ); + aExportFilterName = aExpPropsHM.getUnpackedValueOrDefault( u"Name"_ustr, OUString() ); } } } @@ -840,7 +856,7 @@ uno::Sequence< beans::PropertyValue > MimeConfigurationHelper::SearchForFilter( if ( xFilterEnum->nextElement() >>= aProps ) { SequenceAsHashMap aPropsHM( aProps ); - SfxFilterFlags nFlags = static_cast<SfxFilterFlags>(aPropsHM.getUnpackedValueOrDefault("Flags", + SfxFilterFlags nFlags = static_cast<SfxFilterFlags>(aPropsHM.getUnpackedValueOrDefault(u"Flags"_ustr, sal_Int32(0) )); if ( ( ( nFlags & nMustFlags ) == nMustFlags ) && !( nFlags & nDontFlags ) ) { diff --git a/comphelper/source/misc/namedvaluecollection.cxx b/comphelper/source/misc/namedvaluecollection.cxx index 574f8e0a1898..11ef15b30854 100644 --- a/comphelper/source/misc/namedvaluecollection.cxx +++ b/comphelper/source/misc/namedvaluecollection.cxx @@ -201,9 +201,54 @@ namespace comphelper nullptr, 0 ); } + // static + bool NamedValueCollection::get_ensureType( const css::uno::Sequence<css::beans::PropertyValue>& rPropSeq, + std::u16string_view _rValueName, void* _pValueLocation, const Type& _rExpectedValueType ) + { + for (const css::beans::PropertyValue& rPropVal : rPropSeq) + { + if (rPropVal.Name == _rValueName) + { + if ( uno_type_assignData( + _pValueLocation, _rExpectedValueType.getTypeLibType(), + const_cast< void* >( rPropVal.Value.getValue() ), rPropVal.Value.getValueType().getTypeLibType(), + reinterpret_cast< uno_QueryInterfaceFunc >( cpp_queryInterface ), + reinterpret_cast< uno_AcquireFunc >( cpp_acquire ), + reinterpret_cast< uno_ReleaseFunc >( cpp_release ) + ) ) + // argument exists, and could be extracted + return true; + + // argument exists, but is of wrong type + throw IllegalArgumentException( + OUString::Concat("Invalid value type for '") + _rValueName + + "'.\nExpected: " + _rExpectedValueType.getTypeName() + + "\nFound: " + rPropVal.Value.getValueType().getTypeName(), + nullptr, 0 ); + } + } + // argument does not exist + return false; + } + + // static + const css::uno::Any& NamedValueCollection::get( const css::uno::Sequence<css::beans::PropertyValue>& rPropSeq, + std::u16string_view _rValueName ) + { + static const Any theEmptyDefault; + for (const css::beans::PropertyValue& rPropVal : rPropSeq) + { + if (rPropVal.Name == _rValueName) + { + return rPropVal.Value; + } + } + return theEmptyDefault; + } + const Any& NamedValueCollection::impl_get( const OUString& _rValueName ) const { - static Any theEmptyDefault; + static const Any theEmptyDefault; auto pos = maValues.find( _rValueName ); if ( pos != maValues.end() ) return pos->second; diff --git a/comphelper/source/misc/numberedcollection.cxx b/comphelper/source/misc/numberedcollection.cxx index efadf0fd5a6d..e47c30ee0a32 100644 --- a/comphelper/source/misc/numberedcollection.cxx +++ b/comphelper/source/misc/numberedcollection.cxx @@ -24,7 +24,7 @@ namespace comphelper{ -constexpr OUStringLiteral ERRMSG_INVALID_COMPONENT_PARAM = u"NULL as component reference not allowed."; +constexpr OUString ERRMSG_INVALID_COMPONENT_PARAM = u"NULL as component reference not allowed."_ustr; NumberedCollection::NumberedCollection() @@ -100,7 +100,7 @@ void SAL_CALL NumberedCollection::releaseNumber(::sal_Int32 nNumber) std::scoped_lock aLock(m_aMutex); if (nNumber == css::frame::UntitledNumbersConst::INVALID_NUMBER) - throw css::lang::IllegalArgumentException ("Special valkud INVALID_NUMBER not allowed as input parameter.", m_xOwner.get(), 1); + throw css::lang::IllegalArgumentException (u"Special value INVALID_NUMBER not allowed as input parameter."_ustr, m_xOwner.get(), 1); TDeadItemList lDeadItems; TNumberedItemHash::iterator pComponent; @@ -178,43 +178,25 @@ OUString SAL_CALL NumberedCollection::getUntitledPrefix() */ ::sal_Int32 NumberedCollection::impl_searchFreeNumber () { - // create ordered list of all possible numbers. - std::vector< ::sal_Int32 > lPossibleNumbers; - ::sal_Int32 c = static_cast<::sal_Int32>(m_lComponents.size ()); - ::sal_Int32 i = 1; + // create bitset, where each position represents one possible number. + std::vector<bool> aUsedNumbers((m_lComponents.size() * 2) + 1, false); - // c can't be less than 0 ... otherwise hash.size() has an error :-) - // But we need at least n+1 numbers here. - c += 1; - - for (i=1; i<=c; ++i) - lPossibleNumbers.push_back (i); - - TDeadItemList lDeadItems; - - for (const auto& [rComponent, rItem] : m_lComponents) + for (const auto& rPair : m_lComponents) { - const css::uno::Reference< css::uno::XInterface > xItem = rItem.xItem.get(); - - if ( ! xItem.is ()) - { - lDeadItems.push_back(rComponent); - continue; - } - - std::vector< ::sal_Int32 >::iterator pPossible = std::find(lPossibleNumbers.begin (), lPossibleNumbers.end (), rItem.nNumber); - if (pPossible != lPossibleNumbers.end ()) - lPossibleNumbers.erase (pPossible); + // numbers start at 1 + sal_Int32 pos = rPair.second.nNumber - 1; + if (pos >= static_cast<sal_Int32>(aUsedNumbers.size())) + aUsedNumbers.resize(pos * 2, false); // should be rare + aUsedNumbers[pos] = true; } - impl_cleanUpDeadItems(m_lComponents, lDeadItems); - // a) non free numbers ... return INVALID_NUMBER - if (lPossibleNumbers.empty()) + auto it = std::find(aUsedNumbers.begin(), aUsedNumbers.end(), false); + if (it == aUsedNumbers.end()) return css::frame::UntitledNumbersConst::INVALID_NUMBER; // b) return first free number - return *(lPossibleNumbers.begin ()); + return it - aUsedNumbers.begin() + 1; } void NumberedCollection::impl_cleanUpDeadItems ( TNumberedItemHash& lItems , diff --git a/comphelper/source/misc/numbers.cxx b/comphelper/source/misc/numbers.cxx index f3b609392ceb..9bff08c79ae7 100644 --- a/comphelper/source/misc/numbers.cxx +++ b/comphelper/source/misc/numbers.cxx @@ -37,7 +37,7 @@ sal_Int16 getNumberFormatType(const css::uno::Reference<css::util::XNumberFormat { css::uno::Reference<css::beans::XPropertySet> xFormat(xFormats->getByKey(nKey)); if (xFormat.is()) - xFormat->getPropertyValue("Type") >>= nReturn; + xFormat->getPropertyValue(u"Type"_ustr) >>= nReturn; } catch(...) { @@ -67,7 +67,7 @@ css::uno::Any getNumberFormatDecimals(const css::uno::Reference<css::util::XNumb css::uno::Reference<css::beans::XPropertySet> xFormat( xFormats->getByKey(nKey)); if (xFormat.is()) { - return xFormat->getPropertyValue( "Decimals" ); + return xFormat->getPropertyValue( u"Decimals"_ustr ); } } catch(...) diff --git a/comphelper/source/misc/officerestartmanager.cxx b/comphelper/source/misc/officerestartmanager.cxx index 39c61a4e53a3..95110c75a7ab 100644 --- a/comphelper/source/misc/officerestartmanager.cxx +++ b/comphelper/source/misc/officerestartmanager.cxx @@ -36,10 +36,10 @@ namespace comphelper void SAL_CALL OOfficeRestartManager::requestRestart( const uno::Reference< task::XInteractionHandler >& /* xInteractionHandler */ ) { if ( !m_xContext.is() ) - throw uno::RuntimeException(); + throw uno::RuntimeException(u"no component context"_ustr); { - ::osl::MutexGuard aGuard( m_aMutex ); + std::unique_lock aGuard( m_aMutex ); // if the restart already running there is no need to trigger it again if ( m_bRestartRequested ) @@ -60,7 +60,7 @@ void SAL_CALL OOfficeRestartManager::requestRestart( const uno::Reference< task: uno::Reference< awt::XRequestCallback > xRequestCallback( xFactory->createInstanceWithContext( - "com.sun.star.awt.AsyncCallback", + u"com.sun.star.awt.AsyncCallback"_ustr, m_xContext ), uno::UNO_QUERY_THROW ); @@ -76,7 +76,7 @@ void SAL_CALL OOfficeRestartManager::requestRestart( const uno::Reference< task: sal_Bool SAL_CALL OOfficeRestartManager::isRestartRequested( sal_Bool bOfficeInitialized ) { - ::osl::MutexGuard aGuard( m_aMutex ); + std::unique_lock aGuard( m_aMutex ); if ( bOfficeInitialized && !m_bOfficeInitialized ) m_bOfficeInitialized = bOfficeInitialized; @@ -98,7 +98,7 @@ void SAL_CALL OOfficeRestartManager::notify( const uno::Any& /* aData */ ) // Turn Quickstarter veto off uno::Reference< beans::XPropertySet > xPropertySet( xDesktop, uno::UNO_QUERY_THROW ); - OUString aVetoPropName( "SuspendQuickstartVeto" ); + OUString aVetoPropName( u"SuspendQuickstartVeto"_ustr ); uno::Any aValue; aValue <<= true; xPropertySet->setPropertyValue( aVetoPropName, aValue ); @@ -130,7 +130,7 @@ void SAL_CALL OOfficeRestartManager::notify( const uno::Any& /* aData */ ) OUString SAL_CALL OOfficeRestartManager::getImplementationName() { - return "com.sun.star.comp.task.OfficeRestartManager"; + return u"com.sun.star.comp.task.OfficeRestartManager"_ustr; } sal_Bool SAL_CALL OOfficeRestartManager::supportsService( const OUString& aServiceName ) @@ -140,7 +140,7 @@ sal_Bool SAL_CALL OOfficeRestartManager::supportsService( const OUString& aServi uno::Sequence< OUString > SAL_CALL OOfficeRestartManager::getSupportedServiceNames() { - return { "com.sun.star.comp.task.OfficeRestartManager" }; + return { u"com.sun.star.comp.task.OfficeRestartManager"_ustr }; } } // namespace comphelper diff --git a/comphelper/source/misc/officerestartmanager.hxx b/comphelper/source/misc/officerestartmanager.hxx index 8b3658a8e892..ecf59c543270 100644 --- a/comphelper/source/misc/officerestartmanager.hxx +++ b/comphelper/source/misc/officerestartmanager.hxx @@ -24,8 +24,9 @@ #include <com/sun/star/awt/XCallback.hpp> #include <com/sun/star/uno/XComponentContext.hpp> -#include <osl/mutex.hxx> +#include <mutex> #include <cppuhelper/implbase.hxx> +#include <utility> namespace comphelper { @@ -34,15 +35,15 @@ class OOfficeRestartManager : public ::cppu::WeakImplHelper< css::task::XRestart , css::awt::XCallback , css::lang::XServiceInfo > { - ::osl::Mutex m_aMutex; + std::mutex m_aMutex; css::uno::Reference< css::uno::XComponentContext > m_xContext; bool m_bOfficeInitialized; bool m_bRestartRequested; public: - explicit OOfficeRestartManager( const css::uno::Reference< css::uno::XComponentContext >& xContext ) - : m_xContext( xContext ) + explicit OOfficeRestartManager( css::uno::Reference< css::uno::XComponentContext > xContext ) + : m_xContext(std::move( xContext )) , m_bOfficeInitialized( false ) , m_bRestartRequested( false ) {} diff --git a/comphelper/source/misc/sequenceashashmap.cxx b/comphelper/source/misc/sequenceashashmap.cxx index c6ac57326935..ba4955e09780 100644 --- a/comphelper/source/misc/sequenceashashmap.cxx +++ b/comphelper/source/misc/sequenceashashmap.cxx @@ -30,6 +30,8 @@ #include <comphelper/processfactory.hxx> #include <comphelper/propertysequence.hxx> #include <sal/log.hxx> +#include <o3tl/string_view.hxx> +#include <comphelper/sequence.hxx> using namespace com::sun::star; @@ -47,7 +49,7 @@ uno::Any jsonToUnoAny(const boost::property_tree::ptree& aTree) uno::Sequence<uno::Reference<reflection::XIdlField>> aFields; uno::Reference<reflection::XIdlClass> xIdlClass = css::reflection::theCoreReflection::get(comphelper::getProcessComponentContext()) - ->forName(OUString::fromUtf8(rType.c_str())); + ->forName(OUString::fromUtf8(rType)); if (xIdlClass.is()) { uno::TypeClass aTypeClass = xIdlClass->getTypeClass(); @@ -73,23 +75,23 @@ uno::Any jsonToUnoAny(const boost::property_tree::ptree& aTree) if (aTypeClass == uno::TypeClass_VOID) aAny.clear(); else if (aTypeClass == uno::TypeClass_BYTE) - aAny <<= static_cast<sal_Int8>(OString(rValue.c_str()).toInt32()); + aAny <<= static_cast<sal_Int8>(o3tl::toInt32(rValue)); else if (aTypeClass == uno::TypeClass_BOOLEAN) - aAny <<= OString(rValue.c_str()).toBoolean(); + aAny <<= rtl_str_toBoolean(rValue.c_str()); else if (aTypeClass == uno::TypeClass_SHORT) - aAny <<= static_cast<sal_Int16>(OString(rValue.c_str()).toInt32()); + aAny <<= static_cast<sal_Int16>(o3tl::toInt32(rValue)); else if (aTypeClass == uno::TypeClass_UNSIGNED_SHORT) - aAny <<= static_cast<sal_uInt16>(OString(rValue.c_str()).toUInt32()); + aAny <<= static_cast<sal_uInt16>(o3tl::toUInt32(rValue)); else if (aTypeClass == uno::TypeClass_LONG) - aAny <<= OString(rValue.c_str()).toInt32(); + aAny <<= o3tl::toInt32(rValue); else if (aTypeClass == uno::TypeClass_UNSIGNED_LONG) - aAny <<= static_cast<sal_uInt32>(OString(rValue.c_str()).toInt32()); + aAny <<= static_cast<sal_uInt32>(o3tl::toInt32(rValue)); else if (aTypeClass == uno::TypeClass_FLOAT) - aAny <<= OString(rValue.c_str()).toFloat(); + aAny <<= rtl_str_toFloat(rValue.c_str()); else if (aTypeClass == uno::TypeClass_DOUBLE) - aAny <<= OString(rValue.c_str()).toDouble(); + aAny <<= o3tl::toDouble(rValue); else if (aTypeClass == uno::TypeClass_STRING) - aAny <<= OUString::fromUtf8(rValue.c_str()); + aAny <<= OUString::fromUtf8(rValue); } } return aAny; @@ -147,7 +149,7 @@ void SequenceAsHashMap::operator<<(const css::uno::Any& aSource) } throw css::lang::IllegalArgumentException( - "Any contains wrong type.", css::uno::Reference<css::uno::XInterface>(), + u"Any contains wrong type."_ustr, css::uno::Reference<css::uno::XInterface>(), -1); } @@ -157,6 +159,7 @@ void SequenceAsHashMap::operator<<(const css::uno::Sequence< css::uno::Any >& lS sal_Int32 c = lSource.getLength(); sal_Int32 i = 0; + m_aMap.reserve(c); for (i=0; i<c; ++i) { css::beans::PropertyValue lP; @@ -167,7 +170,7 @@ void SequenceAsHashMap::operator<<(const css::uno::Sequence< css::uno::Any >& lS (!lP.Value.hasValue()) ) throw css::lang::IllegalArgumentException( - "PropertyValue struct contains no useful information.", + u"PropertyValue struct contains no useful information."_ustr, css::uno::Reference<css::uno::XInterface>(), -1); (*this)[lP.Name] = lP.Value; continue; @@ -181,7 +184,7 @@ void SequenceAsHashMap::operator<<(const css::uno::Sequence< css::uno::Any >& lS (!lN.Value.hasValue()) ) throw css::lang::IllegalArgumentException( - "NamedValue struct contains no useful information.", + u"NamedValue struct contains no useful information."_ustr, css::uno::Reference<css::uno::XInterface>(), -1); (*this)[lN.Name] = lN.Value; continue; @@ -190,7 +193,7 @@ void SequenceAsHashMap::operator<<(const css::uno::Sequence< css::uno::Any >& lS // ignore VOID Any ... but reject wrong filled ones! if (lSource[i].hasValue()) throw css::lang::IllegalArgumentException( - "Any contains wrong type.", + u"Any contains wrong type."_ustr, css::uno::Reference<css::uno::XInterface>(), -1); } } @@ -199,22 +202,18 @@ void SequenceAsHashMap::operator<<(const css::uno::Sequence< css::beans::Propert { clear(); - sal_Int32 c = lSource.getLength(); - const css::beans::PropertyValue* pSource = lSource.getConstArray(); - - for (sal_Int32 i=0; i<c; ++i) - (*this)[pSource[i].Name] = pSource[i].Value; + m_aMap.reserve(lSource.getLength()); + for (auto& rSource : lSource) + (*this)[rSource.Name] = rSource.Value; } void SequenceAsHashMap::operator<<(const css::uno::Sequence< css::beans::NamedValue >& lSource) { clear(); - sal_Int32 c = lSource.getLength(); - const css::beans::NamedValue* pSource = lSource.getConstArray(); - - for (sal_Int32 i=0; i<c; ++i) - (*this)[pSource[i].Name] = pSource[i].Value; + m_aMap.reserve(lSource.getLength()); + for (auto& rSource : lSource) + (*this)[rSource.Name] = rSource.Value; } void SequenceAsHashMap::operator>>(css::uno::Sequence< css::beans::PropertyValue >& lDestination) const @@ -228,7 +227,7 @@ void SequenceAsHashMap::operator>>(css::uno::Sequence< css::beans::PropertyValue pThis != end() ; ++pThis ) { - pDestination[i].Name = pThis->first ; + pDestination[i].Name = pThis->first.maString; pDestination[i].Value = pThis->second; ++i; } @@ -245,7 +244,7 @@ void SequenceAsHashMap::operator>>(css::uno::Sequence< css::beans::NamedValue >& pThis != end() ; ++pThis ) { - pDestination[i].Name = pThis->first ; + pDestination[i].Name = pThis->first.maString; pDestination[i].Value = pThis->second; ++i; } @@ -279,7 +278,7 @@ bool SequenceAsHashMap::match(const SequenceAsHashMap& rCheck) const { for (auto const& elem : rCheck) { - const OUString& sCheckName = elem.first; + const OUString& sCheckName = elem.first.maString; const css::uno::Any& aCheckValue = elem.second; const_iterator pFound = find(sCheckName); @@ -296,12 +295,10 @@ bool SequenceAsHashMap::match(const SequenceAsHashMap& rCheck) const void SequenceAsHashMap::update(const SequenceAsHashMap& rUpdate) { - for (auto const& elem : rUpdate) + m_aMap.reserve(std::max(size(), rUpdate.size())); + for (auto const& elem : rUpdate.m_aMap) { - const OUString& sName = elem.first; - const css::uno::Any& aValue = elem.second; - - (*this)[sName] = aValue; + m_aMap[elem.first] = elem.second; } } @@ -309,7 +306,7 @@ std::vector<css::beans::PropertyValue> JsonToPropertyValues(const OString& rJson { std::vector<beans::PropertyValue> aArguments; boost::property_tree::ptree aTree, aNodeNull, aNodeValue; - std::stringstream aStream(rJson.getStr()); + std::stringstream aStream((std::string(rJson))); boost::property_tree::read_json(aStream, aTree); for (const auto& rPair : aTree) @@ -318,31 +315,31 @@ std::vector<css::beans::PropertyValue> JsonToPropertyValues(const OString& rJson const std::string& rValue = rPair.second.get<std::string>("value", ""); beans::PropertyValue aValue; - aValue.Name = OUString::fromUtf8(rPair.first.c_str()); + aValue.Name = OUString::fromUtf8(rPair.first); if (rType == "string") - aValue.Value <<= OUString::fromUtf8(rValue.c_str()); + aValue.Value <<= OUString::fromUtf8(rValue); else if (rType == "boolean") - aValue.Value <<= OString(rValue.c_str()).toBoolean(); + aValue.Value <<= rtl_str_toBoolean(rValue.c_str()); else if (rType == "float") - aValue.Value <<= OString(rValue.c_str()).toFloat(); + aValue.Value <<= rtl_str_toFloat(rValue.c_str()); else if (rType == "long") - aValue.Value <<= OString(rValue.c_str()).toInt32(); + aValue.Value <<= o3tl::toInt32(rValue); else if (rType == "short") - aValue.Value <<= sal_Int16(OString(rValue.c_str()).toInt32()); + aValue.Value <<= sal_Int16(o3tl::toInt32(rValue)); else if (rType == "unsigned short") - aValue.Value <<= sal_uInt16(OString(rValue.c_str()).toUInt32()); + aValue.Value <<= sal_uInt16(o3tl::toUInt32(rValue)); else if (rType == "int64") - aValue.Value <<= OString(rValue.c_str()).toInt64(); + aValue.Value <<= o3tl::toInt64(rValue); else if (rType == "int32") - aValue.Value <<= OString(rValue.c_str()).toInt32(); + aValue.Value <<= o3tl::toInt32(rValue); else if (rType == "int16") - aValue.Value <<= sal_Int16(OString(rValue.c_str()).toInt32()); + aValue.Value <<= sal_Int16(o3tl::toInt32(rValue)); else if (rType == "uint64") - aValue.Value <<= OString(rValue.c_str()).toUInt64(); + aValue.Value <<= rtl_str_toUInt64(rValue.c_str(), 10); else if (rType == "uint32") - aValue.Value <<= OString(rValue.c_str()).toUInt32(); + aValue.Value <<= o3tl::toUInt32(rValue); else if (rType == "uint16") - aValue.Value <<= sal_uInt16(OString(rValue.c_str()).toUInt32()); + aValue.Value <<= sal_uInt16(o3tl::toUInt32(rValue)); else if (rType == "[]byte") { aNodeValue = rPair.second.get_child("value", aNodeNull); @@ -364,6 +361,27 @@ std::vector<css::beans::PropertyValue> JsonToPropertyValues(const OString& rJson aValue.Value <<= aSeq; } } + else if (rType == "[]com.sun.star.beans.PropertyValue") + { + aNodeValue = rPair.second.get_child("value", aNodeNull); + std::stringstream s; + boost::property_tree::write_json(s, aNodeValue); + std::vector<beans::PropertyValue> aPropertyValues = JsonToPropertyValues(OString(s.str())); + aValue.Value <<= comphelper::containerToSequence(aPropertyValues); + } + else if (rType == "[][]com.sun.star.beans.PropertyValue") + { + aNodeValue = rPair.second.get_child("value", aNodeNull); + std::vector<uno::Sequence<beans::PropertyValue>> aSeqs; + for (const auto& rItem : aNodeValue) + { + std::stringstream s; + boost::property_tree::write_json(s, rItem.second); + std::vector<beans::PropertyValue> aPropertyValues = JsonToPropertyValues(OString(s.str())); + aSeqs.push_back(comphelper::containerToSequence(aPropertyValues)); + } + aValue.Value <<= comphelper::containerToSequence(aSeqs); + } else SAL_WARN("comphelper", "JsonToPropertyValues: unhandled type '" << rType << "'"); aArguments.push_back(aValue); diff --git a/comphelper/source/misc/servicedecl.cxx b/comphelper/source/misc/servicedecl.cxx deleted file mode 100644 index 1955f6b56251..000000000000 --- a/comphelper/source/misc/servicedecl.cxx +++ /dev/null @@ -1,160 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ -/* - * This file is part of the LibreOffice project. - * - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - * - * This file incorporates work covered by the following license notice: - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed - * with this work for additional information regarding copyright - * ownership. The ASF licenses this file to you under the Apache - * License, Version 2.0 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.apache.org/licenses/LICENSE-2.0 . - */ - - -#include <comphelper/servicedecl.hxx> -#include <rtl/string.hxx> -#include <cppuhelper/implbase.hxx> -#include <comphelper/sequence.hxx> -#include <com/sun/star/lang/XSingleComponentFactory.hpp> -#include <cassert> -#include <vector> - -using namespace com::sun::star; - -namespace comphelper::service_decl { - -const char cDelim = ';'; - -class ServiceDecl::Factory : - public cppu::WeakImplHelper<lang::XSingleComponentFactory, - lang::XServiceInfo> -{ -public: - explicit Factory( ServiceDecl const& rServiceDecl ) - : m_rServiceDecl(rServiceDecl) {} - // noncopyable - Factory(const Factory&) = delete; - const Factory& operator=(const Factory&) = delete; - - // XServiceInfo: - virtual OUString SAL_CALL getImplementationName() override; - virtual sal_Bool SAL_CALL supportsService( OUString const& name ) override; - virtual uno::Sequence<OUString> SAL_CALL getSupportedServiceNames() override; - // XSingleComponentFactory: - virtual uno::Reference<uno::XInterface> SAL_CALL createInstanceWithContext( - uno::Reference<uno::XComponentContext> const& xContext ) override; - virtual uno::Reference<uno::XInterface> SAL_CALL - createInstanceWithArgumentsAndContext( - uno::Sequence<uno::Any> const& args, - uno::Reference<uno::XComponentContext> const& xContext ) override; - -private: - virtual ~Factory() override; - - ServiceDecl const& m_rServiceDecl; -}; - -ServiceDecl::Factory::~Factory() -{ -} - -// XServiceInfo: -OUString ServiceDecl::Factory::getImplementationName() -{ - return m_rServiceDecl.getImplementationName(); -} - -sal_Bool ServiceDecl::Factory::supportsService( OUString const& name ) -{ - return m_rServiceDecl.supportsService(name); -} - -uno::Sequence<OUString> ServiceDecl::Factory::getSupportedServiceNames() -{ - return m_rServiceDecl.getSupportedServiceNames(); -} - -// XSingleComponentFactory: -uno::Reference<uno::XInterface> ServiceDecl::Factory::createInstanceWithContext( - uno::Reference<uno::XComponentContext> const& xContext ) -{ - return m_rServiceDecl.m_createFunc( - m_rServiceDecl, uno::Sequence<uno::Any>(), xContext ); -} - -uno::Reference<uno::XInterface> -ServiceDecl::Factory::createInstanceWithArgumentsAndContext( - uno::Sequence<uno::Any > const& args, - uno::Reference<uno::XComponentContext> const& xContext ) -{ - return m_rServiceDecl.m_createFunc( - m_rServiceDecl, args, xContext ); -} - -void * ServiceDecl::getFactory( char const* pImplName ) const -{ - if (rtl_str_compare(m_pImplName, pImplName) == 0) { - lang::XSingleComponentFactory * const pFac( new Factory(*this) ); - pFac->acquire(); - return pFac; - } - return nullptr; -} - -uno::Sequence<OUString> ServiceDecl::getSupportedServiceNames() const -{ - std::vector<OUString> vec; - - OString const str(m_pServiceNames); - sal_Int32 nIndex = 0; - do { - OString const token( str.getToken( 0, cDelim, nIndex ) ); - vec.emplace_back( token.getStr(), token.getLength(), - RTL_TEXTENCODING_ASCII_US ); - } - while (nIndex >= 0); - - return comphelper::containerToSequence(vec); -} - -bool ServiceDecl::supportsService( OUString const& name ) const -{ - OString const str(m_pServiceNames); - sal_Int32 nIndex = 0; - do { - OString const token( str.getToken( 0, cDelim, nIndex ) ); - if (name.equalsAsciiL( token.getStr(), token.getLength() )) - return true; - } - while (nIndex >= 0); - return false; -} - -OUString ServiceDecl::getImplementationName() const -{ - return OUString::createFromAscii(m_pImplName); -} - -void* component_getFactoryHelper( const char* pImplName, - std::initializer_list<ServiceDecl const *> args ) -{ - for (auto const i: args) { - assert(i != nullptr); - void * fac = i->getFactory(pImplName); - if (fac != nullptr) { - return fac; - } - } - return nullptr; -} - -} // namespace - -/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/comphelper/source/misc/simplefileaccessinteraction.cxx b/comphelper/source/misc/simplefileaccessinteraction.cxx index 48c99598fac5..8cd77af7d693 100644 --- a/comphelper/source/misc/simplefileaccessinteraction.cxx +++ b/comphelper/source/misc/simplefileaccessinteraction.cxx @@ -32,38 +32,26 @@ const sal_Int32 HANDLE_AUTHENTICATIONREQUEST = 4; SimpleFileAccessInteraction::SimpleFileAccessInteraction( const css::uno::Reference<css::task::XInteractionHandler>& xHandler) { - std::vector<::ucbhelper::InterceptedInteraction::InterceptedRequest> lInterceptions; - ::ucbhelper::InterceptedInteraction::InterceptedRequest aInterceptedRequest; - - //intercept standard IO error exception (local file and WebDAV) - aInterceptedRequest.Handle = HANDLE_INTERACTIVEIOEXCEPTION; - aInterceptedRequest.Request <<= css::ucb::InteractiveIOException(); - aInterceptedRequest.Continuation = cppu::UnoType<css::task::XInteractionAbort>::get(); - lInterceptions.push_back(aInterceptedRequest); - - //intercept internal error - aInterceptedRequest.Handle = HANDLE_UNSUPPORTEDDATASINKEXCEPTION; - aInterceptedRequest.Request <<= css::ucb::UnsupportedDataSinkException(); - aInterceptedRequest.Continuation = cppu::UnoType<css::task::XInteractionAbort>::get(); - lInterceptions.push_back(aInterceptedRequest); - - //intercept network error exception (WebDAV ucp provider) - aInterceptedRequest.Handle = HANDLE_INTERACTIVENETWORKEXCEPTION; - aInterceptedRequest.Request <<= css::ucb::InteractiveNetworkException(); - aInterceptedRequest.Continuation = cppu::UnoType<css::task::XInteractionAbort>::get(); - lInterceptions.push_back(aInterceptedRequest); - - //intercept certificate validation request (WebDAV ucp provider) - aInterceptedRequest.Handle = HANDLE_CERTIFICATEREQUEST; - aInterceptedRequest.Request <<= css::ucb::CertificateValidationRequest(); - aInterceptedRequest.Continuation = cppu::UnoType<css::task::XInteractionAbort>::get(); - lInterceptions.push_back(aInterceptedRequest); - - //intercept authentication request (WebDAV ucp provider) - aInterceptedRequest.Handle = HANDLE_AUTHENTICATIONREQUEST; - aInterceptedRequest.Request <<= css::ucb::AuthenticationRequest(); - aInterceptedRequest.Continuation = cppu::UnoType<css::task::XInteractionApprove>::get(); - lInterceptions.push_back(aInterceptedRequest); + std::vector<::ucbhelper::InterceptedInteraction::InterceptedRequest> lInterceptions{ + { //intercept standard IO error exception (local file and WebDAV) + css::uno::Any(css::ucb::InteractiveIOException()), + cppu::UnoType<css::task::XInteractionAbort>::get(), HANDLE_INTERACTIVEIOEXCEPTION }, + { //intercept internal error + css::uno::Any(css::ucb::UnsupportedDataSinkException()), + cppu::UnoType<css::task::XInteractionAbort>::get(), HANDLE_UNSUPPORTEDDATASINKEXCEPTION }, + { + //intercept network error exception (WebDAV ucp provider) + css::uno::Any(css::ucb::InteractiveNetworkException()), + cppu::UnoType<css::task::XInteractionAbort>::get(), + HANDLE_INTERACTIVENETWORKEXCEPTION, + }, + { //intercept certificate validation request (WebDAV ucp provider) + css::uno::Any(css::ucb::CertificateValidationRequest()), + cppu::UnoType<css::task::XInteractionAbort>::get(), HANDLE_CERTIFICATEREQUEST }, + { //intercept authentication request (WebDAV ucp provider) + css::uno::Any(css::ucb::AuthenticationRequest()), + cppu::UnoType<css::task::XInteractionApprove>::get(), HANDLE_AUTHENTICATIONREQUEST } + }; setInterceptedHandler(xHandler); setInterceptions(std::move(lInterceptions)); diff --git a/comphelper/source/misc/solarmutex.cxx b/comphelper/source/misc/solarmutex.cxx index 5d1052327154..3e45ae14582d 100644 --- a/comphelper/source/misc/solarmutex.cxx +++ b/comphelper/source/misc/solarmutex.cxx @@ -38,7 +38,6 @@ SolarMutex *SolarMutex::get() SolarMutex::SolarMutex() : m_nCount( 0 ) - , m_nThreadId( 0 ) , m_aBeforeReleaseHandler( nullptr ) { assert(!g_pSolarMutex); @@ -54,7 +53,7 @@ void SolarMutex::doAcquire( const sal_uInt32 nLockCount ) { for ( sal_uInt32 n = nLockCount; n ; --n ) m_aMutex.acquire(); - m_nThreadId = osl::Thread::getCurrentIdentifier(); + m_nThreadId = std::this_thread::get_id(); m_nCount += nLockCount; } @@ -72,7 +71,7 @@ sal_uInt32 SolarMutex::doRelease( bool bUnlockAll ) { if ( m_aBeforeReleaseHandler ) m_aBeforeReleaseHandler(); - m_nThreadId = 0; + m_nThreadId = std::thread::id(); } for ( sal_uInt32 n = nCount ; n ; --n ) @@ -83,14 +82,14 @@ sal_uInt32 SolarMutex::doRelease( bool bUnlockAll ) bool SolarMutex::IsCurrentThread() const { - return m_nThreadId == osl::Thread::getCurrentIdentifier(); + return m_nThreadId == std::this_thread::get_id(); } bool SolarMutex::tryToAcquire() { if ( m_aMutex.tryToAcquire() ) { - m_nThreadId = osl::Thread::getCurrentIdentifier(); + m_nThreadId = std::this_thread::get_id(); m_nCount++; return true; } diff --git a/comphelper/source/misc/stillreadwriteinteraction.cxx b/comphelper/source/misc/stillreadwriteinteraction.cxx index d9333f389166..88bc25bc46cb 100644 --- a/comphelper/source/misc/stillreadwriteinteraction.cxx +++ b/comphelper/source/misc/stillreadwriteinteraction.cxx @@ -30,16 +30,18 @@ #include <com/sun/star/ucb/AuthenticationRequest.hpp> #include <com/sun/star/ucb/CertificateValidationRequest.hpp> +#include <utility> namespace comphelper{ StillReadWriteInteraction::StillReadWriteInteraction(const css::uno::Reference< css::task::XInteractionHandler >& xHandler, - const css::uno::Reference< css::task::XInteractionHandler >& xAuxiliaryHandler) + css::uno::Reference< css::task::XInteractionHandler > xAuxiliaryHandler) : m_bUsed (false) , m_bHandledByMySelf (false) - , m_xAuxiliaryHandler(xAuxiliaryHandler) + , m_xAuxiliaryHandler(std::move(xAuxiliaryHandler)) { std::vector< ::ucbhelper::InterceptedInteraction::InterceptedRequest > lInterceptions; + lInterceptions.reserve(4); ::ucbhelper::InterceptedInteraction::InterceptedRequest aInterceptedRequest; aInterceptedRequest.Handle = HANDLE_INTERACTIVEIOEXCEPTION; diff --git a/comphelper/source/misc/storagehelper.cxx b/comphelper/source/misc/storagehelper.cxx index 13e9eb3aa288..ab6f71c7c734 100644 --- a/comphelper/source/misc/storagehelper.cxx +++ b/comphelper/source/misc/storagehelper.cxx @@ -27,15 +27,13 @@ #include <com/sun/star/embed/FileSystemStorageFactory.hpp> #include <com/sun/star/io/IOException.hpp> #include <com/sun/star/lang/XSingleServiceFactory.hpp> +#include <com/sun/star/lang/XUnoTunnel.hpp> #include <com/sun/star/lang/WrappedTargetRuntimeException.hpp> #include <com/sun/star/ucb/SimpleFileAccess.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/beans/PropertyValue.hpp> #include <com/sun/star/beans/NamedValue.hpp> #include <com/sun/star/beans/IllegalTypeException.hpp> -#include <com/sun/star/xml/crypto/NSSInitializer.hpp> -#include <com/sun/star/xml/crypto/XDigestContext.hpp> -#include <com/sun/star/xml/crypto/DigestID.hpp> #include <com/sun/star/security/DocumentDigitalSignatures.hpp> #include <com/sun/star/security/XCertificate.hpp> @@ -48,6 +46,8 @@ #include <ucbhelper/content.hxx> +#include <comphelper/bytereader.hxx> +#include <comphelper/diagnose_ex.hxx> #include <comphelper/fileformat.h> #include <comphelper/hash.hxx> #include <comphelper/processfactory.hxx> @@ -56,6 +56,7 @@ #include <comphelper/storagehelper.hxx> #include <comphelper/sequence.hxx> #include <cppuhelper/exc_hlp.hxx> +#include <o3tl/string_view.hxx> #if HAVE_FEATURE_GPGME # include <context.h> @@ -132,7 +133,7 @@ uno::Reference< embed::XStorage > OStorageHelper::GetStorageFromURL2( if (!xFact.is()) { if (anyEx.hasValue()) - throw css::lang::WrappedTargetRuntimeException( "", nullptr, anyEx ); + throw css::lang::WrappedTargetRuntimeException( u""_ustr, nullptr, anyEx ); else throw uno::RuntimeException(); } @@ -172,19 +173,30 @@ void OStorageHelper::CopyInputToOutput( { static const sal_Int32 nConstBufferSize = 32000; + if (auto pByteReader = dynamic_cast< comphelper::ByteReader* >( xInput.get() )) + { + if (auto pByteWriter = dynamic_cast< comphelper::ByteWriter* >( xOutput.get() )) + { + sal_Int32 nRead; + sal_Int8 aTempBuf[ nConstBufferSize ]; + do + { + nRead = pByteReader->readSomeBytes ( aTempBuf, nConstBufferSize ); + pByteWriter->writeBytes ( aTempBuf, nRead ); + } + while ( nRead == nConstBufferSize ); + return; + } + } + sal_Int32 nRead; uno::Sequence < sal_Int8 > aSequence ( nConstBufferSize ); - do { nRead = xInput->readBytes ( aSequence, nConstBufferSize ); if ( nRead < nConstBufferSize ) - { - uno::Sequence < sal_Int8 > aTempBuf ( aSequence.getConstArray(), nRead ); - xOutput->writeBytes ( aTempBuf ); - } - else - xOutput->writeBytes ( aSequence ); + aSequence.realloc( nRead ); + xOutput->writeBytes ( aSequence ); } while ( nRead == nConstBufferSize ); } @@ -208,7 +220,7 @@ void OStorageHelper::SetCommonStorageEncryptionData( { uno::Reference< embed::XEncryptionProtectedStorage > xEncrSet( xStorage, uno::UNO_QUERY ); if ( !xEncrSet.is() ) - throw io::IOException("no XEncryptionProtectedStorage"); // TODO + throw io::IOException(u"no XEncryptionProtectedStorage"_ustr); // TODO if ( aEncryptionData.getLength() == 2 && aEncryptionData[0].Name == "GpgInfos" && @@ -230,7 +242,7 @@ sal_Int32 OStorageHelper::GetXStorageFormat( uno::Reference< beans::XPropertySet > xStorProps( xStorage, uno::UNO_QUERY_THROW ); OUString aMediaType; - xStorProps->getPropertyValue("MediaType") >>= aMediaType; + xStorProps->getPropertyValue(u"MediaType"_ustr) >>= aMediaType; sal_Int32 nResult = 0; @@ -293,7 +305,7 @@ uno::Reference< embed::XStorage > OStorageHelper::GetStorageOfFormatFromURL( sal_Int32 nStorageMode, const uno::Reference< uno::XComponentContext >& rxContext ) { - uno::Sequence< beans::PropertyValue > aProps{ comphelper::makePropertyValue("StorageFormat", + uno::Sequence< beans::PropertyValue > aProps{ comphelper::makePropertyValue(u"StorageFormat"_ustr, aFormat) }; uno::Sequence< uno::Any > aArgs{ uno::Any(aURL), uno::Any(nStorageMode), uno::Any(aProps) }; @@ -360,21 +372,19 @@ uno::Sequence< beans::NamedValue > OStorageHelper::CreatePackageEncryptionData( // generate SHA256 start key try { - uno::Reference< uno::XComponentContext > xContext = ::comphelper::getProcessComponentContext(); - - uno::Reference< css::xml::crypto::XNSSInitializer > xDigestContextSupplier = css::xml::crypto::NSSInitializer::create(xContext); - uno::Reference< css::xml::crypto::XDigestContext > xDigestContext( xDigestContextSupplier->getDigestContext( css::xml::crypto::DigestID::SHA256, uno::Sequence< beans::NamedValue >() ), uno::UNO_SET_THROW ); - OString aUTF8Password( OUStringToOString( aPassword, RTL_TEXTENCODING_UTF8 ) ); - xDigestContext->updateDigest( uno::Sequence< sal_Int8 >( reinterpret_cast< const sal_Int8* >( aUTF8Password.getStr() ), aUTF8Password.getLength() ) ); - uno::Sequence< sal_Int8 > aDigest = xDigestContext->finalizeDigestAndDispose(); + std::vector<unsigned char> const hash(comphelper::Hash::calculateHash( + reinterpret_cast<unsigned char const*>(aUTF8Password.getStr()), aUTF8Password.getLength(), + comphelper::HashType::SHA256)); + uno::Sequence<sal_Int8> aDigest(reinterpret_cast<const sal_Int8*>(hash.data()), hash.size()); ++nSha1Ind; aEncryptionData = { { PACKAGE_ENCRYPTIONDATA_SHA256UTF8, uno::Any(aDigest) } }; } catch ( uno::Exception& ) { - OSL_ENSURE( false, "Can not create SHA256 digest!" ); + TOOLS_WARN_EXCEPTION("comphelper", "Can not create SHA256 digest!" ); + throw; // tdf#159519 DO NOT RETURN SUCCESS } // MS_1252 encoding was used for SO60 document format password encoding, @@ -431,7 +441,10 @@ uno::Sequence< beans::NamedValue > OStorageHelper::CreateGpgPackageEncryptionDat // get 32 random chars out of it uno::Sequence < sal_Int8 > aVector(32); - rtl_random_getBytes( aRandomPool, aVector.getArray(), aVector.getLength() ); + if (rtl_random_getBytes(aRandomPool, aVector.getArray(), aVector.getLength()) != rtl_Random_E_None) + { + throw uno::RuntimeException(u"rtl_random_getBytes failed"_ustr); + } rtl_random_destroyPool(aRandomPool); @@ -455,15 +468,20 @@ uno::Sequence< beans::NamedValue > OStorageHelper::CreateGpgPackageEncryptionDat std::unique_ptr<GpgME::Context> ctx; GpgME::Error err = GpgME::checkEngine(GpgME::OpenPGP); if (err) - throw uno::RuntimeException("The GpgME library failed to initialize for the OpenPGP protocol."); - - ctx.reset( GpgME::Context::createForProtocol(GpgME::OpenPGP) ); - if (ctx == nullptr) - throw uno::RuntimeException("The GpgME library failed to initialize for the OpenPGP protocol."); - ctx->setArmor(false); + throw uno::RuntimeException(u"The GpgME library failed to initialize for the OpenPGP protocol."_ustr); + bool bResetContext = true; for (const auto & cert : xSignCertificates) { + if (bResetContext) + { + bResetContext = false; + ctx.reset( GpgME::Context::createForProtocol(GpgME::OpenPGP) ); + if (ctx == nullptr) + throw uno::RuntimeException(u"The GpgME library failed to initialize for the OpenPGP protocol."_ustr); + ctx->setArmor(false); + } + uno::Sequence < sal_Int8 > aKeyID; if (cert.is()) aKeyID = cert->getSHA1Thumbprint(); @@ -485,6 +503,29 @@ uno::Sequence< beans::NamedValue > OStorageHelper::CreateGpgPackageEncryptionDat keys, plain, cipher, GpgME::Context::NoCompress); + // tdf#160184 ask user if they want to trust an untrusted certificate + // gpgme contexts uses the "auto" trust model by default which only + // allows encrypting with keys that have their trust level set to + // "Ultimate". The gpg command, however, gives the user the option + // to encrypt with a certificate that has a lower trust level so + // emulate that behavior by asking the user if they want to trust + // the certificate for just this operation only. + if (crypt_res.error().code() == GPG_ERR_UNUSABLE_PUBKEY) + { + if (xSigner->trustUntrustedCertificate(cert)) + { + // Reset the trust model back to "auto" before processing + // the next certificate + bResetContext = true; + + ctx->setFlag("trust-model", "tofu+pgp"); + ctx->setFlag("tofu-default-policy", "unknown"); + crypt_res = ctx->encrypt( + keys, plain, + cipher, GpgME::Context::NoCompress); + } + } + off_t result = cipher.seek(0,SEEK_SET); (void) result; assert(result == 0); @@ -494,21 +535,21 @@ uno::Sequence< beans::NamedValue > OStorageHelper::CreateGpgPackageEncryptionDat if(crypt_res.error() || !len) throw lang::IllegalArgumentException( - "Not a suitable key, or failed to encrypt.", + u"Not a suitable key, or failed to encrypt."_ustr, css::uno::Reference<css::uno::XInterface>(), -1); uno::Sequence < sal_Int8 > aCipherValue(len); result = cipher.seek(0,SEEK_SET); assert(result == 0); if( cipher.read(aCipherValue.getArray(), len) != len ) - throw uno::RuntimeException("The GpgME library failed to read the encrypted value."); + throw uno::RuntimeException(u"The GpgME library failed to read the encrypted value."_ustr); SAL_INFO("comphelper.crypto", "Generated gpg crypto of length: " << len); uno::Sequence< beans::NamedValue > aGpgEncryptionEntry{ - { "KeyId", uno::Any(aKeyID) }, - { "KeyPacket", uno::Any(aKeyID) }, - { "CipherValue", uno::Any(aCipherValue) } + { u"KeyId"_ustr, uno::Any(aKeyID) }, + { u"KeyPacket"_ustr, uno::Any(aKeyID) }, + { u"CipherValue"_ustr, uno::Any(aCipherValue) } }; aGpgEncryptions.push_back(aGpgEncryptionEntry); @@ -518,8 +559,8 @@ uno::Sequence< beans::NamedValue > OStorageHelper::CreateGpgPackageEncryptionDat = { { PACKAGE_ENCRYPTIONDATA_SHA256UTF8, uno::Any(aVector) } }; uno::Sequence<beans::NamedValue> aContainer - = { { "GpgInfos", uno::Any(comphelper::containerToSequence(aGpgEncryptions)) }, - { "EncryptionKey", uno::Any(aEncryptionData) } }; + = { { u"GpgInfos"_ustr, uno::Any(comphelper::containerToSequence(aGpgEncryptions)) }, + { u"EncryptionKey"_ustr, uno::Any(aEncryptionData) } }; return aContainer; #else @@ -527,18 +568,11 @@ uno::Sequence< beans::NamedValue > OStorageHelper::CreateGpgPackageEncryptionDat #endif } -bool OStorageHelper::IsValidZipEntryFileName( const OUString& aName, bool bSlashAllowed ) -{ - return IsValidZipEntryFileName( aName.getStr(), aName.getLength(), bSlashAllowed ); -} - - -bool OStorageHelper::IsValidZipEntryFileName( - const sal_Unicode *pChar, sal_Int32 nLength, bool bSlashAllowed ) +bool OStorageHelper::IsValidZipEntryFileName( std::u16string_view aName, bool bSlashAllowed ) { - for ( sal_Int32 i = 0; i < nLength; i++ ) + for ( size_t i = 0; i < aName.size(); i++ ) { - switch ( pChar[i] ) + switch ( aName[i] ) { case '\\': case '?': @@ -553,7 +587,7 @@ bool OStorageHelper::IsValidZipEntryFileName( return false; break; default: - if ( pChar[i] < 32 || (pChar[i] >= 0xD800 && pChar[i] <= 0xDFFF) ) + if ( aName[i] < 32 || (aName[i] >= 0xD800 && aName[i] <= 0xDFFF) ) return false; } } @@ -561,27 +595,27 @@ bool OStorageHelper::IsValidZipEntryFileName( } -bool OStorageHelper::PathHasSegment( const OUString& aPath, const OUString& aSegment ) +bool OStorageHelper::PathHasSegment( std::u16string_view aPath, std::u16string_view aSegment ) { bool bResult = false; - const sal_Int32 nPathLen = aPath.getLength(); - const sal_Int32 nSegLen = aSegment.getLength(); + const size_t nPathLen = aPath.size(); + const size_t nSegLen = aSegment.size(); - if ( !aSegment.isEmpty() && nPathLen >= nSegLen ) + if ( !aSegment.empty() && nPathLen >= nSegLen ) { - OUString aEndSegment = "/" + aSegment; + OUString aEndSegment = OUString::Concat("/") + aSegment; OUString aInternalSegment = aEndSegment + "/"; - if ( aPath.indexOf( aInternalSegment ) >= 0 ) + if ( aPath.find( aInternalSegment ) != std::u16string_view::npos ) bResult = true; - if ( !bResult && aPath.startsWith( aSegment ) ) + if ( !bResult && o3tl::starts_with(aPath, aSegment ) ) { if ( nPathLen == nSegLen || aPath[nSegLen] == '/' ) bResult = true; } - if ( !bResult && nPathLen > nSegLen && aPath.subView( nPathLen - nSegLen - 1, nSegLen + 1 ) == aEndSegment ) + if ( !bResult && nPathLen > nSegLen && aPath.substr( nPathLen - nSegLen - 1, nSegLen + 1 ) == aEndSegment ) bResult = true; } @@ -606,11 +640,10 @@ void LifecycleProxy::commitStorages() }); } -static void splitPath( std::vector<OUString> &rElems, - const OUString& rPath ) +static void splitPath( std::vector<OUString> &rElems, std::u16string_view rPath ) { for (sal_Int32 i = 0; i >= 0;) - rElems.push_back( rPath.getToken( 0, '/', i ) ); + rElems.push_back( OUString(o3tl::getToken(rPath, 0, '/', i )) ); } static uno::Reference< embed::XStorage > LookupStorageAtPath( @@ -630,7 +663,7 @@ static uno::Reference< embed::XStorage > LookupStorageAtPath( uno::Reference< embed::XStorage > OStorageHelper::GetStorageAtPath( const uno::Reference< embed::XStorage > &xStorage, - const OUString& rPath, sal_uInt32 nOpenMode, + std::u16string_view rPath, sal_uInt32 nOpenMode, LifecycleProxy const &rNastiness ) { std::vector<OUString> aElems; @@ -640,7 +673,7 @@ uno::Reference< embed::XStorage > OStorageHelper::GetStorageAtPath( uno::Reference< io::XStream > OStorageHelper::GetStreamAtPath( const uno::Reference< embed::XStorage > &xParentStorage, - const OUString& rPath, sal_uInt32 nOpenMode, + std::u16string_view rPath, sal_uInt32 nOpenMode, LifecycleProxy const &rNastiness ) { std::vector<OUString> aElems; @@ -673,7 +706,7 @@ OUString OStorageHelper::GetODFVersionFromStorage(const uno::Reference<embed::XS try { uno::Reference<beans::XPropertySet> xPropSet(xStorage, uno::UNO_QUERY_THROW); - xPropSet->getPropertyValue("Version") >>= aODFVersion; + xPropSet->getPropertyValue(u"Version"_ustr) >>= aODFVersion; } catch (uno::Exception&) { diff --git a/comphelper/source/misc/string.cxx b/comphelper/source/misc/string.cxx index a3ee9bc58521..8b72ad5f34a5 100644 --- a/comphelper/source/misc/string.cxx +++ b/comphelper/source/misc/string.cxx @@ -19,16 +19,21 @@ #include <sal/config.h> +#include <cassert> #include <cstddef> #include <string_view> +#include <utility> #include <vector> #include <algorithm> +#include <o3tl/safeint.hxx> +#include <o3tl/string_view.hxx> #include <rtl/character.hxx> #include <rtl/ustring.hxx> #include <rtl/ustrbuf.hxx> #include <rtl/string.hxx> #include <rtl/strbuf.hxx> +#include <sal/log.hxx> #include <sal/types.h> #include <comphelper/string.hxx> @@ -61,16 +66,43 @@ namespace return rIn.substr(i); } + template <typename T, typename C> T tmpl_stripStartString(const T &rIn, + const C cRemove) + { + if (rIn.isEmpty()) + return rIn; + + sal_Int32 i = 0; + + while (i < rIn.getLength()) + { + if (rIn[i] != cRemove) + break; + ++i; + } + + return rIn.copy(i); + } +} + +OString stripStart(const OString& rIn, char c) +{ + return tmpl_stripStartString<OString, char>(rIn, c); } -OString stripStart(std::string_view rIn, char c) +std::string_view stripStart(std::string_view rIn, char c) { - return OString(tmpl_stripStart<std::string_view, char>(rIn, c)); + return tmpl_stripStart<std::string_view, char>(rIn, c); } -OUString stripStart(std::u16string_view rIn, sal_Unicode c) +OUString stripStart(const OUString& rIn, sal_Unicode c) { - return OUString(tmpl_stripStart<std::u16string_view, sal_Unicode>(rIn, c)); + return tmpl_stripStartString<OUString, sal_Unicode>(rIn, c); +} + +std::u16string_view stripStart(std::u16string_view rIn, sal_Unicode c) +{ + return tmpl_stripStart<std::u16string_view, sal_Unicode>(rIn, c); } namespace @@ -92,28 +124,114 @@ namespace return rIn.substr(0, i); } + template <typename T, typename C> T tmpl_stripEndString(const T &rIn, + const C cRemove) + { + if (rIn.isEmpty()) + return rIn; + + sal_Int32 i = rIn.getLength(); + + while (i > 0) + { + if (rIn[i-1] != cRemove) + break; + --i; + } + + return rIn.copy(0, i); + } } -OString stripEnd(std::string_view rIn, char c) +OString stripEnd(const OString& rIn, char c) { - return OString(tmpl_stripEnd<std::string_view, char>(rIn, c)); + return tmpl_stripEndString<OString, char>(rIn, c); } -OUString stripEnd(std::u16string_view rIn, sal_Unicode c) +std::string_view stripEnd(std::string_view rIn, char c) { - return OUString(tmpl_stripEnd<std::u16string_view, sal_Unicode>(rIn, c)); + return tmpl_stripEnd<std::string_view, char>(rIn, c); } -OString strip(std::string_view rIn, char c) +OUString stripEnd(const OUString& rIn, sal_Unicode c) { - auto x = tmpl_stripStart<std::string_view, char>(rIn, c); - return stripEnd(x, c); + return tmpl_stripEndString<OUString, sal_Unicode>(rIn, c); } -OUString strip(std::u16string_view rIn, sal_Unicode c) +std::u16string_view stripEnd(std::u16string_view rIn, sal_Unicode c) { - auto x = tmpl_stripStart<std::u16string_view, sal_Unicode>(rIn, c); - return stripEnd(x, c); + return tmpl_stripEnd<std::u16string_view, sal_Unicode>(rIn, c); +} + +namespace +{ + template <typename T, typename C> T tmpl_strip(const T &rIn, + const C cRemove) + { + if (rIn.empty()) + return rIn; + + typename T::size_type end = rIn.size(); + while (end > 0) + { + if (rIn[end-1] != cRemove) + break; + --end; + } + + typename T::size_type start = 0; + while (start < end) + { + if (rIn[start] != cRemove) + break; + ++start; + } + + return rIn.substr(start, end - start); + } + template <typename T, typename C> T tmpl_stripString(const T &rIn, + const C cRemove) + { + if (rIn.isEmpty()) + return rIn; + + sal_Int32 end = rIn.getLength(); + while (end > 0) + { + if (rIn[end-1] != cRemove) + break; + --end; + } + sal_Int32 start = 0; + while (start < end) + { + if (rIn[start] != cRemove) + break; + ++start; + } + + return rIn.copy(start, end - start); + } +} + +OString strip(const OString& rIn, char c) +{ + return tmpl_stripString<OString, char>(rIn, c); +} + +std::string_view strip(std::string_view rIn, char c) +{ + return tmpl_strip<std::string_view, char>(rIn, c); +} + +OUString strip(const OUString& rIn, sal_Unicode c) +{ + return tmpl_stripString<OUString, sal_Unicode>(rIn, c); +} + +std::u16string_view strip(std::u16string_view rIn, sal_Unicode c) +{ + return tmpl_strip<std::u16string_view, sal_Unicode>(rIn, c); } namespace @@ -145,13 +263,12 @@ sal_Int32 getTokenCount(std::u16string_view rIn, sal_Unicode cTok) return tmpl_getTokenCount<std::u16string_view, sal_Unicode>(rIn, cTok); } -static sal_uInt32 decimalStringToNumber( - OUString const & str, sal_Int32 nStart, sal_Int32 nLength ) +sal_uInt32 decimalStringToNumber(std::u16string_view str) { sal_uInt32 result = 0; - for( sal_Int32 i = nStart; i < nStart + nLength; ) + for( std::size_t i = 0; i < str.size(); ) { - sal_uInt32 c = str.iterateCodePoints(&i); + sal_uInt32 c = o3tl::iterateCodePoints(str, &i); sal_uInt32 value = 0; if( c <= 0x0039) // ASCII decimal digits, most common value = c - 0x0030; @@ -242,12 +359,6 @@ static sal_uInt32 decimalStringToNumber( return result; } -sal_uInt32 decimalStringToNumber( - OUString const & str ) -{ - return decimalStringToNumber(str, 0, str.getLength()); -} - using namespace ::com::sun::star; // convert between sequence of string and comma separated string @@ -257,32 +368,31 @@ OUString convertCommaSeparated( { OUStringBuffer buf; ::comphelper::intersperse( - i_rSeq.begin(), i_rSeq.end(), ::comphelper::OUStringBufferAppender(buf), OUString( ", " )); + i_rSeq.begin(), i_rSeq.end(), ::comphelper::OUStringBufferAppender(buf), u", "_ustr); return buf.makeStringAndClear(); } std::vector<OUString> - split(const OUString& rStr, sal_Unicode cSeparator) + split(std::u16string_view rStr, sal_Unicode cSeparator) { std::vector< OUString > vec; - sal_Int32 idx = 0; + std::size_t idx = 0; do { - OUString kw = - rStr.getToken(0, cSeparator, idx); - kw = kw.trim(); - if (!kw.isEmpty()) + std::u16string_view kw = o3tl::getToken(rStr, cSeparator, idx); + kw = o3tl::trim(kw); + if (!kw.empty()) { - vec.push_back(kw); + vec.push_back(OUString(kw)); } - } while (idx >= 0); + } while (idx != std::u16string_view::npos); return vec; } uno::Sequence< OUString > - convertCommaSeparated( OUString const& i_rString ) + convertCommaSeparated( std::u16string_view i_rString ) { std::vector< OUString > vec = split(i_rString, ','); return comphelper::containerToSequence(vec); @@ -312,33 +422,50 @@ sal_Int32 compareNatural( const OUString & rLHS, const OUString & rRHS, sal_Int32 nLHSFirstDigitPos = 0; sal_Int32 nRHSFirstDigitPos = 0; + // Check if the string starts with a digit + sal_Int32 nStartsDigitLHS = rBI->endOfCharBlock(rLHS, nLHSFirstDigitPos, rLocale, i18n::CharType::DECIMAL_DIGIT_NUMBER); + sal_Int32 nStartsDigitRHS = rBI->endOfCharBlock(rRHS, nRHSFirstDigitPos, rLocale, i18n::CharType::DECIMAL_DIGIT_NUMBER); + + if (nStartsDigitLHS > 0 && nStartsDigitRHS > 0) + { + sal_uInt32 nLHS = comphelper::string::decimalStringToNumber(rLHS.subView(0, nStartsDigitLHS)); + sal_uInt32 nRHS = comphelper::string::decimalStringToNumber(rRHS.subView(0, nStartsDigitRHS)); + + if (nLHS != nRHS) + return nLHS < nRHS ? -1 : 1; + nLHSLastNonDigitPos = nStartsDigitLHS; + nRHSLastNonDigitPos = nStartsDigitRHS; + } + else if (nStartsDigitLHS > 0) + return -1; + else if (nStartsDigitRHS > 0) + return 1; + while (nLHSFirstDigitPos < rLHS.getLength() || nRHSFirstDigitPos < rRHS.getLength()) { sal_Int32 nLHSChunkLen; sal_Int32 nRHSChunkLen; //Compare non digit block as normal strings - nLHSFirstDigitPos = rBI->nextCharBlock(rLHS, nLHSLastNonDigitPos, - rLocale, i18n::CharType::DECIMAL_DIGIT_NUMBER); - nRHSFirstDigitPos = rBI->nextCharBlock(rRHS, nRHSLastNonDigitPos, - rLocale, i18n::CharType::DECIMAL_DIGIT_NUMBER); + nLHSFirstDigitPos = rBI->nextCharBlock(rLHS, nLHSLastNonDigitPos, rLocale, i18n::CharType::DECIMAL_DIGIT_NUMBER); + nRHSFirstDigitPos = rBI->nextCharBlock(rRHS, nRHSLastNonDigitPos, rLocale, i18n::CharType::DECIMAL_DIGIT_NUMBER); + if (nLHSFirstDigitPos == -1) nLHSFirstDigitPos = rLHS.getLength(); + if (nRHSFirstDigitPos == -1) nRHSFirstDigitPos = rRHS.getLength(); + nLHSChunkLen = nLHSFirstDigitPos - nLHSLastNonDigitPos; nRHSChunkLen = nRHSFirstDigitPos - nRHSLastNonDigitPos; - nRet = rCollator->compareSubstring(rLHS, nLHSLastNonDigitPos, - nLHSChunkLen, rRHS, nRHSLastNonDigitPos, nRHSChunkLen); + nRet = rCollator->compareSubstring(rLHS, nLHSLastNonDigitPos, nLHSChunkLen, rRHS, nRHSLastNonDigitPos, nRHSChunkLen); if (nRet != 0) break; //Compare digit block as one number vs another - nLHSLastNonDigitPos = rBI->endOfCharBlock(rLHS, nLHSFirstDigitPos, - rLocale, i18n::CharType::DECIMAL_DIGIT_NUMBER); - nRHSLastNonDigitPos = rBI->endOfCharBlock(rRHS, nRHSFirstDigitPos, - rLocale, i18n::CharType::DECIMAL_DIGIT_NUMBER); + nLHSLastNonDigitPos = rBI->endOfCharBlock(rLHS, nLHSFirstDigitPos, rLocale, i18n::CharType::DECIMAL_DIGIT_NUMBER); + nRHSLastNonDigitPos = rBI->endOfCharBlock(rRHS, nRHSFirstDigitPos, rLocale, i18n::CharType::DECIMAL_DIGIT_NUMBER); if (nLHSLastNonDigitPos == -1) nLHSLastNonDigitPos = rLHS.getLength(); if (nRHSLastNonDigitPos == -1) @@ -350,8 +477,8 @@ sal_Int32 compareNatural( const OUString & rLHS, const OUString & rRHS, //numbers outside of the normal 0-9 range, e.g. see GetLocalizedChar in //vcl - sal_uInt32 nLHS = comphelper::string::decimalStringToNumber(rLHS, nLHSFirstDigitPos, nLHSChunkLen); - sal_uInt32 nRHS = comphelper::string::decimalStringToNumber(rRHS, nRHSFirstDigitPos, nRHSChunkLen); + sal_uInt32 nLHS = comphelper::string::decimalStringToNumber(rLHS.subView(nLHSFirstDigitPos, nLHSChunkLen)); + sal_uInt32 nRHS = comphelper::string::decimalStringToNumber(rRHS.subView(nRHSFirstDigitPos, nRHSChunkLen)); if (nLHS != nRHS) { @@ -365,7 +492,7 @@ sal_Int32 compareNatural( const OUString & rLHS, const OUString & rRHS, NaturalStringSorter::NaturalStringSorter( const uno::Reference< uno::XComponentContext > &rContext, - const lang::Locale &rLocale) : m_aLocale(rLocale) + lang::Locale aLocale) : m_aLocale(std::move(aLocale)) { m_xCollator = i18n::Collator::create( rContext ); m_xCollator->loadDefaultCollator(m_aLocale, 0); @@ -386,29 +513,25 @@ bool isdigitAsciiString(std::u16string_view rString) [](sal_Unicode c){ return rtl::isAsciiDigit(c); }); } -namespace -{ - template <typename T, typename I, typename O> T tmpl_reverseString(I rIn) - { - if (rIn.empty()) - return T(); - - typename I::size_type i = rIn.size(); - O sBuf(static_cast<sal_Int32>(i)); - while (i) - sBuf.append(rIn[--i]); - return sBuf.makeStringAndClear(); - } -} - OUString reverseString(std::u16string_view rStr) { - return tmpl_reverseString<OUString, std::u16string_view, OUStringBuffer>(rStr); + if (rStr.empty()) + return OUString(); + + std::size_t i = rStr.size(); + OUStringBuffer sBuf(static_cast<sal_Int32>(i)); + while (i) + sBuf.append(rStr[--i]); + return sBuf.makeStringAndClear(); } -OString reverseString(std::string_view rStr) -{ - return tmpl_reverseString<OString, std::string_view, OStringBuffer>(rStr); +OUString reverseCodePoints(std::u16string_view str) { + auto const len = str.size(); + OUStringBuffer buf(len); + for (sal_Int32 i = len; i != 0;) { + buf.appendUtf32(o3tl::iterateCodePoints(str, &i, -1)); + } + return buf.makeStringAndClear(); } sal_Int32 indexOfAny(std::u16string_view rIn, @@ -494,6 +617,62 @@ OUString setToken(const OUString& rIn, sal_Int32 nToken, sal_Unicode cTok, return rIn; } +/** Similar to OUString::replaceAt, but for an OUStringBuffer. + + Replace n = count characters + from position index in this string with newStr. + */ +void replaceAt(OUStringBuffer& rIn, sal_Int32 nIndex, sal_Int32 nCount, std::u16string_view newStr ) +{ + assert(nIndex >= 0 && nIndex <= rIn.getLength()); + assert(nCount >= 0); + assert(nCount <= rIn.getLength() - nIndex); + + /* Append? */ + const sal_Int32 nOldLength = rIn.getLength(); + if ( nIndex == nOldLength ) + { + rIn.append(newStr); + return; + } + + sal_Int32 nNewLength = nOldLength + newStr.size() - nCount; + if (newStr.size() > o3tl::make_unsigned(nCount)) + rIn.ensureCapacity(nOldLength + newStr.size() - nCount); + + sal_Unicode* pStr = const_cast<sal_Unicode*>(rIn.getStr()); + memmove(pStr + nIndex + newStr.size(), pStr + nIndex + nCount, nOldLength - nIndex + nCount); + memcpy(pStr + nIndex, newStr.data(), newStr.size()); + + rIn.setLength(nNewLength); +} + +OUString sanitizeStringSurrogates(const OUString& rString) +{ + sal_Int32 i=0; + while (i < rString.getLength()) + { + sal_Unicode c = rString[i]; + if (rtl::isHighSurrogate(c)) + { + if (i+1 == rString.getLength() + || !rtl::isLowSurrogate(rString[i+1])) + { + SAL_WARN("comphelper", "Surrogate error: high without low"); + return rString.copy(0, i); + } + ++i; //skip correct low + } + if (rtl::isLowSurrogate(c)) //bare low without preceding high + { + SAL_WARN("comphelper", "Surrogate error: low without high"); + return rString.copy(0, i); + } + ++i; + } + return rString; +} + } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/comphelper/source/misc/syntaxhighlight.cxx b/comphelper/source/misc/syntaxhighlight.cxx index f6eccc7b4fc3..89dcb73752e4 100644 --- a/comphelper/source/misc/syntaxhighlight.cxx +++ b/comphelper/source/misc/syntaxhighlight.cxx @@ -22,6 +22,7 @@ #include <cassert> #include <rtl/character.hxx> +#include <rtl/ustring.hxx> #include <unicode/uchar.h> #include <comphelper/syntaxhighlight.hxx> #include <o3tl/typed_flags_set.hxx> @@ -279,8 +280,8 @@ class SyntaxHighlighter::Tokenizer bool testCharFlags(sal_Unicode c, CharFlags nTestFlags) const; // Get new token, EmptyString == nothing more over there - bool getNextToken(const sal_Unicode*& pos, /*out*/TokenType& reType, - /*out*/const sal_Unicode*& rpStartPos, /*out*/const sal_Unicode*& rpEndPos) const; + bool getNextToken(std::u16string_view::const_iterator& pos, std::u16string_view::const_iterator end, /*out*/TokenType& reType, + /*out*/std::u16string_view::const_iterator& rpStartPos, /*out*/std::u16string_view::const_iterator& rpEndPos) const; const char** ppListKeyWords; sal_uInt16 nKeyWordCount; @@ -290,7 +291,7 @@ public: explicit Tokenizer( HighlighterLanguage aLang ); - void getHighlightPortions(const OUString& rLine, + void getHighlightPortions(std::u16string_view rLine, /*out*/std::vector<HighlightPortion>& portions) const; void setKeyWords( const char** ppKeyWords, sal_uInt16 nCount ); }; @@ -317,24 +318,25 @@ void SyntaxHighlighter::Tokenizer::setKeyWords( const char** ppKeyWords, sal_uIn nKeyWordCount = nCount; } -bool SyntaxHighlighter::Tokenizer::getNextToken(const sal_Unicode*& pos, /*out*/TokenType& reType, - /*out*/const sal_Unicode*& rpStartPos, /*out*/const sal_Unicode*& rpEndPos) const +bool SyntaxHighlighter::Tokenizer::getNextToken(std::u16string_view::const_iterator& pos, std::u16string_view::const_iterator end, + /*out*/TokenType& reType, + /*out*/std::u16string_view::const_iterator& rpStartPos, /*out*/std::u16string_view::const_iterator& rpEndPos) const { reType = TokenType::Unknown; rpStartPos = pos; - sal_Unicode c = *pos; - if( c == 0 ) + if( pos == end ) return false; + sal_Unicode c = *pos; ++pos; //*** Go through all possibilities *** // Space? if ( testCharFlags( c, CharFlags::Space ) ) { - while( testCharFlags( *pos, CharFlags::Space ) ) + while( pos != end && testCharFlags( *pos, CharFlags::Space ) ) ++pos; reType = TokenType::Whitespace; @@ -346,6 +348,8 @@ bool SyntaxHighlighter::Tokenizer::getNextToken(const sal_Unicode*& pos, /*out*/ bool bIdentifierChar; do { + if (pos == end) + break; // Fetch next character c = *pos; bIdentifierChar = testCharFlags( c, CharFlags::InIdentifier ); @@ -374,7 +378,7 @@ bool SyntaxHighlighter::Tokenizer::getNextToken(const sal_Unicode*& pos, /*out*/ if( bCanBeKeyword ) { - OUString aKWString(rpStartPos, nCount); + std::u16string_view aKWString(&*rpStartPos, nCount); OString aByteStr = OUStringToOString(aKWString, RTL_TEXTENCODING_ASCII_US).toAsciiLowerCase(); if ( bsearch( aByteStr.getStr(), ppListKeyWords, nKeyWordCount, sizeof( char* ), @@ -385,10 +389,14 @@ bool SyntaxHighlighter::Tokenizer::getNextToken(const sal_Unicode*& pos, /*out*/ if( aByteStr == "rem" ) { // Remove all characters until end of line or EOF - sal_Unicode cPeek = *pos; - while( cPeek != 0 && !testCharFlags( cPeek, CharFlags::EOL ) ) + for (;;) { - cPeek = *++pos; + if (pos == end) + break; + sal_Unicode cPeek = *pos; + if ( testCharFlags( cPeek, CharFlags::EOL ) ) + break; + ++pos; } reType = TokenType::Comment; @@ -411,6 +419,8 @@ bool SyntaxHighlighter::Tokenizer::getNextToken(const sal_Unicode*& pos, /*out*/ do { // Get next character + if (pos == end) + break; c = *pos; bIdentifierChar = isAlpha(c); if( bIdentifierChar ) @@ -422,14 +432,12 @@ bool SyntaxHighlighter::Tokenizer::getNextToken(const sal_Unicode*& pos, /*out*/ } else if ((c=='-') && (aLanguage == HighlighterLanguage::SQL)) { - sal_Unicode cPeekNext = *pos; - if (cPeekNext=='-') + if (pos != end && *pos=='-') { // Remove all characters until end of line or EOF - while( cPeekNext != 0 && !testCharFlags( cPeekNext, CharFlags::EOL ) ) + while( pos != end && !testCharFlags( *pos, CharFlags::EOL ) ) { ++pos; - cPeekNext = *pos; } reType = TokenType::Comment; } @@ -438,14 +446,12 @@ bool SyntaxHighlighter::Tokenizer::getNextToken(const sal_Unicode*& pos, /*out*/ } else if ((c=='/') && (aLanguage == HighlighterLanguage::SQL)) { - sal_Unicode cPeekNext = *pos; - if (cPeekNext=='/') + if (pos != end && *pos=='/') { // Remove all characters until end of line or EOF - while( cPeekNext != 0 && !testCharFlags( cPeekNext, CharFlags::EOL ) ) + while( pos != end && !testCharFlags( *pos, CharFlags::EOL ) ) { ++pos; - cPeekNext = *pos; } reType = TokenType::Comment; } @@ -459,8 +465,10 @@ bool SyntaxHighlighter::Tokenizer::getNextToken(const sal_Unicode*& pos, /*out*/ { // Skip all characters until end of input or end of line: for (;;) { + if (pos == end) + break; c = *pos; - if (c == 0 || testCharFlags(c, CharFlags::EOL)) { + if (testCharFlags(c, CharFlags::EOL)) { break; } ++pos; @@ -480,7 +488,7 @@ bool SyntaxHighlighter::Tokenizer::getNextToken(const sal_Unicode*& pos, /*out*/ } // Object separator? Must be handled before Number - else if( c == '.' && ( *pos < '0' || *pos > '9' ) ) + else if( c == '.' && ( pos == end || *pos < '0' || *pos > '9' ) ) { reType = TokenType::Operator; } @@ -497,25 +505,25 @@ bool SyntaxHighlighter::Tokenizer::getNextToken(const sal_Unicode*& pos, /*out*/ if( c == '&' ) { // Octal? - if( *pos == 'o' || *pos == 'O' ) + if( pos != end && (*pos == 'o' || *pos == 'O' )) { // remove o ++pos; nRadix = 8; // Octal base // Read all numbers - while( testCharFlags( *pos, CharFlags::InOctNumber ) ) + while( pos != end && testCharFlags( *pos, CharFlags::InOctNumber ) ) ++pos; } // Hexadecimal? - else if( *pos == 'h' || *pos == 'H' ) + else if( pos != end && (*pos == 'h' || *pos == 'H' )) { // remove x ++pos; nRadix = 16; // Hexadecimal base // Read all numbers - while( testCharFlags( *pos, CharFlags::InHexNumber ) ) + while( pos != end && testCharFlags( *pos, CharFlags::InHexNumber ) ) ++pos; } else @@ -531,9 +539,9 @@ bool SyntaxHighlighter::Tokenizer::getNextToken(const sal_Unicode*& pos, /*out*/ bool bAfterExpChar = false; // Read all numbers - while( testCharFlags( *pos, CharFlags::InNumber ) || + while( pos != end && (testCharFlags( *pos, CharFlags::InNumber ) || (bAfterExpChar && *pos == '+' ) || - (bAfterExpChar && *pos == '-' ) ) + (bAfterExpChar && *pos == '-' ) )) // After exponent +/- are OK, too { c = *pos++; @@ -551,10 +559,10 @@ bool SyntaxHighlighter::Tokenizer::getNextToken(const sal_Unicode*& pos, /*out*/ cEndString = ']'; // Read all characters - while( *pos != cEndString ) + while( pos == end || *pos != cEndString ) { // Detect EOF before reading next char, so we do not lose EOF - if( *pos == 0 ) + if( pos == end ) { // ERROR: unterminated string literal reType = TokenType::Error; @@ -583,9 +591,12 @@ bool SyntaxHighlighter::Tokenizer::getNextToken(const sal_Unicode*& pos, /*out*/ else if( testCharFlags( c, CharFlags::EOL ) ) { // If another EOL character comes, read it - sal_Unicode cNext = *pos; - if( cNext != c && testCharFlags( cNext, CharFlags::EOL ) ) - ++pos; + if (pos != end) + { + sal_Unicode cNext = *pos; + if( cNext != c && testCharFlags( cNext, CharFlags::EOL ) ) + ++pos; + } reType = TokenType::EOL; } @@ -676,22 +687,22 @@ SyntaxHighlighter::Tokenizer::Tokenizer( HighlighterLanguage aLang ): aLanguage( nKeyWordCount = 0; } -void SyntaxHighlighter::Tokenizer::getHighlightPortions(const OUString& rLine, +void SyntaxHighlighter::Tokenizer::getHighlightPortions(std::u16string_view rLine, /*out*/std::vector<HighlightPortion>& portions) const { // Set the position to the beginning of the source string - const sal_Unicode* pos = rLine.getStr(); + auto pos = rLine.begin(); // Variables for the out parameter TokenType eType; - const sal_Unicode* pStartPos; - const sal_Unicode* pEndPos; + std::u16string_view::const_iterator pStartPos; + std::u16string_view::const_iterator pEndPos; // Loop over all the tokens - while( getNextToken( pos, eType, pStartPos, pEndPos ) ) + while( getNextToken( pos, rLine.end(), eType, pStartPos, pEndPos ) ) { portions.emplace_back( - pStartPos - rLine.getStr(), pEndPos - rLine.getStr(), eType); + pStartPos - rLine.begin(), pEndPos - rLine.begin(), eType); } } @@ -703,11 +714,11 @@ SyntaxHighlighter::SyntaxHighlighter(HighlighterLanguage language): { case HighlighterLanguage::Basic: m_tokenizer->setKeyWords( strListBasicKeyWords, - SAL_N_ELEMENTS( strListBasicKeyWords )); + std::size( strListBasicKeyWords )); break; case HighlighterLanguage::SQL: m_tokenizer->setKeyWords( strListSqlKeyWords, - SAL_N_ELEMENTS( strListSqlKeyWords )); + std::size( strListSqlKeyWords )); break; default: assert(false); // this cannot happen @@ -716,7 +727,7 @@ SyntaxHighlighter::SyntaxHighlighter(HighlighterLanguage language): SyntaxHighlighter::~SyntaxHighlighter() {} -void SyntaxHighlighter::getHighlightPortions(const OUString& rLine, +void SyntaxHighlighter::getHighlightPortions(std::u16string_view rLine, /*out*/std::vector<HighlightPortion>& portions) const { m_tokenizer->getHighlightPortions( rLine, portions ); diff --git a/comphelper/source/misc/threadpool.cxx b/comphelper/source/misc/threadpool.cxx index 48ff4af2d7c6..f0a71eb05168 100644 --- a/comphelper/source/misc/threadpool.cxx +++ b/comphelper/source/misc/threadpool.cxx @@ -11,6 +11,7 @@ #include <com/sun/star/uno/Exception.hpp> #include <config_options.h> +#include <o3tl/safeint.hxx> #include <sal/config.h> #include <sal/log.hxx> #include <salhelper/thread.hxx> @@ -18,7 +19,9 @@ #include <memory> #include <thread> #include <chrono> +#include <cstddef> #include <comphelper/debuggerinfo.hxx> +#include <utility> #if defined HAVE_VALGRIND_HEADERS #include <valgrind/memcheck.h> @@ -90,7 +93,7 @@ public: } }; -ThreadPool::ThreadPool(sal_Int32 nWorkers) +ThreadPool::ThreadPool(std::size_t nWorkers) : mbTerminate(true) , mnMaxWorkers(nWorkers) , mnBusyWorkers(0) @@ -115,7 +118,7 @@ std::shared_ptr< ThreadPool >& GetStaticThreadPool() static std::shared_ptr< ThreadPool > POOL = []() { - const sal_Int32 nThreads = ThreadPool::getPreferredConcurrency(); + const std::size_t nThreads = ThreadPool::getPreferredConcurrency(); return std::make_shared< ThreadPool >( nThreads ); }(); return POOL; @@ -128,21 +131,22 @@ ThreadPool& ThreadPool::getSharedOptimalPool() return *GetStaticThreadPool(); } -sal_Int32 ThreadPool::getPreferredConcurrency() +std::size_t ThreadPool::getPreferredConcurrency() { - static sal_Int32 ThreadCount = []() + static std::size_t ThreadCount = []() { - const sal_Int32 nHardThreads = std::max(std::thread::hardware_concurrency(), 1U); - sal_Int32 nThreads = nHardThreads; + const std::size_t nHardThreads = o3tl::clamp_to_unsigned<std::size_t>( + std::max(std::thread::hardware_concurrency(), 1U)); + std::size_t nThreads = nHardThreads; const char *pEnv = getenv("MAX_CONCURRENCY"); if (pEnv != nullptr) { // Override with user/admin preference. - nThreads = rtl_str_toInt32(pEnv, 10); + nThreads = o3tl::clamp_to_unsigned<std::size_t>(rtl_str_toInt32(pEnv, 10)); } nThreads = std::min(nHardThreads, nThreads); - return std::max<sal_Int32>(nThreads, 1); + return std::max<std::size_t>(nThreads, 1); }(); return ThreadCount; @@ -304,8 +308,8 @@ bool ThreadPool::isTaskTagDone(const std::shared_ptr<ThreadTaskTag>& pTag) return pTag->isDone(); } -ThreadTask::ThreadTask(const std::shared_ptr<ThreadTaskTag>& pTag) - : mpTag(pTag) +ThreadTask::ThreadTask(std::shared_ptr<ThreadTaskTag> xTag) + : mpTag(std::move(xTag)) { } diff --git a/comphelper/source/misc/traceevent.cxx b/comphelper/source/misc/traceevent.cxx index ab71853e1292..1296404ebd32 100644 --- a/comphelper/source/misc/traceevent.cxx +++ b/comphelper/source/misc/traceevent.cxx @@ -10,6 +10,7 @@ #include <sal/config.h> #include <atomic> +#include <mutex> #include <iostream> #include <comphelper/profilezone.hxx> @@ -34,20 +35,21 @@ static thread_local int nProfileZoneNesting = 0; // Level of Nested Profile Zone namespace { std::vector<OUString> g_aRecording; // recorded data -osl::Mutex g_aMutex; +std::mutex g_aMutex; } void TraceEvent::addRecording(const OUString& sObject) { - osl::MutexGuard aGuard(g_aMutex); + bool bEmitCallback; + { + std::lock_guard aGuard(g_aMutex); - g_aRecording.emplace_back(sObject); + g_aRecording.emplace_back(sObject); - if (s_nBufferSize > 0 && g_aRecording.size() >= s_nBufferSize) - { - if (s_pBufferFullCallback != nullptr) - (*s_pBufferFullCallback)(); + bEmitCallback = s_nBufferSize > 0 && g_aRecording.size() >= s_nBufferSize; } + if (bEmitCallback && s_pBufferFullCallback != nullptr) + (*s_pBufferFullCallback)(); } void TraceEvent::addInstantEvent(const char* sName, const std::map<OUString, OUString>& args) @@ -76,7 +78,7 @@ void TraceEvent::addInstantEvent(const char* sName, const std::map<OUString, OUS void TraceEvent::startRecording() { - osl::MutexGuard aGuard(g_aMutex); + std::lock_guard aGuard(g_aMutex); s_bRecording = true; } @@ -93,7 +95,7 @@ std::vector<OUString> TraceEvent::getEventVectorAndClear() bool bRecording; std::vector<OUString> aRecording; { - osl::MutexGuard aGuard(g_aMutex); + std::lock_guard aGuard(g_aMutex); bRecording = s_bRecording; stopRecording(); aRecording.swap(g_aRecording); diff --git a/comphelper/source/misc/types.cxx b/comphelper/source/misc/types.cxx index 8887d5b5ac92..8e5d42073bff 100644 --- a/comphelper/source/misc/types.cxx +++ b/comphelper/source/misc/types.cxx @@ -95,7 +95,7 @@ sal_Int32 getEnumAsINT32(const Any& _rAny) { sal_Int32 nReturn = 0; if (!::cppu::enum2int(nReturn, _rAny)) - throw IllegalArgumentException("enum2int failed", + throw IllegalArgumentException(u"enum2int failed"_ustr, css::uno::Reference<css::uno::XInterface>(), -1); return nReturn; } diff --git a/comphelper/source/misc/weak.cxx b/comphelper/source/misc/weak.cxx deleted file mode 100644 index 02cf40e2b646..000000000000 --- a/comphelper/source/misc/weak.cxx +++ /dev/null @@ -1,57 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ -/* - * This file is part of the LibreOffice project. - * - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - * - * This file incorporates work covered by the following license notice: - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed - * with this work for additional information regarding copyright - * ownership. The ASF licenses this file to you under the Apache - * License, Version 2.0 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.apache.org/licenses/LICENSE-2.0 . - */ - - -#include <comphelper/weak.hxx> - -using namespace com::sun::star::uno; -using namespace com::sun::star::lang; - -namespace comphelper -{ - -OWeakTypeObject::OWeakTypeObject() -{ -} - -OWeakTypeObject::~OWeakTypeObject() -{ -} - -Any SAL_CALL OWeakTypeObject::queryInterface(const Type & rType ) -{ - if( rType == cppu::UnoType<XTypeProvider>::get() ) - return Any( Reference< XTypeProvider >(this) ); - else - return ::cppu::OWeakObject::queryInterface( rType ); -} - -Sequence< Type > SAL_CALL OWeakTypeObject::getTypes( ) -{ - return Sequence< Type >(); -} - -Sequence< ::sal_Int8 > SAL_CALL OWeakTypeObject::getImplementationId( ) -{ - return Sequence< ::sal_Int8 >(); -} - -} - -/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/comphelper/source/misc/weakeventlistener.cxx b/comphelper/source/misc/weakeventlistener.cxx index e8ce46590559..0543816d0593 100644 --- a/comphelper/source/misc/weakeventlistener.cxx +++ b/comphelper/source/misc/weakeventlistener.cxx @@ -55,7 +55,7 @@ namespace comphelper } - void SAL_CALL OWeakEventListenerAdapter::disposing( ) + void OWeakEventListenerAdapter::disposing( std::unique_lock<std::mutex>& /*rGuard*/ ) { Reference< XComponent > xBroadcaster( getBroadcaster( ), UNO_QUERY ); OSL_ENSURE( xBroadcaster.is(), "OWeakEventListenerAdapter::disposing: broadcaster is invalid in the meantime! How this?" ); diff --git a/comphelper/source/misc/xmlsechelper.cxx b/comphelper/source/misc/xmlsechelper.cxx index bc2cb280a710..e1bb828ba631 100644 --- a/comphelper/source/misc/xmlsechelper.cxx +++ b/comphelper/source/misc/xmlsechelper.cxx @@ -21,6 +21,7 @@ #include <rtl/ustrbuf.hxx> #include <osl/diagnose.h> +#include <o3tl/string_view.hxx> #include <utility> #include <vector> @@ -32,9 +33,9 @@ namespace comphelper::xmlsec switch (rKind) { case css::security::CertificateKind_X509: - return "X.509"; + return u"X.509"_ustr; case css::security::CertificateKind_OPENPGP: - return "OpenPGP"; + return u"OpenPGP"_ustr; default: return OUString(); } @@ -48,7 +49,7 @@ namespace comphelper::xmlsec The second string is for the details view at the bottom. It shows the attribute/value pairs on different lines. All escape characters ('"') are removed. */ - std::pair< OUString, OUString> GetDNForCertDetailsView( const OUString & rRawString) + std::pair< OUString, OUString> GetDNForCertDetailsView( std::u16string_view rRawString) { std::vector< std::pair< OUString, OUString > > vecAttrValueOfDN = parseDN(rRawString); OUStringBuffer s1, s2; @@ -72,18 +73,18 @@ namespace comphelper::xmlsec they are escaped with a double quote. This function removes the escape characters. */ #ifdef _WIN32 -std::vector< std::pair< OUString, OUString> > parseDN(const OUString& rRawString) +std::vector< std::pair< OUString, OUString> > parseDN(std::u16string_view rRawString) { std::vector< std::pair<OUString, OUString> > retVal; bool bInEscape = false; bool bInValue = false; bool bInType = true; sal_Int32 nTypeNameStart = 0; - OUString sType; + std::u16string_view sType; OUStringBuffer sbufValue; - sal_Int32 length = rRawString.getLength(); + size_t length = rRawString.size(); - for (sal_Int32 i = 0; i < length; i++) + for (size_t i = 0; i < length; i++) { sal_Unicode c = rRawString[i]; @@ -91,8 +92,8 @@ std::vector< std::pair< OUString, OUString> > parseDN(const OUString& rRawString { if (! bInValue) { - sType = rRawString.copy(nTypeNameStart, i - nTypeNameStart); - sType = sType.trim(); + sType = rRawString.substr(nTypeNameStart, i - nTypeNameStart); + sType = o3tl::trim(sType); bInType = false; } else @@ -128,9 +129,9 @@ std::vector< std::pair< OUString, OUString> > parseDN(const OUString& rRawString //then we have reached the end of the value if (!bInValue) { - OSL_ASSERT(!sType.isEmpty()); - retVal.push_back(std::make_pair(sType, sbufValue.makeStringAndClear())); - sType.clear(); + OSL_ASSERT(!sType.empty()); + retVal.emplace_back(OUString(sType), sbufValue.makeStringAndClear()); + sType = {}; //The next char is the start of the new type nTypeNameStart = i + 1; bInType = true; @@ -151,13 +152,13 @@ std::vector< std::pair< OUString, OUString> > parseDN(const OUString& rRawString } if (sbufValue.getLength()) { - OSL_ASSERT(!sType.isEmpty()); - retVal.push_back(std::make_pair(sType, sbufValue.makeStringAndClear())); + OSL_ASSERT(!sType.empty()); + retVal.emplace_back(OUString(sType), sbufValue.makeStringAndClear()); } return retVal; } #else -std::vector< std::pair< OUString, OUString> > parseDN(const OUString& rRawString) +std::vector< std::pair< OUString, OUString> > parseDN(std::u16string_view rRawString) { std::vector< std::pair<OUString, OUString> > retVal; //bInEscape == true means that the preceding character is an escape character @@ -165,11 +166,11 @@ std::vector< std::pair< OUString, OUString> > parseDN(const OUString& rRawString bool bInValue = false; bool bInType = true; sal_Int32 nTypeNameStart = 0; - OUString sType; + std::u16string_view sType; OUStringBuffer sbufValue; - sal_Int32 length = rRawString.getLength(); + size_t length = rRawString.size(); - for (sal_Int32 i = 0; i < length; i++) + for (size_t i = 0; i < length; i++) { sal_Unicode c = rRawString[i]; @@ -177,8 +178,8 @@ std::vector< std::pair< OUString, OUString> > parseDN(const OUString& rRawString { if (! bInValue) { - sType = rRawString.copy(nTypeNameStart, i - nTypeNameStart); - sType = sType.trim(); + sType = rRawString.substr(nTypeNameStart, i - nTypeNameStart); + sType = o3tl::trim(sType); bInType = false; } else @@ -223,9 +224,9 @@ std::vector< std::pair< OUString, OUString> > parseDN(const OUString& rRawString //then we have reached the end of the value if (!bInValue) { - OSL_ASSERT(!sType.isEmpty()); + OSL_ASSERT(!sType.empty()); retVal.emplace_back(sType, sbufValue.makeStringAndClear()); - sType.clear(); + sType = {}; //The next char is the start of the new type nTypeNameStart = i + 1; bInType = true; @@ -249,7 +250,7 @@ std::vector< std::pair< OUString, OUString> > parseDN(const OUString& rRawString } if (!sbufValue.isEmpty()) { - OSL_ASSERT(!sType.isEmpty()); + OSL_ASSERT(!sType.empty()); retVal.emplace_back(sType, sbufValue.makeStringAndClear()); } return retVal; @@ -283,18 +284,14 @@ std::vector< std::pair< OUString, OUString> > parseDN(const OUString& rRawString OUString GetHexString( const css::uno::Sequence< sal_Int8 >& _rSeq, const char* _pSep, sal_uInt16 _nLineBreak ) { - const sal_Int8* pSerNumSeq = _rSeq.getConstArray(); - int nCnt = _rSeq.getLength(); OUStringBuffer aStr; const char pHexDigs[ 17 ] = "0123456789ABCDEF"; char pBuffer[ 3 ] = " "; - sal_uInt8 nNum; sal_uInt16 nBreakStart = _nLineBreak? _nLineBreak : 1; sal_uInt16 nBreak = nBreakStart; - for( int i = 0 ; i < nCnt ; ++i ) + for (sal_Int8 n : _rSeq) { - nNum = sal_uInt8( pSerNumSeq[ i ] ); - + sal_uInt8 nNum = static_cast<sal_uInt8>(n); // exchange the buffer[0] and buffer[1], which make it consistent with Mozilla and Windows pBuffer[ 1 ] = pHexDigs[ nNum & 0x0F ]; nNum >>= 4; |