xref: /trunk/main/canvas/source/factory/cf_service.cxx (revision 91144cd0085a7583d2099b982122deb2184ab956)
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_canvas.hxx"
26 
27 #include <osl/mutex.hxx>
28 #include <osl/process.h>
29 #include <cppuhelper/implementationentry.hxx>
30 #include <cppuhelper/factory.hxx>
31 #include <cppuhelper/implbase3.hxx>
32 #include <vcl/configsettings.hxx>
33 
34 #include <com/sun/star/uno/XComponentContext.hpp>
35 #include <com/sun/star/lang/XServiceInfo.hpp>
36 #include <com/sun/star/lang/XSingleComponentFactory.hpp>
37 #include <com/sun/star/container/XContentEnumerationAccess.hpp>
38 #include <com/sun/star/container/XNameAccess.hpp>
39 #include <com/sun/star/container/XHierarchicalNameAccess.hpp>
40 #include <com/sun/star/beans/PropertyValue.hpp>
41 
42 #include <boost/bind.hpp>
43 #include <vector>
44 #include <utility>
45 #include <functional>
46 #include <algorithm>
47 
48 #define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) )
49 #define ARLEN(x) (sizeof (x) / sizeof *(x))
50 
51 
52 using namespace ::com::sun::star;
53 using namespace ::com::sun::star::uno;
54 using ::rtl::OUString;
55 
56 namespace
57 {
58 
getImplName()59 OUString SAL_CALL getImplName()
60 {
61     return OUSTR("com.sun.star.comp.rendering.CanvasFactory");
62 }
63 
getSuppServices()64 Sequence<OUString> SAL_CALL getSuppServices()
65 {
66     OUString name = OUSTR("com.sun.star.rendering.CanvasFactory");
67     return Sequence<OUString>(&name, 1);
68 }
69 
70 //==============================================================================
71 class CanvasFactory
72     : public ::cppu::WeakImplHelper3< lang::XServiceInfo,
73                                       lang::XMultiComponentFactory,
74                                       lang::XMultiServiceFactory >
75 {
76     typedef std::pair<OUString,Sequence<OUString> > AvailPair;
77     typedef std::pair<OUString,OUString>            CachePair;
78     typedef std::vector< AvailPair >                AvailVector;
79     typedef std::vector< CachePair >                CacheVector;
80 
81 
82     mutable ::osl::Mutex              m_mutex;
83     Reference<XComponentContext>      m_xContext;
84     Reference<container::XNameAccess> m_xCanvasConfigNameAccess;
85     AvailVector                       m_aAvailableImplementations;
86     AvailVector                       m_aAcceleratedImplementations;
87     AvailVector                       m_aAAImplementations;
88     mutable CacheVector               m_aCachedImplementations;
89     mutable bool                      m_bCacheHasForcedLastImpl;
90     mutable bool                      m_bCacheHasUseAcceleratedEntry;
91     mutable bool                      m_bCacheHasUseAAEntry;
92 
93     void checkConfigFlag( bool& r_bFlag,
94                           bool& r_CacheFlag,
95                           const OUString& nodeName ) const;
96     Reference<XInterface> use(
97         OUString const & serviceName,
98         Sequence<Any> const & args,
99         Reference<XComponentContext> const & xContext ) const;
100     Reference<XInterface> lookupAndUse(
101         OUString const & serviceName, Sequence<Any> const & args,
102         Reference<XComponentContext> const & xContext ) const;
103 
104 public:
105     virtual ~CanvasFactory();
106     CanvasFactory( Reference<XComponentContext> const & xContext );
107 
108     // XServiceInfo
109     virtual OUString SAL_CALL getImplementationName();
110     virtual sal_Bool SAL_CALL supportsService( OUString const & serviceName );
111     virtual Sequence<OUString> SAL_CALL getSupportedServiceNames();
112 
113     // XMultiComponentFactory
114     virtual Sequence<OUString> SAL_CALL getAvailableServiceNames();
115     virtual Reference<XInterface> SAL_CALL createInstanceWithContext(
116         OUString const & name,
117         Reference<XComponentContext> const & xContext );
118     virtual Reference<XInterface> SAL_CALL
119     createInstanceWithArgumentsAndContext(
120         OUString const & name,
121         Sequence<Any> const & args,
122         Reference<XComponentContext> const & xContext );
123 
124     // XMultiServiceFactory
125     virtual Reference<XInterface> SAL_CALL createInstance(
126         OUString const & name );
127     virtual Reference<XInterface> SAL_CALL createInstanceWithArguments(
128         OUString const & name, Sequence<Any> const & args );
129 };
130 
CanvasFactory(Reference<XComponentContext> const & xContext)131 CanvasFactory::CanvasFactory( Reference<XComponentContext> const & xContext ) :
132     m_mutex(),
133     m_xContext(xContext),
134     m_xCanvasConfigNameAccess(),
135     m_aAvailableImplementations(),
136     m_aAcceleratedImplementations(),
137     m_aAAImplementations(),
138     m_aCachedImplementations(),
139     m_bCacheHasForcedLastImpl(),
140     m_bCacheHasUseAcceleratedEntry(),
141     m_bCacheHasUseAAEntry()
142 {
143     try
144     {
145         // read out configuration for preferred services:
146         Reference<lang::XMultiServiceFactory> xConfigProvider(
147             m_xContext->getServiceManager()->createInstanceWithContext(
148                 OUSTR("com.sun.star.configuration.ConfigurationProvider"),
149                 m_xContext ), UNO_QUERY_THROW );
150 
151         Any propValue(
152             makeAny( beans::PropertyValue(
153                          OUSTR("nodepath"), -1,
154                          makeAny( OUSTR("/org.openoffice.Office.Canvas") ),
155                          beans::PropertyState_DIRECT_VALUE ) ) );
156 
157         m_xCanvasConfigNameAccess.set(
158             xConfigProvider->createInstanceWithArguments(
159                 OUSTR("com.sun.star.configuration.ConfigurationAccess"),
160                 Sequence<Any>( &propValue, 1 ) ),
161             UNO_QUERY_THROW );
162 
163         propValue = makeAny(
164             beans::PropertyValue(
165                 OUSTR("nodepath"), -1,
166                 makeAny( OUSTR("/org.openoffice.Office.Canvas/CanvasServiceList") ),
167                 beans::PropertyState_DIRECT_VALUE ) );
168 
169         Reference<container::XNameAccess> xNameAccess(
170             xConfigProvider->createInstanceWithArguments(
171                 OUSTR("com.sun.star.configuration.ConfigurationAccess"),
172                 Sequence<Any>( &propValue, 1 ) ), UNO_QUERY_THROW );
173         Reference<container::XHierarchicalNameAccess> xHierarchicalNameAccess(
174             xNameAccess, UNO_QUERY_THROW);
175 
176         Sequence<OUString> serviceNames = xNameAccess->getElementNames();
177         const OUString* pCurr = serviceNames.getConstArray();
178         const OUString* const pEnd = pCurr + serviceNames.getLength();
179         while( pCurr != pEnd )
180         {
181             Reference<container::XNameAccess> xEntryNameAccess(
182                 xHierarchicalNameAccess->getByHierarchicalName(*pCurr),
183                 UNO_QUERY );
184 
185             if( xEntryNameAccess.is() )
186             {
187                 Sequence<OUString> implementationList;
188                 if( (xEntryNameAccess->getByName( OUSTR("PreferredImplementations") ) >>= implementationList) )
189                     m_aAvailableImplementations.push_back( std::make_pair(*pCurr,implementationList) );
190                 if( (xEntryNameAccess->getByName( OUSTR("AcceleratedImplementations") ) >>= implementationList) )
191                     m_aAcceleratedImplementations.push_back( std::make_pair(*pCurr,implementationList) );
192                 if( (xEntryNameAccess->getByName( OUSTR("AntialiasingImplementations") ) >>= implementationList) )
193                     m_aAAImplementations.push_back( std::make_pair(*pCurr,implementationList) );
194             }
195 
196             ++pCurr;
197         }
198     }
199     catch (RuntimeException &)
200     {
201         throw;
202     }
203     catch (Exception&)
204     {
205     }
206 
207     if( m_aAvailableImplementations.empty() )
208     {
209         // Ugh. Looks like configuration is borked. Fake minimal
210         // setup.
211         Sequence<OUString> aServices(1);
212         aServices[0] = OUSTR("com.sun.star.comp.rendering.Canvas.VCL");
213         m_aAvailableImplementations.push_back( std::make_pair(OUSTR("com.sun.star.rendering.Canvas"),
214                                                               aServices) );
215 
216         aServices[0] = OUSTR("com.sun.star.comp.rendering.SpriteCanvas.VCL");
217         m_aAvailableImplementations.push_back( std::make_pair(OUSTR("com.sun.star.rendering.SpriteCanvas"),
218                                                               aServices) );
219     }
220 }
221 
~CanvasFactory()222 CanvasFactory::~CanvasFactory()
223 {
224 }
225 
226 //------------------------------------------------------------------------------
create(Reference<XComponentContext> const & xContext)227 Reference<XInterface> create( Reference<XComponentContext> const & xContext )
228 {
229     return static_cast< ::cppu::OWeakObject * >(
230         new CanvasFactory( xContext ) );
231 }
232 
233 // XServiceInfo
234 //______________________________________________________________________________
getImplementationName()235 OUString CanvasFactory::getImplementationName()
236 {
237     return getImplName();
238 }
239 
240 //______________________________________________________________________________
supportsService(OUString const & serviceName)241 sal_Bool CanvasFactory::supportsService( OUString const & serviceName )
242 {
243     return serviceName.equals(getSuppServices()[0]);
244 }
245 
246 //______________________________________________________________________________
getSupportedServiceNames()247 Sequence<OUString> CanvasFactory::getSupportedServiceNames()
248 {
249     return getSuppServices();
250 }
251 
252 // XMultiComponentFactory
253 //______________________________________________________________________________
getAvailableServiceNames()254 Sequence<OUString> CanvasFactory::getAvailableServiceNames()
255 {
256     Sequence<OUString> aServiceNames(m_aAvailableImplementations.size());
257     std::transform(m_aAvailableImplementations.begin(),
258                    m_aAvailableImplementations.end(),
259                    aServiceNames.getArray(),
260                    std::select1st<AvailPair>());
261     return aServiceNames;
262 }
263 
264 //______________________________________________________________________________
createInstanceWithContext(OUString const & name,Reference<XComponentContext> const & xContext)265 Reference<XInterface> CanvasFactory::createInstanceWithContext(
266     OUString const & name, Reference<XComponentContext> const & xContext )
267 {
268     return createInstanceWithArgumentsAndContext(
269         name, Sequence<Any>(), xContext );
270 }
271 
272 //______________________________________________________________________________
use(OUString const & serviceName,Sequence<Any> const & args,Reference<XComponentContext> const & xContext) const273 Reference<XInterface> CanvasFactory::use(
274     OUString const & serviceName,
275     Sequence<Any> const & args,
276     Reference<XComponentContext> const & xContext ) const
277 {
278     try {
279         return m_xContext->getServiceManager()->createInstanceWithArgumentsAndContext(
280             serviceName, args, xContext);
281     }
282     catch (RuntimeException &)
283     {
284         throw;
285     }
286     catch (Exception &)
287     {
288         return Reference<XInterface>();
289     }
290 }
291 
292 //______________________________________________________________________________
checkConfigFlag(bool & r_bFlag,bool & r_CacheFlag,const OUString & nodeName) const293 void CanvasFactory::checkConfigFlag( bool& r_bFlag,
294                                      bool& r_CacheFlag,
295                                      const OUString& nodeName ) const
296 {
297     if( m_xCanvasConfigNameAccess.is() )
298     {
299         m_xCanvasConfigNameAccess->getByName( nodeName ) >>= r_bFlag;
300 
301         if( r_CacheFlag != r_bFlag )
302         {
303             // cache is invalid, because of different order of
304             // elements
305             r_CacheFlag = r_bFlag;
306             m_aCachedImplementations.clear();
307         }
308     }
309 }
310 
311 //______________________________________________________________________________
lookupAndUse(OUString const & serviceName,Sequence<Any> const & args,Reference<XComponentContext> const & xContext) const312 Reference<XInterface> CanvasFactory::lookupAndUse(
313     OUString const & serviceName, Sequence<Any> const & args,
314     Reference<XComponentContext> const & xContext ) const
315 {
316     ::osl::MutexGuard guard(m_mutex);
317 
318     // forcing last entry from impl list, if config flag set
319     bool bForceLastEntry(false);
320     checkConfigFlag( bForceLastEntry,
321                      m_bCacheHasForcedLastImpl,
322                      OUSTR("ForceSafeServiceImpl") );
323 
324     // use anti-aliasing canvas, if config flag set (or not existing)
325     bool bUseAAEntry(true);
326     checkConfigFlag( bUseAAEntry,
327                      m_bCacheHasUseAAEntry,
328                      OUSTR("UseAntialiasingCanvas") );
329 
330     // use accelerated canvas, if config flag set (or not existing)
331     bool bUseAcceleratedEntry(true);
332     checkConfigFlag( bUseAcceleratedEntry,
333                      m_bCacheHasUseAcceleratedEntry,
334                      OUSTR("UseAcceleratedCanvas") );
335 
336     // try to reuse last working implementation for given service name
337     const CacheVector::iterator aEnd(m_aCachedImplementations.end());
338     CacheVector::iterator aMatch;
339     if( (aMatch=std::find_if(m_aCachedImplementations.begin(),
340                              aEnd,
341                              boost::bind(&OUString::equals,
342                                          boost::cref(serviceName),
343                                          boost::bind(
344                                              std::select1st<CachePair>(),
345                                              _1)))) != aEnd )
346     {
347         Reference<XInterface> xCanvas( use( aMatch->second, args, xContext ) );
348         if(xCanvas.is())
349             return xCanvas;
350     }
351 
352     // lookup in available service list
353     const AvailVector::const_iterator aAvailEnd(m_aAvailableImplementations.end());
354     AvailVector::const_iterator aAvailImplsMatch;
355     if( (aAvailImplsMatch=std::find_if(m_aAvailableImplementations.begin(),
356                                        aAvailEnd,
357                                        boost::bind(&OUString::equals,
358                                                    boost::cref(serviceName),
359                                                    boost::bind(
360                                                        std::select1st<AvailPair>(),
361                                                        _1)))) == aAvailEnd )
362     {
363         return Reference<XInterface>();
364     }
365 
366     const AvailVector::const_iterator aAAEnd(m_aAAImplementations.end());
367     AvailVector::const_iterator aAAImplsMatch;
368     if( (aAAImplsMatch=std::find_if(m_aAAImplementations.begin(),
369                                     aAAEnd,
370                                     boost::bind(&OUString::equals,
371                                                 boost::cref(serviceName),
372                                                 boost::bind(
373                                                     std::select1st<AvailPair>(),
374                                                     _1)))) == aAAEnd )
375     {
376         return Reference<XInterface>();
377     }
378 
379     const AvailVector::const_iterator aAccelEnd(m_aAcceleratedImplementations.end());
380     AvailVector::const_iterator aAccelImplsMatch;
381     if( (aAccelImplsMatch=std::find_if(m_aAcceleratedImplementations.begin(),
382                                        aAccelEnd,
383                                        boost::bind(&OUString::equals,
384                                                    boost::cref(serviceName),
385                                                    boost::bind(
386                                                        std::select1st<AvailPair>(),
387                                                        _1)))) == aAccelEnd )
388     {
389         return Reference<XInterface>();
390     }
391 
392     const Sequence<OUString> aPreferredImpls( aAvailImplsMatch->second );
393     const OUString* pCurrImpl = aPreferredImpls.getConstArray();
394     const OUString* const pEndImpl = pCurrImpl + aPreferredImpls.getLength();
395 
396     const Sequence<OUString> aAAImpls( aAAImplsMatch->second );
397     const OUString* const pFirstAAImpl = aAAImpls.getConstArray();
398     const OUString* const pEndAAImpl = pFirstAAImpl + aAAImpls.getLength();
399 
400     const Sequence<OUString> aAccelImpls( aAccelImplsMatch->second );
401     const OUString* const pFirstAccelImpl = aAccelImpls.getConstArray();
402     const OUString* const pEndAccelImpl = pFirstAccelImpl + aAccelImpls.getLength();
403 
404     // force last entry from impl list, if config flag set
405     if( bForceLastEntry )
406         pCurrImpl = pEndImpl-1;
407 
408     while( pCurrImpl != pEndImpl )
409     {
410         const OUString aCurrName(pCurrImpl->trim());
411 
412         // check whether given canvas service is listed in the
413         // sequence of "accelerated canvas implementations"
414         const bool bIsAcceleratedImpl(
415             std::find_if(pFirstAccelImpl,
416                          pEndAccelImpl,
417                          boost::bind(&OUString::equals,
418                                      boost::cref(aCurrName),
419                                      boost::bind(
420                                          &OUString::trim,
421                                          _1))) != pEndAccelImpl );
422 
423         // check whether given canvas service is listed in the
424         // sequence of "antialiasing canvas implementations"
425         const bool bIsAAImpl(
426             std::find_if(pFirstAAImpl,
427                          pEndAAImpl,
428                          boost::bind(&OUString::equals,
429                                      boost::cref(aCurrName),
430                                      boost::bind(
431                                          &OUString::trim,
432                                          _1))) != pEndAAImpl );
433 
434         // try to instantiate canvas *only* if either accel and AA
435         // property match preference, *or*, if there's a mismatch, only
436         // go for a less capable canvas (that effectively let those
437         // pour canvas impls still work as fallbacks, should an
438         // accelerated/AA one fail). Property implies configuration:
439         // http://en.wikipedia.org/wiki/Truth_table#Logical_implication
440         if( (!bIsAAImpl || bUseAAEntry) && (!bIsAcceleratedImpl || bUseAcceleratedEntry) )
441         {
442             Reference<XInterface> xCanvas(
443                 use( pCurrImpl->trim(), args, xContext ) );
444 
445             if(xCanvas.is())
446             {
447                 if( aMatch != aEnd )
448                 {
449                     // cache entry exists, replace dysfunctional
450                     // implementation name
451                     aMatch->second = pCurrImpl->trim();
452                 }
453                 else
454                 {
455                     // new service name, add new cache entry
456                     m_aCachedImplementations.push_back(std::make_pair(serviceName,
457                                                                       pCurrImpl->trim()));
458                 }
459 
460                 return xCanvas;
461             }
462         }
463 
464         ++pCurrImpl;
465     }
466 
467     return Reference<XInterface>();
468 }
469 
470 //______________________________________________________________________________
createInstanceWithArgumentsAndContext(OUString const & preferredOne,Sequence<Any> const & args,Reference<XComponentContext> const & xContext)471 Reference<XInterface> CanvasFactory::createInstanceWithArgumentsAndContext(
472     OUString const & preferredOne, Sequence<Any> const & args,
473     Reference<XComponentContext> const & xContext )
474 {
475     Reference<XInterface> xCanvas(
476         lookupAndUse( preferredOne, args, xContext ) );
477     if(xCanvas.is())
478         return xCanvas;
479 
480     // last resort: try service name directly
481     return use( preferredOne, args, xContext );
482 }
483 
484 // XMultiServiceFactory
485 //______________________________________________________________________________
createInstance(OUString const & name)486 Reference<XInterface> CanvasFactory::createInstance( OUString const & name )
487 {
488     return createInstanceWithArgumentsAndContext(
489         name, Sequence<Any>(), m_xContext );
490 }
491 
492 //______________________________________________________________________________
createInstanceWithArguments(OUString const & name,Sequence<Any> const & args)493 Reference<XInterface> CanvasFactory::createInstanceWithArguments(
494     OUString const & name, Sequence<Any> const & args )
495 {
496     return createInstanceWithArgumentsAndContext(
497         name, args, m_xContext );
498 }
499 
500 const ::cppu::ImplementationEntry s_entries [] = {
501     {
502         create,
503         getImplName,
504         getSuppServices,
505         ::cppu::createSingleComponentFactory,
506         0, 0
507     },
508     { 0, 0, 0, 0, 0, 0 }
509 };
510 
511 } // anon namespace
512 
513 extern "C" {
514 
component_getImplementationEnvironment(const sal_Char ** ppEnvTypeName,uno_Environment **)515 SAL_DLLPUBLIC_EXPORT void SAL_CALL component_getImplementationEnvironment(
516     const sal_Char ** ppEnvTypeName, uno_Environment ** /*ppEnv*/ )
517 {
518     *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
519 }
520 
component_getFactory(sal_Char const * pImplName,lang::XMultiServiceFactory * pServiceManager,registry::XRegistryKey * pRegistryKey)521 SAL_DLLPUBLIC_EXPORT void * SAL_CALL component_getFactory(
522     sal_Char const * pImplName,
523     lang::XMultiServiceFactory * pServiceManager,
524     registry::XRegistryKey * pRegistryKey )
525 {
526     return ::cppu::component_getFactoryHelper(
527         pImplName, pServiceManager, pRegistryKey, s_entries );
528 }
529 
530 }
531