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