xref: /AOO41X/main/sfx2/source/doc/sfxbasemodel.cxx (revision 54628ca40d27d15cc98fe861da7fff7e60c2f7d6)
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_sfx2.hxx"
26 
27 //________________________________________________________________________________________________________
28 //  my own includes
29 //________________________________________________________________________________________________________
30 
31 #include <sfx2/sfxbasemodel.hxx>
32 
33 //________________________________________________________________________________________________________
34 //  include of other projects
35 //________________________________________________________________________________________________________
36 
37 #include <com/sun/star/task/XInteractionHandler.hpp>
38 #include <com/sun/star/task/ErrorCodeRequest.hpp>
39 #include <com/sun/star/view/XSelectionSupplier.hpp>
40 #include <com/sun/star/view/XPrintJobListener.hpp>
41 #include <com/sun/star/lang/DisposedException.hpp>
42 #include <com/sun/star/lang/IllegalArgumentException.hpp>
43 #include <com/sun/star/lang/WrappedTargetRuntimeException.hpp>
44 #include <com/sun/star/frame/IllegalArgumentIOException.hpp>
45 #include <com/sun/star/frame/XUntitledNumbers.hpp>
46 #include <com/sun/star/frame/UntitledNumbersConst.hpp>
47 #include <com/sun/star/embed/XTransactionBroadcaster.hpp>
48 #include <com/sun/star/embed/XStorage.hpp>
49 #include <com/sun/star/embed/EmbedMapUnits.hpp>
50 #include <com/sun/star/document/XStorageChangeListener.hpp>
51 #include <com/sun/star/document/XActionLockable.hpp>
52 #include <com/sun/star/beans/XPropertySet.hpp>
53 #include <com/sun/star/container/XIndexContainer.hpp>
54 #include <com/sun/star/script/provider/XScriptProviderFactory.hpp>
55 #include <com/sun/star/script/provider/XScriptProvider.hpp>
56 #include <com/sun/star/ui/XUIConfigurationStorage.hpp>
57 #include <com/sun/star/ui/XUIConfigurationPersistence.hpp>
58 #include <com/sun/star/lang/WrappedTargetRuntimeException.hpp>
59 #include <com/sun/star/embed/ElementModes.hpp>
60 #include <com/sun/star/embed/Aspects.hpp>
61 #include <com/sun/star/document/XDocumentProperties.hpp>
62 #include <com/sun/star/frame/XTransientDocumentsDocumentContentFactory.hpp>
63 #include <comphelper/enumhelper.hxx>  // can be removed when this is a "real" service
64 
65 #include <cppuhelper/interfacecontainer.hxx>
66 #include <cppuhelper/exc_hlp.hxx>
67 #include <comphelper/processfactory.hxx>  // can be removed when this is a "real" service
68 #include <comphelper/componentcontext.hxx>
69 #include <comphelper/namedvaluecollection.hxx>
70 #include <svl/itemset.hxx>
71 #include <svl/stritem.hxx>
72 #include <svl/eitem.hxx>
73 #include <svl/intitem.hxx>
74 #include <basic/sbx.hxx>
75 #include <basic/sbuno.hxx>
76 #include <tools/urlobj.hxx>
77 #include <tools/diagnose_ex.h>
78 #include <unotools/tempfile.hxx>
79 #include <vos/mutex.hxx>
80 #include <vcl/salctype.hxx>
81 #include <sot/clsids.hxx>
82 #include <sot/storinfo.hxx>
83 #include <comphelper/storagehelper.hxx>
84 #include <toolkit/helper/vclunohelper.hxx>
85 #include <svtools/transfer.hxx>
86 #include <svtools/ehdl.hxx>
87 #include <svtools/sfxecode.hxx>
88 #include <rtl/logfile.hxx>
89 #include <framework/configimporter.hxx>
90 #include <framework/interaction.hxx>
91 #include <framework/titlehelper.hxx>
92 #include <comphelper/numberedcollection.hxx>
93 #include <unotools/ucbstreamhelper.hxx>
94 #include <unotools/ucbhelper.hxx>
95 
96 //________________________________________________________________________________________________________
97 //  includes of my own project
98 //________________________________________________________________________________________________________
99 
100 #include <sfx2/sfxbasecontroller.hxx>
101 #include "sfx2/viewfac.hxx"
102 #include "workwin.hxx"
103 #include <sfx2/signaturestate.hxx>
104 #include <sfx2/sfxuno.hxx>
105 #include <objshimp.hxx>
106 #include <sfx2/viewfrm.hxx>
107 #include <sfx2/viewsh.hxx>
108 #include <sfx2/docfile.hxx>
109 #include <sfx2/dispatch.hxx>
110 #include <sfx2/request.hxx>
111 #include <sfx2/objuno.hxx>
112 #include <sfx2/printer.hxx>
113 #include <sfx2/basmgr.hxx>
114 #include <sfx2/event.hxx>
115 #include <eventsupplier.hxx>
116 #include <sfx2/evntconf.hxx>
117 #include <sfx2/sfx.hrc>
118 #include <sfx2/app.hxx>
119 #include <sfx2/viewfrm.hxx>
120 #include "appdata.hxx"
121 #include <sfx2/docfac.hxx>
122 #include <sfx2/fcontnr.hxx>
123 #include "sfx2/docstoragemodifylistener.hxx"
124 #include "sfx2/brokenpackageint.hxx"
125 #include "graphhelp.hxx"
126 #include "docundomanager.hxx"
127 #include <sfx2/msgpool.hxx>
128 #include <sfx2/DocumentMetadataAccess.hxx>
129 
130 #include <sfx2/sfxresid.hxx>
131 
132 //________________________________________________________________________________________________________
133 // const
134 static const ::rtl::OUString SERVICENAME_DESKTOP = ::rtl::OUString::createFromAscii ("com.sun.star.frame.Desktop");
135 
136 //________________________________________________________________________________________________________
137 //  namespaces
138 //________________________________________________________________________________________________________
139 
140 namespace css = ::com::sun::star;
141 using namespace ::com::sun::star;
142 using namespace ::com::sun::star::uno;
143 using ::com::sun::star::beans::PropertyValue;
144 using ::com::sun::star::frame::XFrame;
145 using ::com::sun::star::frame::XController;
146 using ::com::sun::star::frame::XController2;
147 using ::com::sun::star::lang::IllegalArgumentException;
148 using ::com::sun::star::io::IOException;
149 using ::com::sun::star::lang::WrappedTargetException;
150 using ::com::sun::star::uno::Type;
151 using ::com::sun::star::uno::Sequence;
152 using ::com::sun::star::document::XDocumentRecovery;
153 using ::com::sun::star::document::XUndoManager;
154 using ::com::sun::star::document::XUndoAction;
155 using ::com::sun::star::document::UndoFailedException;
156 using ::com::sun::star::frame::XModel;
157 
158 /** This Listener is used to get notified when the XDocumentProperties of the
159     XModel change.
160  */
161 class SfxDocInfoListener_Impl : public ::cppu::WeakImplHelper1<
162     ::com::sun::star::util::XModifyListener >
163 {
164 
165 public:
166     SfxObjectShell& m_rShell;
167 
168     SfxDocInfoListener_Impl( SfxObjectShell& i_rDoc )
169         : m_rShell(i_rDoc)
170     { };
171 
172     ~SfxDocInfoListener_Impl();
173 
174     virtual void SAL_CALL disposing( const lang::EventObject& )
175         throw ( uno::RuntimeException );
176     virtual void SAL_CALL modified( const lang::EventObject& )
177         throw ( uno::RuntimeException );
178 };
179 SfxDocInfoListener_Impl::~SfxDocInfoListener_Impl()
180 {
181 }
182 void SAL_CALL SfxDocInfoListener_Impl::modified( const lang::EventObject& )
183         throw ( uno::RuntimeException )
184 {
185     ::vos::OGuard aSolarGuard( Application::GetSolarMutex() );
186 
187     // notify changes to the SfxObjectShell
188     m_rShell.FlushDocInfo();
189 }
190 
191 void SAL_CALL SfxDocInfoListener_Impl::disposing( const lang::EventObject& )
192     throw ( uno::RuntimeException )
193 {
194 }
195 
196 //________________________________________________________________________________________________________
197 //  impl. declarations
198 //________________________________________________________________________________________________________
199 
200 
201 struct IMPL_SfxBaseModel_DataContainer : public ::sfx2::IModifiableDocument
202 {
203     // counter for SfxBaseModel instances created.
204     static sal_Int64                                        g_nInstanceCounter      ;
205     SfxObjectShellRef                                       m_pObjectShell          ;
206     ::rtl::OUString                                         m_sURL                  ;
207     ::rtl::OUString                                         m_sRuntimeUID           ;
208     ::rtl::OUString                                         m_aPreusedFilterName;
209     ::cppu::OMultiTypeInterfaceContainerHelper              m_aInterfaceContainer   ;
210     uno::Reference< uno::XInterface >                       m_xParent               ;
211     uno::Reference< frame::XController >                    m_xCurrent              ;
212     uno::Reference< document::XDocumentInfo >               m_xDocumentInfo         ;
213     uno::Reference< document::XDocumentProperties >         m_xDocumentProperties;
214     uno::Reference< script::XStarBasicAccess >              m_xStarBasicAccess      ;
215     uno::Reference< container::XNameReplace >               m_xEvents               ;
216     uno::Sequence< beans::PropertyValue>                    m_seqArguments          ;
217     uno::Sequence< uno::Reference< frame::XController > >   m_seqControllers        ;
218     uno::Reference< container::XIndexAccess >               m_contViewData          ;
219     sal_uInt16                                              m_nControllerLockCount  ;
220     sal_Bool                                                m_bClosed               ;
221     sal_Bool                                                m_bClosing              ;
222     sal_Bool                                                m_bSaving               ;
223     sal_Bool                                                m_bSuicide              ;
224     sal_Bool                                                m_bInitialized          ;
225     sal_Bool                                                m_bExternalTitle        ;
226     sal_Bool                                                m_bModifiedSinceLastSave;
227     uno::Reference< com::sun::star::view::XPrintable>       m_xPrintable            ;
228     uno::Reference< script::provider::XScriptProvider >     m_xScriptProvider;
229     uno::Reference< ui::XUIConfigurationManager >           m_xUIConfigurationManager;
230     ::rtl::Reference< ::sfx2::DocumentStorageModifyListener >   m_pStorageModifyListen;
231     ::rtl::OUString                                         m_sModuleIdentifier;
232     css::uno::Reference< css::frame::XTitle >               m_xTitleHelper;
233     css::uno::Reference< css::frame::XUntitledNumbers >     m_xNumberedControllers;
234     uno::Reference< rdf::XDocumentMetadataAccess>           m_xDocumentMetadata;
235     ::rtl::Reference< ::sfx2::DocumentUndoManager >         m_pDocumentUndoManager;
236 
237 
238     IMPL_SfxBaseModel_DataContainer( ::osl::Mutex& rMutex, SfxObjectShell* pObjectShell )
239             :   m_pObjectShell          ( pObjectShell  )
240             ,   m_aInterfaceContainer   ( rMutex        )
241             ,   m_nControllerLockCount  ( 0             )
242             ,   m_bClosed               ( sal_False     )
243             ,   m_bClosing              ( sal_False     )
244             ,   m_bSaving               ( sal_False     )
245             ,   m_bSuicide              ( sal_False     )
246             ,   m_bInitialized          ( sal_False     )
247             ,   m_bExternalTitle        ( sal_False     )
248             ,   m_bModifiedSinceLastSave( sal_False     )
249             ,   m_pStorageModifyListen  ( NULL          )
250             ,   m_xTitleHelper          ()
251             ,   m_xNumberedControllers  ()
252             ,   m_xDocumentMetadata     () // lazy
253             ,   m_pDocumentUndoManager  ()
254     {
255         // increase global instance counter.
256         ++g_nInstanceCounter;
257         // set own Runtime UID
258         m_sRuntimeUID = rtl::OUString::valueOf( g_nInstanceCounter );
259     }
260 
261     virtual ~IMPL_SfxBaseModel_DataContainer()
262     {
263     }
264 
265     // ::sfx2::IModifiableDocument
266     virtual void storageIsModified()
267     {
268         if ( m_pObjectShell.Is() && !m_pObjectShell->IsModified() )
269             m_pObjectShell->SetModified( sal_True );
270     }
271 
272     uno::Reference<rdf::XDocumentMetadataAccess> GetDMA()
273     {
274         if (!m_xDocumentMetadata.is())
275         {
276             OSL_ENSURE(m_pObjectShell, "GetDMA: no object shell?");
277             if (!m_pObjectShell)
278             {
279                 return 0;
280             }
281 
282             const uno::Reference<uno::XComponentContext> xContext(
283                 ::comphelper::getProcessComponentContext());
284             ::rtl::OUString uri;
285             const uno::Reference<frame::XModel> xModel(
286                 m_pObjectShell->GetModel());
287             const uno::Reference<lang::XMultiComponentFactory> xMsf(
288                 xContext->getServiceManager());
289             const uno::Reference<frame::
290                 XTransientDocumentsDocumentContentFactory> xTDDCF(
291                     xMsf->createInstanceWithContext(
292                         ::rtl::OUString::createFromAscii( "com.sun.star.frame."
293                             "TransientDocumentsDocumentContentFactory"),
294                     xContext),
295                 uno::UNO_QUERY_THROW);
296             const uno::Reference<ucb::XContent> xContent(
297                 xTDDCF->createDocumentContent(xModel) );
298             OSL_ENSURE(xContent.is(), "GetDMA: cannot create DocumentContent");
299             if (!xContent.is())
300             {
301                 return 0;
302             }
303             uri = xContent->getIdentifier()->getContentIdentifier();
304             OSL_ENSURE(uri.getLength(), "GetDMA: empty uri?");
305             if (uri.getLength() && !uri.endsWithAsciiL("/", 1))
306             {
307                 uri = uri + ::rtl::OUString::createFromAscii("/");
308             }
309 
310             m_xDocumentMetadata = new ::sfx2::DocumentMetadataAccess(
311                 xContext, *m_pObjectShell, uri);
312         }
313         return m_xDocumentMetadata;
314     }
315 
316     uno::Reference<rdf::XDocumentMetadataAccess> CreateDMAUninitialized()
317     {
318         return (m_pObjectShell)
319             ? new ::sfx2::DocumentMetadataAccess(
320                 ::comphelper::getProcessComponentContext(), *m_pObjectShell)
321             : 0;
322     }
323 };
324 
325 // static member initialization.
326 sal_Int64 IMPL_SfxBaseModel_DataContainer::g_nInstanceCounter = 0;
327 
328 // =======================================================================================================
329 
330 // Listener that forwards notifications from the PrintHelper to the "real" listeners
331 class SfxPrintHelperListener_Impl : public ::cppu::WeakImplHelper1< ::com::sun::star::view::XPrintJobListener >
332 {
333 public:
334     IMPL_SfxBaseModel_DataContainer* m_pData;
335     SfxPrintHelperListener_Impl( IMPL_SfxBaseModel_DataContainer* pData )
336         : m_pData( pData )
337     {}
338 
339     virtual void SAL_CALL disposing( const lang::EventObject& aEvent ) throw ( uno::RuntimeException ) ;
340     virtual void SAL_CALL printJobEvent( const view::PrintJobEvent& rEvent ) throw ( uno::RuntimeException);
341 };
342 
343 void SAL_CALL SfxPrintHelperListener_Impl::disposing( const lang::EventObject& ) throw ( uno::RuntimeException )
344 {
345     m_pData->m_xPrintable = 0;
346 }
347 
348 void SAL_CALL SfxPrintHelperListener_Impl::printJobEvent( const view::PrintJobEvent& rEvent ) throw (uno::RuntimeException)
349 {
350     ::cppu::OInterfaceContainerHelper* pContainer = m_pData->m_aInterfaceContainer.getContainer( ::getCppuType( ( const uno::Reference< view::XPrintJobListener >*) NULL ) );
351     if ( pContainer!=NULL )
352     {
353         ::cppu::OInterfaceIteratorHelper pIterator(*pContainer);
354         while (pIterator.hasMoreElements())
355             ((view::XPrintJobListener*)pIterator.next())->printJobEvent( rEvent );
356     }
357 }
358 
359 // SfxOwnFramesLocker ====================================================================================
360 // allows to lock all the frames related to the provided SfxObjectShell
361 class SfxOwnFramesLocker
362 {
363     uno::Sequence< uno::Reference< frame::XFrame > > m_aLockedFrames;
364 
365     Window* GetVCLWindow( const uno::Reference< frame::XFrame >& xFrame );
366 public:
367     SfxOwnFramesLocker( SfxObjectShell* ObjechShell );
368     ~SfxOwnFramesLocker();
369     void UnlockFrames();
370 };
371 
372 SfxOwnFramesLocker::SfxOwnFramesLocker( SfxObjectShell* pObjectShell )
373 {
374     if ( !pObjectShell )
375         return;
376 
377     for (   SfxViewFrame *pFrame = SfxViewFrame::GetFirst( pObjectShell );
378             pFrame;
379             pFrame = SfxViewFrame::GetNext( *pFrame, pObjectShell )
380         )
381     {
382         SfxFrame& rSfxFrame = pFrame->GetFrame();
383         try
384         {
385             // get vcl window related to the frame and lock it if it is still not locked
386             uno::Reference< frame::XFrame > xFrame = rSfxFrame.GetFrameInterface();
387             Window* pWindow = GetVCLWindow( xFrame );
388             if ( !pWindow )
389                 throw uno::RuntimeException();
390 
391             if ( pWindow->IsEnabled() )
392             {
393                 pWindow->Disable();
394 
395                 try
396                 {
397                     sal_Int32 nLen = m_aLockedFrames.getLength();
398                     m_aLockedFrames.realloc( nLen + 1 );
399                     m_aLockedFrames[nLen] = xFrame;
400                 }
401                 catch( uno::Exception& )
402                 {
403                     pWindow->Enable();
404                     throw;
405                 }
406             }
407         }
408         catch( uno::Exception& )
409         {
410             OSL_ENSURE( sal_False, "Not possible to lock the frame window!\n" );
411         }
412     }
413 }
414 
415 SfxOwnFramesLocker::~SfxOwnFramesLocker()
416 {
417     UnlockFrames();
418 }
419 
420 Window* SfxOwnFramesLocker::GetVCLWindow( const uno::Reference< frame::XFrame >& xFrame )
421 {
422     Window* pWindow = NULL;
423 
424     if ( xFrame.is() )
425     {
426         uno::Reference< awt::XWindow > xWindow = xFrame->getContainerWindow();
427         if ( xWindow.is() )
428             pWindow = VCLUnoHelper::GetWindow( xWindow );
429     }
430 
431     return pWindow;
432 }
433 
434 void SfxOwnFramesLocker::UnlockFrames()
435 {
436     for ( sal_Int32 nInd = 0; nInd < m_aLockedFrames.getLength(); nInd++ )
437     {
438         try
439         {
440             if ( m_aLockedFrames[nInd].is() )
441             {
442                 // get vcl window related to the frame and unlock it
443                 Window* pWindow = GetVCLWindow( m_aLockedFrames[nInd] );
444                 if ( !pWindow )
445                     throw uno::RuntimeException();
446 
447                 pWindow->Enable();
448 
449                 m_aLockedFrames[nInd] = uno::Reference< frame::XFrame >();
450             }
451         }
452         catch( uno::Exception& )
453         {
454             OSL_ENSURE( sal_False, "Can't unlock the frame window!\n" );
455         }
456     }
457 }
458 
459 // SfxSaveGuard ====================================================================================
460 class SfxSaveGuard
461 {
462     private:
463         uno::Reference< frame::XModel > m_xModel;
464         IMPL_SfxBaseModel_DataContainer* m_pData;
465         SfxOwnFramesLocker* m_pFramesLock;
466 
467     public:
468         SfxSaveGuard(const uno::Reference< frame::XModel >&             xModel                      ,
469                            IMPL_SfxBaseModel_DataContainer* pData                       ,
470                            sal_Bool                         bRejectConcurrentSaveRequest);
471         ~SfxSaveGuard();
472 };
473 
474 SfxSaveGuard::SfxSaveGuard(const uno::Reference< frame::XModel >&             xModel                      ,
475                                  IMPL_SfxBaseModel_DataContainer* pData                       ,
476                                  sal_Bool                         bRejectConcurrentSaveRequest)
477     : m_xModel     (xModel)
478     , m_pData      (pData )
479     , m_pFramesLock(0     )
480 {
481     static ::rtl::OUString MSG_1 = ::rtl::OUString::createFromAscii("Object already disposed."                                       );
482     static ::rtl::OUString MSG_2 = ::rtl::OUString::createFromAscii("Concurrent save requests on the same document are not possible.");
483 
484     if ( m_pData->m_bClosed )
485         throw ::com::sun::star::lang::DisposedException(
486                 MSG_1,
487                 ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >());
488 
489     if (
490         bRejectConcurrentSaveRequest &&
491         m_pData->m_bSaving
492        )
493         throw ::com::sun::star::io::IOException(
494                 MSG_2,
495                 ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >());
496 
497     m_pData->m_bSaving = sal_True;
498     m_pFramesLock = new SfxOwnFramesLocker(m_pData->m_pObjectShell);
499 }
500 
501 SfxSaveGuard::~SfxSaveGuard()
502 {
503     SfxOwnFramesLocker* pFramesLock = m_pFramesLock;
504     m_pFramesLock = 0;
505     delete pFramesLock;
506 
507     m_pData->m_bSaving = sal_False;
508 
509     // m_bSuicide was set e.g. in case somewhere tried to close a document, while it was used for
510     // storing at the same time. Further m_bSuicide was set to sal_True only if close(sal_True) was called.
511     // So the owner ship was delegated to the place where a veto exception was thrown.
512     // Now we have to call close() again and delegate the owner ship to the next one, which
513     // cant accept that. Close(sal_False) cant work in this case. Because then the document will may be never closed ...
514 
515     if ( m_pData->m_bSuicide )
516     {
517         // Reset this state. In case the new close() request is not accepted by somehwere else ...
518         // it's not a good idea to have two "owners" for close .-)
519         m_pData->m_bSuicide = sal_False;
520         try
521         {
522             uno::Reference< util::XCloseable > xClose(m_xModel, uno::UNO_QUERY);
523             if (xClose.is())
524                 xClose->close(sal_True);
525         }
526         catch(const util::CloseVetoException&)
527         {}
528     }
529 }
530 
531 // =======================================================================================================
532 
533 //________________________________________________________________________________________________________
534 //  constructor
535 //________________________________________________________________________________________________________
536 DBG_NAME(sfx2_SfxBaseModel)
537 SfxBaseModel::SfxBaseModel( SfxObjectShell *pObjectShell )
538 : BaseMutex()
539 , m_pData( new IMPL_SfxBaseModel_DataContainer( m_aMutex, pObjectShell ) )
540 , m_bSupportEmbeddedScripts( pObjectShell && pObjectShell->Get_Impl() ? !pObjectShell->Get_Impl()->m_bNoBasicCapabilities : false )
541 , m_bSupportDocRecovery( pObjectShell && pObjectShell->Get_Impl() ? pObjectShell->Get_Impl()->m_bDocRecoverySupport : false )
542 {
543     DBG_CTOR(sfx2_SfxBaseModel,NULL);
544     if ( pObjectShell != NULL )
545     {
546         StartListening( *pObjectShell ) ;
547     }
548 }
549 
550 //________________________________________________________________________________________________________
551 //  destructor
552 //________________________________________________________________________________________________________
553 
554 SfxBaseModel::~SfxBaseModel()
555 {
556     DBG_DTOR(sfx2_SfxBaseModel,NULL);
557 }
558 
559 //________________________________________________________________________________________________________
560 //  XInterface
561 //________________________________________________________________________________________________________
562 
563 uno::Any SAL_CALL SfxBaseModel::queryInterface( const UNOTYPE& rType ) throw( uno::RuntimeException )
564 {
565     if  (   ( !m_bSupportEmbeddedScripts && rType.equals( XEMBEDDEDSCRIPTS::static_type() ) )
566         ||  ( !m_bSupportDocRecovery && rType.equals( XDocumentRecovery::static_type() ) )
567         )
568         return Any();
569 
570     return SfxBaseModel_Base::queryInterface( rType );
571 }
572 
573 //________________________________________________________________________________________________________
574 //  XInterface
575 //________________________________________________________________________________________________________
576 
577 void SAL_CALL SfxBaseModel::acquire() throw( )
578 {
579     // Attention:
580     //  Don't use mutex or guard in this method!!! Is a method of XInterface.
581 
582     // Forward to baseclass
583     OWeakObject::acquire() ;
584 }
585 
586 //________________________________________________________________________________________________________
587 //  XInterface
588 //________________________________________________________________________________________________________
589 
590 void SAL_CALL SfxBaseModel::release() throw( )
591 {
592     // Attention:
593     //  Don't use mutex or guard in this method!!! Is a method of XInterface.
594 
595     // Forward to baseclass
596     OWeakObject::release() ;
597 }
598 
599 //________________________________________________________________________________________________________
600 //  XTypeProvider
601 //________________________________________________________________________________________________________
602 
603 namespace
604 {
605     void lcl_stripType( Sequence< Type >& io_rTypes, const Type& i_rTypeToStrip )
606     {
607         Sequence< UNOTYPE > aStrippedTypes( io_rTypes.getLength() - 1 );
608         ::std::remove_copy_if(
609             io_rTypes.getConstArray(),
610             io_rTypes.getConstArray() + io_rTypes.getLength(),
611             aStrippedTypes.getArray(),
612             ::std::bind2nd( ::std::equal_to< Type >(), i_rTypeToStrip )
613         );
614         io_rTypes = aStrippedTypes;
615     }
616 }
617 
618 uno::Sequence< UNOTYPE > SAL_CALL SfxBaseModel::getTypes() throw( uno::RuntimeException )
619 {
620     uno::Sequence< UNOTYPE > aTypes( SfxBaseModel_Base::getTypes() );
621 
622     if ( !m_bSupportEmbeddedScripts )
623         lcl_stripType( aTypes, XEMBEDDEDSCRIPTS::static_type() );
624 
625     if ( !m_bSupportDocRecovery )
626         lcl_stripType( aTypes, XDocumentRecovery::static_type() );
627 
628     return aTypes;
629 }
630 
631 //________________________________________________________________________________________________________
632 //  XTypeProvider
633 //________________________________________________________________________________________________________
634 
635 uno::Sequence< sal_Int8 > SAL_CALL SfxBaseModel::getImplementationId() throw( uno::RuntimeException )
636 {
637     // Create one Id for all instances of this class.
638     // Use ethernet address to do this! (sal_True)
639 
640     // Optimize this method
641     // We initialize a static variable only one time. And we don't must use a mutex at every call!
642     // For the first call; pID is NULL - for the second call pID is different from NULL!
643     static ::cppu::OImplementationId* pID = NULL ;
644 
645     if ( pID == NULL )
646     {
647         // Ready for multithreading; get global mutex for first call of this method only! see before
648         ::osl::MutexGuard aGuard( MUTEX::getGlobalMutex() ) ;
649 
650         // Control these pointer again ... it can be, that another instance will be faster then these!
651         if ( pID == NULL )
652         {
653             // Create a new static ID ...
654             static ::cppu::OImplementationId aID( sal_False ) ;
655             // ... and set his address to static pointer!
656             pID = &aID ;
657         }
658     }
659 
660     return pID->getImplementationId() ;
661 }
662 
663 //________________________________________________________________________________________________________
664 //  XStarBasicAccess
665 //________________________________________________________________________________________________________
666 
667 uno::Reference< script::XStarBasicAccess > implGetStarBasicAccess( SfxObjectShell* pObjectShell )
668 {
669     uno::Reference< script::XStarBasicAccess > xRet;
670     if( pObjectShell )
671     {
672         BasicManager* pMgr = pObjectShell->GetBasicManager();
673         xRet = getStarBasicAccess( pMgr );
674     }
675     return xRet;
676 }
677 
678 uno::Reference< XNAMECONTAINER > SAL_CALL SfxBaseModel::getLibraryContainer() throw( uno::RuntimeException )
679 {
680     SfxModelGuard aGuard( *this );
681 
682     uno::Reference< script::XStarBasicAccess >& rxAccess = m_pData->m_xStarBasicAccess;
683     if( !rxAccess.is() && m_pData->m_pObjectShell.Is() )
684         rxAccess = implGetStarBasicAccess( m_pData->m_pObjectShell );
685 
686     uno::Reference< XNAMECONTAINER > xRet;
687     if( rxAccess.is() )
688         xRet = rxAccess->getLibraryContainer();
689     return xRet;
690 }
691 
692 /**___________________________________________________________________________________________________
693     @seealso    XStarBasicAccess
694 */
695 void SAL_CALL SfxBaseModel::createLibrary( const ::rtl::OUString& LibName, const ::rtl::OUString& Password,
696     const ::rtl::OUString& ExternalSourceURL, const ::rtl::OUString& LinkTargetURL )
697         throw(ELEMENTEXISTEXCEPTION, uno::RuntimeException)
698 {
699     SfxModelGuard aGuard( *this );
700 
701     uno::Reference< script::XStarBasicAccess >& rxAccess = m_pData->m_xStarBasicAccess;
702     if( !rxAccess.is() && m_pData->m_pObjectShell.Is() )
703         rxAccess = implGetStarBasicAccess( m_pData->m_pObjectShell );
704 
705     if( rxAccess.is() )
706         rxAccess->createLibrary( LibName, Password, ExternalSourceURL, LinkTargetURL );
707 }
708 
709 /**___________________________________________________________________________________________________
710     @seealso    XStarBasicAccess
711 */
712 void SAL_CALL SfxBaseModel::addModule( const ::rtl::OUString& LibraryName, const ::rtl::OUString& ModuleName,
713     const ::rtl::OUString& Language, const ::rtl::OUString& Source )
714         throw( NOSUCHELEMENTEXCEPTION, uno::RuntimeException)
715 {
716     SfxModelGuard aGuard( *this );
717 
718     uno::Reference< script::XStarBasicAccess >& rxAccess = m_pData->m_xStarBasicAccess;
719     if( !rxAccess.is() && m_pData->m_pObjectShell.Is() )
720         rxAccess = implGetStarBasicAccess( m_pData->m_pObjectShell );
721 
722     if( rxAccess.is() )
723         rxAccess->addModule( LibraryName, ModuleName, Language, Source );
724 }
725 
726 /**___________________________________________________________________________________________________
727     @seealso    XStarBasicAccess
728 */
729 void SAL_CALL SfxBaseModel::addDialog( const ::rtl::OUString& LibraryName, const ::rtl::OUString& DialogName,
730     const ::com::sun::star::uno::Sequence< sal_Int8 >& Data )
731         throw(NOSUCHELEMENTEXCEPTION, uno::RuntimeException)
732 {
733     SfxModelGuard aGuard( *this );
734 
735     uno::Reference< script::XStarBasicAccess >& rxAccess = m_pData->m_xStarBasicAccess;
736     if( !rxAccess.is() && m_pData->m_pObjectShell.Is() )
737         rxAccess = implGetStarBasicAccess( m_pData->m_pObjectShell );
738 
739     if( rxAccess.is() )
740         rxAccess->addDialog( LibraryName, DialogName, Data );
741 }
742 
743 
744 //________________________________________________________________________________________________________
745 //  XChild
746 //________________________________________________________________________________________________________
747 
748 uno::Reference< uno::XInterface > SAL_CALL SfxBaseModel::getParent() throw( uno::RuntimeException )
749 {
750     SfxModelGuard aGuard( *this );
751 
752     return m_pData->m_xParent;
753 }
754 
755 //________________________________________________________________________________________________________
756 //  XChild
757 //________________________________________________________________________________________________________
758 
759 void SAL_CALL SfxBaseModel::setParent(const uno::Reference< uno::XInterface >& Parent) throw(NOSUPPORTEXCEPTION, uno::RuntimeException)
760 {
761     SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );
762     m_pData->m_xParent = Parent;
763 }
764 
765 //________________________________________________________________________________________________________
766 //  XChild
767 //________________________________________________________________________________________________________
768 
769 void SAL_CALL SfxBaseModel::dispose() throw(::com::sun::star::uno::RuntimeException)
770 {
771     SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );
772 
773     if  ( !m_pData->m_bClosed )
774     {
775         // gracefully accept wrong dispose calls instead of close call
776         // and try to make it work (may be really disposed later!)
777         try
778         {
779             close( sal_True );
780         }
781         catch ( com::sun::star::util::CloseVetoException& )
782         {
783         }
784 
785         return;
786     }
787 
788     if ( m_pData->m_pStorageModifyListen.is() )
789     {
790         m_pData->m_pStorageModifyListen->dispose();
791         m_pData->m_pStorageModifyListen = NULL;
792     }
793 
794     if ( m_pData->m_pDocumentUndoManager.is() )
795     {
796         m_pData->m_pDocumentUndoManager->disposing();
797         m_pData->m_pDocumentUndoManager = NULL;
798     }
799 
800     lang::EventObject aEvent( (frame::XModel *)this );
801     m_pData->m_aInterfaceContainer.disposeAndClear( aEvent );
802 
803     if ( m_pData->m_xDocumentInfo.is() )
804     {
805         // as long as an SfxObjectShell is assigned to an SfxBaseModel it is still existing here
806         // so we can't dispose the shared DocumentInfoObject here
807         // uno::Reference < lang::XComponent > xComp( m_pData->m_xDocumentInfo, uno::UNO_QUERY );
808         // xComp->dispose();
809         m_pData->m_xDocumentInfo = 0;
810     }
811 
812     m_pData->m_xDocumentProperties.clear();
813 
814     m_pData->m_xDocumentMetadata.clear();
815 
816     EndListening( *m_pData->m_pObjectShell );
817 
818     m_pData->m_xCurrent = uno::Reference< frame::XController > ();
819     m_pData->m_seqControllers = uno::Sequence< uno::Reference< frame::XController > > () ;
820 
821     // m_pData member must be set to zero before 0delete is called to
822     // force disposed exception whenever someone tries to access our
823     // instance while in the dtor.
824     IMPL_SfxBaseModel_DataContainer* pData = m_pData;
825     m_pData = 0;
826     delete pData;
827 }
828 
829 //________________________________________________________________________________________________________
830 //  XChild
831 //________________________________________________________________________________________________________
832 
833 void SAL_CALL SfxBaseModel::addEventListener( const uno::Reference< XEVENTLISTENER >& aListener )
834     throw(::com::sun::star::uno::RuntimeException)
835 {
836     SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );
837     m_pData->m_aInterfaceContainer.addInterface( ::getCppuType((const uno::Reference< XEVENTLISTENER >*)0), aListener );
838 }
839 
840 //________________________________________________________________________________________________________
841 //  XChild
842 //________________________________________________________________________________________________________
843 
844 void SAL_CALL SfxBaseModel::removeEventListener( const uno::Reference< XEVENTLISTENER >& aListener )
845     throw(::com::sun::star::uno::RuntimeException)
846 {
847     SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );
848     m_pData->m_aInterfaceContainer.removeInterface( ::getCppuType((const uno::Reference< XEVENTLISTENER >*)0), aListener );
849 }
850 
851 //________________________________________________________________________________________________________
852 //  document::XDocumentInfoSupplier
853 //________________________________________________________________________________________________________
854 
855 uno::Reference< document::XDocumentInfo > SAL_CALL SfxBaseModel::getDocumentInfo() throw(::com::sun::star::uno::RuntimeException)
856 {
857     SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );
858     if ( !m_pData->m_xDocumentInfo.is() )
859     {
860         // WARNING: this will only work if (when loading a document) the
861         // document meta-data has already been read and completely written
862         // into the XDocumentProperties at this point
863         // ==> DO NOT call getDocumentInfo before document info has been read!
864         uno::Reference< document::XDocumentInfo > xDocInfo =
865             new SfxDocumentInfoObject;
866         uno::Reference< document::XDocumentProperties > xDocProps =
867             getDocumentProperties();
868         uno::Sequence< uno::Any > args(1);
869         args[0] <<= xDocProps;
870         uno::Reference< lang::XInitialization > xInit(
871             xDocInfo, uno::UNO_QUERY_THROW);
872         try {
873             xInit->initialize(args);
874             ((SfxBaseModel*)this)->m_pData->m_xDocumentInfo = xDocInfo;
875         } catch (uno::RuntimeException &) {
876             throw;
877         } catch (uno::Exception & e) {
878             throw lang::WrappedTargetRuntimeException(::rtl::OUString::createFromAscii(
879                 "SfxBaseModel::getDocumentInfo: cannot initialize"), *this,
880                 uno::makeAny(e));
881         }
882         try {
883             rtl::OUString aName = rtl::OUString::createFromAscii("MediaType");
884             uno::Reference < beans::XPropertySet > xSet(
885                 getDocumentStorage(), uno::UNO_QUERY );
886             uno::Any aMediaType = xSet->getPropertyValue( aName );
887             uno::Reference < beans::XPropertySet > xDocSet(
888                 m_pData->m_xDocumentInfo, uno::UNO_QUERY );
889             xDocSet->setPropertyValue( aName, aMediaType );
890         } catch (uno::Exception &) {
891             //ignore
892         }
893     }
894 
895     return m_pData->m_xDocumentInfo;
896 }
897 
898 // document::XDocumentPropertiesSupplier:
899 uno::Reference< document::XDocumentProperties > SAL_CALL
900 SfxBaseModel::getDocumentProperties()
901     throw(::com::sun::star::uno::RuntimeException)
902 {
903     SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );
904     if ( !m_pData->m_xDocumentProperties.is() )
905     {
906         uno::Reference< lang::XInitialization > xDocProps(
907             ::comphelper::getProcessServiceFactory()->createInstance(
908                 DEFINE_CONST_UNICODE("com.sun.star.document.DocumentProperties") ),
909             uno::UNO_QUERY_THROW);
910 //        xDocProps->initialize(uno::Sequence<uno::Any>());
911         m_pData->m_xDocumentProperties.set(xDocProps, uno::UNO_QUERY_THROW);
912         uno::Reference<util::XModifyBroadcaster> xMB(m_pData->m_xDocumentProperties, uno::UNO_QUERY_THROW);
913         xMB->addModifyListener(new SfxDocInfoListener_Impl(*m_pData->m_pObjectShell));
914     }
915 
916     return m_pData->m_xDocumentProperties;
917 }
918 
919 
920 //________________________________________________________________________________________________________
921 //  XEVENTLISTENER
922 //________________________________________________________________________________________________________
923 
924 void SAL_CALL SfxBaseModel::disposing( const lang::EventObject& aObject )
925     throw(::com::sun::star::uno::RuntimeException)
926 {
927     ::vos::OGuard aGuard( Application::GetSolarMutex() );
928     if ( impl_isDisposed() )
929         return;
930 
931     uno::Reference< XMODIFYLISTENER >  xMod( aObject.Source, uno::UNO_QUERY );
932     uno::Reference< XEVENTLISTENER >  xListener( aObject.Source, uno::UNO_QUERY );
933     uno::Reference< XDOCEVENTLISTENER >  xDocListener( aObject.Source, uno::UNO_QUERY );
934 
935     if ( xMod.is() )
936         m_pData->m_aInterfaceContainer.removeInterface( ::getCppuType((const uno::Reference< XMODIFYLISTENER >*)0), xMod );
937     else if ( xListener.is() )
938         m_pData->m_aInterfaceContainer.removeInterface( ::getCppuType((const uno::Reference< XEVENTLISTENER >*)0), xListener );
939     else if ( xDocListener.is() )
940         m_pData->m_aInterfaceContainer.removeInterface( ::getCppuType((const uno::Reference< XDOCEVENTLISTENER >*)0), xListener );
941 }
942 
943 //________________________________________________________________________________________________________
944 //  frame::XModel
945 //________________________________________________________________________________________________________
946 
947 sal_Bool SAL_CALL SfxBaseModel::attachResource( const   ::rtl::OUString&                   rURL    ,
948                                                 const   uno::Sequence< beans::PropertyValue >&  rArgs   )
949     throw(::com::sun::star::uno::RuntimeException)
950 {
951     SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );
952     if ( rURL.getLength() == 0 && rArgs.getLength() == 1 && rArgs[0].Name.equalsAscii( "SetEmbedded" ) )
953     {
954         // allows to set a windowless document to EMBEDDED state
955         // but _only_ before load() or initNew() methods
956         if ( m_pData->m_pObjectShell.Is() && !m_pData->m_pObjectShell->GetMedium() )
957         {
958             sal_Bool bEmb = sal_Bool();
959             if ( ( rArgs[0].Value >>= bEmb ) && bEmb )
960                 m_pData->m_pObjectShell->SetCreateMode_Impl( SFX_CREATE_MODE_EMBEDDED );
961         }
962 
963         return sal_True;
964     }
965 
966     if ( m_pData->m_pObjectShell.Is() )
967     {
968         m_pData->m_sURL = rURL;
969 
970         SfxObjectShell* pObjectShell = m_pData->m_pObjectShell;
971 
972         ::comphelper::NamedValueCollection aArgs( rArgs );
973 
974         Sequence< sal_Int32 > aWinExtent;
975         if ( ( aArgs.get( "WinExtent" ) >>= aWinExtent )&& ( aWinExtent.getLength() == 4 ) )
976         {
977             Rectangle aVisArea( aWinExtent[0], aWinExtent[1], aWinExtent[2], aWinExtent[3] );
978             aVisArea = OutputDevice::LogicToLogic( aVisArea, MAP_100TH_MM, pObjectShell->GetMapUnit() );
979             pObjectShell->SetVisArea( aVisArea );
980         }
981 
982         sal_Bool bBreakMacroSign = sal_False;
983         if ( aArgs.get( "BreakMacroSignature" ) >>= bBreakMacroSign )
984         {
985             pObjectShell->BreakMacroSign_Impl( bBreakMacroSign );
986         }
987 
988         aArgs.remove( "WinExtent" );
989         aArgs.remove( "BreakMacroSignature" );
990         aArgs.remove( "Stream" );
991         aArgs.remove( "InputStream" );
992         aArgs.remove( "URL" );
993         aArgs.remove( "Frame" );
994         aArgs.remove( "Password" );
995         aArgs.remove( "EncryptionData" );
996 
997         // TODO/LATER: all the parameters that are accepted by ItemSet of the DocShell must be removed here
998 
999         m_pData->m_seqArguments = aArgs.getPropertyValues();
1000 
1001         SfxMedium* pMedium = pObjectShell->GetMedium();
1002         if ( pMedium )
1003         {
1004             SfxAllItemSet aSet( pObjectShell->GetPool() );
1005             TransformParameters( SID_OPENDOC, rArgs, aSet );
1006 
1007             // the arguments are not allowed to reach the medium
1008             aSet.ClearItem( SID_FILE_NAME );
1009             aSet.ClearItem( SID_FILLFRAME );
1010 
1011             pMedium->GetItemSet()->Put( aSet );
1012             SFX_ITEMSET_ARG( &aSet, pItem, SfxStringItem, SID_FILTER_NAME, sal_False );
1013             if ( pItem )
1014                 pMedium->SetFilter(
1015                     pObjectShell->GetFactory().GetFilterContainer()->GetFilter4FilterName( pItem->GetValue() ) );
1016 
1017             SFX_ITEMSET_ARG( &aSet, pTitleItem, SfxStringItem, SID_DOCINFO_TITLE, sal_False );
1018             if ( pTitleItem )
1019             {
1020                 SfxViewFrame* pFrame = SfxViewFrame::GetFirst( pObjectShell );
1021                 if ( pFrame )
1022                     pFrame->UpdateTitle();
1023             }
1024         }
1025     }
1026 
1027     return sal_True ;
1028 }
1029 
1030 //________________________________________________________________________________________________________
1031 //  frame::XModel
1032 //________________________________________________________________________________________________________
1033 
1034 ::rtl::OUString SAL_CALL SfxBaseModel::getURL() throw(::com::sun::star::uno::RuntimeException)
1035 {
1036     SfxModelGuard aGuard( *this );
1037     return m_pData->m_sURL ;
1038 }
1039 
1040 //________________________________________________________________________________________________________
1041 //  frame::XModel
1042 //________________________________________________________________________________________________________
1043 
1044 uno::Sequence< beans::PropertyValue > SAL_CALL SfxBaseModel::getArgs() throw(::com::sun::star::uno::RuntimeException)
1045 {
1046     SfxModelGuard aGuard( *this );
1047     if ( m_pData->m_pObjectShell.Is() )
1048     {
1049         uno::Sequence< beans::PropertyValue > seqArgsNew;
1050         uno::Sequence< beans::PropertyValue > seqArgsOld;
1051         SfxAllItemSet aSet( m_pData->m_pObjectShell->GetPool() );
1052 
1053         // we need to know which properties are supported by the transformer
1054         // hopefully it is a temporary solution, I guess nonconvertable properties
1055         // should not be supported so then there will be only ItemSet from medium
1056 
1057         TransformItems( SID_OPENDOC, *(m_pData->m_pObjectShell->GetMedium()->GetItemSet()), seqArgsNew );
1058         TransformParameters( SID_OPENDOC, m_pData->m_seqArguments, aSet );
1059         TransformItems( SID_OPENDOC, aSet, seqArgsOld );
1060 
1061         sal_Int32 nOrgLength = m_pData->m_seqArguments.getLength();
1062         sal_Int32 nOldLength = seqArgsOld.getLength();
1063         sal_Int32 nNewLength = seqArgsNew.getLength();
1064 
1065         // "WinExtent" property should be updated always.
1066         // We can store it now to overwrite an old value
1067         // since it is not from ItemSet
1068         Rectangle aTmpRect = m_pData->m_pObjectShell->GetVisArea( ASPECT_CONTENT );
1069         aTmpRect = OutputDevice::LogicToLogic( aTmpRect, m_pData->m_pObjectShell->GetMapUnit(), MAP_100TH_MM );
1070 
1071         Sequence< sal_Int32 > aRectSeq(4);
1072         aRectSeq[0] = aTmpRect.Left();
1073         aRectSeq[1] = aTmpRect.Top();
1074         aRectSeq[2] = aTmpRect.Right();
1075         aRectSeq[3] = aTmpRect.Bottom();
1076 
1077         seqArgsNew.realloc( ++nNewLength );
1078         seqArgsNew[ nNewLength - 1 ].Name = ::rtl::OUString::createFromAscii( "WinExtent" );
1079         seqArgsNew[ nNewLength - 1 ].Value <<= aRectSeq;
1080 
1081         if ( m_pData->m_aPreusedFilterName.getLength() )
1082         {
1083             seqArgsNew.realloc( ++nNewLength );
1084             seqArgsNew[ nNewLength - 1 ].Name = ::rtl::OUString::createFromAscii( "PreusedFilterName" );
1085             seqArgsNew[ nNewLength - 1 ].Value <<= m_pData->m_aPreusedFilterName;
1086         }
1087 
1088         SfxViewFrame* pFrame = SfxViewFrame::GetFirst( m_pData->m_pObjectShell );
1089         if ( pFrame )
1090         {
1091             SvBorder aBorder = pFrame->GetBorderPixelImpl( pFrame->GetViewShell() );
1092 
1093             Sequence< sal_Int32 > aBorderSeq(4);
1094             aBorderSeq[0] = aBorder.Left();
1095             aBorderSeq[1] = aBorder.Top();
1096             aBorderSeq[2] = aBorder.Right();
1097             aBorderSeq[3] = aBorder.Bottom();
1098 
1099             seqArgsNew.realloc( ++nNewLength );
1100             seqArgsNew[ nNewLength - 1 ].Name = ::rtl::OUString::createFromAscii( "DocumentBorder" );
1101             seqArgsNew[ nNewLength - 1 ].Value <<= aBorderSeq;
1102         }
1103 
1104         // only the values that are not supported by the ItemSet must be cached here
1105         uno::Sequence< beans::PropertyValue > aFinalCache;
1106         sal_Int32 nFinalLength = 0;
1107 
1108         for ( sal_Int32 nOrg = 0; nOrg < nOrgLength; nOrg++ )
1109         {
1110             sal_Int32 nOldInd = 0;
1111             while ( nOldInd < nOldLength )
1112             {
1113                 if ( m_pData->m_seqArguments[nOrg].Name.equals( seqArgsOld[nOldInd].Name ) )
1114                     break;
1115                 nOldInd++;
1116             }
1117 
1118             if ( nOldInd == nOldLength )
1119             {
1120                 // the entity with this name should be new for seqArgsNew
1121                 // since it is not supported by transformer
1122 
1123                 seqArgsNew.realloc( ++nNewLength );
1124                 seqArgsNew[ nNewLength - 1 ] = m_pData->m_seqArguments[nOrg];
1125 
1126                 aFinalCache.realloc( ++nFinalLength );
1127                 aFinalCache[ nFinalLength - 1 ] = m_pData->m_seqArguments[nOrg];
1128             }
1129         }
1130 
1131         m_pData->m_seqArguments = aFinalCache;
1132 
1133         return seqArgsNew;
1134     }
1135 
1136     return m_pData->m_seqArguments;
1137 }
1138 
1139 //________________________________________________________________________________________________________
1140 //  frame::XModel
1141 //________________________________________________________________________________________________________
1142 
1143 void SAL_CALL SfxBaseModel::connectController( const uno::Reference< frame::XController >& xController )
1144     throw(::com::sun::star::uno::RuntimeException)
1145 {
1146     SfxModelGuard aGuard( *this );
1147     OSL_PRECOND( xController.is(), "SfxBaseModel::connectController: invalid controller!" );
1148     if ( !xController.is() )
1149         return;
1150 
1151     sal_uInt32 nOldCount = m_pData->m_seqControllers.getLength();
1152     uno::Sequence< uno::Reference< frame::XController > > aNewSeq( nOldCount + 1 );
1153     for ( sal_uInt32 n = 0; n < nOldCount; n++ )
1154         aNewSeq.getArray()[n] = m_pData->m_seqControllers.getConstArray()[n];
1155     aNewSeq.getArray()[nOldCount] = xController;
1156     m_pData->m_seqControllers = aNewSeq;
1157 
1158     if ( m_pData->m_seqControllers.getLength() == 1 )
1159     {
1160         SfxViewFrame* pViewFrame = SfxViewFrame::Get( xController, GetObjectShell() );
1161         ENSURE_OR_THROW( pViewFrame, "SFX document without SFX view!?" );
1162         pViewFrame->UpdateDocument_Impl();
1163         const String sDocumentURL = GetObjectShell()->GetMedium()->GetName();
1164         if ( sDocumentURL.Len() )
1165             SFX_APP()->Broadcast( SfxStringHint( SID_OPENURL, sDocumentURL ) );
1166     }
1167 }
1168 
1169 //________________________________________________________________________________________________________
1170 //  frame::XModel
1171 //________________________________________________________________________________________________________
1172 
1173 void SAL_CALL SfxBaseModel::disconnectController( const uno::Reference< frame::XController >& xController ) throw(::com::sun::star::uno::RuntimeException)
1174 {
1175     SfxModelGuard aGuard( *this );
1176 
1177     sal_uInt32 nOldCount = m_pData->m_seqControllers.getLength();
1178     if ( !nOldCount )
1179         return;
1180 
1181     uno::Sequence< uno::Reference< frame::XController > > aNewSeq( nOldCount - 1 );
1182     for ( sal_uInt32 nOld = 0, nNew = 0; nOld < nOldCount; ++nOld )
1183     {
1184         if ( xController != m_pData->m_seqControllers.getConstArray()[nOld] )
1185         {
1186             aNewSeq.getArray()[nNew] = m_pData->m_seqControllers.getConstArray()[nOld];
1187             ++nNew;
1188         }
1189     }
1190 
1191     m_pData->m_seqControllers = aNewSeq;
1192 
1193     if ( xController == m_pData->m_xCurrent )
1194         m_pData->m_xCurrent = uno::Reference< frame::XController > ();
1195 }
1196 
1197 namespace
1198 {
1199     typedef ::cppu::WeakImplHelper1< XUndoAction > ControllerLockUndoAction_Base;
1200     class ControllerLockUndoAction : public ControllerLockUndoAction_Base
1201     {
1202     public:
1203         ControllerLockUndoAction( const Reference< XModel >& i_model, const bool i_undoIsUnlock )
1204             :m_xModel( i_model )
1205             ,m_bUndoIsUnlock( i_undoIsUnlock )
1206         {
1207         }
1208 
1209         // XUndoAction
1210         virtual ::rtl::OUString SAL_CALL getTitle() throw (RuntimeException);
1211         virtual void SAL_CALL undo(  ) throw (UndoFailedException, RuntimeException);
1212         virtual void SAL_CALL redo(  ) throw (UndoFailedException, RuntimeException);
1213 
1214     private:
1215         const Reference< XModel >   m_xModel;
1216         const bool                  m_bUndoIsUnlock;
1217     };
1218 
1219     ::rtl::OUString SAL_CALL ControllerLockUndoAction::getTitle() throw (RuntimeException)
1220     {
1221         // this action is intended to be used within an UndoContext only, so nobody will ever see this title ...
1222         return ::rtl::OUString();
1223     }
1224 
1225     void SAL_CALL ControllerLockUndoAction::undo(  ) throw (UndoFailedException, RuntimeException)
1226     {
1227         if ( m_bUndoIsUnlock )
1228             m_xModel->unlockControllers();
1229         else
1230             m_xModel->lockControllers();
1231     }
1232 
1233     void SAL_CALL ControllerLockUndoAction::redo(  ) throw (UndoFailedException, RuntimeException)
1234     {
1235         if ( m_bUndoIsUnlock )
1236             m_xModel->lockControllers();
1237         else
1238             m_xModel->unlockControllers();
1239     }
1240 }
1241 
1242 //________________________________________________________________________________________________________
1243 //  frame::XModel
1244 //________________________________________________________________________________________________________
1245 
1246 void SAL_CALL SfxBaseModel::lockControllers() throw(::com::sun::star::uno::RuntimeException)
1247 {
1248     SfxModelGuard aGuard( *this );
1249 
1250     ++m_pData->m_nControllerLockCount ;
1251 
1252     if  (   m_pData->m_pDocumentUndoManager.is()
1253         &&  m_pData->m_pDocumentUndoManager->isInContext()
1254         &&  !m_pData->m_pDocumentUndoManager->isLocked()
1255         )
1256     {
1257         m_pData->m_pDocumentUndoManager->addUndoAction( new ControllerLockUndoAction( this, true ) );
1258     }
1259 }
1260 
1261 //________________________________________________________________________________________________________
1262 //  frame::XModel
1263 //________________________________________________________________________________________________________
1264 
1265 void SAL_CALL SfxBaseModel::unlockControllers() throw(::com::sun::star::uno::RuntimeException)
1266 {
1267     SfxModelGuard aGuard( *this );
1268 
1269     --m_pData->m_nControllerLockCount ;
1270 
1271     if  (   m_pData->m_pDocumentUndoManager.is()
1272         &&  m_pData->m_pDocumentUndoManager->isInContext()
1273         &&  !m_pData->m_pDocumentUndoManager->isLocked()
1274         )
1275     {
1276         m_pData->m_pDocumentUndoManager->addUndoAction( new ControllerLockUndoAction( this, false ) );
1277     }
1278 }
1279 
1280 //________________________________________________________________________________________________________
1281 //  frame::XModel
1282 //________________________________________________________________________________________________________
1283 
1284 sal_Bool SAL_CALL SfxBaseModel::hasControllersLocked() throw(::com::sun::star::uno::RuntimeException)
1285 {
1286     SfxModelGuard aGuard( *this );
1287     return ( m_pData->m_nControllerLockCount != 0 ) ;
1288 }
1289 
1290 //________________________________________________________________________________________________________
1291 //  frame::XModel
1292 //________________________________________________________________________________________________________
1293 
1294 uno::Reference< frame::XController > SAL_CALL SfxBaseModel::getCurrentController() throw(::com::sun::star::uno::RuntimeException)
1295 {
1296     SfxModelGuard aGuard( *this );
1297 
1298     // get the last active controller of this model
1299     if ( m_pData->m_xCurrent.is() )
1300         return m_pData->m_xCurrent;
1301 
1302     // get the first controller of this model
1303     return m_pData->m_seqControllers.getLength() ? m_pData->m_seqControllers.getConstArray()[0] : m_pData->m_xCurrent;
1304 }
1305 
1306 //________________________________________________________________________________________________________
1307 //  frame::XModel
1308 //________________________________________________________________________________________________________
1309 
1310 void SAL_CALL SfxBaseModel::setCurrentController( const uno::Reference< frame::XController >& xCurrentController )
1311         throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::uno::RuntimeException)
1312 {
1313     SfxModelGuard aGuard( *this );
1314 
1315     m_pData->m_xCurrent = xCurrentController;
1316 }
1317 
1318 //________________________________________________________________________________________________________
1319 //  frame::XModel
1320 //________________________________________________________________________________________________________
1321 
1322 uno::Reference< uno::XInterface > SAL_CALL SfxBaseModel::getCurrentSelection() throw(::com::sun::star::uno::RuntimeException)
1323 {
1324     SfxModelGuard aGuard( *this );
1325 
1326     uno::Reference< uno::XInterface >     xReturn;
1327     uno::Reference< frame::XController >    xController =   getCurrentController()      ;
1328 
1329     if ( xController.is() )
1330     {
1331         uno::Reference< view::XSelectionSupplier >  xDocView( xController, uno::UNO_QUERY );
1332         if ( xDocView.is() )
1333         {
1334             uno::Any xSel = xDocView->getSelection();
1335             xSel >>= xReturn ;
1336         }
1337     }
1338 
1339     return xReturn ;
1340 }
1341 
1342 //________________________________________________________________________________________________________
1343 //  XModifiable2
1344 //________________________________________________________________________________________________________
1345 
1346 sal_Bool SAL_CALL SfxBaseModel::disableSetModified() throw (::com::sun::star::uno::RuntimeException)
1347 {
1348     SfxModelGuard aGuard( *this );
1349 
1350     if ( !m_pData->m_pObjectShell.Is() )
1351         throw uno::RuntimeException();
1352 
1353     sal_Bool bResult = m_pData->m_pObjectShell->IsEnableSetModified();
1354     m_pData->m_pObjectShell->EnableSetModified( sal_False );
1355 
1356     return bResult;
1357 }
1358 
1359 sal_Bool SAL_CALL SfxBaseModel::enableSetModified() throw (::com::sun::star::uno::RuntimeException)
1360 {
1361     SfxModelGuard aGuard( *this );
1362 
1363     if ( !m_pData->m_pObjectShell.Is() )
1364         throw uno::RuntimeException();
1365 
1366     sal_Bool bResult = m_pData->m_pObjectShell->IsEnableSetModified();
1367     m_pData->m_pObjectShell->EnableSetModified( sal_True );
1368 
1369     return bResult;
1370 }
1371 
1372 sal_Bool SAL_CALL SfxBaseModel::isSetModifiedEnabled() throw (::com::sun::star::uno::RuntimeException)
1373 {
1374     SfxModelGuard aGuard( *this );
1375 
1376     if ( !m_pData->m_pObjectShell.Is() )
1377         throw uno::RuntimeException();
1378 
1379     return m_pData->m_pObjectShell->IsEnableSetModified();
1380 }
1381 
1382 //________________________________________________________________________________________________________
1383 //  XModifiable
1384 //________________________________________________________________________________________________________
1385 
1386 sal_Bool SAL_CALL SfxBaseModel::isModified() throw(::com::sun::star::uno::RuntimeException)
1387 {
1388     SfxModelGuard aGuard( *this );
1389 
1390     return m_pData->m_pObjectShell.Is() ? m_pData->m_pObjectShell->IsModified() : sal_False;
1391 }
1392 
1393 //________________________________________________________________________________________________________
1394 //  XModifiable
1395 //________________________________________________________________________________________________________
1396 
1397 void SAL_CALL SfxBaseModel::setModified( sal_Bool bModified )
1398         throw (::com::sun::star::beans::PropertyVetoException, ::com::sun::star::uno::RuntimeException)
1399 {
1400     SfxModelGuard aGuard( *this );
1401 
1402     if ( m_pData->m_pObjectShell.Is() )
1403         m_pData->m_pObjectShell->SetModified(bModified);
1404 }
1405 
1406 //________________________________________________________________________________________________________
1407 //  XModifiable
1408 //________________________________________________________________________________________________________
1409 
1410 void SAL_CALL SfxBaseModel::addModifyListener(const uno::Reference< XMODIFYLISTENER >& xListener) throw( uno::RuntimeException )
1411 {
1412     SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );
1413 
1414     m_pData->m_aInterfaceContainer.addInterface( ::getCppuType((const uno::Reference< XMODIFYLISTENER >*)0),xListener );
1415 }
1416 
1417 //________________________________________________________________________________________________________
1418 //  XModifiable
1419 //________________________________________________________________________________________________________
1420 
1421 void SAL_CALL SfxBaseModel::removeModifyListener(const uno::Reference< XMODIFYLISTENER >& xListener) throw( uno::RuntimeException )
1422 {
1423     SfxModelGuard aGuard( *this );
1424 
1425     m_pData->m_aInterfaceContainer.removeInterface( ::getCppuType((const uno::Reference< XMODIFYLISTENER >*)0), xListener );
1426 }
1427 
1428 //____________________________________________________________________________________________________
1429 //  XCloseable
1430 //____________________________________________________________________________________________________
1431 
1432 void SAL_CALL SfxBaseModel::close( sal_Bool bDeliverOwnership ) throw (util::CloseVetoException, uno::RuntimeException)
1433 {
1434     static ::rtl::OUString MSG_1 = ::rtl::OUString::createFromAscii("Cant close while saving.");
1435 
1436     ::vos::OGuard aGuard( Application::GetSolarMutex() );
1437     if ( impl_isDisposed() || m_pData->m_bClosed || m_pData->m_bClosing )
1438         return;
1439 
1440     uno::Reference< uno::XInterface > xSelfHold( static_cast< ::cppu::OWeakObject* >(this) );
1441     lang::EventObject             aSource    (static_cast< ::cppu::OWeakObject*>(this));
1442     ::cppu::OInterfaceContainerHelper* pContainer = m_pData->m_aInterfaceContainer.getContainer( ::getCppuType( ( const uno::Reference< util::XCloseListener >*) NULL ) );
1443     if (pContainer!=NULL)
1444     {
1445         ::cppu::OInterfaceIteratorHelper pIterator(*pContainer);
1446         while (pIterator.hasMoreElements())
1447         {
1448             try
1449             {
1450                 ((util::XCloseListener*)pIterator.next())->queryClosing( aSource, bDeliverOwnership );
1451             }
1452             catch( uno::RuntimeException& )
1453             {
1454                 pIterator.remove();
1455             }
1456         }
1457     }
1458 
1459     if ( m_pData->m_bSaving )
1460     {
1461         if (bDeliverOwnership)
1462             m_pData->m_bSuicide = sal_True;
1463         throw util::CloseVetoException(
1464                 MSG_1,
1465                 static_cast< ::com::sun::star::util::XCloseable* >(this));
1466     }
1467 
1468     // no own objections against closing!
1469     m_pData->m_bClosing = sal_True;
1470     pContainer = m_pData->m_aInterfaceContainer.getContainer( ::getCppuType( ( const uno::Reference< util::XCloseListener >*) NULL ) );
1471     if (pContainer!=NULL)
1472     {
1473         ::cppu::OInterfaceIteratorHelper pCloseIterator(*pContainer);
1474         while (pCloseIterator.hasMoreElements())
1475         {
1476             try
1477             {
1478                 ((util::XCloseListener*)pCloseIterator.next())->notifyClosing( aSource );
1479             }
1480             catch( uno::RuntimeException& )
1481             {
1482                 pCloseIterator.remove();
1483             }
1484         }
1485     }
1486 
1487     m_pData->m_bClosed = sal_True;
1488     m_pData->m_bClosing = sal_False;
1489 
1490     dispose();
1491 }
1492 
1493 //____________________________________________________________________________________________________
1494 //  XCloseBroadcaster
1495 //____________________________________________________________________________________________________
1496 
1497 void SAL_CALL SfxBaseModel::addCloseListener( const uno::Reference< XCLOSELISTENER >& xListener ) throw (uno::RuntimeException)
1498 {
1499     SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );
1500 
1501     m_pData->m_aInterfaceContainer.addInterface( ::getCppuType((const uno::Reference< XCLOSELISTENER >*)0), xListener );
1502 }
1503 
1504 //____________________________________________________________________________________________________
1505 //  XCloseBroadcaster
1506 //____________________________________________________________________________________________________
1507 
1508 void SAL_CALL SfxBaseModel::removeCloseListener( const uno::Reference< XCLOSELISTENER >& xListener ) throw (uno::RuntimeException)
1509 {
1510     SfxModelGuard aGuard( *this );
1511 
1512     m_pData->m_aInterfaceContainer.removeInterface( ::getCppuType((const uno::Reference< XCLOSELISTENER >*)0), xListener );
1513 }
1514 
1515 //________________________________________________________________________________________________________
1516 //  XPrintable
1517 //________________________________________________________________________________________________________
1518 
1519 uno::Sequence< beans::PropertyValue > SAL_CALL SfxBaseModel::getPrinter() throw(::com::sun::star::uno::RuntimeException)
1520 {
1521     SfxModelGuard aGuard( *this );
1522 
1523     if ( impl_getPrintHelper() )
1524         return m_pData->m_xPrintable->getPrinter();
1525     else
1526         return uno::Sequence< beans::PropertyValue >();
1527 }
1528 
1529 void SAL_CALL SfxBaseModel::setPrinter(const uno::Sequence< beans::PropertyValue >& rPrinter)
1530         throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException)
1531 {
1532     SfxModelGuard aGuard( *this );
1533 
1534     if ( impl_getPrintHelper() )
1535         m_pData->m_xPrintable->setPrinter( rPrinter );
1536 }
1537 
1538 void SAL_CALL SfxBaseModel::print(const uno::Sequence< beans::PropertyValue >& rOptions)
1539         throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException)
1540 {
1541     SfxModelGuard aGuard( *this );
1542 
1543     if ( impl_getPrintHelper() )
1544         m_pData->m_xPrintable->print( rOptions );
1545 }
1546 
1547 //________________________________________________________________________________________________________
1548 //  XStorable
1549 //________________________________________________________________________________________________________
1550 
1551 sal_Bool SAL_CALL SfxBaseModel::hasLocation() throw(::com::sun::star::uno::RuntimeException)
1552 {
1553     SfxModelGuard aGuard( *this );
1554 
1555     return m_pData->m_pObjectShell.Is() ? m_pData->m_pObjectShell->HasName() : sal_False;
1556 }
1557 
1558 //________________________________________________________________________________________________________
1559 //  XStorable
1560 //________________________________________________________________________________________________________
1561 
1562 ::rtl::OUString SAL_CALL SfxBaseModel::getLocation() throw(::com::sun::star::uno::RuntimeException)
1563 {
1564     SfxModelGuard aGuard( *this );
1565 
1566     if ( m_pData->m_pObjectShell.Is() )
1567     {
1568         // TODO/LATER: is it correct that the shared document returns shared file location?
1569         if ( m_pData->m_pObjectShell->IsDocShared() )
1570             return m_pData->m_pObjectShell->GetSharedFileURL();
1571         else
1572             return ::rtl::OUString(m_pData->m_pObjectShell->GetMedium()->GetName());
1573     }
1574 
1575     return m_pData->m_sURL;
1576 }
1577 
1578 //________________________________________________________________________________________________________
1579 //  XStorable
1580 //________________________________________________________________________________________________________
1581 
1582 sal_Bool SAL_CALL SfxBaseModel::isReadonly() throw(::com::sun::star::uno::RuntimeException)
1583 {
1584     SfxModelGuard aGuard( *this );
1585 
1586     return m_pData->m_pObjectShell.Is() ? m_pData->m_pObjectShell->IsReadOnly() : sal_True;
1587 }
1588 
1589 //________________________________________________________________________________________________________
1590 //  XStorable2
1591 //________________________________________________________________________________________________________
1592 
1593 void SAL_CALL SfxBaseModel::storeSelf( const    uno::Sequence< beans::PropertyValue >&  aSeqArgs )
1594         throw ( ::com::sun::star::lang::IllegalArgumentException,
1595                 ::com::sun::star::io::IOException,
1596                 ::com::sun::star::uno::RuntimeException )
1597 {
1598     RTL_LOGFILE_PRODUCT_CONTEXT( aPerfLog, "PERFORMANCE - SfxBaseModel::storeSelf" );
1599 
1600     SfxModelGuard aGuard( *this );
1601 
1602     if ( m_pData->m_pObjectShell.Is() )
1603     {
1604         m_pData->m_pObjectShell->AddLog( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX "storeSelf" ) ) );
1605         SfxSaveGuard aSaveGuard(this, m_pData, sal_False);
1606 
1607         for ( sal_Int32 nInd = 0; nInd < aSeqArgs.getLength(); nInd++ )
1608         {
1609             // check that only acceptable parameters are provided here
1610             if ( !aSeqArgs[nInd].Name.equals( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "VersionComment" ) ) )
1611               && !aSeqArgs[nInd].Name.equals( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Author" ) ) )
1612               && !aSeqArgs[nInd].Name.equals( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "InteractionHandler" ) ) )
1613               && !aSeqArgs[nInd].Name.equals( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "StatusIndicator" ) ) ) )
1614             {
1615                 m_pData->m_pObjectShell->AddLog( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX "unexpected parameter for storeSelf, might be no problem if SaveAs is executed." ) ) );
1616                 m_pData->m_pObjectShell->StoreLog();
1617 
1618                 ::rtl::OUString aMessage( RTL_CONSTASCII_USTRINGPARAM( "Unexpected MediaDescriptor parameter: " ) );
1619                 aMessage += aSeqArgs[nInd].Name;
1620                 throw lang::IllegalArgumentException( aMessage, uno::Reference< uno::XInterface >(), 1 );
1621             }
1622         }
1623 
1624         SfxAllItemSet *pParams = new SfxAllItemSet( SFX_APP()->GetPool() );
1625         TransformParameters( SID_SAVEDOC, aSeqArgs, *pParams );
1626 
1627         SFX_APP()->NotifyEvent( SfxEventHint( SFX_EVENT_SAVEDOC, GlobalEventConfig::GetEventName(STR_EVENT_SAVEDOC), m_pData->m_pObjectShell ) );
1628 
1629         sal_Bool bRet = sal_False;
1630 
1631         // TODO/LATER: let the embedded case of saving be handled more careful
1632         if ( m_pData->m_pObjectShell->GetCreateMode() == SFX_CREATE_MODE_EMBEDDED )
1633         {
1634             // If this is an embedded object that has no URL based location it should be stored to own storage.
1635             // An embedded object can have a location based on URL in case it is a link, then it should be
1636             // stored in normal way.
1637             if ( !hasLocation() || getLocation().compareToAscii( "private:", 8 ) == 0 )
1638             {
1639                 // actually in this very rare case only UI parameters have sence
1640                 // TODO/LATER: should be done later, after integration of sb19
1641                 bRet = m_pData->m_pObjectShell->DoSave()
1642                     && m_pData->m_pObjectShell->DoSaveCompleted();
1643             }
1644             else
1645             {
1646                 bRet = m_pData->m_pObjectShell->Save_Impl( pParams );
1647             }
1648         }
1649         else
1650             bRet = m_pData->m_pObjectShell->Save_Impl( pParams );
1651 
1652         DELETEZ( pParams );
1653 
1654         sal_uInt32 nErrCode = m_pData->m_pObjectShell->GetError() ? m_pData->m_pObjectShell->GetError()
1655                                                                     : ERRCODE_IO_CANTWRITE;
1656         m_pData->m_pObjectShell->ResetError();
1657 
1658         if ( bRet )
1659         {
1660             m_pData->m_pObjectShell->AddLog( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX "successful saving." ) ) );
1661             m_pData->m_aPreusedFilterName = GetMediumFilterName_Impl();
1662 
1663             SFX_APP()->NotifyEvent( SfxEventHint( SFX_EVENT_SAVEDOCDONE, GlobalEventConfig::GetEventName(STR_EVENT_SAVEDOCDONE), m_pData->m_pObjectShell ) );
1664         }
1665         else
1666         {
1667             m_pData->m_pObjectShell->AddLog( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX "Storing failed!" ) ) );
1668             m_pData->m_pObjectShell->StoreLog();
1669 
1670             // write the contents of the logger to the file
1671             SFX_APP()->NotifyEvent( SfxEventHint( SFX_EVENT_SAVEDOCFAILED, GlobalEventConfig::GetEventName(STR_EVENT_SAVEDOCFAILED), m_pData->m_pObjectShell ) );
1672 
1673             throw task::ErrorCodeIOException( ::rtl::OUString(), uno::Reference< uno::XInterface >(), nErrCode );
1674         }
1675     }
1676 
1677 }
1678 
1679 //________________________________________________________________________________________________________
1680 //  XStorable
1681 //________________________________________________________________________________________________________
1682 
1683 void SAL_CALL SfxBaseModel::store() throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException)
1684 {
1685     storeSelf( uno::Sequence< beans::PropertyValue >() );
1686 }
1687 
1688 //________________________________________________________________________________________________________
1689 //  XStorable
1690 //________________________________________________________________________________________________________
1691 
1692 void SAL_CALL SfxBaseModel::storeAsURL( const   ::rtl::OUString&                   rURL    ,
1693                                         const   uno::Sequence< beans::PropertyValue >&  rArgs   )
1694         throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException)
1695 {
1696     RTL_LOGFILE_PRODUCT_CONTEXT( aPerfLog, "PERFORMANCE - SfxBaseModel::storeAsURL" );
1697 
1698     SfxModelGuard aGuard( *this );
1699 
1700     if ( m_pData->m_pObjectShell.Is() )
1701     {
1702         m_pData->m_pObjectShell->AddLog( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX "storeAsURL" ) ) );
1703         SfxSaveGuard aSaveGuard(this, m_pData, sal_False);
1704 
1705         impl_store( rURL, rArgs, sal_False );
1706 
1707         uno::Sequence< beans::PropertyValue > aSequence ;
1708         TransformItems( SID_OPENDOC, *m_pData->m_pObjectShell->GetMedium()->GetItemSet(), aSequence );
1709         attachResource( rURL, aSequence );
1710 
1711 #if OSL_DEBUG_LEVEL > 0
1712         SFX_ITEMSET_ARG( m_pData->m_pObjectShell->GetMedium()->GetItemSet(), pPasswdItem, SfxStringItem, SID_PASSWORD, sal_False);
1713         OSL_ENSURE( !pPasswdItem, "There should be no Password property in the document MediaDescriptor!" );
1714 #endif
1715     }
1716 }
1717 
1718 //________________________________________________________________________________________________________
1719 //  XUndoManagerSupplier
1720 //________________________________________________________________________________________________________
1721 Reference< XUndoManager > SAL_CALL SfxBaseModel::getUndoManager(  ) throw (RuntimeException)
1722 {
1723     SfxModelGuard aGuard( *this );
1724     if ( !m_pData->m_pDocumentUndoManager.is() )
1725         m_pData->m_pDocumentUndoManager.set( new ::sfx2::DocumentUndoManager( *this ) );
1726     return m_pData->m_pDocumentUndoManager.get();
1727 }
1728 
1729 //________________________________________________________________________________________________________
1730 //  XStorable
1731 //________________________________________________________________________________________________________
1732 
1733 void SAL_CALL SfxBaseModel::storeToURL( const   ::rtl::OUString&                   rURL    ,
1734                                         const   uno::Sequence< beans::PropertyValue >&  rArgs   )
1735         throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException)
1736 {
1737     SfxModelGuard aGuard( *this );
1738 
1739     if ( m_pData->m_pObjectShell.Is() )
1740     {
1741         m_pData->m_pObjectShell->AddLog( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX "storeToURL" ) ) );
1742         SfxSaveGuard aSaveGuard(this, m_pData, sal_False);
1743         impl_store( rURL, rArgs, sal_True );
1744     }
1745 }
1746 
1747 ::sal_Bool SAL_CALL SfxBaseModel::wasModifiedSinceLastSave() throw ( RuntimeException )
1748 {
1749     SfxModelGuard aGuard( *this );
1750     return m_pData->m_bModifiedSinceLastSave;
1751 }
1752 
1753 void SAL_CALL SfxBaseModel::storeToRecoveryFile( const ::rtl::OUString& i_TargetLocation, const Sequence< PropertyValue >& i_MediaDescriptor ) throw ( RuntimeException, IOException, WrappedTargetException )
1754 {
1755     SfxModelGuard aGuard( *this );
1756 
1757     // delegate
1758     SfxSaveGuard aSaveGuard( this, m_pData, sal_False );
1759     impl_store( i_TargetLocation, i_MediaDescriptor, sal_True );
1760 
1761     // no need for subsequent calls to storeToRecoveryFile, unless we're modified, again
1762     m_pData->m_bModifiedSinceLastSave = sal_False;
1763 }
1764 
1765 void SAL_CALL SfxBaseModel::recoverFromFile( const ::rtl::OUString& i_SourceLocation, const ::rtl::OUString& i_SalvagedFile, const Sequence< PropertyValue >& i_MediaDescriptor ) throw ( RuntimeException, IOException, WrappedTargetException )
1766 {
1767     SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );
1768 
1769     // delegate to our "load" method
1770     ::comphelper::NamedValueCollection aMediaDescriptor( i_MediaDescriptor );
1771 
1772     // our load implementation expects the SalvagedFile to be in the media descriptor
1773     OSL_ENSURE( !aMediaDescriptor.has( "SalvagedFile" ) || ( aMediaDescriptor.getOrDefault( "SalvagedFile", ::rtl::OUString() ) == i_SalvagedFile ),
1774         "SfxBaseModel::recoverFromFile: inconsistent information!" );
1775     aMediaDescriptor.put( "SalvagedFile", i_SalvagedFile );
1776 
1777     // similar for the to-be-loaded file
1778     OSL_ENSURE( !aMediaDescriptor.has( "URL" ) || ( aMediaDescriptor.getOrDefault( "URL", ::rtl::OUString() ) == i_SourceLocation ),
1779         "SfxBaseModel::recoverFromFile: inconsistent information!" );
1780     aMediaDescriptor.put( "URL", i_SourceLocation );
1781 
1782     load( aMediaDescriptor.getPropertyValues() );
1783 
1784     // Note: The XDocumentRecovery interface specification requires us to do an attachResource after loading.
1785     // However, we will not do this here, as we know that our load implementation (respectively some method
1786     // called from there) already did so.
1787     // In particular, the load process might already have modified some elements of the media
1788     // descriptor, for instance the MacroExecMode (in case the user was involved to decide about it), and we do
1789     // not want to overwrite it with the "old" elements passed to this method here.
1790 }
1791 
1792 //________________________________________________________________________________________________________
1793 // XLoadable
1794 //________________________________________________________________________________________________________
1795 
1796 void SAL_CALL SfxBaseModel::initNew()
1797         throw (::com::sun::star::frame::DoubleInitializationException,
1798                ::com::sun::star::io::IOException,
1799                ::com::sun::star::uno::RuntimeException,
1800                ::com::sun::star::uno::Exception)
1801 {
1802     SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );
1803     if ( IsInitialized() )
1804         throw ::com::sun::star::frame::DoubleInitializationException( ::rtl::OUString(), *this );
1805 
1806     // the object shell should exist always
1807     DBG_ASSERT( m_pData->m_pObjectShell.Is(), "Model is useless without an ObjectShell" );
1808     if ( m_pData->m_pObjectShell.Is() )
1809     {
1810         if( m_pData->m_pObjectShell->GetMedium() )
1811             throw DOUBLEINITIALIZATIONEXCEPTION();
1812 
1813         sal_Bool bRes = m_pData->m_pObjectShell->DoInitNew( NULL );
1814         sal_uInt32 nErrCode = m_pData->m_pObjectShell->GetError() ?
1815                                     m_pData->m_pObjectShell->GetError() : ERRCODE_IO_CANTCREATE;
1816         m_pData->m_pObjectShell->ResetError();
1817 
1818         if ( !bRes )
1819             throw task::ErrorCodeIOException( ::rtl::OUString(), uno::Reference< uno::XInterface >(), nErrCode );
1820     }
1821 }
1822 
1823 //________________________________________________________________________________________________________
1824 // XLoadable
1825 //________________________________________________________________________________________________________
1826 
1827 void SAL_CALL SfxBaseModel::load(   const uno::Sequence< beans::PropertyValue >& seqArguments )
1828         throw (::com::sun::star::frame::DoubleInitializationException,
1829                ::com::sun::star::io::IOException,
1830                ::com::sun::star::uno::RuntimeException,
1831                ::com::sun::star::uno::Exception)
1832 {
1833     SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );
1834     if ( IsInitialized() )
1835         throw ::com::sun::star::frame::DoubleInitializationException( ::rtl::OUString(), *this );
1836 
1837     // the object shell should exist always
1838     DBG_ASSERT( m_pData->m_pObjectShell.Is(), "Model is useless without an ObjectShell" );
1839 
1840     if ( m_pData->m_pObjectShell.Is() )
1841     {
1842         if( m_pData->m_pObjectShell->GetMedium() )
1843             // if a Medium is present, the document is already initialized
1844             throw DOUBLEINITIALIZATIONEXCEPTION();
1845 
1846         SfxMedium* pMedium = new SfxMedium( seqArguments );
1847         String aFilterName;
1848         SFX_ITEMSET_ARG( pMedium->GetItemSet(), pFilterNameItem, SfxStringItem, SID_FILTER_NAME, sal_False );
1849         if( pFilterNameItem )
1850             aFilterName = pFilterNameItem->GetValue();
1851         if( !m_pData->m_pObjectShell->GetFactory().GetFilterContainer()->GetFilter4FilterName( aFilterName ) )
1852         {
1853             // filtername is not valid
1854             delete pMedium;
1855             throw frame::IllegalArgumentIOException();
1856         }
1857 
1858         // !TODO: currently not working
1859         //SFX_ITEMSET_ARG( pParams, pFrameItem, SfxFrameItem, SID_DOCFRAME, sal_False );
1860         //if( pFrameItem && pFrameItem->GetFrame() )
1861         //{
1862         //  SfxFrame* pFrame = pFrameItem->GetFrame();
1863         //  pMedium->SetLoadTargetFrame( pFrame );
1864         //}
1865 
1866         SFX_ITEMSET_ARG( pMedium->GetItemSet(), pSalvageItem, SfxStringItem, SID_DOC_SALVAGE, sal_False );
1867         sal_Bool bSalvage = pSalvageItem ? sal_True : sal_False;
1868 
1869         // SFX_ITEMSET_ARG( pMedium->GetItemSet(), pTemplateItem, SfxBoolItem, SID_TEMPLATE, sal_False);
1870         // sal_Bool bTemplate = pTemplateItem && pTemplateItem->GetValue();
1871         //
1872         // does already happen in DoLoad call
1873         //m_pData->m_pObjectShell->SetActivateEvent_Impl( bTemplate ? SFX_EVENT_CREATEDOC : SFX_EVENT_OPENDOC );
1874 
1875         // load document
1876         sal_uInt32 nError = ERRCODE_NONE;
1877         if ( !m_pData->m_pObjectShell->DoLoad(pMedium) )
1878             nError=ERRCODE_IO_GENERAL;
1879 
1880         // QUESTION: if the following happens outside of DoLoad, something important is missing there!
1881         ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionHandler > xHandler = pMedium->GetInteractionHandler();
1882         if( m_pData->m_pObjectShell->GetErrorCode() )
1883         {
1884             nError = m_pData->m_pObjectShell->GetErrorCode();
1885             if ( nError == ERRCODE_IO_BROKENPACKAGE && xHandler.is() )
1886             {
1887                 ::rtl::OUString aDocName = pMedium->GetURLObject().getName( INetURLObject::LAST_SEGMENT, true, INetURLObject::DECODE_WITH_CHARSET );
1888                 SFX_ITEMSET_ARG( pMedium->GetItemSet(), pRepairItem, SfxBoolItem, SID_REPAIRPACKAGE, sal_False );
1889                 if ( !pRepairItem || !pRepairItem->GetValue() )
1890                 {
1891                     RequestPackageReparation aRequest( aDocName );
1892                     xHandler->handle( aRequest.GetRequest() );
1893                     if( aRequest.isApproved() )
1894                     {
1895                         // broken package: try second loading and allow repair
1896                         pMedium->GetItemSet()->Put( SfxBoolItem( SID_REPAIRPACKAGE, sal_True ) );
1897                         pMedium->GetItemSet()->Put( SfxBoolItem( SID_TEMPLATE, sal_True ) );
1898                         pMedium->GetItemSet()->Put( SfxStringItem( SID_DOCINFO_TITLE, aDocName ) );
1899 
1900                         // the error must be reset and the storage must be reopened in new mode
1901                         pMedium->ResetError();
1902                         pMedium->CloseStorage();
1903                         m_pData->m_pObjectShell->PrepareSecondTryLoad_Impl();
1904                         if ( !m_pData->m_pObjectShell->DoLoad(pMedium) )
1905                             nError=ERRCODE_IO_GENERAL;
1906                         nError = m_pData->m_pObjectShell->GetErrorCode();
1907                     }
1908                 }
1909 
1910                 if ( nError == ERRCODE_IO_BROKENPACKAGE )
1911                 {
1912                     // repair either not allowed or not successful
1913                     NotifyBrokenPackage aRequest( aDocName );
1914                     xHandler->handle( aRequest.GetRequest() );
1915                 }
1916             }
1917         }
1918 
1919         if( m_pData->m_pObjectShell->IsAbortingImport() )
1920             nError = ERRCODE_ABORT;
1921 
1922         if( bSalvage )
1923         {
1924             // file recovery: restore original filter
1925             SFX_ITEMSET_ARG( pMedium->GetItemSet(), pFilterItem, SfxStringItem, SID_FILTER_NAME, sal_False );
1926             SfxFilterMatcher& rMatcher = SFX_APP()->GetFilterMatcher();
1927             const SfxFilter* pSetFilter = rMatcher.GetFilter4FilterName( pFilterItem->GetValue() );
1928             pMedium->SetFilter( pSetFilter );
1929             m_pData->m_pObjectShell->SetModified(sal_True);
1930         }
1931 
1932         // TODO/LATER: may be the mode should be retrieved from outside and the preused filter should not be set
1933         if ( m_pData->m_pObjectShell->GetCreateMode() == SFX_CREATE_MODE_EMBEDDED )
1934         {
1935             SFX_ITEMSET_ARG( pMedium->GetItemSet(), pFilterItem, SfxStringItem, SID_FILTER_NAME, sal_False );
1936             if ( pFilterItem )
1937                 m_pData->m_aPreusedFilterName = pFilterItem->GetValue();
1938         }
1939 
1940         if ( !nError )
1941             nError = pMedium->GetError();
1942 
1943         m_pData->m_pObjectShell->ResetError();
1944 
1945         if ( nError )
1946         {
1947             sal_Bool bSilent = sal_False;
1948             SFX_ITEMSET_ARG( pMedium->GetItemSet(), pSilentItem, SfxBoolItem, SID_SILENT, sal_False);
1949             if( pSilentItem )
1950                 bSilent = pSilentItem->GetValue();
1951 
1952             sal_Bool bWarning = ((nError & ERRCODE_WARNING_MASK) == ERRCODE_WARNING_MASK);
1953             if ( nError != ERRCODE_IO_BROKENPACKAGE && !bSilent )
1954             {
1955                 // broken package was handled already
1956                 if ( SfxObjectShell::UseInteractionToHandleError( xHandler, nError ) && !bWarning )
1957                 {
1958                     // abort loading (except for warnings)
1959                     nError = ERRCODE_IO_ABORT;
1960                 }
1961             }
1962 
1963             if ( m_pData->m_pObjectShell->GetMedium() != pMedium )
1964             {
1965                 // for whatever reason document now has another medium
1966                 DBG_ERROR("Document has rejected the medium?!");
1967                 delete pMedium;
1968             }
1969 
1970             if ( !bWarning )    // #i30711# don't abort loading if it's only a warning
1971             {
1972                 throw task::ErrorCodeIOException( ::rtl::OUString(),
1973                                                     uno::Reference< uno::XInterface >(),
1974                                                     nError ? nError : ERRCODE_IO_CANTREAD );
1975             }
1976         }
1977 
1978         sal_Bool bHidden = sal_False;
1979         SFX_ITEMSET_ARG( pMedium->GetItemSet(), pHidItem, SfxBoolItem, SID_HIDDEN, sal_False);
1980         if ( pHidItem )
1981             bHidden = pHidItem->GetValue();
1982 
1983 #if OSL_DEBUG_LEVEL > 0
1984         SFX_ITEMSET_ARG( pMedium->GetItemSet(), pPasswdItem, SfxStringItem, SID_PASSWORD, sal_False);
1985         OSL_ENSURE( !pPasswdItem, "There should be no Password property in the document MediaDescriptor!" );
1986 #endif
1987         // !TODO: will be done by Framework!
1988         pMedium->SetUpdatePickList( !bHidden );
1989     }
1990 }
1991 
1992 //________________________________________________________________________________________________________
1993 // XTransferable
1994 //________________________________________________________________________________________________________
1995 
1996 uno::Any SAL_CALL SfxBaseModel::getTransferData( const DATAFLAVOR& aFlavor )
1997         throw (::com::sun::star::datatransfer::UnsupportedFlavorException,
1998                ::com::sun::star::io::IOException,
1999                ::com::sun::star::uno::RuntimeException)
2000 {
2001     SfxModelGuard aGuard( *this );
2002 
2003     uno::Any aAny;
2004 
2005     if ( m_pData->m_pObjectShell.Is() )
2006     {
2007         if ( aFlavor.MimeType.equalsAscii( "application/x-openoffice-objectdescriptor-xml;windows_formatname=\"Star Object Descriptor (XML)\"" ) )
2008         {
2009             if ( aFlavor.DataType == getCppuType( (const Sequence< sal_Int8 >*) 0 ) )
2010             {
2011                 TransferableObjectDescriptor aDesc;
2012 
2013                 aDesc.maClassName = m_pData->m_pObjectShell->GetClassName();
2014                 aDesc.maTypeName = aFlavor.HumanPresentableName;
2015 
2016                 // TODO/LATER: ViewAspect needs to be sal_Int64
2017                 aDesc.mnViewAspect = sal::static_int_cast< sal_uInt16 >( embed::Aspects::MSOLE_CONTENT );
2018 
2019                 //TODO/LATER: status needs to become sal_Int64
2020                 aDesc.mnOle2Misc = m_pData->m_pObjectShell->GetMiscStatus();
2021                 Size aSize = m_pData->m_pObjectShell->GetVisArea().GetSize();
2022 
2023                 MapUnit aMapUnit = m_pData->m_pObjectShell->GetMapUnit();
2024                 aDesc.maSize = OutputDevice::LogicToLogic( aSize, aMapUnit, MAP_100TH_MM );
2025                 aDesc.maDragStartPos = Point();
2026                 aDesc.maDisplayName = String();
2027                 aDesc.mbCanLink = sal_False;
2028 
2029                 SvMemoryStream aMemStm( 1024, 1024 );
2030                 aMemStm << aDesc;
2031                 aAny <<= Sequence< sal_Int8 >( reinterpret_cast< const sal_Int8* >( aMemStm.GetData() ), aMemStm.Tell() );
2032             }
2033             else
2034                 throw datatransfer::UnsupportedFlavorException();
2035         }
2036         else if ( aFlavor.MimeType.equalsAscii( "application/x-openoffice-embed-source;windows_formatname=\"Star EMBS\"" ) )
2037         {
2038             if ( aFlavor.DataType == getCppuType( (const Sequence< sal_Int8 >*) 0 ) )
2039             {
2040                 try
2041                 {
2042                     utl::TempFile aTmp;
2043                     aTmp.EnableKillingFile( sal_True );
2044                     storeToURL( aTmp.GetURL(), uno::Sequence < beans::PropertyValue >() );
2045                     SvStream* pStream = aTmp.GetStream( STREAM_READ );
2046                     const sal_uInt32 nLen = pStream->Seek( STREAM_SEEK_TO_END );
2047                     ::com::sun::star::uno::Sequence< sal_Int8 > aSeq( nLen );
2048                     pStream->Seek( STREAM_SEEK_TO_BEGIN );
2049                     pStream->Read( aSeq.getArray(),  nLen );
2050                     delete pStream;
2051                     if( aSeq.getLength() )
2052                         aAny <<= aSeq;
2053                 }
2054                 catch ( uno::Exception& )
2055                 {
2056                 }
2057             }
2058             else
2059                 throw datatransfer::UnsupportedFlavorException();
2060         }
2061         else if ( aFlavor.MimeType.equalsAscii( "application/x-openoffice-gdimetafile;windows_formatname=\"GDIMetaFile\"" ) )
2062         {
2063             if ( aFlavor.DataType == getCppuType( (const Sequence< sal_Int8 >*) 0 ) )
2064             {
2065 
2066                 ::boost::shared_ptr<GDIMetaFile> pMetaFile =
2067                     m_pData->m_pObjectShell->GetPreviewMetaFile( sal_True );
2068 
2069                 if ( pMetaFile )
2070                 {
2071                     SvMemoryStream aMemStm( 65535, 65535 );
2072                     aMemStm.SetVersion( SOFFICE_FILEFORMAT_CURRENT );
2073 
2074                     pMetaFile->Write( aMemStm );
2075                     aAny <<= Sequence< sal_Int8 >( reinterpret_cast< const sal_Int8* >( aMemStm.GetData() ),
2076                                                     aMemStm.Seek( STREAM_SEEK_TO_END ) );
2077                 }
2078             }
2079             else
2080                 throw datatransfer::UnsupportedFlavorException();
2081         }
2082         else if ( aFlavor.MimeType.equalsAscii( "application/x-openoffice-highcontrast-gdimetafile;windows_formatname=\"GDIMetaFile\"" ) )
2083         {
2084             if ( aFlavor.DataType == getCppuType( (const Sequence< sal_Int8 >*) 0 ) )
2085             {
2086                 ::boost::shared_ptr<GDIMetaFile> pMetaFile =
2087                     m_pData->m_pObjectShell->CreatePreviewMetaFile_Impl( sal_True, sal_True );
2088 
2089                 if ( pMetaFile )
2090                 {
2091                     SvMemoryStream aMemStm( 65535, 65535 );
2092                     aMemStm.SetVersion( SOFFICE_FILEFORMAT_CURRENT );
2093 
2094                     pMetaFile->Write( aMemStm );
2095                     aAny <<= Sequence< sal_Int8 >( reinterpret_cast< const sal_Int8* >( aMemStm.GetData() ),
2096                                                     aMemStm.Seek( STREAM_SEEK_TO_END ) );
2097                 }
2098             }
2099             else
2100                 throw datatransfer::UnsupportedFlavorException();
2101         }
2102         else if ( aFlavor.MimeType.equalsAscii( "application/x-openoffice-emf;windows_formatname=\"Image EMF\"" ) )
2103         {
2104             if ( aFlavor.DataType == getCppuType( (const Sequence< sal_Int8 >*) 0 ) )
2105             {
2106                 ::boost::shared_ptr<GDIMetaFile> pMetaFile =
2107                     m_pData->m_pObjectShell->GetPreviewMetaFile( sal_True );
2108 
2109                 if ( pMetaFile )
2110                 {
2111                     ::boost::shared_ptr<SvMemoryStream> pStream(
2112                         GraphicHelper::getFormatStrFromGDI_Impl(
2113                             pMetaFile.get(), CVT_EMF ) );
2114                     if ( pStream )
2115                     {
2116                         pStream->SetVersion( SOFFICE_FILEFORMAT_CURRENT );
2117                         aAny <<= Sequence< sal_Int8 >( reinterpret_cast< const sal_Int8* >( pStream->GetData() ),
2118                                                         pStream->Seek( STREAM_SEEK_TO_END ) );
2119                     }
2120                 }
2121             }
2122             else if ( GraphicHelper::supportsMetaFileHandle_Impl()
2123               && aFlavor.DataType == getCppuType( (const sal_uInt64*) 0 ) )
2124             {
2125                 ::boost::shared_ptr<GDIMetaFile> pMetaFile =
2126                     m_pData->m_pObjectShell->GetPreviewMetaFile( sal_True );
2127 
2128                 if ( pMetaFile )
2129                 {
2130                     aAny <<= reinterpret_cast< const sal_uInt64 >(
2131                         GraphicHelper::getEnhMetaFileFromGDI_Impl( pMetaFile.get() ) );
2132                 }
2133             }
2134             else
2135                 throw datatransfer::UnsupportedFlavorException();
2136         }
2137         else if ( aFlavor.MimeType.equalsAscii( "application/x-openoffice-wmf;windows_formatname=\"Image WMF\"" ) )
2138         {
2139             if ( aFlavor.DataType == getCppuType( (const Sequence< sal_Int8 >*) 0 ) )
2140             {
2141                 ::boost::shared_ptr<GDIMetaFile> pMetaFile =
2142                     m_pData->m_pObjectShell->GetPreviewMetaFile( sal_True );
2143 
2144                 if ( pMetaFile )
2145                 {
2146                     ::boost::shared_ptr<SvMemoryStream> pStream(
2147                         GraphicHelper::getFormatStrFromGDI_Impl(
2148                             pMetaFile.get(), CVT_WMF ) );
2149 
2150                     if ( pStream )
2151                     {
2152                         pStream->SetVersion( SOFFICE_FILEFORMAT_CURRENT );
2153                         aAny <<= Sequence< sal_Int8 >( reinterpret_cast< const sal_Int8* >( pStream->GetData() ),
2154                                                         pStream->Seek( STREAM_SEEK_TO_END ) );
2155                     }
2156                 }
2157             }
2158             else if ( GraphicHelper::supportsMetaFileHandle_Impl()
2159               && aFlavor.DataType == getCppuType( (const sal_uInt64*) 0 ) )
2160             {
2161                 // means HGLOBAL handler to memory storage containing METAFILEPICT structure
2162 
2163                 ::boost::shared_ptr<GDIMetaFile> pMetaFile =
2164                     m_pData->m_pObjectShell->GetPreviewMetaFile( sal_True );
2165 
2166                 if ( pMetaFile )
2167                 {
2168                     Size aMetaSize = pMetaFile->GetPrefSize();
2169                     aAny <<= reinterpret_cast< const sal_uInt64 >(
2170                         GraphicHelper::getWinMetaFileFromGDI_Impl(
2171                             pMetaFile.get(), aMetaSize ) );
2172                 }
2173             }
2174             else
2175                 throw datatransfer::UnsupportedFlavorException();
2176         }
2177         else if ( aFlavor.MimeType.equalsAscii( "application/x-openoffice-bitmap;windows_formatname=\"Bitmap\"" ) )
2178         {
2179             if ( aFlavor.DataType == getCppuType( (const Sequence< sal_Int8 >*) 0 ) )
2180             {
2181                 ::boost::shared_ptr<GDIMetaFile> pMetaFile =
2182                     m_pData->m_pObjectShell->GetPreviewMetaFile( sal_True );
2183 
2184                 if ( pMetaFile )
2185                 {
2186                     ::boost::shared_ptr<SvMemoryStream> pStream(
2187                         GraphicHelper::getFormatStrFromGDI_Impl(
2188                             pMetaFile.get(), CVT_BMP ) );
2189 
2190                     if ( pStream )
2191                     {
2192                         pStream->SetVersion( SOFFICE_FILEFORMAT_CURRENT );
2193                         aAny <<= Sequence< sal_Int8 >( reinterpret_cast< const sal_Int8* >( pStream->GetData() ),
2194                                                         pStream->Seek( STREAM_SEEK_TO_END ) );
2195                     }
2196                 }
2197             }
2198             else
2199                 throw datatransfer::UnsupportedFlavorException();
2200         }
2201         else if ( aFlavor.MimeType.equalsAscii( "image/png" ) )
2202         {
2203             if ( aFlavor.DataType == getCppuType( (const Sequence< sal_Int8 >*) 0 ) )
2204             {
2205                 ::boost::shared_ptr<GDIMetaFile> pMetaFile =
2206                     m_pData->m_pObjectShell->GetPreviewMetaFile( sal_True );
2207 
2208                 if ( pMetaFile )
2209                 {
2210                     ::boost::shared_ptr<SvMemoryStream> pStream(
2211                         GraphicHelper::getFormatStrFromGDI_Impl(
2212                             pMetaFile.get(), CVT_PNG ) );
2213 
2214                     if ( pStream )
2215                     {
2216                         pStream->SetVersion( SOFFICE_FILEFORMAT_CURRENT );
2217                         aAny <<= Sequence< sal_Int8 >( reinterpret_cast< const sal_Int8* >( pStream->GetData() ),
2218                                                         pStream->Seek( STREAM_SEEK_TO_END ) );
2219                     }
2220                 }
2221             }
2222             else
2223                 throw datatransfer::UnsupportedFlavorException();
2224         }
2225         else
2226             throw datatransfer::UnsupportedFlavorException();
2227     }
2228 
2229     return aAny;
2230 }
2231 
2232 //________________________________________________________________________________________________________
2233 // XTransferable
2234 //________________________________________________________________________________________________________
2235 
2236 
2237 uno::Sequence< DATAFLAVOR > SAL_CALL SfxBaseModel::getTransferDataFlavors()
2238         throw (::com::sun::star::uno::RuntimeException)
2239 {
2240     SfxModelGuard aGuard( *this );
2241 
2242     sal_Int32 nSuppFlavors = GraphicHelper::supportsMetaFileHandle_Impl() ? 10 : 8;
2243     uno::Sequence< DATAFLAVOR > aFlavorSeq( nSuppFlavors );
2244 
2245     aFlavorSeq[0].MimeType =
2246         ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "application/x-openoffice-gdimetafile;windows_formatname=\"GDIMetaFile\"" ) );
2247     aFlavorSeq[0].HumanPresentableName = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "GDIMetaFile" ) );
2248     aFlavorSeq[0].DataType = getCppuType( (const Sequence< sal_Int8 >*) 0 );
2249 
2250     aFlavorSeq[1].MimeType =
2251         ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "application/x-openoffice-highcontrast-gdimetafile;windows_formatname=\"GDIMetaFile\"" ) );
2252     aFlavorSeq[1].HumanPresentableName = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "GDIMetaFile" ) );
2253     aFlavorSeq[1].DataType = getCppuType( (const Sequence< sal_Int8 >*) 0 );
2254 
2255     aFlavorSeq[2].MimeType =
2256         ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "application/x-openoffice-emf;windows_formatname=\"Image EMF\"" ) );
2257     aFlavorSeq[2].HumanPresentableName = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Enhanced Windows MetaFile" ) );
2258     aFlavorSeq[2].DataType = getCppuType( (const Sequence< sal_Int8 >*) 0 );
2259 
2260     aFlavorSeq[3].MimeType =
2261         ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "application/x-openoffice-wmf;windows_formatname=\"Image WMF\"" ) );
2262     aFlavorSeq[3].HumanPresentableName = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Windows MetaFile" ) );
2263     aFlavorSeq[3].DataType = getCppuType( (const Sequence< sal_Int8 >*) 0 );
2264 
2265     aFlavorSeq[4].MimeType =
2266         ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "application/x-openoffice-objectdescriptor-xml;windows_formatname=\"Star Object Descriptor (XML)\"" ) );
2267     aFlavorSeq[4].HumanPresentableName = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Star Object Descriptor (XML)" ) );
2268     aFlavorSeq[4].DataType = getCppuType( (const Sequence< sal_Int8 >*) 0 );
2269 
2270     aFlavorSeq[5].MimeType =
2271         ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "application/x-openoffice-embed-source-xml;windows_formatname=\"Star Embed Source (XML)\"" ) );
2272     aFlavorSeq[5].HumanPresentableName = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Star Embed Source (XML)" ) );
2273     aFlavorSeq[5].DataType = getCppuType( (const Sequence< sal_Int8 >*) 0 );
2274 
2275     aFlavorSeq[6].MimeType =
2276         ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "application/x-openoffice-bitmap;windows_formatname=\"Bitmap\"" ) );
2277     aFlavorSeq[6].HumanPresentableName = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Bitmap" ) );
2278     aFlavorSeq[6].DataType = getCppuType( (const Sequence< sal_Int8 >*) 0 );
2279 
2280     aFlavorSeq[7].MimeType =
2281         ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "image/png" ) );
2282     aFlavorSeq[7].HumanPresentableName = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PNG" ) );
2283     aFlavorSeq[7].DataType = getCppuType( (const Sequence< sal_Int8 >*) 0 );
2284 
2285     if ( nSuppFlavors == 10 )
2286     {
2287         aFlavorSeq[8].MimeType =
2288             ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "application/x-openoffice-emf;windows_formatname=\"Image EMF\"" ) );
2289         aFlavorSeq[8].HumanPresentableName = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Enhanced Windows MetaFile" ) );
2290         aFlavorSeq[8].DataType = getCppuType( (const sal_uInt64*) 0 );
2291 
2292         aFlavorSeq[9].MimeType =
2293             ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "application/x-openoffice-wmf;windows_formatname=\"Image WMF\"" ) );
2294         aFlavorSeq[9].HumanPresentableName = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Windows MetaFile" ) );
2295         aFlavorSeq[9].DataType = getCppuType( (const sal_uInt64*) 0 );
2296     }
2297 
2298     return aFlavorSeq;
2299 }
2300 
2301 //________________________________________________________________________________________________________
2302 // XTransferable
2303 //________________________________________________________________________________________________________
2304 
2305 
2306 sal_Bool SAL_CALL SfxBaseModel::isDataFlavorSupported( const DATAFLAVOR& aFlavor )
2307         throw (::com::sun::star::uno::RuntimeException)
2308 {
2309     SfxModelGuard aGuard( *this );
2310 
2311     if ( aFlavor.MimeType.equalsAscii( "application/x-openoffice-gdimetafile;windows_formatname=\"GDIMetaFile\"" ) )
2312     {
2313         if ( aFlavor.DataType == getCppuType( (const Sequence< sal_Int8 >*) 0 ) )
2314             return sal_True;
2315     }
2316     else if ( aFlavor.MimeType.equalsAscii( "application/x-openoffice-highcontrast-gdimetafile;windows_formatname=\"GDIMetaFile\"" ) )
2317     {
2318         if ( aFlavor.DataType == getCppuType( (const Sequence< sal_Int8 >*) 0 ) )
2319             return sal_True;
2320     }
2321     else if ( aFlavor.MimeType.equalsAscii( "application/x-openoffice-emf;windows_formatname=\"Image EMF\"" ) )
2322     {
2323         if ( aFlavor.DataType == getCppuType( (const Sequence< sal_Int8 >*) 0 ) )
2324             return sal_True;
2325         else if ( GraphicHelper::supportsMetaFileHandle_Impl()
2326           && aFlavor.DataType == getCppuType( (const sal_uInt64*) 0 ) )
2327             return sal_True;
2328     }
2329     else if ( aFlavor.MimeType.equalsAscii( "application/x-openoffice-wmf;windows_formatname=\"Image WMF\"" ) )
2330     {
2331         if ( aFlavor.DataType == getCppuType( (const Sequence< sal_Int8 >*) 0 ) )
2332             return sal_True;
2333         else if ( GraphicHelper::supportsMetaFileHandle_Impl()
2334           && aFlavor.DataType == getCppuType( (const sal_uInt64*) 0 ) )
2335             return sal_True;
2336     }
2337     else if ( aFlavor.MimeType.equalsAscii( "application/x-openoffice-objectdescriptor-xml;windows_formatname=\"Star Object Descriptor (XML)\"" ) )
2338     {
2339         if ( aFlavor.DataType == getCppuType( (const Sequence< sal_Int8 >*) 0 ) )
2340             return sal_True;
2341     }
2342     else if ( aFlavor.MimeType.equalsAscii( "application/x-openoffice-embed-source;windows_formatname=\"Star EMBS\"" ) )
2343     {
2344         if ( aFlavor.DataType == getCppuType( (const Sequence< sal_Int8 >*) 0 ) )
2345             return sal_True;
2346     }
2347     else if ( aFlavor.MimeType.equalsAscii( "application/x-openoffice-bitmap;windows_formatname=\"Bitmap\"" ) )
2348     {
2349         if ( aFlavor.DataType == getCppuType( (const Sequence< sal_Int8 >*) 0 ) )
2350             return sal_True;
2351     }
2352     else if ( aFlavor.MimeType.equalsAscii( "image/png" ) )
2353     {
2354         if ( aFlavor.DataType == getCppuType( (const Sequence< sal_Int8 >*) 0 ) )
2355             return sal_True;
2356     }
2357 
2358     return sal_False;
2359 }
2360 
2361 
2362 //--------------------------------------------------------------------------------------------------------
2363 //  XEventsSupplier
2364 //--------------------------------------------------------------------------------------------------------
2365 
2366 uno::Reference< container::XNameReplace > SAL_CALL SfxBaseModel::getEvents() throw( uno::RuntimeException )
2367 {
2368     SfxModelGuard aGuard( *this );
2369 
2370     if ( ! m_pData->m_xEvents.is() )
2371     {
2372         m_pData->m_xEvents = new SfxEvents_Impl( m_pData->m_pObjectShell, this );
2373     }
2374 
2375     return m_pData->m_xEvents;
2376 }
2377 
2378 //--------------------------------------------------------------------------------------------------------
2379 //  XEmbeddedScripts
2380 //--------------------------------------------------------------------------------------------------------
2381 
2382 uno::Reference< script::XStorageBasedLibraryContainer > SAL_CALL SfxBaseModel::getBasicLibraries() throw (RuntimeException)
2383 {
2384     SfxModelGuard aGuard( *this );
2385 
2386     uno::Reference< script::XStorageBasedLibraryContainer > xBasicLibraries;
2387     if ( m_pData->m_pObjectShell )
2388         xBasicLibraries.set( m_pData->m_pObjectShell->GetBasicContainer(), UNO_QUERY_THROW );
2389     return xBasicLibraries;
2390 }
2391 
2392 uno::Reference< script::XStorageBasedLibraryContainer > SAL_CALL SfxBaseModel::getDialogLibraries() throw (RuntimeException)
2393 {
2394     SfxModelGuard aGuard( *this );
2395 
2396     uno::Reference< script::XStorageBasedLibraryContainer > xDialogLibraries;
2397     if ( m_pData->m_pObjectShell )
2398         xDialogLibraries.set( m_pData->m_pObjectShell->GetDialogContainer(), UNO_QUERY_THROW );
2399     return xDialogLibraries;
2400 }
2401 
2402 ::sal_Bool SAL_CALL SfxBaseModel::getAllowMacroExecution() throw (RuntimeException)
2403 {
2404     SfxModelGuard aGuard( *this );
2405 
2406     if ( m_pData->m_pObjectShell )
2407         return m_pData->m_pObjectShell->AdjustMacroMode( String(), false );
2408     return sal_False;
2409 }
2410 
2411 //--------------------------------------------------------------------------------------------------------
2412 //  XScriptInvocationContext
2413 //--------------------------------------------------------------------------------------------------------
2414 
2415 Reference< document::XEmbeddedScripts > SAL_CALL SfxBaseModel::getScriptContainer() throw (RuntimeException)
2416 {
2417     SfxModelGuard aGuard( *this );
2418 
2419     Reference< document::XEmbeddedScripts > xDocumentScripts;
2420 
2421     try
2422     {
2423         Reference< frame::XModel > xDocument( this );
2424         xDocumentScripts.set( xDocument, uno::UNO_QUERY );
2425         while ( !xDocumentScripts.is() && xDocument.is() )
2426         {
2427             Reference< container::XChild > xDocAsChild( xDocument, uno::UNO_QUERY );
2428             if ( !xDocAsChild.is() )
2429             {
2430                 xDocument = NULL;
2431                 break;
2432             }
2433 
2434             xDocument.set( xDocAsChild->getParent(), uno::UNO_QUERY );
2435             xDocumentScripts.set( xDocument, uno::UNO_QUERY );
2436         }
2437     }
2438     catch( const Exception& )
2439     {
2440         DBG_UNHANDLED_EXCEPTION();
2441         xDocumentScripts = NULL;
2442     }
2443 
2444     return xDocumentScripts;
2445 }
2446 
2447 //--------------------------------------------------------------------------------------------------------
2448 //  XEventBroadcaster
2449 //--------------------------------------------------------------------------------------------------------
2450 
2451 void SAL_CALL SfxBaseModel::addEventListener( const uno::Reference< XDOCEVENTLISTENER >& aListener ) throw( uno::RuntimeException )
2452 {
2453     SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );
2454 
2455     m_pData->m_aInterfaceContainer.addInterface( ::getCppuType((const uno::Reference< XDOCEVENTLISTENER >*)0), aListener );
2456 }
2457 
2458 //--------------------------------------------------------------------------------------------------------
2459 //  XEventBroadcaster
2460 //--------------------------------------------------------------------------------------------------------
2461 
2462 void SAL_CALL SfxBaseModel::removeEventListener( const uno::Reference< XDOCEVENTLISTENER >& aListener ) throw( uno::RuntimeException )
2463 {
2464     SfxModelGuard aGuard( *this );
2465 
2466     m_pData->m_aInterfaceContainer.removeInterface( ::getCppuType((const uno::Reference< XDOCEVENTLISTENER >*)0), aListener );
2467 }
2468 
2469 //--------------------------------------------------------------------------------------------------------
2470 //  XDocumentEventBroadcaster
2471 //--------------------------------------------------------------------------------------------------------
2472 // ---------------------------------
2473 void SAL_CALL SfxBaseModel::addDocumentEventListener( const uno::Reference< document::XDocumentEventListener >& aListener )
2474     throw ( uno::RuntimeException )
2475 {
2476     SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );
2477     m_pData->m_aInterfaceContainer.addInterface( ::getCppuType((const uno::Reference< document::XDocumentEventListener >*)0), aListener );
2478 }
2479 
2480 // ---------------------------------
2481 void SAL_CALL SfxBaseModel::removeDocumentEventListener( const uno::Reference< document::XDocumentEventListener >& aListener )
2482     throw ( uno::RuntimeException )
2483 {
2484     SfxModelGuard aGuard( *this );
2485     m_pData->m_aInterfaceContainer.removeInterface( ::getCppuType((const uno::Reference< document::XDocumentEventListener >*)0), aListener );
2486 }
2487 
2488 // ---------------------------------
2489 void SAL_CALL SfxBaseModel::notifyDocumentEvent( const ::rtl::OUString&, const uno::Reference< frame::XController2 >&, const uno::Any& )
2490     throw ( lang::IllegalArgumentException, lang::NoSupportException, uno::RuntimeException )
2491 {
2492     throw lang::NoSupportException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "SfxBaseModel controlls all the sent notifications itself!" ) ), uno::Reference< uno::XInterface >() );
2493 }
2494 
2495 //________________________________________________________________________________________________________
2496 //  SfxListener
2497 //________________________________________________________________________________________________________
2498 
2499 void addTitle_Impl( Sequence < ::com::sun::star::beans::PropertyValue >& rSeq, const ::rtl::OUString& rTitle )
2500 {
2501     sal_Int32 nCount = rSeq.getLength();
2502     sal_Int32 nArg;
2503 
2504     for ( nArg = 0; nArg < nCount; nArg++ )
2505     {
2506         ::com::sun::star::beans::PropertyValue& rProp = rSeq[nArg];
2507         if ( rProp.Name.equalsAscii("Title") )
2508         {
2509             rProp.Value <<= rTitle;
2510             break;
2511         }
2512     }
2513 
2514     if ( nArg == nCount )
2515     {
2516         rSeq.realloc( nCount+1 );
2517         rSeq[nCount].Name = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("Title") );
2518         rSeq[nCount].Value <<= rTitle;
2519     }
2520 }
2521 
2522 void SfxBaseModel::NotifyStorageListeners_Impl()
2523 {
2524     uno::Reference< uno::XInterface > xSelfHold( static_cast< ::cppu::OWeakObject* >(this) );
2525 
2526     if ( m_pData->m_pObjectShell )
2527     {
2528         ::cppu::OInterfaceContainerHelper* pContainer =
2529             m_pData->m_aInterfaceContainer.getContainer(
2530                 ::getCppuType( ( const uno::Reference< document::XStorageChangeListener >*) NULL ) );
2531         if ( pContainer != NULL )
2532         {
2533             uno::Reference< embed::XStorage > xNewStorage = m_pData->m_pObjectShell->GetStorage();
2534             ::cppu::OInterfaceIteratorHelper pIterator(*pContainer);
2535             while ( pIterator.hasMoreElements() )
2536             {
2537                 try
2538                 {
2539                     ((document::XStorageChangeListener*)pIterator.next())->notifyStorageChange(
2540                                                                             xSelfHold,
2541                                                                             xNewStorage );
2542                 }
2543                 catch( uno::RuntimeException& )
2544                 {
2545                     pIterator.remove();
2546                 }
2547             }
2548         }
2549     }
2550 }
2551 
2552 void SfxBaseModel::Notify(          SfxBroadcaster& rBC     ,
2553                             const   SfxHint&        rHint   )
2554 {
2555     if ( !m_pData )
2556         return;
2557 
2558     if ( &rBC == m_pData->m_pObjectShell )
2559     {
2560         SfxSimpleHint* pSimpleHint = PTR_CAST( SfxSimpleHint, &rHint );
2561         if ( pSimpleHint && pSimpleHint->GetId() == SFX_HINT_DOCCHANGED )
2562             changing();
2563 
2564         SfxEventHint* pNamedHint = PTR_CAST( SfxEventHint, &rHint );
2565         if ( pNamedHint )
2566         {
2567 
2568             switch ( pNamedHint->GetEventId() )
2569             {
2570             case SFX_EVENT_STORAGECHANGED:
2571             {
2572                 // for now this event is sent only on creation of a new storage for new document
2573                 // and in case of reload of medium without document reload
2574                 // other events are used to detect storage change
2575                 // NotifyStorageListeners_Impl();
2576 
2577                 if ( m_pData->m_xUIConfigurationManager.is()
2578                   && m_pData->m_pObjectShell->GetCreateMode() != SFX_CREATE_MODE_EMBEDDED )
2579                 {
2580                     uno::Reference< XSTORAGE > xConfigStorage;
2581                     rtl::OUString aUIConfigFolderName( RTL_CONSTASCII_USTRINGPARAM( "Configurations2" ));
2582 
2583                     xConfigStorage = getDocumentSubStorage( aUIConfigFolderName, com::sun::star::embed::ElementModes::READWRITE );
2584                     if ( !xConfigStorage.is() )
2585                         xConfigStorage = getDocumentSubStorage( aUIConfigFolderName, com::sun::star::embed::ElementModes::READ );
2586 
2587                     if ( xConfigStorage.is() || !m_pData->m_pObjectShell->GetStorage()->hasByName( aUIConfigFolderName ) )
2588                     {
2589                         // the storage is different, since otherwise it could not be opened, so it must be exchanged
2590                         Reference< ui::XUIConfigurationStorage > xUIConfigStorage( m_pData->m_xUIConfigurationManager, uno::UNO_QUERY );
2591                         xUIConfigStorage->setStorage( xConfigStorage );
2592                     }
2593                     else
2594                     {
2595                         OSL_ENSURE( sal_False, "Unexpected scenario!\n" );
2596                     }
2597                 }
2598 
2599                 ListenForStorage_Impl( m_pData->m_pObjectShell->GetStorage() );
2600             }
2601             break;
2602 
2603             case SFX_EVENT_LOADFINISHED:
2604             {
2605                 impl_getPrintHelper();
2606                 ListenForStorage_Impl( m_pData->m_pObjectShell->GetStorage() );
2607                 m_pData->m_bModifiedSinceLastSave = sal_False;
2608             }
2609             break;
2610 
2611             case SFX_EVENT_SAVEASDOCDONE:
2612             {
2613                 m_pData->m_sURL = m_pData->m_pObjectShell->GetMedium()->GetName();
2614 
2615                 SfxItemSet *pSet = m_pData->m_pObjectShell->GetMedium()->GetItemSet();
2616                 ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aArgs;
2617                 ::rtl::OUString aTitle = m_pData->m_pObjectShell->GetTitle();
2618                 TransformItems( SID_SAVEASDOC, *pSet, aArgs );
2619                 addTitle_Impl( aArgs, aTitle );
2620                 attachResource( m_pData->m_pObjectShell->GetMedium()->GetName(), aArgs );
2621             }
2622             break;
2623 
2624             case SFX_EVENT_DOCCREATED:
2625             {
2626                 impl_getPrintHelper();
2627                 m_pData->m_bModifiedSinceLastSave = sal_False;
2628             }
2629             break;
2630 
2631             case SFX_EVENT_MODIFYCHANGED:
2632             {
2633                 m_pData->m_bModifiedSinceLastSave = isModified();
2634             }
2635             break;
2636             }
2637 
2638 
2639             SfxViewEventHint* pViewHint = PTR_CAST( SfxViewEventHint, &rHint );
2640             postEvent_Impl( pNamedHint->GetEventName(), pViewHint ? pViewHint->GetController() : uno::Reference< frame::XController2 >() );
2641         }
2642 
2643         if ( pSimpleHint )
2644         {
2645             if ( pSimpleHint->GetId() == SFX_HINT_TITLECHANGED )
2646             {
2647                 ::rtl::OUString aTitle = m_pData->m_pObjectShell->GetTitle();
2648                 addTitle_Impl( m_pData->m_seqArguments, aTitle );
2649                 postEvent_Impl( GlobalEventConfig::GetEventName( STR_EVENT_TITLECHANGED ) );
2650             }
2651             if ( pSimpleHint->GetId() == SFX_HINT_MODECHANGED )
2652             {
2653                 postEvent_Impl( GlobalEventConfig::GetEventName( STR_EVENT_MODECHANGED ) );
2654             }
2655 /*
2656             else if ( pSimpleHint->GetId() == SFX_HINT_DYING
2657                 || pSimpleHint->GetId() == SFX_HINT_DEINITIALIZING )
2658             {
2659                 SfxObjectShellLock pShellLock = m_pData->m_pObjectShellLock;
2660                 m_pData->m_pObjectShellLock = SfxObjectShellLock();
2661             }
2662 */
2663         }
2664     }
2665 }
2666 
2667 //________________________________________________________________________________________________________
2668 //  public impl.
2669 //________________________________________________________________________________________________________
2670 
2671 void SfxBaseModel::NotifyModifyListeners_Impl() const
2672 {
2673     ::cppu::OInterfaceContainerHelper* pIC = m_pData->m_aInterfaceContainer.getContainer( ::getCppuType((const uno::Reference< XMODIFYLISTENER >*)0) );
2674     if ( pIC )
2675     {
2676         lang::EventObject aEvent( (frame::XModel *)this );
2677         pIC->notifyEach( &util::XModifyListener::modified, aEvent );
2678     }
2679 
2680     // this notification here is done too generously, we cannot simply assume that we're really modified
2681     // now, but we need to check it ...
2682     m_pData->m_bModifiedSinceLastSave = const_cast< SfxBaseModel* >( this )->isModified();
2683 }
2684 
2685 void SfxBaseModel::changing()
2686 {
2687     SfxModelGuard aGuard( *this );
2688 
2689     // the notification should not be sent if the document can not be modified
2690     if ( !m_pData->m_pObjectShell.Is() || !m_pData->m_pObjectShell->IsEnableSetModified() )
2691         return;
2692 
2693     NotifyModifyListeners_Impl();
2694 }
2695 
2696 void SfxBaseModel::impl_change()
2697 {
2698     // object already disposed?
2699     if ( impl_isDisposed() )
2700         return;
2701 
2702     NotifyModifyListeners_Impl();
2703 }
2704 
2705 //________________________________________________________________________________________________________
2706 //  public impl.
2707 //________________________________________________________________________________________________________
2708 
2709 SfxObjectShell* SfxBaseModel::GetObjectShell() const
2710 {
2711     return m_pData ? (SfxObjectShell*) m_pData->m_pObjectShell : 0;
2712 }
2713 
2714 SfxObjectShell* SfxBaseModel::impl_getObjectShell() const
2715 {
2716     return m_pData ? (SfxObjectShell*) m_pData->m_pObjectShell : 0;
2717 }
2718 
2719 //________________________________________________________________________________________________________
2720 //  public impl.
2721 //________________________________________________________________________________________________________
2722 
2723 sal_Bool SfxBaseModel::IsInitialized() const
2724 {
2725     if ( !m_pData || !m_pData->m_pObjectShell )
2726     {
2727         OSL_ENSURE( false, "SfxBaseModel::IsInitialized: this should have been caught earlier!" );
2728         return sal_False;
2729     }
2730 
2731     return m_pData->m_pObjectShell->GetMedium() != NULL;
2732 }
2733 
2734 void SfxBaseModel::MethodEntryCheck( const bool i_mustBeInitialized ) const
2735 {
2736     if ( impl_isDisposed() )
2737         throw ::com::sun::star::lang::DisposedException( ::rtl::OUString(), *const_cast< SfxBaseModel* >( this ) );
2738     if ( i_mustBeInitialized && !IsInitialized() )
2739         throw ::com::sun::star::lang::NotInitializedException( ::rtl::OUString(), *const_cast< SfxBaseModel* >( this ) );
2740 }
2741 
2742 sal_Bool SfxBaseModel::impl_isDisposed() const
2743 {
2744     return ( m_pData == NULL ) ;
2745 }
2746 
2747 //________________________________________________________________________________________________________
2748 //  private impl.
2749 //________________________________________________________________________________________________________
2750 
2751 ::rtl::OUString SfxBaseModel::GetMediumFilterName_Impl()
2752 {
2753     const SfxFilter* pFilter = NULL;
2754     SfxMedium* pMedium = m_pData->m_pObjectShell->GetMedium();
2755     if ( pMedium )
2756         pFilter = pMedium->GetFilter();
2757 
2758     if ( pFilter )
2759         return pFilter->GetName();
2760 
2761     return ::rtl::OUString();
2762 }
2763 
2764 void SfxBaseModel::impl_store(  const   ::rtl::OUString&                   sURL            ,
2765                                 const   uno::Sequence< beans::PropertyValue >&  seqArguments    ,
2766                                         sal_Bool                    bSaveTo         )
2767 {
2768     if( !sURL.getLength() )
2769         throw frame::IllegalArgumentIOException();
2770 
2771     //sal_Bool aSaveAsTemplate = sal_False;
2772 
2773     sal_Bool bSaved = sal_False;
2774     if ( !bSaveTo && m_pData->m_pObjectShell && sURL.getLength()
2775       && sURL.compareToAscii( "private:stream", 14 ) != COMPARE_EQUAL
2776       && ::utl::UCBContentHelper::EqualURLs( getLocation(), sURL ) )
2777     {
2778         // this is the same file URL as the current document location, try to use storeOwn if possible
2779 
2780         ::comphelper::SequenceAsHashMap aArgHash( seqArguments );
2781         ::rtl::OUString aFilterString( RTL_CONSTASCII_USTRINGPARAM( "FilterName" ) );
2782         ::rtl::OUString aFilterName = aArgHash.getUnpackedValueOrDefault( aFilterString, ::rtl::OUString() );
2783         if ( aFilterName.getLength() )
2784         {
2785             SfxMedium* pMedium = m_pData->m_pObjectShell->GetMedium();
2786             if ( pMedium )
2787             {
2788                 const SfxFilter* pFilter = pMedium->GetFilter();
2789                 if ( pFilter && aFilterName.equals( pFilter->GetFilterName() ) )
2790                 {
2791                     // 119366 - If the former file saving with password, do not trying in StoreSelf anyway...
2792                     bool bFormerPassword = false;
2793                     {
2794                         uno::Sequence< beans::NamedValue > aOldEncryptionData;
2795                         if (GetEncryptionData_Impl( pMedium->GetItemSet(), aOldEncryptionData ))
2796                         {
2797                             bFormerPassword = true;
2798                         }
2799                     }
2800                     if ( !bFormerPassword )
2801                     {
2802                         aArgHash.erase( aFilterString );
2803                         aArgHash.erase( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "URL" ) ) );
2804 
2805                         try
2806                         {
2807                             storeSelf( aArgHash.getAsConstPropertyValueList() );
2808                             bSaved = sal_True;
2809                         }
2810                         catch( const lang::IllegalArgumentException& )
2811                         {
2812                             // some additional arguments do not allow to use saving, SaveAs should be done
2813                             // but only for normal documents, the shared documents would be overwritten in this case
2814                             // that would mean an information loss
2815                             // TODO/LATER: need a new interaction for this case
2816                             if ( m_pData->m_pObjectShell->IsDocShared() )
2817                             {
2818                                 m_pData->m_pObjectShell->AddLog( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX "Can't store shared document!" ) ) );
2819                                 m_pData->m_pObjectShell->StoreLog();
2820 
2821                                 uno::Sequence< beans::NamedValue > aNewEncryptionData = aArgHash.getUnpackedValueOrDefault( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "EncryptionData" ) ), uno::Sequence< beans::NamedValue >() );
2822                                 if ( !aNewEncryptionData.getLength() )
2823                                 {
2824                                     ::rtl::OUString aNewPassword = aArgHash.getUnpackedValueOrDefault( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Password" ) ), ::rtl::OUString() );
2825                                     aNewEncryptionData = ::comphelper::OStorageHelper::CreatePackageEncryptionData( aNewPassword );
2826                                 }
2827 
2828                                 uno::Sequence< beans::NamedValue > aOldEncryptionData;
2829                                 GetEncryptionData_Impl( pMedium->GetItemSet(), aOldEncryptionData );
2830 
2831                                 if ( !aOldEncryptionData.getLength() && !aNewEncryptionData.getLength() )
2832                                     throw;
2833                                 else
2834                                 {
2835                                     // if the password is changed a special error should be used in case of shared document
2836                                     throw task::ErrorCodeIOException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Cant change password for shared document." ) ), uno::Reference< uno::XInterface >(), ERRCODE_SFX_SHARED_NOPASSWORDCHANGE );
2837                                 }
2838                             }
2839                         }
2840                     }
2841                 }
2842             }
2843         }
2844     }
2845 
2846     if ( !bSaved && m_pData->m_pObjectShell )
2847     {
2848         SFX_APP()->NotifyEvent( SfxEventHint( bSaveTo ? SFX_EVENT_SAVETODOC : SFX_EVENT_SAVEASDOC, GlobalEventConfig::GetEventName( bSaveTo ? STR_EVENT_SAVETODOC : STR_EVENT_SAVEASDOC ),
2849                                                 m_pData->m_pObjectShell ) );
2850 
2851         SfxAllItemSet *aParams = new SfxAllItemSet( SFX_APP()->GetPool() );
2852         aParams->Put( SfxStringItem( SID_FILE_NAME, String(sURL) ) );
2853         if ( bSaveTo )
2854             aParams->Put( SfxBoolItem( SID_SAVETO, sal_True ) );
2855 
2856         TransformParameters( SID_SAVEASDOC, seqArguments, *aParams );
2857 
2858         SFX_ITEMSET_ARG( aParams, pCopyStreamItem, SfxBoolItem, SID_COPY_STREAM_IF_POSSIBLE, sal_False );
2859 
2860         if ( pCopyStreamItem && pCopyStreamItem->GetValue() && !bSaveTo )
2861         {
2862             m_pData->m_pObjectShell->AddLog( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX "Misuse of CopyStreamIfPossible!" ) ) );
2863             m_pData->m_pObjectShell->StoreLog();
2864 
2865             throw frame::IllegalArgumentIOException(
2866                     ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("CopyStreamIfPossible parameter is not acceptable for storeAsURL() call!") ),
2867                     uno::Reference< uno::XInterface >() );
2868         }
2869 
2870         sal_uInt32 nModifyPasswordHash = 0;
2871         uno::Sequence< beans::PropertyValue > aModifyPasswordInfo;
2872         SFX_ITEMSET_ARG( aParams, pModifyPasswordInfoItem, SfxUnoAnyItem, SID_MODIFYPASSWORDINFO, sal_False );
2873         if ( pModifyPasswordInfoItem )
2874         {
2875             // it contains either a simple hash or a set of PropertyValues
2876             // TODO/LATER: the sequence of PropertyValue should replace the hash completely in future
2877             sal_Int32 nMPHTmp = 0;
2878             pModifyPasswordInfoItem->GetValue() >>= nMPHTmp;
2879             nModifyPasswordHash = (sal_uInt32)nMPHTmp;
2880             pModifyPasswordInfoItem->GetValue() >>= aModifyPasswordInfo;
2881         }
2882         aParams->ClearItem( SID_MODIFYPASSWORDINFO );
2883         sal_uInt32 nOldModifyPasswordHash = m_pData->m_pObjectShell->GetModifyPasswordHash();
2884         m_pData->m_pObjectShell->SetModifyPasswordHash( nModifyPasswordHash );
2885         uno::Sequence< beans::PropertyValue > aOldModifyPasswordInfo = m_pData->m_pObjectShell->GetModifyPasswordInfo();
2886         m_pData->m_pObjectShell->SetModifyPasswordInfo( aModifyPasswordInfo );
2887 
2888         // since saving a document modifies its DocumentInfo, the current
2889         // DocumentInfo must be saved on "SaveTo", so it can be restored
2890         // after saving
2891         sal_Bool bCopyTo =  bSaveTo ||
2892             m_pData->m_pObjectShell->GetCreateMode() == SFX_CREATE_MODE_EMBEDDED;
2893         uno::Reference<document::XDocumentProperties> xOldDocProps;
2894         uno::Reference<document::XDocumentInfo> xOldDocInfo;
2895         if ( bCopyTo )
2896         {
2897             xOldDocProps = getDocumentProperties();
2898             if (m_pData->m_xDocumentInfo.is())
2899             {
2900                 xOldDocInfo = getDocumentInfo();
2901                 const Reference<util::XCloneable> xCloneable(xOldDocInfo,
2902                     UNO_QUERY_THROW);
2903                 const Reference<document::XDocumentInfo> xNewDocInfo(
2904                     xCloneable->createClone(), UNO_QUERY_THROW);
2905                 const Reference<document::XDocumentPropertiesSupplier> xDPS(
2906                     xNewDocInfo, UNO_QUERY_THROW);
2907                 const Reference<document::XDocumentProperties> xNewDocProps(
2908                     xDPS->getDocumentProperties());
2909                 m_pData->m_xDocumentProperties = xNewDocProps;
2910                 m_pData->m_xDocumentInfo = xNewDocInfo;
2911             }
2912             else // try not to create DocumentInfo if it does not exist...
2913             {
2914                 const Reference<util::XCloneable> xCloneable(xOldDocProps,
2915                     UNO_QUERY_THROW);
2916                 const Reference<document::XDocumentProperties> xNewDocProps(
2917                     xCloneable->createClone(), UNO_QUERY_THROW);
2918                 m_pData->m_xDocumentProperties = xNewDocProps;
2919             }
2920         }
2921 
2922         sal_Bool bRet = m_pData->m_pObjectShell->APISaveAs_Impl( sURL, aParams );
2923 
2924         if ( bCopyTo )
2925         {
2926             // restore DocumentInfo if a copy was created
2927             m_pData->m_xDocumentProperties = xOldDocProps;
2928             m_pData->m_xDocumentInfo = xOldDocInfo;
2929         }
2930 
2931         uno::Reference < task::XInteractionHandler > xHandler;
2932         SFX_ITEMSET_ARG( aParams, pItem, SfxUnoAnyItem, SID_INTERACTIONHANDLER, sal_False);
2933         if ( pItem )
2934             pItem->GetValue() >>= xHandler;
2935 
2936         DELETEZ( aParams );
2937 
2938         sal_uInt32 nErrCode = m_pData->m_pObjectShell->GetErrorCode();
2939         if ( !bRet && !nErrCode )
2940         {
2941             m_pData->m_pObjectShell->AddLog( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX "Storing has failed, no error is set!" ) ) );
2942             nErrCode = ERRCODE_IO_CANTWRITE;
2943         }
2944         m_pData->m_pObjectShell->ResetError();
2945 
2946         if ( bRet )
2947         {
2948             if ( nErrCode )
2949             {
2950                 // must be a warning - use Interactionhandler if possible or abandone
2951                 if ( xHandler.is() )
2952                 {
2953                     // TODO/LATER: a general way to set the error context should be available
2954                     SfxErrorContext aEc( ERRCTX_SFX_SAVEASDOC, m_pData->m_pObjectShell->GetTitle() );
2955 
2956                     ::com::sun::star::task::ErrorCodeRequest aErrorCode;
2957                     aErrorCode.ErrCode = nErrCode;
2958                     SfxMedium::CallApproveHandler( xHandler, uno::makeAny( aErrorCode ), sal_False );
2959                 }
2960             }
2961 
2962             m_pData->m_pObjectShell->AddLog( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX "Storing succeeded!" ) ) );
2963             if ( !bSaveTo )
2964             {
2965                 m_pData->m_aPreusedFilterName = GetMediumFilterName_Impl();
2966                 m_pData->m_pObjectShell->SetModifyPasswordEntered();
2967 
2968                 SFX_APP()->NotifyEvent( SfxEventHint( SFX_EVENT_SAVEASDOCDONE, GlobalEventConfig::GetEventName(STR_EVENT_SAVEASDOCDONE), m_pData->m_pObjectShell ) );
2969             }
2970             else
2971             {
2972                 m_pData->m_pObjectShell->SetModifyPasswordHash( nOldModifyPasswordHash );
2973                 m_pData->m_pObjectShell->SetModifyPasswordInfo( aOldModifyPasswordInfo );
2974 
2975                 SFX_APP()->NotifyEvent( SfxEventHint( SFX_EVENT_SAVETODOCDONE, GlobalEventConfig::GetEventName(STR_EVENT_SAVETODOCDONE), m_pData->m_pObjectShell ) );
2976             }
2977         }
2978         else
2979         {
2980             // let the logring be stored to the related file
2981             m_pData->m_pObjectShell->AddLog( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX "Storing failed!" ) ) );
2982             m_pData->m_pObjectShell->StoreLog();
2983 
2984             m_pData->m_pObjectShell->SetModifyPasswordHash( nOldModifyPasswordHash );
2985             m_pData->m_pObjectShell->SetModifyPasswordInfo( aOldModifyPasswordInfo );
2986 
2987 
2988             SFX_APP()->NotifyEvent( SfxEventHint( bSaveTo ? SFX_EVENT_SAVETODOCFAILED : SFX_EVENT_SAVEASDOCFAILED, GlobalEventConfig::GetEventName( bSaveTo ? STR_EVENT_SAVETODOCFAILED : STR_EVENT_SAVEASDOCFAILED),
2989                                                     m_pData->m_pObjectShell ) );
2990 
2991             throw task::ErrorCodeIOException( ::rtl::OUString(), uno::Reference< uno::XInterface >(), nErrCode );
2992         }
2993     }
2994 }
2995 
2996 //********************************************************************************************************
2997 namespace {
2998 template< typename ListenerT, typename EventT >
2999 class NotifySingleListenerIgnoreRE
3000 {
3001 private:
3002     typedef void ( SAL_CALL ListenerT::*NotificationMethod )( const EventT& );
3003     NotificationMethod  m_pMethod;
3004     const EventT&       m_rEvent;
3005 public:
3006     NotifySingleListenerIgnoreRE( NotificationMethod method, const EventT& event ) : m_pMethod( method ), m_rEvent( event ) { }
3007 
3008     void operator()( const uno::Reference<ListenerT>& listener ) const
3009     {
3010         try
3011         {
3012             (listener.get()->*m_pMethod)( m_rEvent );
3013         }
3014         catch( uno::RuntimeException& )
3015         {
3016             // this exception is ignored to avoid problems with invalid listeners, the listener should be probably thrown away in future
3017         }
3018     }
3019 };
3020 } // anonymous namespace
3021 
3022 void SfxBaseModel::postEvent_Impl( const ::rtl::OUString& aName, const uno::Reference< frame::XController2 >& xController )
3023 {
3024     // object already disposed?
3025     if ( impl_isDisposed() )
3026         return;
3027 
3028     DBG_ASSERT( aName.getLength(), "Empty event name!" );
3029     if (!aName.getLength())
3030         return;
3031 
3032     ::cppu::OInterfaceContainerHelper* pIC =
3033         m_pData->m_aInterfaceContainer.getContainer( ::getCppuType( (const uno::Reference< document::XDocumentEventListener >*)0 ) );
3034     if ( pIC )
3035     {
3036 #ifdef DBG_UTIL
3037         ByteString aTmp( "SfxDocumentEvent: " );
3038         aTmp += ByteString( String(aName), RTL_TEXTENCODING_UTF8 );
3039         DBG_TRACE( aTmp.GetBuffer() );
3040 #endif
3041 
3042         document::DocumentEvent aDocumentEvent( (frame::XModel*)this, aName, xController, uno::Any() );
3043 
3044         pIC->forEach< document::XDocumentEventListener, NotifySingleListenerIgnoreRE< document::XDocumentEventListener, document::DocumentEvent > >(
3045             NotifySingleListenerIgnoreRE< document::XDocumentEventListener, document::DocumentEvent >(
3046                 &document::XDocumentEventListener::documentEventOccured,
3047                 aDocumentEvent ) );
3048     }
3049 
3050     pIC = m_pData->m_aInterfaceContainer.getContainer( ::getCppuType( (const uno::Reference< document::XEventListener >*)0 ) );
3051     if ( pIC )
3052     {
3053 #ifdef DBG_UTIL
3054         ByteString aTmp( "SfxEvent: " );
3055         aTmp += ByteString( String(aName), RTL_TEXTENCODING_UTF8 );
3056         DBG_TRACE( aTmp.GetBuffer() );
3057 #endif
3058 
3059         document::EventObject aEvent( (frame::XModel*)this, aName );
3060 
3061         pIC->forEach< document::XEventListener, NotifySingleListenerIgnoreRE< document::XEventListener, document::EventObject > >(
3062             NotifySingleListenerIgnoreRE< document::XEventListener, document::EventObject >(
3063                 &document::XEventListener::notifyEvent,
3064                 aEvent ) );
3065     }
3066 
3067 }
3068 
3069 uno::Reference < container::XIndexAccess > SAL_CALL SfxBaseModel::getViewData() throw(::com::sun::star::uno::RuntimeException)
3070 {
3071     SfxModelGuard aGuard( *this );
3072 
3073     if ( m_pData->m_pObjectShell.Is() && !m_pData->m_contViewData.is() )
3074     {
3075         SfxViewFrame *pActFrame = SfxViewFrame::Current();
3076         if ( !pActFrame || pActFrame->GetObjectShell() != m_pData->m_pObjectShell )
3077             pActFrame = SfxViewFrame::GetFirst( m_pData->m_pObjectShell );
3078 
3079         if ( !pActFrame || !pActFrame->GetViewShell() )
3080             // currently no frame for this document at all or View is under construction
3081             return uno::Reference < container::XIndexAccess >();
3082 
3083         m_pData->m_contViewData = Reference < container::XIndexAccess >(
3084                 ::comphelper::getProcessServiceFactory()->createInstance(
3085                 DEFINE_CONST_UNICODE("com.sun.star.document.IndexedPropertyValues") ),
3086                 uno::UNO_QUERY );
3087 
3088         if ( !m_pData->m_contViewData.is() )
3089         {
3090             // error: no container class available!
3091             return uno::Reference < container::XIndexAccess >();
3092         }
3093 
3094         uno::Reference < container::XIndexContainer > xCont( m_pData->m_contViewData, uno::UNO_QUERY );
3095         sal_Int32 nCount = 0;
3096         uno::Sequence < beans::PropertyValue > aSeq;
3097         ::com::sun::star::uno::Any aAny;
3098         for ( SfxViewFrame *pFrame = SfxViewFrame::GetFirst( m_pData->m_pObjectShell ); pFrame;
3099                 pFrame = SfxViewFrame::GetNext( *pFrame, m_pData->m_pObjectShell ) )
3100         {
3101             sal_Bool bIsActive = ( pFrame == pActFrame );
3102             pFrame->GetViewShell()->WriteUserDataSequence( aSeq );
3103             aAny <<= aSeq;
3104             xCont->insertByIndex( bIsActive ? 0 : nCount, aAny );
3105             nCount++;
3106         }
3107     }
3108 
3109     return m_pData->m_contViewData;
3110 }
3111 
3112 void SAL_CALL SfxBaseModel::setViewData( const uno::Reference < container::XIndexAccess >& aData ) throw(::com::sun::star::uno::RuntimeException)
3113 {
3114     SfxModelGuard aGuard( *this );
3115 
3116     m_pData->m_contViewData = aData;
3117 }
3118 
3119 /** calls all XEventListeners */
3120 void SfxBaseModel::notifyEvent( const ::com::sun::star::document::EventObject& aEvent ) const
3121 {
3122     // object already disposed?
3123     if ( impl_isDisposed() )
3124         return;
3125 
3126     ::cppu::OInterfaceContainerHelper* pIC = m_pData->m_aInterfaceContainer.getContainer(
3127                                         ::getCppuType((const uno::Reference< XDOCEVENTLISTENER >*)0) );
3128     if( pIC )
3129 
3130     {
3131         ::cppu::OInterfaceIteratorHelper aIt( *pIC );
3132         while( aIt.hasMoreElements() )
3133         {
3134             try
3135             {
3136                 ((XDOCEVENTLISTENER *)aIt.next())->notifyEvent( aEvent );
3137             }
3138             catch( uno::RuntimeException& )
3139             {
3140                 aIt.remove();
3141             }
3142         }
3143     }
3144 }
3145 
3146 /** returns true if someone added a XEventListener to this XEventBroadcaster */
3147 sal_Bool SfxBaseModel::hasEventListeners() const
3148 {
3149     return !impl_isDisposed() && (NULL != m_pData->m_aInterfaceContainer.getContainer( ::getCppuType((const uno::Reference< XDOCEVENTLISTENER >*)0) ) );
3150 }
3151 
3152 void SAL_CALL SfxBaseModel::addPrintJobListener( const uno::Reference< view::XPrintJobListener >& xListener ) throw (uno::RuntimeException)
3153 {
3154     SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );
3155 
3156     if ( impl_getPrintHelper() )
3157     {
3158         uno::Reference < view::XPrintJobBroadcaster > xPJB( m_pData->m_xPrintable, uno::UNO_QUERY );
3159         if ( xPJB.is() )
3160             xPJB->addPrintJobListener( xListener );
3161     }
3162 //  else
3163 //      m_pData->m_aInterfaceContainer.addInterface( ::getCppuType((const uno::Reference< view::XPrintJobListener >*)0), xListener );
3164 }
3165 
3166 void SAL_CALL SfxBaseModel::removePrintJobListener( const uno::Reference< view::XPrintJobListener >& xListener ) throw (uno::RuntimeException)
3167 {
3168     SfxModelGuard aGuard( *this );
3169 
3170     if ( impl_getPrintHelper() )
3171     {
3172         uno::Reference < view::XPrintJobBroadcaster > xPJB( m_pData->m_xPrintable, uno::UNO_QUERY );
3173         if ( xPJB.is() )
3174             xPJB->removePrintJobListener( xListener );
3175     }
3176 //  else
3177 //      m_pData->m_aInterfaceContainer.addInterface( ::getCppuType((const uno::Reference< view::XPrintJobListener >*)0), xListener );
3178 }
3179 
3180 // simple declaration of class SvObject is enough
3181 // the corresponding <so3/iface.hxx> cannon be included because it provides
3182 // declaration of class SvBorder that conflicts with ../../inc/viewfrm.hxx
3183 class SvObject;
3184 sal_Int64 SAL_CALL SfxBaseModel::getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException)
3185 {
3186     ::vos::OGuard aGuard( Application::GetSolarMutex() );
3187     if ( GetObjectShell() )
3188     {
3189         SvGlobalName aName( aIdentifier );
3190         if ( aName == SvGlobalName( SO3_GLOBAL_CLASSID ) )
3191             return (sal_Int64)(sal_IntPtr)(SvObject*)GetObjectShell();
3192         else if ( aName == SvGlobalName( SFX_GLOBAL_CLASSID ) )
3193             return (sal_Int64)(sal_IntPtr)(SfxObjectShell*)GetObjectShell();
3194     }
3195 
3196     return 0;
3197 }
3198 
3199 //____________________________________________________________________________________________________
3200 //  XDocumentSubStorageSupplier
3201 //____________________________________________________________________________________________________
3202 
3203 void SfxBaseModel::ListenForStorage_Impl( const uno::Reference< embed::XStorage >& xStorage )
3204 {
3205     uno::Reference< util::XModifiable > xModifiable( xStorage, uno::UNO_QUERY );
3206     if ( xModifiable.is() )
3207     {
3208         if ( !m_pData->m_pStorageModifyListen.is() )
3209         {
3210             m_pData->m_pStorageModifyListen = new ::sfx2::DocumentStorageModifyListener( *m_pData, Application::GetSolarMutex() );
3211         }
3212 
3213         // no need to deregister the listening for old storage since it should be disposed automatically
3214         xModifiable->addModifyListener( m_pData->m_pStorageModifyListen.get() );
3215     }
3216 }
3217 
3218 uno::Reference< XSTORAGE > SAL_CALL SfxBaseModel::getDocumentSubStorage( const ::rtl::OUString& aStorageName, sal_Int32 nMode )
3219     throw ( uno::RuntimeException)
3220 {
3221     SfxModelGuard aGuard( *this );
3222 
3223     uno::Reference< XSTORAGE > xResult;
3224     if ( m_pData->m_pObjectShell.Is() )
3225     {
3226         uno::Reference< embed::XStorage > xStorage = m_pData->m_pObjectShell->GetStorage();
3227         if ( xStorage.is() )
3228         {
3229             try
3230             {
3231                 xResult = xStorage->openStorageElement( aStorageName, nMode );
3232             }
3233             catch ( uno::Exception& )
3234             {
3235             }
3236         }
3237     }
3238 
3239     return xResult;
3240 }
3241 
3242 Sequence< ::rtl::OUString > SAL_CALL SfxBaseModel::getDocumentSubStoragesNames()
3243     throw ( io::IOException,
3244             RuntimeException )
3245 {
3246     SfxModelGuard aGuard( *this );
3247 
3248     Sequence< ::rtl::OUString > aResult;
3249     sal_Int32 nResultSize = 0;
3250     sal_Bool bSuccess = sal_False;
3251     if ( m_pData->m_pObjectShell.Is() )
3252     {
3253         uno::Reference < embed::XStorage > xStorage = m_pData->m_pObjectShell->GetStorage();
3254         uno::Reference < container::XNameAccess > xAccess( xStorage, uno::UNO_QUERY );
3255         if ( xAccess.is() )
3256         {
3257             Sequence< ::rtl::OUString > aTemp = xAccess->getElementNames();
3258             for ( sal_Int32 n = 0; n < aTemp.getLength(); n++ )
3259             {
3260                 if ( xStorage->isStorageElement( aTemp[n] ) )
3261                 {
3262                     aResult.realloc( ++nResultSize );
3263                     aResult[ nResultSize - 1 ] = aTemp[n];
3264                 }
3265             }
3266 
3267             bSuccess = sal_True;
3268         }
3269     }
3270 
3271     if ( !bSuccess )
3272         throw io::IOException();
3273 
3274        return aResult;
3275 }
3276 
3277 //____________________________________________________________________________________________________
3278 //  XScriptProviderSupplier
3279 //____________________________________________________________________________________________________
3280 
3281 
3282 uno::Reference< script::provider::XScriptProvider > SAL_CALL SfxBaseModel::getScriptProvider()
3283     throw ( uno::RuntimeException )
3284 {
3285     SfxModelGuard aGuard( *this );
3286 
3287     uno::Reference< script::provider::XScriptProvider > xScriptProvider;
3288 
3289     ::comphelper::ComponentContext aContext( ::comphelper::getProcessServiceFactory() );
3290     Reference< script::provider::XScriptProviderFactory > xScriptProviderFactory(
3291         aContext.getSingleton( "com.sun.star.script.provider.theMasterScriptProviderFactory" ), uno::UNO_QUERY_THROW );
3292 
3293     try
3294     {
3295         Reference< XScriptInvocationContext > xScriptContext( this );
3296         xScriptProvider.set( xScriptProviderFactory->createScriptProvider( makeAny( xScriptContext ) ), uno::UNO_SET_THROW );
3297     }
3298     catch( const uno::RuntimeException& )
3299     {
3300         throw;
3301     }
3302     catch( const lang::IllegalArgumentException& )
3303     {
3304         throw lang::WrappedTargetRuntimeException(
3305             ::rtl::OUString(),
3306             *this,
3307             ::cppu::getCaughtException()
3308         );
3309     }
3310 
3311     return xScriptProvider;
3312 }
3313 
3314 //____________________________________________________________________________________________________
3315 //  XUIConfigurationManagerSupplier
3316 //____________________________________________________________________________________________________
3317 
3318 rtl::OUString SfxBaseModel::getRuntimeUID() const
3319 {
3320     OSL_ENSURE( m_pData->m_sRuntimeUID.getLength() > 0,
3321                 "SfxBaseModel::getRuntimeUID - ID is empty!" );
3322     return m_pData->m_sRuntimeUID;
3323 }
3324 
3325 sal_Bool SfxBaseModel::hasValidSignatures() const
3326 {
3327     ::vos::OGuard aGuard( Application::GetSolarMutex() );
3328     if ( m_pData->m_pObjectShell.Is() )
3329         return ( m_pData->m_pObjectShell->ImplGetSignatureState( sal_False ) == SIGNATURESTATE_SIGNATURES_OK );
3330     return sal_False;
3331 }
3332 
3333 static void GetCommandFromSequence( rtl::OUString& rCommand, sal_Int32& nIndex, const uno::Sequence< beans::PropertyValue >& rSeqPropValue )
3334 {
3335     rtl::OUString aCommand;
3336     nIndex = -1;
3337 
3338     for ( sal_Int32 i = 0; i < rSeqPropValue.getLength(); i++ )
3339     {
3340         if ( rSeqPropValue[i].Name.equalsAsciiL( "Command", 7 ))
3341         {
3342             rSeqPropValue[i].Value >>= rCommand;
3343             nIndex = i;
3344             return;
3345         }
3346     }
3347 }
3348 
3349 static void ConvertSlotsToCommands( SfxObjectShell* pDoc, uno::Reference< container::XIndexContainer >& rToolbarDefinition )
3350 {
3351     if ( pDoc )
3352     {
3353         Any           aAny;
3354         SfxModule*    pModule( pDoc->GetFactory().GetModule() );
3355         rtl::OUString aSlotCmd( RTL_CONSTASCII_USTRINGPARAM( "slot:" ));
3356         rtl::OUString aUnoCmd( RTL_CONSTASCII_USTRINGPARAM( ".uno:" ));
3357         uno::Sequence< beans::PropertyValue > aSeqPropValue;
3358 
3359         for ( sal_Int32 i = 0; i < rToolbarDefinition->getCount(); i++ )
3360         {
3361             sal_Int32 nIndex( -1 );
3362             rtl::OUString aCommand;
3363 
3364             if ( rToolbarDefinition->getByIndex( i ) >>= aSeqPropValue )
3365             {
3366                 GetCommandFromSequence( aCommand, nIndex, aSeqPropValue );
3367                 if ( nIndex >= 0 && ( aCommand.indexOf( aSlotCmd ) == 0 ))
3368                 {
3369                     rtl::OUString aSlot( aCommand.copy( 5 ));
3370 
3371                     // We have to replace the old "slot-Command" with our new ".uno:-Command"
3372                     const SfxSlot* pSlot = pModule->GetSlotPool()->GetSlot( sal_uInt16( aSlot.toInt32() ));
3373                     if ( pSlot )
3374                     {
3375                         rtl::OUStringBuffer aStrBuf( aUnoCmd );
3376                         aStrBuf.appendAscii( pSlot->GetUnoName() );
3377 
3378                         aCommand = aStrBuf.makeStringAndClear();
3379                         aSeqPropValue[nIndex].Value <<= aCommand;
3380                         rToolbarDefinition->replaceByIndex( i, Any( aSeqPropValue ));
3381                     }
3382                 }
3383             }
3384         }
3385     }
3386 }
3387 
3388 uno::Reference< ui::XUIConfigurationManager > SAL_CALL SfxBaseModel::getUIConfigurationManager()
3389         throw ( uno::RuntimeException )
3390 {
3391     SfxModelGuard aGuard( *this );
3392 
3393     if ( !m_pData->m_xUIConfigurationManager.is() )
3394     {
3395         uno::Reference< ui::XUIConfigurationManager > xNewUIConfMan(
3396             ::comphelper::getProcessServiceFactory()->createInstance(
3397                 ::rtl::OUString::createFromAscii( "com.sun.star.ui.UIConfigurationManager" )),
3398                 uno::UNO_QUERY );
3399 
3400         Reference< ui::XUIConfigurationStorage > xUIConfigStorage( xNewUIConfMan, uno::UNO_QUERY );
3401         if ( xUIConfigStorage.is() )
3402         {
3403             uno::Reference< XSTORAGE > xConfigStorage;
3404 
3405             rtl::OUString aUIConfigFolderName( RTL_CONSTASCII_USTRINGPARAM( "Configurations2" ));
3406             // First try to open with READWRITE and then READ
3407             xConfigStorage = getDocumentSubStorage( aUIConfigFolderName, embed::ElementModes::READWRITE );
3408             if ( xConfigStorage.is() )
3409             {
3410                 rtl::OUString aMediaTypeProp( RTL_CONSTASCII_USTRINGPARAM( "MediaType" ));
3411                 rtl::OUString aUIConfigMediaType(
3412                         RTL_CONSTASCII_USTRINGPARAM( "application/vnd.sun.xml.ui.configuration" ) );
3413                 rtl::OUString aMediaType;
3414                 uno::Reference< beans::XPropertySet > xPropSet( xConfigStorage, uno::UNO_QUERY );
3415                 Any a = xPropSet->getPropertyValue( aMediaTypeProp );
3416                 if ( !( a >>= aMediaType ) || ( aMediaType.getLength() == 0 ))
3417                 {
3418                     a <<= aUIConfigMediaType;
3419                     xPropSet->setPropertyValue( aMediaTypeProp, a );
3420                 }
3421             }
3422             else
3423                 xConfigStorage = getDocumentSubStorage( aUIConfigFolderName, embed::ElementModes::READ );
3424 
3425             // initialize ui configuration manager with document substorage
3426             xUIConfigStorage->setStorage( xConfigStorage );
3427 
3428             // embedded objects did not support local configuration data until OOo 3.0, so there's nothing to
3429             // migrate
3430             if ( m_pData->m_pObjectShell->GetCreateMode() != SFX_CREATE_MODE_EMBEDDED )
3431             {
3432                 // Import old UI configuration from OOo 1.x
3433                 uno::Reference< XSTORAGE > xOOo1ConfigStorage;
3434                 rtl::OUString         aOOo1UIConfigFolderName( RTL_CONSTASCII_USTRINGPARAM( "Configurations" ));
3435 
3436                 // Try to open with READ
3437                 xOOo1ConfigStorage = getDocumentSubStorage( aOOo1UIConfigFolderName, embed::ElementModes::READ );
3438                 if ( xOOo1ConfigStorage.is() )
3439                 {
3440                     uno::Reference< lang::XMultiServiceFactory > xServiceMgr( ::comphelper::getProcessServiceFactory() );
3441                     uno::Sequence< uno::Reference< container::XIndexContainer > > rToolbars;
3442 
3443                     sal_Bool bImported = framework::UIConfigurationImporterOOo1x::ImportCustomToolbars(
3444                                             xNewUIConfMan, rToolbars, xServiceMgr, xOOo1ConfigStorage );
3445                     if ( bImported )
3446                     {
3447                         SfxObjectShell* pObjShell = SfxBaseModel::GetObjectShell();
3448 
3449                         char aNum[]   = "private:resource/toolbar/custom_OOo1x_0";
3450                         char aTitle[] = "Toolbar 0";
3451                         sal_Int32 nNumIndex = strlen( aNum )-1;
3452                         sal_Int32 nTitleIndex = strlen( aTitle )-1;
3453                         for ( sal_Int32 i = 0; i < rToolbars.getLength(); i++ )
3454                         {
3455                             aNum[nNumIndex]++;
3456                             aTitle[nTitleIndex]++;
3457 
3458                             rtl::OUString aCustomTbxName( RTL_CONSTASCII_USTRINGPARAM( aNum ));
3459                             rtl::OUString aCustomTbxTitle( RTL_CONSTASCII_USTRINGPARAM( aTitle ));
3460 
3461                             uno::Reference< container::XIndexContainer > xToolbar = rToolbars[i];
3462                             ConvertSlotsToCommands( pObjShell, xToolbar );
3463                             if ( !xNewUIConfMan->hasSettings( aCustomTbxName ))
3464                             {
3465                                 // Set UIName for the toolbar with container property
3466                                 uno::Reference< beans::XPropertySet > xPropSet( xToolbar, UNO_QUERY );
3467                                 if ( xPropSet.is() )
3468                                 {
3469                                     try
3470                                     {
3471                                         rtl::OUString aPropName( RTL_CONSTASCII_USTRINGPARAM( "UIName" ));
3472                                         Any           aAny( aCustomTbxTitle );
3473                                         xPropSet->setPropertyValue( aPropName, aAny );
3474                                     }
3475                                     catch ( beans::UnknownPropertyException& )
3476                                     {
3477                                     }
3478                                 }
3479 
3480                                 uno::Reference< container::XIndexAccess > xToolbarData( xToolbar, uno::UNO_QUERY );
3481                                 xNewUIConfMan->insertSettings( aCustomTbxName, xToolbarData );
3482                                 uno::Reference< ui::XUIConfigurationPersistence > xPersist( xNewUIConfMan, uno::UNO_QUERY );
3483                                 xPersist->store();
3484                             }
3485                         }
3486                     }
3487                 }
3488             }
3489         }
3490 
3491         m_pData->m_xUIConfigurationManager = xNewUIConfMan;
3492     }
3493 
3494     return m_pData->m_xUIConfigurationManager;
3495 }
3496 
3497 //____________________________________________________________________________________________________
3498 //  XVisualObject
3499 //____________________________________________________________________________________________________
3500 
3501 void SAL_CALL SfxBaseModel::setVisualAreaSize( sal_Int64 nAspect, const awt::Size& aSize )
3502         throw ( lang::IllegalArgumentException,
3503                 embed::WrongStateException,
3504                 uno::Exception,
3505                 uno::RuntimeException )
3506 {
3507     SfxModelGuard aGuard( *this );
3508 
3509     if ( !m_pData->m_pObjectShell.Is() )
3510         throw uno::Exception(); // TODO: error handling
3511 
3512     SfxViewFrame* pViewFrm = SfxViewFrame::GetFirst( m_pData->m_pObjectShell, sal_False );
3513     if ( pViewFrm && m_pData->m_pObjectShell->GetCreateMode() == SFX_CREATE_MODE_EMBEDDED && !pViewFrm->GetFrame().IsInPlace() )
3514     {
3515         Window* pWindow = VCLUnoHelper::GetWindow( pViewFrm->GetFrame().GetFrameInterface()->getContainerWindow() );
3516         Size aWinSize = pWindow->GetSizePixel();
3517         awt::Size aCurrent = getVisualAreaSize( nAspect );
3518         Size aDiff( aSize.Width-aCurrent.Width, aSize.Height-aCurrent.Height );
3519         Size aWrongDiff = OutputDevice::LogicToLogic( aDiff , m_pData->m_pObjectShell->GetMapUnit(), pWindow->GetMapMode() );
3520         aDiff = pViewFrm->GetViewShell()->GetWindow()->LogicToPixel( aDiff );
3521         aWinSize.Width() += aDiff.Width();
3522         aWinSize.Height() += aDiff.Height();
3523         pWindow->SetSizePixel( aWinSize );
3524     }
3525     else
3526     {
3527         Rectangle aTmpRect = m_pData->m_pObjectShell->GetVisArea( ASPECT_CONTENT );
3528         aTmpRect.SetSize( Size( aSize.Width, aSize.Height ) );
3529         m_pData->m_pObjectShell->SetVisArea( aTmpRect );
3530     }
3531 }
3532 
3533 awt::Size SAL_CALL SfxBaseModel::getVisualAreaSize( sal_Int64 /*nAspect*/ )
3534         throw ( lang::IllegalArgumentException,
3535                 embed::WrongStateException,
3536                 uno::Exception,
3537                 uno::RuntimeException)
3538 {
3539     SfxModelGuard aGuard( *this );
3540 
3541     if ( !m_pData->m_pObjectShell.Is() )
3542         throw uno::Exception(); // TODO: error handling
3543 
3544     Rectangle aTmpRect = m_pData->m_pObjectShell->GetVisArea( ASPECT_CONTENT );
3545 
3546 #if 0
3547     Window* pWindow = NULL;
3548     SfxViewFrame* pViewFrm = m_pData->m_pObjectShell.Is() ?
3549                                 SfxViewFrame::GetFirst( m_pData->m_pObjectShell, 0, sal_False ) : 0;
3550 
3551     if ( pWindow )
3552     {
3553         MapMode aInternalMapMode( pViewFrm->GetWindow().GetMapMode() );
3554         MapMode aExternalMapMode( m_pData->m_pObjectShell->GetMapUnit() );
3555 
3556         aTmpRect = OutputDevice::LogicToLogic( aTmpRect, aInternalMapMode, aExternalMapMode );
3557     }
3558 #endif
3559 
3560     return awt::Size( aTmpRect.GetWidth(), aTmpRect.GetHeight() );
3561 }
3562 
3563 
3564 sal_Int32 SAL_CALL SfxBaseModel::getMapUnit( sal_Int64 /*nAspect*/ )
3565         throw ( uno::Exception,
3566                 uno::RuntimeException)
3567 {
3568     SfxModelGuard aGuard( *this );
3569 
3570     if ( !m_pData->m_pObjectShell.Is() )
3571         throw uno::Exception(); // TODO: error handling
3572 
3573     return VCLUnoHelper::VCL2UnoEmbedMapUnit( m_pData->m_pObjectShell->GetMapUnit() );
3574 }
3575 
3576 embed::VisualRepresentation SAL_CALL SfxBaseModel::getPreferredVisualRepresentation( ::sal_Int64 /*nAspect*/ )
3577         throw ( lang::IllegalArgumentException,
3578                 embed::WrongStateException,
3579                 uno::Exception,
3580                 uno::RuntimeException )
3581 {
3582     SfxModelGuard aGuard( *this );
3583 
3584     datatransfer::DataFlavor aDataFlavor(
3585             ::rtl::OUString::createFromAscii( "application/x-openoffice-gdimetafile;windows_formatname=\"GDIMetaFile\"" ),
3586             ::rtl::OUString::createFromAscii( "GDIMetaFile" ),
3587             ::getCppuType( (const uno::Sequence< sal_Int8 >*) NULL ) );
3588 
3589     embed::VisualRepresentation aVisualRepresentation;
3590     aVisualRepresentation.Data = getTransferData( aDataFlavor );
3591     aVisualRepresentation.Flavor = aDataFlavor;
3592 
3593     return aVisualRepresentation;
3594 }
3595 
3596 //____________________________________________________________________________________________________
3597 //  XStorageBasedDocument
3598 //____________________________________________________________________________________________________
3599 
3600 void SAL_CALL SfxBaseModel::loadFromStorage( const uno::Reference< XSTORAGE >& xStorage,
3601                                              const uno::Sequence< beans::PropertyValue >& aMediaDescriptor )
3602     throw ( lang::IllegalArgumentException,
3603             DOUBLEINITIALIZATIONEXCEPTION,
3604             IOEXCEPTION,
3605             EXCEPTION,
3606             uno::RuntimeException )
3607 {
3608     SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );
3609     if ( IsInitialized() )
3610         throw ::com::sun::star::frame::DoubleInitializationException( ::rtl::OUString(), *this );
3611 
3612     // after i36090 is fixed the pool from object shell can be used
3613     // SfxAllItemSet aSet( m_pData->m_pObjectShell->GetPool() );
3614     SfxAllItemSet aSet( SFX_APP()->GetPool() );
3615 
3616     // the BaseURL is part of the ItemSet
3617     SfxMedium* pMedium = new SfxMedium( xStorage, String() );
3618     TransformParameters( SID_OPENDOC, aMediaDescriptor, aSet );
3619     pMedium->GetItemSet()->Put( aSet );
3620 
3621     // allow to use an interactionhandler (if there is one)
3622     pMedium->UseInteractionHandler( sal_True );
3623 
3624     SFX_ITEMSET_ARG( &aSet, pTemplateItem, SfxBoolItem, SID_TEMPLATE, sal_False);
3625     sal_Bool bTemplate = pTemplateItem && pTemplateItem->GetValue();
3626     m_pData->m_pObjectShell->SetActivateEvent_Impl( bTemplate ? SFX_EVENT_CREATEDOC : SFX_EVENT_OPENDOC );
3627     m_pData->m_pObjectShell->Get_Impl()->bOwnsStorage = sal_False;
3628 
3629     // load document
3630     if ( !m_pData->m_pObjectShell->DoLoad(pMedium) )
3631     {
3632         sal_uInt32 nError = m_pData->m_pObjectShell->GetErrorCode();
3633         throw task::ErrorCodeIOException( ::rtl::OUString(),
3634                                             uno::Reference< uno::XInterface >(),
3635                                             nError ? nError : ERRCODE_IO_CANTREAD );
3636     }
3637 }
3638 
3639 void SAL_CALL SfxBaseModel::storeToStorage( const uno::Reference< XSTORAGE >& xStorage,
3640                                 const uno::Sequence< beans::PropertyValue >& aMediaDescriptor )
3641     throw ( lang::IllegalArgumentException,
3642             IOEXCEPTION,
3643             EXCEPTION,
3644             uno::RuntimeException )
3645 {
3646     SfxModelGuard aGuard( *this );
3647 
3648     uno::Reference< XSTORAGE > xResult;
3649     if ( !m_pData->m_pObjectShell.Is() )
3650         throw IOEXCEPTION(); // TODO:
3651 
3652     SfxAllItemSet aSet( m_pData->m_pObjectShell->GetPool() );
3653     TransformParameters( SID_SAVEASDOC, aMediaDescriptor, aSet );
3654 
3655     // TODO/LATER: may be a special URL "private:storage" should be used
3656     SFX_ITEMSET_ARG( &aSet, pItem, SfxStringItem, SID_FILTER_NAME, sal_False );
3657     sal_Int32 nVersion = SOFFICE_FILEFORMAT_CURRENT;
3658     if( pItem )
3659     {
3660         String aFilterName = pItem->GetValue();
3661         const SfxFilter* pFilter = SFX_APP()->GetFilterMatcher().GetFilter4FilterName( aFilterName );
3662         if ( pFilter && pFilter->UsesStorage() )
3663             nVersion = pFilter->GetVersion();
3664     }
3665 
3666     sal_Bool bSuccess = sal_False;
3667     if ( xStorage == m_pData->m_pObjectShell->GetStorage() )
3668     {
3669         // storing to the own storage
3670         bSuccess = m_pData->m_pObjectShell->DoSave();
3671     }
3672     else
3673     {
3674         // TODO/LATER: if the provided storage has some data inside the storing might fail, probably the storage must be truncated
3675         // TODO/LATER: is it possible to have a template here?
3676         m_pData->m_pObjectShell->SetupStorage( xStorage, nVersion, sal_False );
3677 
3678         // BaseURL is part of the ItemSet
3679         SfxMedium aMedium( xStorage, String(), &aSet );
3680         aMedium.CanDisposeStorage_Impl( sal_False );
3681         if ( aMedium.GetFilter() )
3682         {
3683             // storing without a valid filter will often crash
3684             bSuccess = m_pData->m_pObjectShell->DoSaveObjectAs( aMedium, sal_True );
3685             m_pData->m_pObjectShell->DoSaveCompleted( NULL );
3686         }
3687     }
3688 
3689     sal_uInt32 nError = m_pData->m_pObjectShell->GetErrorCode();
3690     m_pData->m_pObjectShell->ResetError();
3691 
3692     // the warnings are currently not transported
3693     if ( !bSuccess )
3694     {
3695         throw task::ErrorCodeIOException( ::rtl::OUString(),
3696                                             uno::Reference< uno::XInterface >(),
3697                                             nError ? nError : ERRCODE_IO_GENERAL );
3698     }
3699 }
3700 
3701 void SAL_CALL SfxBaseModel::switchToStorage( const uno::Reference< XSTORAGE >& xStorage )
3702         throw ( lang::IllegalArgumentException,
3703                 IOEXCEPTION,
3704                 EXCEPTION,
3705                 uno::RuntimeException )
3706 {
3707     SfxModelGuard aGuard( *this );
3708 
3709     uno::Reference< XSTORAGE > xResult;
3710     if ( !m_pData->m_pObjectShell.Is() )
3711         throw IOEXCEPTION(); // TODO:
3712 
3713     // the persistence should be switched only if the storage is different
3714     if ( xStorage != m_pData->m_pObjectShell->GetStorage()
3715       && !m_pData->m_pObjectShell->SwitchPersistance( xStorage ) )
3716     {
3717         sal_uInt32 nError = m_pData->m_pObjectShell->GetErrorCode();
3718         throw task::ErrorCodeIOException( ::rtl::OUString(),
3719                                             uno::Reference< uno::XInterface >(),
3720                                             nError ? nError : ERRCODE_IO_GENERAL );
3721     }
3722 
3723     m_pData->m_pObjectShell->Get_Impl()->bOwnsStorage = sal_False;
3724 }
3725 
3726 uno::Reference< XSTORAGE > SAL_CALL SfxBaseModel::getDocumentStorage()
3727         throw ( IOEXCEPTION,
3728                 EXCEPTION,
3729                 uno::RuntimeException )
3730 {
3731     SfxModelGuard aGuard( *this );
3732 
3733     uno::Reference< XSTORAGE > xResult;
3734     if ( !m_pData->m_pObjectShell.Is() )
3735         throw IOEXCEPTION(); // TODO
3736 
3737     return m_pData->m_pObjectShell->GetStorage();
3738 }
3739 
3740 void SAL_CALL SfxBaseModel::addStorageChangeListener(
3741             const uno::Reference< document::XStorageChangeListener >& xListener )
3742         throw ( uno::RuntimeException )
3743 {
3744     SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );
3745 
3746     m_pData->m_aInterfaceContainer.addInterface(
3747                                     ::getCppuType((const uno::Reference< document::XStorageChangeListener >*)0), xListener );
3748 }
3749 
3750 void SAL_CALL SfxBaseModel::removeStorageChangeListener(
3751             const uno::Reference< document::XStorageChangeListener >& xListener )
3752         throw ( uno::RuntimeException )
3753 {
3754     SfxModelGuard aGuard( *this );
3755 
3756     m_pData->m_aInterfaceContainer.removeInterface(
3757                                     ::getCppuType((const uno::Reference< document::XStorageChangeListener >*)0), xListener );
3758 }
3759 
3760 #include "printhelper.hxx"
3761 bool SfxBaseModel::impl_getPrintHelper()
3762 {
3763     if ( m_pData->m_xPrintable.is() )
3764         return true;
3765     m_pData->m_xPrintable = new SfxPrintHelper();
3766     uno::Reference < lang::XInitialization > xInit( m_pData->m_xPrintable, uno::UNO_QUERY );
3767     uno::Sequence < uno::Any > aValues(1);
3768     aValues[0] <<= uno::Reference < frame::XModel > (static_cast< frame::XModel* >(this), uno::UNO_QUERY );
3769     xInit->initialize( aValues );
3770     uno::Reference < view::XPrintJobBroadcaster > xBrd( m_pData->m_xPrintable, uno::UNO_QUERY );
3771     xBrd->addPrintJobListener( new SfxPrintHelperListener_Impl( m_pData ) );
3772     return true;
3773 }
3774 
3775 //=============================================================================
3776 // css.frame.XModule
3777  void SAL_CALL SfxBaseModel::setIdentifier(const ::rtl::OUString& Identifier)
3778     throw (css::uno::RuntimeException)
3779 {
3780     SfxModelGuard aGuard( *this );
3781     m_pData->m_sModuleIdentifier = Identifier;
3782 }
3783 
3784 //=============================================================================
3785 // css.frame.XModule
3786  ::rtl::OUString SAL_CALL SfxBaseModel::getIdentifier()
3787     throw (css::uno::RuntimeException)
3788 {
3789     SfxModelGuard aGuard( *this );
3790     if (m_pData->m_sModuleIdentifier.getLength() > 0)
3791         return m_pData->m_sModuleIdentifier;
3792     if (m_pData->m_pObjectShell)
3793         return m_pData->m_pObjectShell->GetFactory().GetDocumentServiceName();
3794     return ::rtl::OUString();
3795 }
3796 
3797 //=============================================================================
3798 css::uno::Reference< css::frame::XTitle > SfxBaseModel::impl_getTitleHelper ()
3799 {
3800     SfxModelGuard aGuard( *this );
3801 
3802     if ( ! m_pData->m_xTitleHelper.is ())
3803     {
3804         css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR   = ::comphelper::getProcessServiceFactory ();
3805         css::uno::Reference< css::frame::XUntitledNumbers >    xDesktop(xSMGR->createInstance(SERVICENAME_DESKTOP), css::uno::UNO_QUERY_THROW);
3806         css::uno::Reference< css::frame::XModel >              xThis   (static_cast< css::frame::XModel* >(this), css::uno::UNO_QUERY_THROW);
3807 
3808         ::framework::TitleHelper* pHelper = new ::framework::TitleHelper(xSMGR);
3809         m_pData->m_xTitleHelper = css::uno::Reference< css::frame::XTitle >(static_cast< ::cppu::OWeakObject* >(pHelper), css::uno::UNO_QUERY_THROW);
3810         pHelper->setOwner                   (xThis   );
3811         pHelper->connectWithUntitledNumbers (xDesktop);
3812     }
3813 
3814     return m_pData->m_xTitleHelper;
3815 }
3816 
3817 //=============================================================================
3818 css::uno::Reference< css::frame::XUntitledNumbers > SfxBaseModel::impl_getUntitledHelper ()
3819 {
3820     SfxModelGuard aGuard( *this );
3821 
3822     if ( ! m_pData->m_xNumberedControllers.is ())
3823     {
3824         css::uno::Reference< css::frame::XModel > xThis   (static_cast< css::frame::XModel* >(this), css::uno::UNO_QUERY_THROW);
3825         ::comphelper::NumberedCollection*         pHelper = new ::comphelper::NumberedCollection();
3826 
3827         m_pData->m_xNumberedControllers = css::uno::Reference< css::frame::XUntitledNumbers >(static_cast< ::cppu::OWeakObject* >(pHelper), css::uno::UNO_QUERY_THROW);
3828 
3829         pHelper->setOwner          (xThis);
3830         pHelper->setUntitledPrefix (::rtl::OUString::createFromAscii(" : "));
3831     }
3832 
3833     return m_pData->m_xNumberedControllers;
3834 }
3835 
3836 //=============================================================================
3837 // css.frame.XTitle
3838 ::rtl::OUString SAL_CALL SfxBaseModel::getTitle()
3839     throw (css::uno::RuntimeException)
3840 {
3841     // SYNCHRONIZED ->
3842     SfxModelGuard aGuard( *this );
3843 
3844     ::rtl::OUString aResult = impl_getTitleHelper()->getTitle ();
3845     if ( !m_pData->m_bExternalTitle && m_pData->m_pObjectShell )
3846     {
3847         SfxMedium* pMedium = m_pData->m_pObjectShell->GetMedium();
3848         if ( pMedium )
3849         {
3850             SFX_ITEMSET_ARG( pMedium->GetItemSet(), pRepairedDocItem, SfxBoolItem, SID_REPAIRPACKAGE, sal_False );
3851             if ( pRepairedDocItem && pRepairedDocItem->GetValue() )
3852                 aResult += String( SfxResId(STR_REPAIREDDOCUMENT) );
3853         }
3854 
3855         if ( m_pData->m_pObjectShell->IsReadOnlyUI() || (pMedium && pMedium->IsReadOnly()) )
3856             aResult += ::rtl::OUString( String( SfxResId(STR_READONLY) ) );
3857         else if ( m_pData->m_pObjectShell->IsDocShared() )
3858             aResult += ::rtl::OUString( String( SfxResId(STR_SHARED) ) );
3859 
3860         if ( m_pData->m_pObjectShell->GetDocumentSignatureState() == SIGNATURESTATE_SIGNATURES_OK )
3861             aResult += String( SfxResId( RID_XMLSEC_DOCUMENTSIGNED ) );
3862     }
3863 
3864     return aResult;
3865 }
3866 
3867 //=============================================================================
3868 // css.frame.XTitle
3869 void SAL_CALL SfxBaseModel::setTitle( const ::rtl::OUString& sTitle )
3870     throw (css::uno::RuntimeException)
3871 {
3872     // SYNCHRONIZED ->
3873     SfxModelGuard aGuard( *this );
3874 
3875     impl_getTitleHelper()->setTitle (sTitle);
3876     m_pData->m_bExternalTitle = sal_True;
3877 }
3878 
3879 //=============================================================================
3880 // css.frame.XTitleChangeBroadcaster
3881 void SAL_CALL SfxBaseModel::addTitleChangeListener( const css::uno::Reference< css::frame::XTitleChangeListener >& xListener )
3882     throw (css::uno::RuntimeException)
3883 {
3884     // SYNCHRONIZED ->
3885     SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );
3886 
3887     css::uno::Reference< css::frame::XTitleChangeBroadcaster > xBroadcaster(impl_getTitleHelper(), css::uno::UNO_QUERY);
3888     if (xBroadcaster.is ())
3889         xBroadcaster->addTitleChangeListener (xListener);
3890 }
3891 
3892 //=============================================================================
3893 // css.frame.XTitleChangeBroadcaster
3894 void SAL_CALL SfxBaseModel::removeTitleChangeListener( const css::uno::Reference< css::frame::XTitleChangeListener >& xListener )
3895     throw (css::uno::RuntimeException)
3896 {
3897     // SYNCHRONIZED ->
3898     SfxModelGuard aGuard( *this );
3899 
3900     css::uno::Reference< css::frame::XTitleChangeBroadcaster > xBroadcaster(impl_getTitleHelper(), css::uno::UNO_QUERY);
3901     if (xBroadcaster.is ())
3902         xBroadcaster->removeTitleChangeListener (xListener);
3903 }
3904 
3905 //=============================================================================
3906 // css.frame.XUntitledNumbers
3907 ::sal_Int32 SAL_CALL SfxBaseModel::leaseNumber( const css::uno::Reference< css::uno::XInterface >& xComponent )
3908     throw (css::lang::IllegalArgumentException,
3909            css::uno::RuntimeException         )
3910 {
3911     SfxModelGuard aGuard( *this );
3912 
3913     return impl_getUntitledHelper ()->leaseNumber (xComponent);
3914 }
3915 
3916 //=============================================================================
3917 // css.frame.XUntitledNumbers
3918 void SAL_CALL SfxBaseModel::releaseNumber( ::sal_Int32 nNumber )
3919     throw (css::lang::IllegalArgumentException,
3920            css::uno::RuntimeException         )
3921 {
3922     SfxModelGuard aGuard( *this );
3923     impl_getUntitledHelper ()->releaseNumber (nNumber);
3924 }
3925 
3926 //=============================================================================
3927 // css.frame.XUntitledNumbers
3928 void SAL_CALL SfxBaseModel::releaseNumberForComponent( const css::uno::Reference< css::uno::XInterface >& xComponent )
3929     throw (css::lang::IllegalArgumentException,
3930            css::uno::RuntimeException         )
3931 {
3932     SfxModelGuard aGuard( *this );
3933     impl_getUntitledHelper ()->releaseNumberForComponent (xComponent);
3934 }
3935 
3936 //=============================================================================
3937 // css.frame.XUntitledNumbers
3938 ::rtl::OUString SAL_CALL SfxBaseModel::getUntitledPrefix()
3939     throw (css::uno::RuntimeException)
3940 {
3941     SfxModelGuard aGuard( *this );
3942     return impl_getUntitledHelper ()->getUntitledPrefix ();
3943 }
3944 
3945 //=============================================================================
3946 // css::frame::XModel2
3947 css::uno::Reference< css::container::XEnumeration > SAL_CALL SfxBaseModel::getControllers()
3948     throw (css::uno::RuntimeException)
3949 {
3950     SfxModelGuard aGuard( *this );
3951 
3952     sal_Int32 c = m_pData->m_seqControllers.getLength();
3953     sal_Int32 i = 0;
3954     css::uno::Sequence< css::uno::Any > lEnum(c);
3955     for (i=0; i<c; ++i)
3956         lEnum[i] <<= m_pData->m_seqControllers[i];
3957 
3958     ::comphelper::OAnyEnumeration*                      pEnum = new ::comphelper::OAnyEnumeration(lEnum);
3959     css::uno::Reference< css::container::XEnumeration > xEnum(static_cast< css::container::XEnumeration* >(pEnum), css::uno::UNO_QUERY_THROW);
3960     return xEnum;
3961 }
3962 
3963 //=============================================================================
3964 // css::frame::XModel2
3965 css::uno::Sequence< ::rtl::OUString > SAL_CALL SfxBaseModel::getAvailableViewControllerNames()
3966     throw (css::uno::RuntimeException)
3967 {
3968     SfxModelGuard aGuard( *this );
3969 
3970     const SfxObjectFactory& rDocumentFactory = GetObjectShell()->GetFactory();
3971     const sal_Int32 nViewFactoryCount = rDocumentFactory.GetViewFactoryCount();
3972 
3973     Sequence< ::rtl::OUString > aViewNames( nViewFactoryCount );
3974     for ( sal_Int32 nViewNo = 0; nViewNo < nViewFactoryCount; ++nViewNo )
3975         aViewNames[nViewNo] = rDocumentFactory.GetViewFactory( nViewNo ).GetAPIViewName();
3976     return aViewNames;
3977 }
3978 
3979 //=============================================================================
3980 // css::frame::XModel2
3981 css::uno::Reference< css::frame::XController2 > SAL_CALL SfxBaseModel::createDefaultViewController( const css::uno::Reference< css::frame::XFrame >& i_rFrame )
3982     throw (css::uno::RuntimeException         ,
3983            css::lang::IllegalArgumentException,
3984            css::uno::Exception                )
3985 {
3986     SfxModelGuard aGuard( *this );
3987 
3988     const SfxObjectFactory& rDocumentFactory = GetObjectShell()->GetFactory();
3989     const ::rtl::OUString sDefaultViewName = rDocumentFactory.GetViewFactory( 0 ).GetAPIViewName();
3990 
3991     aGuard.clear();
3992 
3993     return createViewController( sDefaultViewName, Sequence< PropertyValue >(), i_rFrame );
3994 }
3995 
3996 //=============================================================================
3997 namespace sfx { namespace intern {
3998 
3999     /** a class which, in its dtor, cleans up variuos objects (well, at the moment only the frame) collected during
4000         the creation of a document view, unless the creation was successful.
4001     */
4002     class SAL_DLLPRIVATE ViewCreationGuard
4003     {
4004     public:
4005         ViewCreationGuard()
4006             :m_bSuccess( false )
4007         {
4008         }
4009 
4010         ~ViewCreationGuard()
4011         {
4012             if ( !m_bSuccess )
4013                 impl_closeAll();
4014         }
4015 
4016         void takeFrameOwnership( SfxFrame* i_pFrame )
4017         {
4018             OSL_PRECOND( !m_aWeakFrame, "ViewCreationGuard::takeFrameOwnership: already have a frame!" );
4019             OSL_PRECOND( i_pFrame != NULL, "ViewCreationGuard::takeFrameOwnership: invalid frame!" );
4020             m_aWeakFrame = i_pFrame;
4021         }
4022 
4023         void    releaseAll()
4024         {
4025             m_bSuccess = true;
4026         }
4027 
4028     private:
4029         void impl_closeAll()
4030         {
4031             if ( m_aWeakFrame && !m_aWeakFrame->GetCurrentDocument() )
4032             {
4033                 m_aWeakFrame->SetFrameInterface_Impl( NULL );
4034                 m_aWeakFrame->DoClose();
4035             }
4036         }
4037 
4038     private:
4039         bool            m_bSuccess;
4040         SfxFrameWeak    m_aWeakFrame;
4041     };
4042 } }
4043 
4044 //=============================================================================
4045 SfxViewFrame* SfxBaseModel::FindOrCreateViewFrame_Impl( const Reference< XFrame >& i_rFrame, ::sfx::intern::ViewCreationGuard& i_rGuard ) const
4046 {
4047     SfxViewFrame* pViewFrame = NULL;
4048     for (   pViewFrame = SfxViewFrame::GetFirst( GetObjectShell(), sal_False );
4049             pViewFrame;
4050             pViewFrame= SfxViewFrame::GetNext( *pViewFrame, GetObjectShell(), sal_False )
4051         )
4052     {
4053         if ( pViewFrame->GetFrame().GetFrameInterface() == i_rFrame )
4054             break;
4055     }
4056     if ( !pViewFrame )
4057     {
4058     #if OSL_DEBUG_LEVEL > 0
4059         for (   SfxFrame* pCheckFrame = SfxFrame::GetFirst();
4060                 pCheckFrame;
4061                 pCheckFrame = SfxFrame::GetNext( *pCheckFrame )
4062              )
4063         {
4064             if ( pCheckFrame->GetFrameInterface() == i_rFrame )
4065             {
4066                 if  (   ( pCheckFrame->GetCurrentViewFrame() != NULL )
4067                     ||  ( pCheckFrame->GetCurrentDocument() != NULL )
4068                     )
4069                     // Note that it is perfectly letgitimate that during loading into an XFrame which already contains
4070                     // a document, there exist two SfxFrame instances bound to this XFrame - the old one, which will be
4071                     // destroyed later, and the new one, which we're going to create
4072                     continue;
4073 
4074                 OSL_ENSURE( false, "SfxBaseModel::FindOrCreateViewFrame_Impl: there already is an SfxFrame for the given XFrame, but no view in it!" );
4075                     // nowadays, we're the only instance allowed to create an SfxFrame for an XFrame, so this case here should not happen
4076                 break;
4077             }
4078         }
4079     #endif
4080 
4081         SfxFrame* pTargetFrame = SfxFrame::Create( i_rFrame );
4082         ENSURE_OR_THROW( pTargetFrame, "could not create an SfxFrame" );
4083         i_rGuard.takeFrameOwnership( pTargetFrame );
4084 
4085         // prepare it
4086         pTargetFrame->PrepareForDoc_Impl( *GetObjectShell() );
4087 
4088         // create view frame
4089         pViewFrame = new SfxViewFrame( *pTargetFrame, GetObjectShell() );
4090     }
4091     return pViewFrame;
4092 }
4093 
4094 //=============================================================================
4095 // css::frame::XModel2
4096 css::uno::Reference< css::frame::XController2 > SAL_CALL SfxBaseModel::createViewController(
4097         const ::rtl::OUString& i_rViewName, const Sequence< PropertyValue >& i_rArguments, const Reference< XFrame >& i_rFrame )
4098     throw (css::uno::RuntimeException         ,
4099            css::lang::IllegalArgumentException,
4100            css::uno::Exception                )
4101 {
4102     SfxModelGuard aGuard( *this );
4103 
4104     if ( !i_rFrame.is() )
4105         throw css::lang::IllegalArgumentException( ::rtl::OUString(), *this, 3 );
4106 
4107     // find the proper SFX view factory
4108     SfxViewFactory* pViewFactory = GetObjectShell()->GetFactory().GetViewFactoryByViewName( i_rViewName );
4109     if ( !pViewFactory )
4110         throw IllegalArgumentException( ::rtl::OUString(), *this, 1 );
4111 
4112     // determine previous shell (used in some special cases)
4113     Reference< XController > xPreviousController( i_rFrame->getController() );
4114     const Reference< XModel > xMe( this );
4115     if  (   ( xPreviousController.is() )
4116         &&  ( xMe != xPreviousController->getModel() )
4117         )
4118     {
4119         xPreviousController.clear();
4120     }
4121     SfxViewShell* pOldViewShell = SfxViewShell::Get( xPreviousController );
4122     OSL_ENSURE( !xPreviousController.is() || ( pOldViewShell != NULL ),
4123         "SfxBaseModel::createViewController: invalid old controller!" );
4124 
4125     // a guard which will clean up in case of failure
4126     ::sfx::intern::ViewCreationGuard aViewCreationGuard;
4127 
4128     // determine the ViewFrame belonging to the given XFrame
4129     SfxViewFrame* pViewFrame = FindOrCreateViewFrame_Impl( i_rFrame, aViewCreationGuard );
4130     OSL_POSTCOND( pViewFrame, "SfxBaseModel::createViewController: no frame?" );
4131 
4132     // delegate to SFX' view factory
4133     pViewFrame->GetBindings().ENTERREGISTRATIONS();
4134     SfxViewShell* pViewShell = pViewFactory->CreateInstance( pViewFrame, pOldViewShell );
4135     pViewFrame->GetBindings().LEAVEREGISTRATIONS();
4136     ENSURE_OR_THROW( pViewShell, "invalid view shell provided by factory" );
4137 
4138     // by setting the ViewShell it is prevented that disposing the Controller will destroy this ViewFrame also
4139     pViewFrame->GetDispatcher()->SetDisableFlags( 0 );
4140     pViewFrame->SetViewShell_Impl( pViewShell );
4141 
4142     // remember ViewID
4143     pViewFrame->SetCurViewId_Impl( pViewFactory->GetOrdinal() );
4144 
4145     // ensure a default controller, if the view shell did not provide an own implementation
4146     if ( !pViewShell->GetController().is() )
4147         pViewShell->SetController( new SfxBaseController( pViewShell ) );
4148 
4149     // pass the creation arguments to the controller
4150     SfxBaseController* pBaseController = pViewShell->GetBaseController_Impl();
4151     ENSURE_OR_THROW( pBaseController, "invalid controller implementation!" );
4152     pBaseController->SetCreationArguments_Impl( i_rArguments );
4153 
4154     // some initial view settings, coming from our most recent attachResource call
4155     ::comphelper::NamedValueCollection aDocumentLoadArgs( getArgs() );
4156     if ( aDocumentLoadArgs.getOrDefault( "ViewOnly", false ) )
4157         pViewFrame->GetFrame().SetMenuBarOn_Impl( sal_False );
4158 
4159     const sal_Int16 nPluginMode = aDocumentLoadArgs.getOrDefault( "PluginMode", sal_Int16( 0 ) );
4160     if ( nPluginMode == 1 )
4161     {
4162         pViewFrame->ForceOuterResize_Impl( sal_False );
4163         pViewFrame->GetBindings().HidePopups( sal_True );
4164 
4165         SfxFrame& rFrame = pViewFrame->GetFrame();
4166         // MBA: layoutmanager of inplace frame starts locked and invisible
4167         rFrame.GetWorkWindow_Impl()->MakeVisible_Impl( sal_False );
4168         rFrame.GetWorkWindow_Impl()->Lock_Impl( sal_True );
4169 
4170         rFrame.GetWindow().SetBorderStyle( WINDOW_BORDER_NOBORDER );
4171         pViewFrame->GetWindow().SetBorderStyle( WINDOW_BORDER_NOBORDER );
4172     }
4173 
4174     // tell the guard we were successful
4175     aViewCreationGuard.releaseAll();
4176 
4177     // outta gere
4178     return pBaseController;
4179 }
4180 
4181 //=============================================================================
4182 // RDF DocumentMetadataAccess
4183 
4184 // ::com::sun::star::rdf::XRepositorySupplier:
4185 uno::Reference< rdf::XRepository > SAL_CALL
4186 SfxBaseModel::getRDFRepository() throw (uno::RuntimeException)
4187 {
4188     SfxModelGuard aGuard( *this );
4189 
4190     const uno::Reference<rdf::XDocumentMetadataAccess> xDMA(m_pData->GetDMA());
4191     if (!xDMA.is()) {
4192         throw uno::RuntimeException( ::rtl::OUString::createFromAscii(
4193             "model has no document metadata"), *this );
4194     }
4195 
4196     return xDMA->getRDFRepository();
4197 }
4198 
4199 // ::com::sun::star::rdf::XNode:
4200 ::rtl::OUString SAL_CALL
4201 SfxBaseModel::getStringValue() throw (uno::RuntimeException)
4202 {
4203     SfxModelGuard aGuard( *this );
4204 
4205     const uno::Reference<rdf::XDocumentMetadataAccess> xDMA(m_pData->GetDMA());
4206     if (!xDMA.is()) {
4207         throw uno::RuntimeException( ::rtl::OUString::createFromAscii(
4208             "model has no document metadata"), *this );
4209     }
4210 
4211     return xDMA->getStringValue();
4212 }
4213 
4214 // ::com::sun::star::rdf::XURI:
4215 ::rtl::OUString SAL_CALL
4216 SfxBaseModel::getNamespace() throw (uno::RuntimeException)
4217 {
4218     SfxModelGuard aGuard( *this );
4219 
4220     const uno::Reference<rdf::XDocumentMetadataAccess> xDMA(m_pData->GetDMA());
4221     if (!xDMA.is()) {
4222         throw uno::RuntimeException( ::rtl::OUString::createFromAscii(
4223             "model has no document metadata"), *this );
4224     }
4225 
4226     return xDMA->getNamespace();
4227 }
4228 
4229 ::rtl::OUString SAL_CALL
4230 SfxBaseModel::getLocalName() throw (uno::RuntimeException)
4231 {
4232     SfxModelGuard aGuard( *this );
4233 
4234     const uno::Reference<rdf::XDocumentMetadataAccess> xDMA(m_pData->GetDMA());
4235     if (!xDMA.is()) {
4236         throw uno::RuntimeException( ::rtl::OUString::createFromAscii(
4237             "model has no document metadata"), *this );
4238     }
4239 
4240     return xDMA->getLocalName();
4241 }
4242 
4243 // ::com::sun::star::rdf::XDocumentMetadataAccess:
4244 uno::Reference< rdf::XMetadatable > SAL_CALL
4245 SfxBaseModel::getElementByMetadataReference(
4246     const ::com::sun::star::beans::StringPair & i_rReference)
4247 throw (uno::RuntimeException)
4248 {
4249     SfxModelGuard aGuard( *this );
4250 
4251     const uno::Reference<rdf::XDocumentMetadataAccess> xDMA(m_pData->GetDMA());
4252     if (!xDMA.is()) {
4253         throw uno::RuntimeException( ::rtl::OUString::createFromAscii(
4254             "model has no document metadata"), *this );
4255     }
4256 
4257     return xDMA->getElementByMetadataReference(i_rReference);
4258 }
4259 
4260 uno::Reference< rdf::XMetadatable > SAL_CALL
4261 SfxBaseModel::getElementByURI(const uno::Reference< rdf::XURI > & i_xURI)
4262 throw (uno::RuntimeException, lang::IllegalArgumentException)
4263 {
4264     SfxModelGuard aGuard( *this );
4265 
4266     const uno::Reference<rdf::XDocumentMetadataAccess> xDMA(m_pData->GetDMA());
4267     if (!xDMA.is()) {
4268         throw uno::RuntimeException( ::rtl::OUString::createFromAscii(
4269             "model has no document metadata"), *this );
4270     }
4271 
4272     return xDMA->getElementByURI(i_xURI);
4273 }
4274 
4275 uno::Sequence< uno::Reference< rdf::XURI > > SAL_CALL
4276 SfxBaseModel::getMetadataGraphsWithType(
4277     const uno::Reference<rdf::XURI> & i_xType)
4278 throw (uno::RuntimeException, lang::IllegalArgumentException)
4279 {
4280     SfxModelGuard aGuard( *this );
4281 
4282     const uno::Reference<rdf::XDocumentMetadataAccess> xDMA(m_pData->GetDMA());
4283     if (!xDMA.is()) {
4284         throw uno::RuntimeException( ::rtl::OUString::createFromAscii(
4285             "model has no document metadata"), *this );
4286     }
4287 
4288     return xDMA->getMetadataGraphsWithType(i_xType);
4289 }
4290 
4291 uno::Reference<rdf::XURI> SAL_CALL
4292 SfxBaseModel::addMetadataFile(const ::rtl::OUString & i_rFileName,
4293     const uno::Sequence < uno::Reference< rdf::XURI > > & i_rTypes)
4294 throw (uno::RuntimeException, lang::IllegalArgumentException,
4295     container::ElementExistException)
4296 {
4297     SfxModelGuard aGuard( *this );
4298 
4299     const uno::Reference<rdf::XDocumentMetadataAccess> xDMA(m_pData->GetDMA());
4300     if (!xDMA.is()) {
4301         throw uno::RuntimeException( ::rtl::OUString::createFromAscii(
4302             "model has no document metadata"), *this );
4303     }
4304 
4305     return xDMA->addMetadataFile(i_rFileName, i_rTypes);
4306 }
4307 
4308 uno::Reference<rdf::XURI> SAL_CALL
4309 SfxBaseModel::importMetadataFile(::sal_Int16 i_Format,
4310     const uno::Reference< io::XInputStream > & i_xInStream,
4311     const ::rtl::OUString & i_rFileName,
4312     const uno::Reference< rdf::XURI > & i_xBaseURI,
4313     const uno::Sequence < uno::Reference< rdf::XURI > > & i_rTypes)
4314 throw (uno::RuntimeException, lang::IllegalArgumentException,
4315     datatransfer::UnsupportedFlavorException,
4316     container::ElementExistException, rdf::ParseException, io::IOException)
4317 {
4318     SfxModelGuard aGuard( *this );
4319 
4320     const uno::Reference<rdf::XDocumentMetadataAccess> xDMA(m_pData->GetDMA());
4321     if (!xDMA.is()) {
4322         throw uno::RuntimeException( ::rtl::OUString::createFromAscii(
4323             "model has no document metadata"), *this );
4324     }
4325 
4326     return xDMA->importMetadataFile(i_Format,
4327         i_xInStream, i_rFileName, i_xBaseURI, i_rTypes);
4328 }
4329 
4330 void SAL_CALL
4331 SfxBaseModel::removeMetadataFile(
4332     const uno::Reference< rdf::XURI > & i_xGraphName)
4333 throw (uno::RuntimeException, lang::IllegalArgumentException,
4334     container::NoSuchElementException)
4335 {
4336     SfxModelGuard aGuard( *this );
4337 
4338     const uno::Reference<rdf::XDocumentMetadataAccess> xDMA(m_pData->GetDMA());
4339     if (!xDMA.is()) {
4340         throw uno::RuntimeException( ::rtl::OUString::createFromAscii(
4341             "model has no document metadata"), *this );
4342     }
4343 
4344     return xDMA->removeMetadataFile(i_xGraphName);
4345 }
4346 
4347 void SAL_CALL
4348 SfxBaseModel::addContentOrStylesFile(const ::rtl::OUString & i_rFileName)
4349 throw (uno::RuntimeException, lang::IllegalArgumentException,
4350     container::ElementExistException)
4351 {
4352     SfxModelGuard aGuard( *this );
4353 
4354     const uno::Reference<rdf::XDocumentMetadataAccess> xDMA(m_pData->GetDMA());
4355     if (!xDMA.is()) {
4356         throw uno::RuntimeException( ::rtl::OUString::createFromAscii(
4357             "model has no document metadata"), *this );
4358     }
4359 
4360     return xDMA->addContentOrStylesFile(i_rFileName);
4361 }
4362 
4363 void SAL_CALL
4364 SfxBaseModel::removeContentOrStylesFile(const ::rtl::OUString & i_rFileName)
4365 throw (uno::RuntimeException, lang::IllegalArgumentException,
4366     container::NoSuchElementException)
4367 {
4368     SfxModelGuard aGuard( *this );
4369 
4370     const uno::Reference<rdf::XDocumentMetadataAccess> xDMA(m_pData->GetDMA());
4371     if (!xDMA.is()) {
4372         throw uno::RuntimeException( ::rtl::OUString::createFromAscii(
4373             "model has no document metadata"), *this );
4374     }
4375 
4376     return xDMA->removeContentOrStylesFile(i_rFileName);
4377 }
4378 
4379 void SAL_CALL
4380 SfxBaseModel::loadMetadataFromStorage(
4381     uno::Reference< embed::XStorage > const & i_xStorage,
4382     uno::Reference<rdf::XURI> const & i_xBaseURI,
4383     uno::Reference<task::XInteractionHandler> const & i_xHandler)
4384 throw (uno::RuntimeException, lang::IllegalArgumentException,
4385     lang::WrappedTargetException)
4386 {
4387     SfxModelGuard aGuard( *this );
4388 
4389     const uno::Reference<rdf::XDocumentMetadataAccess> xDMA(
4390         m_pData->CreateDMAUninitialized());
4391     if (!xDMA.is()) {
4392         throw uno::RuntimeException( ::rtl::OUString::createFromAscii(
4393             "model has no document metadata"), *this );
4394     }
4395 
4396     try {
4397         xDMA->loadMetadataFromStorage(i_xStorage, i_xBaseURI, i_xHandler);
4398     } catch (lang::IllegalArgumentException &) {
4399         throw; // not initialized
4400     } catch (uno::Exception &) {
4401         // UGLY: if it's a RuntimeException, we can't be sure DMA is initialzed
4402         m_pData->m_xDocumentMetadata = xDMA;
4403         throw;
4404     }
4405     m_pData->m_xDocumentMetadata = xDMA;
4406 
4407 }
4408 
4409 void SAL_CALL
4410 SfxBaseModel::storeMetadataToStorage(
4411     uno::Reference< embed::XStorage > const & i_xStorage)
4412 throw (uno::RuntimeException, lang::IllegalArgumentException,
4413     lang::WrappedTargetException)
4414 {
4415     SfxModelGuard aGuard( *this );
4416 
4417     const uno::Reference<rdf::XDocumentMetadataAccess> xDMA(m_pData->GetDMA());
4418     if (!xDMA.is()) {
4419         throw uno::RuntimeException( ::rtl::OUString::createFromAscii(
4420             "model has no document metadata"), *this );
4421     }
4422 
4423     return xDMA->storeMetadataToStorage(i_xStorage);
4424 }
4425 
4426 void SAL_CALL
4427 SfxBaseModel::loadMetadataFromMedium(
4428     const uno::Sequence< beans::PropertyValue > & i_rMedium)
4429 throw (uno::RuntimeException, lang::IllegalArgumentException,
4430     lang::WrappedTargetException)
4431 {
4432     SfxModelGuard aGuard( *this );
4433 
4434     const uno::Reference<rdf::XDocumentMetadataAccess> xDMA(
4435         m_pData->CreateDMAUninitialized());
4436     if (!xDMA.is()) {
4437         throw uno::RuntimeException( ::rtl::OUString::createFromAscii(
4438             "model has no document metadata"), *this );
4439     }
4440 
4441     try {
4442         xDMA->loadMetadataFromMedium(i_rMedium);
4443     } catch (lang::IllegalArgumentException &) {
4444         throw; // not initialized
4445     } catch (uno::Exception &) {
4446         // UGLY: if it's a RuntimeException, we can't be sure DMA is initialzed
4447         m_pData->m_xDocumentMetadata = xDMA;
4448         throw;
4449     }
4450     m_pData->m_xDocumentMetadata = xDMA;
4451 }
4452 
4453 void SAL_CALL
4454 SfxBaseModel::storeMetadataToMedium(
4455     const uno::Sequence< beans::PropertyValue > & i_rMedium)
4456 throw (uno::RuntimeException, lang::IllegalArgumentException,
4457     lang::WrappedTargetException)
4458 {
4459     SfxModelGuard aGuard( *this );
4460 
4461     const uno::Reference<rdf::XDocumentMetadataAccess> xDMA(m_pData->GetDMA());
4462     if (!xDMA.is()) {
4463         throw uno::RuntimeException( ::rtl::OUString::createFromAscii(
4464             "model has no document metadata"), *this );
4465     }
4466 
4467     return xDMA->storeMetadataToMedium(i_rMedium);
4468 }
4469 
4470 // =====================================================================================================================
4471 // = SfxModelSubComponent
4472 // =====================================================================================================================
4473 
4474 SfxModelSubComponent::~SfxModelSubComponent()
4475 {
4476 }
4477 
4478 void SfxModelSubComponent::disposing()
4479 {
4480     // nothing to do here
4481 }
4482 
4483