Get the style color and number just once
[LibreOffice.git] / sfx2 / source / notify / eventsupplier.cxx
blobbe47bed36cfbda3fd7f058f0a68f9fdf8fe1671e
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
20 #include <com/sun/star/beans/PropertyValue.hpp>
22 #include <com/sun/star/util/URL.hpp>
23 #include <com/sun/star/frame/Desktop.hpp>
24 #include <com/sun/star/uno/Sequence.hxx>
25 #include <com/sun/star/util/URLTransformer.hpp>
26 #include <com/sun/star/util/XURLTransformer.hpp>
27 #include <tools/urlobj.hxx>
28 #include <svl/macitem.hxx>
29 #include <sfx2/objsh.hxx>
30 #include <sfx2/evntconf.hxx>
31 #include <unotools/eventcfg.hxx>
32 #include <sal/log.hxx>
34 #include <comphelper/processfactory.hxx>
35 #include <comphelper/namedvaluecollection.hxx>
36 #include <comphelper/sequence.hxx>
37 #include <officecfg/Office/Common.hxx>
38 #include <eventsupplier.hxx>
40 #include <sfx2/app.hxx>
42 #include <sfx2/viewfrm.hxx>
43 #include <sfx2/frame.hxx>
44 #include <macroloader.hxx>
46 #include <unicode/errorcode.h>
47 #include <unicode/regex.h>
48 #include <unicode/unistr.h>
50 using namespace css;
51 using namespace ::com::sun::star;
55 // --- XNameReplace ---
57 void SAL_CALL SfxEvents_Impl::replaceByName( const OUString & aName, const uno::Any & rElement )
59 std::unique_lock aGuard( maMutex );
61 // find the event in the list and replace the data
62 auto nIndex = comphelper::findValue(maEventNames, aName);
63 if (nIndex == -1)
64 throw container::NoSuchElementException();
66 // check for correct type of the element
67 if ( !::comphelper::NamedValueCollection::canExtractFrom( rElement ) )
68 throw lang::IllegalArgumentException();
69 ::comphelper::NamedValueCollection const aEventDescriptor( rElement );
71 // create Configuration at first, creation might call this method also and that would overwrite everything
72 // we might have stored before!
73 if ( mpObjShell && !mpObjShell->IsLoading() )
75 // SetModified will end up calling into our documentEventOccured method
76 aGuard.unlock();
77 mpObjShell->SetModified();
78 aGuard.lock();
81 ::comphelper::NamedValueCollection aNormalizedDescriptor;
82 NormalizeMacro( aEventDescriptor, aNormalizedDescriptor, mpObjShell );
84 OUString sType;
85 if ( ( aNormalizedDescriptor.size() == 1 )
86 && !aNormalizedDescriptor.has( PROP_EVENT_TYPE ) //TODO
87 && ( aNormalizedDescriptor.get( PROP_EVENT_TYPE ) >>= sType )
88 && ( sType.isEmpty() )
91 // An empty event type means no binding. Therefore reset data
92 // to reflect that state.
93 // (that's for compatibility only. Nowadays, the Tools/Customize dialog should
94 // set an empty sequence to indicate the request for resetting the assignment.)
95 OSL_ENSURE( false, "legacy event assignment format detected" );
96 aNormalizedDescriptor.clear();
99 if ( !aNormalizedDescriptor.empty() )
101 maEventData[nIndex] = aNormalizedDescriptor.getPropertyValues();
103 else
105 maEventData[nIndex] = {};
110 // --- XNameAccess ---
112 uno::Any SAL_CALL SfxEvents_Impl::getByName( const OUString& aName )
114 std::unique_lock aGuard( maMutex );
116 // find the event in the list and return the data
118 auto nIndex = comphelper::findValue(maEventNames, aName);
119 if (nIndex != -1)
120 return uno::Any(maEventData[nIndex]);
122 throw container::NoSuchElementException();
126 uno::Sequence< OUString > SAL_CALL SfxEvents_Impl::getElementNames()
128 return maEventNames;
132 sal_Bool SAL_CALL SfxEvents_Impl::hasByName( const OUString& aName )
134 std::unique_lock aGuard( maMutex );
136 // find the event in the list and return the data
138 return comphelper::findValue(maEventNames, aName) != -1;
142 // --- XElementAccess ( parent of XNameAccess ) ---
144 uno::Type SAL_CALL SfxEvents_Impl::getElementType()
146 uno::Type aElementType = cppu::UnoType<uno::Sequence < beans::PropertyValue >>::get();
147 return aElementType;
151 sal_Bool SAL_CALL SfxEvents_Impl::hasElements()
153 std::unique_lock aGuard( maMutex );
155 return maEventNames.hasElements();
158 bool SfxEvents_Impl::isScriptURLAllowed(const OUString& aScriptURL)
160 std::optional<css::uno::Sequence<OUString>> allowedEvents(
161 officecfg::Office::Common::Security::Scripting::AllowedDocumentEventURLs::get());
162 // When AllowedDocumentEventURLs is empty, all event URLs are allowed
163 if (!allowedEvents)
164 return true;
166 icu::ErrorCode status;
167 const uint32_t rMatcherFlags = UREGEX_CASE_INSENSITIVE;
168 icu::UnicodeString usInput(aScriptURL.getStr());
169 const css::uno::Sequence<OUString>& rAllowedEvents = *allowedEvents;
170 for (auto const& allowedEvent : rAllowedEvents)
172 icu::UnicodeString usRegex(allowedEvent.getStr());
173 icu::RegexMatcher rmatch1(usRegex, usInput, rMatcherFlags, status);
174 if (aScriptURL.startsWith(allowedEvent) || rmatch1.matches(status))
176 return true;
180 return false;
183 void SfxEvents_Impl::Execute( css::uno::Sequence < css::beans::PropertyValue > const & aProperties, const document::DocumentEvent& aTrigger, SfxObjectShell* pDoc )
185 OUString aType;
186 OUString aScript;
187 OUString aLibrary;
188 OUString aMacroName;
190 if ( !aProperties.hasElements() )
191 return;
193 for (const auto& rProp : aProperties)
195 if ( rProp.Name == PROP_EVENT_TYPE )
196 rProp.Value >>= aType;
197 else if ( rProp.Name == PROP_SCRIPT )
198 rProp.Value >>= aScript;
199 else if ( rProp.Name == PROP_LIBRARY )
200 rProp.Value >>= aLibrary;
201 else if ( rProp.Name == PROP_MACRO_NAME )
202 rProp.Value >>= aMacroName;
203 else {
204 OSL_FAIL("Unknown property value!");
208 if (aType.isEmpty())
210 // Empty type means no active binding for the event. Just ignore do nothing.
211 return;
214 if (aScript.isEmpty())
215 return;
217 if (!isScriptURLAllowed(aScript))
218 return;
220 if (!pDoc)
221 pDoc = SfxObjectShell::Current();
223 if (pDoc && !SfxObjectShell::isScriptAccessAllowed(pDoc->GetModel()))
224 return;
226 if (aType == STAR_BASIC)
228 uno::Any aAny;
229 SfxMacroLoader::loadMacro( aScript, aAny, pDoc );
231 else if (aType == "Service" || aType == "Script")
233 util::URL aURL;
234 uno::Reference < util::XURLTransformer > xTrans( util::URLTransformer::create( ::comphelper::getProcessComponentContext() ) );
236 aURL.Complete = aScript;
237 xTrans->parseStrict( aURL );
239 bool bAllowed = !SfxObjectShell::UnTrustedScript(aURL.Complete);
241 if (bAllowed)
243 SfxViewFrame* pView = SfxViewFrame::GetFirst(pDoc);
245 uno::Reference
246 < frame::XDispatchProvider > xProv;
248 if ( pView != nullptr )
250 xProv = uno::Reference
251 < frame::XDispatchProvider > (
252 pView->GetFrame().GetFrameInterface(), uno::UNO_QUERY );
254 else
256 xProv = frame::Desktop::create( ::comphelper::getProcessComponentContext() );
259 uno::Reference < frame::XDispatch > xDisp;
260 if ( xProv.is() )
261 xDisp = xProv->queryDispatch( aURL, OUString(), 0 );
263 if ( xDisp.is() )
265 beans::PropertyValue aEventParam;
266 aEventParam.Value <<= aTrigger;
267 uno::Sequence< beans::PropertyValue > aDispatchArgs( &aEventParam, 1 );
268 xDisp->dispatch( aURL, aDispatchArgs );
272 else
274 SAL_WARN( "sfx.notify", "notifyEvent(): Unsupported event type" );
279 // --- ::document::XEventListener ---
281 void SAL_CALL SfxEvents_Impl::documentEventOccured( const document::DocumentEvent& aEvent )
283 std::unique_lock aGuard( maMutex );
285 // get the event name, find the corresponding data, execute the data
287 auto nIndex = comphelper::findValue(maEventNames, aEvent.EventName);
288 if ( nIndex == -1 )
289 return;
291 css::uno::Sequence < css::beans::PropertyValue > aEventData = maEventData[ nIndex ];
292 aGuard.unlock();
293 Execute( aEventData, aEvent, mpObjShell );
297 // --- ::lang::XEventListener ---
299 void SAL_CALL SfxEvents_Impl::disposing( const lang::EventObject& /*Source*/ )
301 std::unique_lock aGuard( maMutex );
303 if ( mxBroadcaster.is() )
305 mxBroadcaster->removeDocumentEventListener( this );
306 mxBroadcaster = nullptr;
311 SfxEvents_Impl::SfxEvents_Impl( SfxObjectShell* pShell,
312 uno::Reference< document::XDocumentEventBroadcaster > const & xBroadcaster )
314 // get the list of supported events and store it
315 if ( pShell )
316 maEventNames = pShell->GetEventNames();
317 else
318 maEventNames = rtl::Reference<GlobalEventConfig>(new GlobalEventConfig)->getElementNames();
320 maEventData.resize( maEventNames.getLength() );
322 mpObjShell = pShell;
323 mxBroadcaster = xBroadcaster;
325 if ( mxBroadcaster.is() )
326 mxBroadcaster->addDocumentEventListener( this );
330 SfxEvents_Impl::~SfxEvents_Impl()
335 std::unique_ptr<SvxMacro> SfxEvents_Impl::ConvertToMacro( const uno::Any& rElement, SfxObjectShell* pObjShell )
337 std::unique_ptr<SvxMacro> pMacro;
338 uno::Sequence < beans::PropertyValue > aProperties;
339 uno::Any aAny;
340 NormalizeMacro( rElement, aAny, pObjShell );
342 if ( aAny >>= aProperties )
344 OUString aType;
345 OUString aScriptURL;
346 OUString aLibrary;
347 OUString aMacroName;
349 if ( !aProperties.hasElements() )
350 return pMacro;
352 for (const auto& rProp : aProperties)
354 if ( rProp.Name == PROP_EVENT_TYPE )
355 rProp.Value >>= aType;
356 else if ( rProp.Name == PROP_SCRIPT )
357 rProp.Value >>= aScriptURL;
358 else if ( rProp.Name == PROP_LIBRARY )
359 rProp.Value >>= aLibrary;
360 else if ( rProp.Name == PROP_MACRO_NAME )
361 rProp.Value >>= aMacroName;
362 else {
363 OSL_FAIL("Unknown property value!");
367 // Get the type
368 ScriptType eType( STARBASIC );
369 if ( aType == STAR_BASIC )
370 eType = STARBASIC;
371 else if (aType == "Script" && !aScriptURL.isEmpty())
372 eType = EXTENDED_STYPE;
373 else if ( aType == SVX_MACRO_LANGUAGE_JAVASCRIPT )
374 eType = JAVASCRIPT;
375 else {
376 SAL_WARN( "sfx.notify", "ConvertToMacro: Unknown macro type" );
379 if ( !aMacroName.isEmpty() )
381 if ( aLibrary == "application" )
382 aLibrary = SfxGetpApp()->GetName();
383 else
384 aLibrary.clear();
385 pMacro.reset(new SvxMacro( aMacroName, aLibrary, eType ));
387 else if ( eType == EXTENDED_STYPE )
388 pMacro.reset(new SvxMacro( aScriptURL, aType ));
391 return pMacro;
394 void SfxEvents_Impl::NormalizeMacro( const uno::Any& rEvent, uno::Any& rRet, SfxObjectShell* pDoc )
396 const ::comphelper::NamedValueCollection aEventDescriptor( rEvent );
397 ::comphelper::NamedValueCollection aEventDescriptorOut;
399 NormalizeMacro( aEventDescriptor, aEventDescriptorOut, pDoc );
401 rRet <<= aEventDescriptorOut.getPropertyValues();
404 void SfxEvents_Impl::NormalizeMacro( const ::comphelper::NamedValueCollection& i_eventDescriptor,
405 ::comphelper::NamedValueCollection& o_normalizedDescriptor, SfxObjectShell* i_document )
407 SfxObjectShell* pDoc = i_document;
408 if ( !pDoc )
409 pDoc = SfxObjectShell::Current();
411 OUString aType = i_eventDescriptor.getOrDefault( PROP_EVENT_TYPE, OUString() );
412 OUString aScript = i_eventDescriptor.getOrDefault( PROP_SCRIPT, OUString() );
413 OUString aLibrary = i_eventDescriptor.getOrDefault( PROP_LIBRARY, OUString() );
414 OUString aMacroName = i_eventDescriptor.getOrDefault( PROP_MACRO_NAME, OUString() );
416 if ( !aType.isEmpty() )
417 o_normalizedDescriptor.put( PROP_EVENT_TYPE, aType );
418 if ( !aScript.isEmpty() )
419 o_normalizedDescriptor.put( PROP_SCRIPT, aScript );
421 if ( aType != STAR_BASIC )
422 return;
424 if ( !aScript.isEmpty() )
426 if ( aMacroName.isEmpty() || aLibrary.isEmpty() )
428 sal_Int32 nThirdSlashPos = aScript.indexOf( '/', 8 );
429 sal_Int32 nArgsPos = aScript.indexOf( '(' );
430 if ( ( nThirdSlashPos != -1 ) && ( nArgsPos == -1 || nThirdSlashPos < nArgsPos ) )
432 OUString aBasMgrName( INetURLObject::decode( aScript.subView( 8, nThirdSlashPos-8 ), INetURLObject::DecodeMechanism::WithCharset ) );
433 if (pDoc && aBasMgrName == ".")
434 aLibrary = pDoc->GetTitle();
435 else
436 aLibrary = SfxGetpApp()->GetName();
438 // Get the macro name
439 aMacroName = aScript.copy( nThirdSlashPos+1, nArgsPos - nThirdSlashPos - 1 );
441 else
443 SAL_WARN( "sfx.notify", "ConvertToMacro: Unknown macro url format" );
447 else if ( !aMacroName.isEmpty() )
449 aScript = "macro://";
450 if ( aLibrary != SfxGetpApp()->GetName() && aLibrary != "StarDesktop" && aLibrary != "application" )
451 aScript += ".";
452 aScript += "/" + aMacroName + "()";
454 else
455 // wrong properties
456 return;
458 if (aLibrary != "document")
460 if ( aLibrary.isEmpty() || (pDoc && ( aLibrary == pDoc->GetTitle( SFX_TITLE_APINAME ) || aLibrary == pDoc->GetTitle() )) )
461 aLibrary = "document";
462 else
463 aLibrary = "application";
466 o_normalizedDescriptor.put( PROP_SCRIPT, aScript );
467 o_normalizedDescriptor.put( PROP_LIBRARY, aLibrary );
468 o_normalizedDescriptor.put( PROP_MACRO_NAME, aMacroName );
471 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */