1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3  * This file is part of the LibreOffice project.
4  *
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/.
8  *
9  * This file incorporates work covered by the following license notice:
10  *
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 .
18  */
19 
20 #include <unotools/eventcfg.hxx>
21 #include <unotools/configmgr.hxx>
22 #include <unotools/configitem.hxx>
23 #include <com/sun/star/uno/Any.hxx>
24 #include <com/sun/star/uno/Sequence.hxx>
25 #include <com/sun/star/beans/PropertyValue.hpp>
26 #include <o3tl/enumarray.hxx>
27 #include <o3tl/enumrange.hxx>
28 #include <rtl/ref.hxx>
29 #include <sal/log.hxx>
30 
31 #include "itemholder1.hxx"
32 
33 #include <algorithm>
34 #include <unordered_map>
35 
36 using namespace ::std;
37 using namespace ::utl;
38 using namespace ::osl;
39 using namespace ::com::sun::star::uno;
40 using namespace ::com::sun::star;
41 
42 #define PATHDELIMITER "/"
43 #define SETNODE_BINDINGS "Bindings"
44 #define PROPERTYNAME_BINDINGURL "BindingURL"
45 
46 static o3tl::enumarray<GlobalEventId, const char*> pEventAsciiNames =
47 {
48 "OnStartApp",
49 "OnCloseApp",
50 "OnCreate",
51 "OnNew",
52 "OnLoadFinished",
53 "OnLoad",
54 "OnPrepareUnload",
55 "OnUnload",
56 "OnSave",
57 "OnSaveDone",
58 "OnSaveFailed",
59 "OnSaveAs",
60 "OnSaveAsDone",
61 "OnSaveAsFailed",
62 "OnCopyTo",
63 "OnCopyToDone",
64 "OnCopyToFailed",
65 "OnFocus",
66 "OnUnfocus",
67 "OnPrint",
68 "OnViewCreated",
69 "OnPrepareViewClosing",
70 "OnViewClosed",
71 "OnModifyChanged",
72 "OnTitleChanged",
73 "OnVisAreaChanged",
74 "OnModeChanged",
75 "OnStorageChanged"
76 };
77 
78 typedef std::unordered_map< OUString, OUString > EventBindingHash;
79 typedef o3tl::enumarray< GlobalEventId, OUString > SupportedEventsVector;
80 
81 class GlobalEventConfig_Impl : public utl::ConfigItem
82 {
83 private:
84     EventBindingHash m_eventBindingHash;
85     SupportedEventsVector m_supportedEvents;
86 
87     void initBindingInfo();
88 
89     virtual void ImplCommit() override;
90 
91 public:
92     GlobalEventConfig_Impl( );
93     virtual ~GlobalEventConfig_Impl( ) override;
94 
95     void            Notify( const css::uno::Sequence<OUString>& aPropertyNames) override;
96 
97     /// @throws css::lang::IllegalArgumentException
98     /// @throws css::container::NoSuchElementException
99     /// @throws css::lang::WrappedTargetException
100     /// @throws css::uno::RuntimeException
101     void replaceByName( const OUString& aName, const css::uno::Any& aElement );
102     /// @throws css::container::NoSuchElementException
103     /// @throws css::lang::WrappedTargetException
104     /// @throws css::uno::RuntimeException
105     css::uno::Any getByName( const OUString& aName );
106     /// @throws css::uno::RuntimeException
107     css::uno::Sequence< OUString > getElementNames(  );
108     /// @throws css::uno::RuntimeException
109     bool hasByName( const OUString& aName );
110     /// @throws css::uno::RuntimeException
111     static css::uno::Type const & getElementType(  );
112     /// @throws css::uno::RuntimeException
113     bool hasElements() const;
114     OUString const & GetEventName( GlobalEventId nID ) const;
115 };
116 
117 
GlobalEventConfig_Impl()118 GlobalEventConfig_Impl::GlobalEventConfig_Impl()
119     :   ConfigItem( "Office.Events/ApplicationEvents", ConfigItemMode::NONE )
120 {
121     // the supported event names
122     for (const GlobalEventId id : o3tl::enumrange<GlobalEventId>())
123         m_supportedEvents[id] = OUString::createFromAscii( pEventAsciiNames[id] );
124 
125     initBindingInfo();
126 
127 /*TODO: Not used in the moment! see Notify() ...
128     // Enable notification mechanism of our baseclass.
129     // We need it to get information about changes outside these class on our used configuration keys! */
130     Sequence<OUString> aNotifySeq { "Events" };
131     EnableNotification( aNotifySeq, true );
132 }
133 
134 //  destructor
135 
~GlobalEventConfig_Impl()136 GlobalEventConfig_Impl::~GlobalEventConfig_Impl()
137 {
138     assert(!IsModified()); // should have been committed
139 }
140 
GetEventName(GlobalEventId nIndex) const141 OUString const & GlobalEventConfig_Impl::GetEventName( GlobalEventId nIndex ) const
142 {
143     return m_supportedEvents[nIndex];
144 }
145 
146 //  public method
147 
Notify(const Sequence<OUString> &)148 void GlobalEventConfig_Impl::Notify( const Sequence< OUString >& )
149 {
150     MutexGuard aGuard( GlobalEventConfig::GetOwnStaticMutex() );
151 
152     initBindingInfo();
153 }
154 
155 //  public method
156 
ImplCommit()157 void GlobalEventConfig_Impl::ImplCommit()
158 {
159     //DF need to check it this is correct??
160     SAL_INFO("unotools", "In GlobalEventConfig_Impl::ImplCommit");
161     // clear the existing nodes
162     ClearNodeSet( SETNODE_BINDINGS );
163     Sequence< beans::PropertyValue > seqValues( 1 );
164     OUString sNode;
165     //step through the list of events
166     for(const auto& rEntry : m_eventBindingHash)
167     {
168         //no point in writing out empty bindings!
169         if(rEntry.second.isEmpty() )
170             continue;
171         sNode = SETNODE_BINDINGS PATHDELIMITER "BindingType['" +
172                 rEntry.first +
173                 "']" PATHDELIMITER PROPERTYNAME_BINDINGURL;
174         SAL_INFO("unotools", "writing binding for: " << sNode);
175         seqValues[ 0 ].Name = sNode;
176         seqValues[ 0 ].Value <<= rEntry.second;
177         //write the data to the registry
178         SetSetProperties(SETNODE_BINDINGS,seqValues);
179     }
180 }
181 
182 //  private method
183 
initBindingInfo()184 void GlobalEventConfig_Impl::initBindingInfo()
185 {
186     // Get ALL names of current existing list items in configuration!
187     const Sequence< OUString > lEventNames = GetNodeNames( SETNODE_BINDINGS, utl::ConfigNameFormat::LocalPath );
188 
189     OUString aSetNode = SETNODE_BINDINGS PATHDELIMITER;
190     OUString aCommandKey = PATHDELIMITER PROPERTYNAME_BINDINGURL;
191 
192     // Expand all keys
193     Sequence< OUString > lMacros(1);
194     for (const auto& rEventName : lEventNames )
195     {
196         lMacros[0] = aSetNode + rEventName + aCommandKey;
197         SAL_INFO("unotools", "reading binding for: " << lMacros[0]);
198         Sequence< Any > lValues = GetProperties( lMacros );
199         OUString sMacroURL;
200         if( lValues.hasElements() )
201         {
202             lValues[0] >>= sMacroURL;
203             sal_Int32 startIndex = rEventName.indexOf('\'');
204             sal_Int32 endIndex =  rEventName.lastIndexOf('\'');
205             if( startIndex >=0 && endIndex > 0 )
206             {
207                 startIndex++;
208                 OUString eventName = rEventName.copy(startIndex,endIndex-startIndex);
209                 m_eventBindingHash[ eventName ] = sMacroURL;
210             }
211         }
212     }
213 }
214 
replaceByName(const OUString & aName,const Any & aElement)215 void GlobalEventConfig_Impl::replaceByName( const OUString& aName, const Any& aElement )
216 {
217     Sequence< beans::PropertyValue > props;
218     //DF should we prepopulate the hash with a list of valid event Names?
219     if( !( aElement >>= props ) )
220     {
221         throw lang::IllegalArgumentException( OUString(),
222                 Reference< XInterface > (), 2);
223     }
224     OUString macroURL;
225     for( const auto& rProp : std::as_const(props) )
226     {
227         if ( rProp.Name == "Script" )
228             rProp.Value >>= macroURL;
229     }
230     m_eventBindingHash[ aName ] = macroURL;
231     SetModified();
232 }
233 
getByName(const OUString & aName)234 Any GlobalEventConfig_Impl::getByName( const OUString& aName )
235 {
236     Any aRet;
237     Sequence< beans::PropertyValue > props(2);
238     props[0].Name = "EventType";
239     props[0].Value <<= OUString("Script");
240     props[1].Name = "Script";
241     EventBindingHash::const_iterator it = m_eventBindingHash.find( aName );
242     if( it != m_eventBindingHash.end() )
243     {
244         props[1].Value <<= it->second;
245     }
246     else
247     {
248         // not yet accessed - is it a supported name?
249         SupportedEventsVector::iterator pos = ::std::find(
250             m_supportedEvents.begin(), m_supportedEvents.end(), aName );
251         if ( pos == m_supportedEvents.end() )
252             throw container::NoSuchElementException( aName );
253 
254         props[1].Value <<= OUString();
255     }
256     aRet <<= props;
257     return aRet;
258 }
259 
getElementNames()260 Sequence< OUString > GlobalEventConfig_Impl::getElementNames(  )
261 {
262     return uno::Sequence< OUString >(m_supportedEvents.data(), SupportedEventsVector::size());
263 }
264 
hasByName(const OUString & aName)265 bool GlobalEventConfig_Impl::hasByName( const OUString& aName )
266 {
267     if ( m_eventBindingHash.find( aName ) != m_eventBindingHash.end() )
268         return true;
269 
270     // never accessed before - is it supported in general?
271     SupportedEventsVector::iterator pos = ::std::find(
272         m_supportedEvents.begin(), m_supportedEvents.end(), aName );
273     return pos != m_supportedEvents.end();
274 }
275 
getElementType()276 Type const & GlobalEventConfig_Impl::getElementType(  )
277 {
278     //DF definitely not sure about this??
279     return cppu::UnoType<Sequence<beans::PropertyValue>>::get();
280 }
281 
hasElements() const282 bool GlobalEventConfig_Impl::hasElements() const
283 {
284     return !m_eventBindingHash.empty();
285 }
286 
287 // and now the wrapper
288 
289 //initialize static member
290 GlobalEventConfig_Impl*     GlobalEventConfig::m_pImpl = nullptr;
291 sal_Int32                   GlobalEventConfig::m_nRefCount      = 0;
292 
GlobalEventConfig()293 GlobalEventConfig::GlobalEventConfig()
294 {
295     // Global access, must be guarded (multithreading!).
296     MutexGuard aGuard( GetOwnStaticMutex() );
297     // Increase our refcount ...
298     ++m_nRefCount;
299     // ... and initialize our data container only if it not already exist!
300     if( m_pImpl == nullptr )
301     {
302         m_pImpl = new GlobalEventConfig_Impl;
303         ItemHolder1::holdConfigItem(EItem::EventConfig);
304     }
305 }
306 
~GlobalEventConfig()307 GlobalEventConfig::~GlobalEventConfig()
308 {
309     // Global access, must be guarded (multithreading!)
310     MutexGuard aGuard( GetOwnStaticMutex() );
311     // Decrease our refcount.
312     --m_nRefCount;
313     // If last instance was deleted ...
314     // we must destroy our static data container!
315     if( m_nRefCount <= 0 )
316     {
317         delete m_pImpl;
318         m_pImpl = nullptr;
319     }
320 }
321 
getEvents()322 Reference< container::XNameReplace > SAL_CALL GlobalEventConfig::getEvents()
323 {
324     MutexGuard aGuard( GetOwnStaticMutex() );
325     Reference< container::XNameReplace > ret(this);
326     return ret;
327 }
328 
replaceByName(const OUString & aName,const Any & aElement)329 void SAL_CALL GlobalEventConfig::replaceByName( const OUString& aName, const Any& aElement )
330 {
331     MutexGuard aGuard( GetOwnStaticMutex() );
332     m_pImpl->replaceByName( aName, aElement );
333 }
getByName(const OUString & aName)334 Any SAL_CALL GlobalEventConfig::getByName( const OUString& aName )
335 {
336     MutexGuard aGuard( GetOwnStaticMutex() );
337     return m_pImpl->getByName( aName );
338 }
getElementNames()339 Sequence< OUString > SAL_CALL GlobalEventConfig::getElementNames(  )
340 {
341     MutexGuard aGuard( GetOwnStaticMutex() );
342     return m_pImpl->getElementNames( );
343 }
hasByName(const OUString & aName)344 sal_Bool SAL_CALL GlobalEventConfig::hasByName( const OUString& aName )
345 {
346     MutexGuard aGuard( GetOwnStaticMutex() );
347     return m_pImpl->hasByName( aName );
348 }
getElementType()349 Type SAL_CALL GlobalEventConfig::getElementType(  )
350 {
351     MutexGuard aGuard( GetOwnStaticMutex() );
352     return GlobalEventConfig_Impl::getElementType( );
353 }
hasElements()354 sal_Bool SAL_CALL GlobalEventConfig::hasElements(  )
355 {
356     MutexGuard aGuard( GetOwnStaticMutex() );
357     return m_pImpl->hasElements( );
358 }
359 
360 namespace
361 {
362     class theGlobalEventConfigMutex : public rtl::Static<osl::Mutex, theGlobalEventConfigMutex>{};
363 }
364 
GetOwnStaticMutex()365 Mutex& GlobalEventConfig::GetOwnStaticMutex()
366 {
367     return theGlobalEventConfigMutex::get();
368 }
369 
GetEventName(GlobalEventId nIndex)370 OUString GlobalEventConfig::GetEventName( GlobalEventId nIndex )
371 {
372     if (utl::ConfigManager::IsFuzzing())
373         return OUString();
374     rtl::Reference<GlobalEventConfig> createImpl(new GlobalEventConfig);
375     return GlobalEventConfig::m_pImpl->GetEventName( nIndex );
376 }
377 
378 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
379