1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 
23 
24 // MARKER(update_precomp.py): autogen include statement, do not remove
25 #include "precompiled_unotools.hxx"
26 
27 #include <unotools/eventcfg.hxx>
28 #include <unotools/configmgr.hxx>
29 #include <unotools/configitem.hxx>
30 #include <tools/debug.hxx>
31 #include <com/sun/star/uno/Any.hxx>
32 #include <com/sun/star/uno/Sequence.hxx>
33 #include <com/sun/star/beans/PropertyValue.hpp>
34 #include <cppuhelper/weakref.hxx>
35 
36 #ifndef __SGI_STL_HASH_MAP
37 #include <hash_map>
38 #endif
39 #include <tools/urlobj.hxx>
40 #include <rtl/ustrbuf.hxx>
41 
42 #include <itemholder1.hxx>
43 
44 #include <algorithm>
45 
46 using namespace ::std					;
47 using namespace ::utl					;
48 using namespace ::rtl					;
49 using namespace ::osl					;
50 using namespace ::com::sun::star::uno	;
51 using namespace ::com::sun::star;
52 
53 #define ROOTNODE_EVENTS OUString(RTL_CONSTASCII_USTRINGPARAM("Office.Events/ApplicationEvents" ))
54 #define PATHDELIMITER OUString(RTL_CONSTASCII_USTRINGPARAM("/"))
55 #define SETNODE_BINDINGS OUString(RTL_CONSTASCII_USTRINGPARAM("Bindings" ))
56 #define PROPERTYNAME_BINDINGURL OUString(RTL_CONSTASCII_USTRINGPARAM("BindingURL"))
57 
58 const char* pEventAsciiNames[] =
59 {
60 "OnStartApp",
61 "OnCloseApp",
62 "OnCreate",
63 "OnNew",
64 "OnLoadFinished",
65 "OnLoad",
66 "OnPrepareUnload",
67 "OnUnload",
68 "OnSave",
69 "OnSaveDone",
70 "OnSaveFailed",
71 "OnSaveAs",
72 "OnSaveAsDone",
73 "OnSaveAsFailed",
74 "OnCopyTo",
75 "OnCopyToDone",
76 "OnCopyToFailed",
77 "OnFocus",
78 "OnUnfocus",
79 "OnPrint",
80 "OnViewCreated",
81 "OnPrepareViewClosing",
82 "OnViewClosed",
83 "OnModifyChanged",
84 "OnTitleChanged",
85 "OnVisAreaChanged",
86 "OnModeChanged",
87 "OnStorageChanged"
88 };
89 
GlobalEventConfig_Impl()90 GlobalEventConfig_Impl::GlobalEventConfig_Impl()
91     :   ConfigItem( ROOTNODE_EVENTS, CONFIG_MODE_IMMEDIATE_UPDATE )
92 {
93     // the supported event names
94     m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_STARTAPP] ) );
95     m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_CLOSEAPP] ) );
96     m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_DOCCREATED] ) );
97     m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_CREATEDOC] ) );
98     m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_LOADFINISHED] ) );
99     m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_OPENDOC] ) );
100     m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_PREPARECLOSEDOC] ) );
101     m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_CLOSEDOC] ) );
102     m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_SAVEDOC] ) );
103     m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_SAVEDOCDONE] ) );
104     m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_SAVEDOCFAILED] ) );
105     m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_SAVEASDOC] ) );
106     m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_SAVEASDOCDONE] ) );
107     m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_SAVEASDOCFAILED] ) );
108     m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_SAVETODOC] ) );
109     m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_SAVETODOCDONE] ) );
110     m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_SAVETODOCFAILED] ) );
111     m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_ACTIVATEDOC] ) );
112     m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_DEACTIVATEDOC] ) );
113     m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_PRINTDOC] ) );
114     m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_VIEWCREATED] ) );
115     m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_PREPARECLOSEVIEW] ) );
116     m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_CLOSEVIEW] ) );
117     m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_MODIFYCHANGED] ) );
118     m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_TITLECHANGED] ) );
119     m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_VISAREACHANGED] ) );
120     m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_MODECHANGED] ) );
121     m_supportedEvents.push_back(::rtl::OUString::createFromAscii( pEventAsciiNames[STR_EVENT_STORAGECHANGED] ) );
122 
123     initBindingInfo();
124 
125 /*TODO: Not used in the moment! see Notify() ...
126 	// Enable notification mechanism of our baseclass.
127 	// We need it to get information about changes outside these class on our used configuration keys! */
128     Sequence< OUString > aNotifySeq( 1 );
129     aNotifySeq[0] = OUString( RTL_CONSTASCII_USTRINGPARAM( "Events" ));
130     EnableNotification( aNotifySeq, sal_True );
131 }
132 
133 //*****************************************************************************************************************
134 //	destructor
135 //*****************************************************************************************************************
~GlobalEventConfig_Impl()136 GlobalEventConfig_Impl::~GlobalEventConfig_Impl()
137 {
138 	// We must save our current values .. if user forget it!
139 	if( IsModified() == sal_True )
140 	{
141 		Commit();
142 	}
143 }
144 
GetEventName(sal_Int32 nIndex)145 ::rtl::OUString GlobalEventConfig_Impl::GetEventName( sal_Int32 nIndex )
146 {
147 	if ( nIndex < (sal_Int32) m_supportedEvents.size() )
148 		return m_supportedEvents[nIndex];
149 	else
150 		return rtl::OUString();
151 }
152 
153 //*****************************************************************************************************************
154 //	public method
155 //*****************************************************************************************************************
Notify(const Sequence<OUString> &)156 void GlobalEventConfig_Impl::Notify( const Sequence< OUString >& )
157 {
158     MutexGuard aGuard( GlobalEventConfig::GetOwnStaticMutex() );
159 
160     initBindingInfo();
161 
162     // dont forget to update all existing frames and her might cached dispatch objects!
163     // But look for already killed frames. We hold weak references instead of hard ones ...
164     for (FrameVector::const_iterator pIt  = m_lFrames.begin();
165                                         pIt != m_lFrames.end()  ;
166                                       ++pIt                     )
167     {
168         ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame(pIt->get(), ::com::sun::star::uno::UNO_QUERY);
169         if (xFrame.is())
170             xFrame->contextChanged();
171     }
172 }
173 
174 //*****************************************************************************************************************
175 //	public method
176 //*****************************************************************************************************************
Commit()177 void GlobalEventConfig_Impl::Commit()
178 {
179     //DF need to check it this is correct??
180     OSL_TRACE("In GlobalEventConfig_Impl::Commit");
181     EventBindingHash::const_iterator it = m_eventBindingHash.begin();
182     EventBindingHash::const_iterator it_end = m_eventBindingHash.end();
183     // clear the existing nodes
184     ClearNodeSet( SETNODE_BINDINGS );
185     Sequence< beans::PropertyValue > seqValues( 1 );
186     OUString sNode;
187     static const OUString sPrefix(SETNODE_BINDINGS + PATHDELIMITER + OUString::createFromAscii("BindingType['"));
188     static const OUString sPostfix(OUString::createFromAscii("']") + PATHDELIMITER + PROPERTYNAME_BINDINGURL);
189     //step through the list of events
190     for(int i=0;it!=it_end;++it,++i)
191     {
192         //no point in writing out empty bindings!
193         if(it->second.getLength() == 0 )
194             continue;
195         sNode = sPrefix + it->first + sPostfix;
196         OSL_TRACE("writing binding for: %s",::rtl::OUStringToOString(sNode , RTL_TEXTENCODING_ASCII_US ).pData->buffer);
197         seqValues[ 0 ].Name = sNode;
198         seqValues[ 0 ].Value <<= it->second;
199         //write the data to the registry
200         SetSetProperties(SETNODE_BINDINGS,seqValues);
201     }
202 }
203 
204 //*****************************************************************************************************************
205 //  public method
206 //*****************************************************************************************************************
EstablishFrameCallback(const::com::sun::star::uno::Reference<::com::sun::star::frame::XFrame> & xFrame)207 void GlobalEventConfig_Impl::EstablishFrameCallback(const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame)
208 {
209     // check if frame already exists inside list
210     // ignore double registrations
211     // every frame must be notified one times only!
212     ::com::sun::star::uno::WeakReference< ::com::sun::star::frame::XFrame > xWeak(xFrame);
213     FrameVector::const_iterator pIt = ::std::find(m_lFrames.begin(), m_lFrames.end(), xWeak);
214     if (pIt == m_lFrames.end())
215         m_lFrames.push_back(xWeak);
216 }
217 
218 //*****************************************************************************************************************
219 //	private method
220 //*****************************************************************************************************************
initBindingInfo()221 void GlobalEventConfig_Impl::initBindingInfo()
222 {
223 	// Get ALL names of current existing list items in configuration!
224     Sequence< OUString > lEventNames      = GetNodeNames( SETNODE_BINDINGS, utl::CONFIG_NAME_LOCAL_PATH );
225 
226 	OUString aSetNode( SETNODE_BINDINGS );
227 	aSetNode += PATHDELIMITER;
228 
229 	OUString aCommandKey( PATHDELIMITER );
230 	aCommandKey += PROPERTYNAME_BINDINGURL;
231 
232 	// Expand all keys
233     Sequence< OUString > lMacros(1);
234 	for (sal_Int32 i=0; i<lEventNames.getLength(); ++i )
235 	{
236 		OUStringBuffer aBuffer( 32 );
237 		aBuffer.append( aSetNode );
238 		aBuffer.append( lEventNames[i] );
239 		aBuffer.append( aCommandKey );
240 		lMacros[0] = aBuffer.makeStringAndClear();
241         OSL_TRACE("reading binding for: %s",::rtl::OUStringToOString(lMacros[0] , RTL_TEXTENCODING_ASCII_US ).pData->buffer);
242         Sequence< Any > lValues = GetProperties( lMacros );
243         OUString sMacroURL;
244         if( lValues.getLength() > 0 )
245         {
246             lValues[0] >>= sMacroURL;
247             sal_Int32 startIndex = lEventNames[i].indexOf('\'');
248             sal_Int32 endIndex =  lEventNames[i].lastIndexOf('\'');
249             if( startIndex >=0 && endIndex > 0 )
250             {
251                 startIndex++;
252                 OUString eventName = lEventNames[i].copy(startIndex,endIndex-startIndex);
253                 m_eventBindingHash[ eventName ] = sMacroURL;
254             }
255         }
256 	}
257 }
258 
getEvents()259 Reference< container::XNameReplace > SAL_CALL GlobalEventConfig_Impl::getEvents() throw (::com::sun::star::uno::RuntimeException)
260 {
261     //how to return this object as an XNameReplace?
262     Reference< container::XNameReplace > ret;
263     return ret;
264 }
265 
replaceByName(const OUString & aName,const Any & aElement)266 void SAL_CALL GlobalEventConfig_Impl::replaceByName( const OUString& aName, const Any& aElement ) throw (lang::IllegalArgumentException, container::NoSuchElementException, lang::WrappedTargetException, RuntimeException)
267 {
268     Sequence< beans::PropertyValue > props;
269     //DF should we prepopulate the hash with a list of valid event Names?
270     if( sal_False == ( aElement >>= props ) )
271     {
272         throw lang::IllegalArgumentException( OUString(),
273                 Reference< XInterface > (), 2);
274     }
275     OUString macroURL;
276     sal_Int32 nPropCount = props.getLength();
277     for( sal_Int32 index = 0 ; index < nPropCount ; ++index )
278     {
279         if ( props[ index ].Name.compareToAscii( "Script" ) == 0 )
280             props[ index ].Value >>= macroURL;
281     }
282     m_eventBindingHash[ aName ] = macroURL;
283     SetModified();
284 }
285 
getByName(const OUString & aName)286 Any SAL_CALL GlobalEventConfig_Impl::getByName( const OUString& aName ) throw (container::NoSuchElementException, lang::WrappedTargetException, RuntimeException)
287 {
288     Any aRet;
289     Sequence< beans::PropertyValue > props(2);
290     props[0].Name = OUString::createFromAscii("EventType");
291     props[0].Value <<= OUString::createFromAscii("Script");
292     props[1].Name = OUString::createFromAscii("Script");
293     EventBindingHash::const_iterator it = m_eventBindingHash.find( aName );
294     if( it != m_eventBindingHash.end() )
295     {
296         props[1].Value <<= it->second;
297     }
298     else
299     {
300         // not yet accessed - is it a supported name?
301         SupportedEventsVector::const_iterator pos = ::std::find(
302             m_supportedEvents.begin(), m_supportedEvents.end(), aName );
303         if ( pos == m_supportedEvents.end() )
304             throw container::NoSuchElementException( aName, NULL );
305 
306         props[1].Value <<= OUString();
307     }
308     aRet <<= props;
309     return aRet;
310 }
311 
getElementNames()312 Sequence< OUString > SAL_CALL GlobalEventConfig_Impl::getElementNames(  ) throw (RuntimeException)
313 {
314     const ::rtl::OUString* pRet = m_supportedEvents.empty() ? NULL : &m_supportedEvents[0];
315 	return uno::Sequence< ::rtl::OUString >(pRet, m_supportedEvents.size());
316 }
317 
hasByName(const OUString & aName)318 sal_Bool SAL_CALL GlobalEventConfig_Impl::hasByName( const OUString& aName ) throw (RuntimeException)
319 {
320     if ( m_eventBindingHash.find( aName ) != m_eventBindingHash.end() )
321         return sal_True;
322 
323     // never accessed before - is it supported in general?
324     SupportedEventsVector::const_iterator pos = ::std::find(
325         m_supportedEvents.begin(), m_supportedEvents.end(), aName );
326     if ( pos != m_supportedEvents.end() )
327         return sal_True;
328 
329     return sal_False;
330 }
331 
getElementType()332 Type SAL_CALL GlobalEventConfig_Impl::getElementType(  ) throw (RuntimeException)
333 {
334     //DF definitly not sure about this??
335     return ::getCppuType((const Sequence<beans::PropertyValue>*)0);
336 }
337 
hasElements()338 sal_Bool SAL_CALL GlobalEventConfig_Impl::hasElements(  ) throw (RuntimeException)
339 {
340     return ( m_eventBindingHash.empty() );
341 }
342 
343 // and now the wrapper
344 
345 
346 //initialize static member
347 GlobalEventConfig_Impl*     GlobalEventConfig::m_pImpl = NULL  ;
348 sal_Int32                   GlobalEventConfig::m_nRefCount      = 0     ;
349 
GlobalEventConfig()350 GlobalEventConfig::GlobalEventConfig()
351 {
352     // Global access, must be guarded (multithreading!).
353     MutexGuard aGuard( GetOwnStaticMutex() );
354 	// Increase our refcount ...
355 	++m_nRefCount;
356 	// ... and initialize our data container only if it not already exist!
357     if( m_pImpl == NULL )
358 	{
359         m_pImpl = new GlobalEventConfig_Impl;
360         ItemHolder1::holdConfigItem(E_EVENTCFG);
361 	}
362 }
363 
~GlobalEventConfig()364 GlobalEventConfig::~GlobalEventConfig()
365 {
366     // Global access, must be guarded (multithreading!)
367     MutexGuard aGuard( GetOwnStaticMutex() );
368 	// Decrease our refcount.
369 	--m_nRefCount;
370 	// If last instance was deleted ...
371 	// we must destroy our static data container!
372     if( m_nRefCount <= 0 )
373 	{
374 		delete m_pImpl;
375 		m_pImpl = NULL;
376 	}
377 }
378 
EstablishFrameCallback(const::com::sun::star::uno::Reference<::com::sun::star::frame::XFrame> & xFrame)379 void GlobalEventConfig::EstablishFrameCallback(const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame)
380 {
381     MutexGuard aGuard( GetOwnStaticMutex() );
382     m_pImpl->EstablishFrameCallback( xFrame );
383 }
384 
getEvents()385 Reference< container::XNameReplace > SAL_CALL GlobalEventConfig::getEvents() throw (::com::sun::star::uno::RuntimeException)
386 {
387     MutexGuard aGuard( GetOwnStaticMutex() );
388     Reference< container::XNameReplace > ret(this);
389     return ret;
390 }
391 
replaceByName(const OUString & aName,const Any & aElement)392 void SAL_CALL GlobalEventConfig::replaceByName( const OUString& aName, const Any& aElement ) throw (lang::IllegalArgumentException, container::NoSuchElementException, lang::WrappedTargetException, RuntimeException)
393 {
394     MutexGuard aGuard( GetOwnStaticMutex() );
395     m_pImpl->replaceByName( aName, aElement );
396 }
getByName(const OUString & aName)397 Any SAL_CALL GlobalEventConfig::getByName( const OUString& aName ) throw (container::NoSuchElementException, lang::WrappedTargetException, RuntimeException)
398 {
399     MutexGuard aGuard( GetOwnStaticMutex() );
400     return m_pImpl->getByName( aName );
401 }
getElementNames()402 Sequence< OUString > SAL_CALL GlobalEventConfig::getElementNames(  ) throw (RuntimeException)
403 {
404     MutexGuard aGuard( GetOwnStaticMutex() );
405     return m_pImpl->getElementNames( );
406 }
hasByName(const OUString & aName)407 sal_Bool SAL_CALL GlobalEventConfig::hasByName( const OUString& aName ) throw (RuntimeException)
408 {
409     MutexGuard aGuard( GetOwnStaticMutex() );
410     return m_pImpl->hasByName( aName );
411 }
getElementType()412 Type SAL_CALL GlobalEventConfig::getElementType(  ) throw (RuntimeException)
413 {
414     MutexGuard aGuard( GetOwnStaticMutex() );
415     return m_pImpl->getElementType( );
416 }
hasElements()417 sal_Bool SAL_CALL GlobalEventConfig::hasElements(  ) throw (RuntimeException)
418 {
419     MutexGuard aGuard( GetOwnStaticMutex() );
420     return m_pImpl->hasElements( );
421 }
422 
GetOwnStaticMutex()423 Mutex& GlobalEventConfig::GetOwnStaticMutex()
424 {
425 	// Initialize static mutex only for one time!
426     static Mutex* pMutex = NULL;
427 	// If these method first called (Mutex not already exist!) ...
428     if( pMutex == NULL )
429     {
430 		// ... we must create a new one. Protect following code with
431         // the global mutex -
432 		// It must be - we create a static variable!
433         MutexGuard aGuard( Mutex::getGlobalMutex() );
434 		// We must check our pointer again - because it can be that
435         // another instance of our class will be faster then these!
436         if( pMutex == NULL )
437         {
438 			// Create the new mutex and set it for return on static variable.
439             static Mutex aMutex;
440             pMutex = &aMutex;
441         }
442     }
443 	// Return new created or already existing mutex object.
444     return *pMutex;
445 }
446 
GetEventName(sal_Int32 nIndex)447 ::rtl::OUString GlobalEventConfig::GetEventName( sal_Int32 nIndex )
448 {
449 	return GlobalEventConfig().m_pImpl->GetEventName( nIndex );
450 }
451 
452