1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
21 #include <com/sun/star/io/XStream.hpp>
22 #include <com/sun/star/beans/XPropertySet.hpp>
23 #include <com/sun/star/embed/XTransactedObject.hpp>
24 #include <com/sun/star/embed/ElementModes.hpp>
25 #include <com/sun/star/embed/XEmbeddedObject.hpp>
26 #include <com/sun/star/embed/XEmbedPersist.hpp>
27 #include <com/sun/star/embed/EmbedStates.hpp>
28 #include <com/sun/star/embed/Aspects.hpp>
29 #include <com/sun/star/lang/WrappedTargetRuntimeException.hpp>
30 #include <osl/diagnose.h>
31 #include <sot/storage.hxx>
32 #include <tools/debug.hxx>
33 #include <sal/log.hxx>
34 #include <unotools/streamwrap.hxx>
35 #include <unotools/tempfile.hxx>
37 #include <svtools/embedhlp.hxx>
38 #include <unotools/ucbstreamhelper.hxx>
39 #include <comphelper/propertyvalue.hxx>
40 #include <comphelper/storagehelper.hxx>
41 #include <comphelper/embeddedobjectcontainer.hxx>
43 #include <comphelper/fileformat.h>
44 #include <cppuhelper/exc_hlp.hxx>
45 #include <cppuhelper/implbase.hxx>
46 #include <svx/xmleohlp.hxx>
51 using namespace ::osl
;
52 using namespace ::cppu
;
53 using namespace ::utl
;
54 using namespace ::com::sun::star
;
55 using namespace ::com::sun::star::document
;
56 using namespace ::com::sun::star::uno
;
57 using namespace ::com::sun::star::container
;
58 using namespace ::com::sun::star::io
;
59 using namespace ::com::sun::star::lang
;
61 constexpr OUStringLiteral XML_CONTAINERSTORAGE_NAME_60
= u
"Pictures";
62 constexpr OUStringLiteral XML_CONTAINERSTORAGE_NAME
= u
"ObjectReplacements";
63 constexpr OUStringLiteral XML_EMBEDDEDOBJECT_URL_BASE
= u
"vnd.sun.star.EmbeddedObject:";
64 constexpr OUStringLiteral XML_EMBEDDEDOBJECTGRAPHIC_URL_BASE
= u
"vnd.sun.star.GraphicObject:";
67 class OutputStorageWrapper_Impl
: public ::cppu::WeakImplHelper
<XOutputStream
>
70 Reference
< XOutputStream
> xOut
;
71 TempFileFast aTempFile
;
72 bool bStreamClosed
: 1;
76 OutputStorageWrapper_Impl();
78 // css::io::XOutputStream
79 virtual void SAL_CALL
writeBytes(const Sequence
< sal_Int8
>& aData
) override
;
80 virtual void SAL_CALL
flush() override
;
81 virtual void SAL_CALL
closeOutput() override
;
83 SvStream
* GetStream();
86 OutputStorageWrapper_Impl::OutputStorageWrapper_Impl()
87 : bStreamClosed( false )
90 pStream
= aTempFile
.GetStream( StreamMode::READWRITE
);
91 xOut
= new OOutputStreamWrapper( *pStream
);
94 SvStream
*OutputStorageWrapper_Impl::GetStream()
101 void SAL_CALL
OutputStorageWrapper_Impl::writeBytes(
102 const Sequence
< sal_Int8
>& aData
)
104 std::scoped_lock
aGuard( maMutex
);
105 xOut
->writeBytes( aData
);
108 void SAL_CALL
OutputStorageWrapper_Impl::flush()
110 std::scoped_lock
aGuard( maMutex
);
114 void SAL_CALL
OutputStorageWrapper_Impl::closeOutput()
116 std::scoped_lock
aGuard( maMutex
);
118 bStreamClosed
= true;
121 SvXMLEmbeddedObjectHelper::SvXMLEmbeddedObjectHelper() :
122 mpDocPersist( nullptr ),
123 meCreateMode( SvXMLEmbeddedObjectHelperMode::Read
)
127 SvXMLEmbeddedObjectHelper::SvXMLEmbeddedObjectHelper( ::comphelper::IEmbeddedHelper
& rDocPersist
, SvXMLEmbeddedObjectHelperMode eCreateMode
) :
128 mpDocPersist( nullptr ),
129 meCreateMode( SvXMLEmbeddedObjectHelperMode::Read
)
131 Init( nullptr, rDocPersist
, eCreateMode
);
134 SvXMLEmbeddedObjectHelper::~SvXMLEmbeddedObjectHelper()
138 void SvXMLEmbeddedObjectHelper::disposing(std::unique_lock
<std::mutex
>&)
140 if( mxTempStorage
.is() )
142 mxTempStorage
->dispose();
143 mxTempStorage
.clear();
147 void SvXMLEmbeddedObjectHelper::splitObjectURL(const OUString
& _aURLNoPar
,
148 OUString
& rContainerStorageName
,
149 OUString
& rObjectStorageName
)
151 DBG_ASSERT(_aURLNoPar
.isEmpty() || '#' != _aURLNoPar
[0], "invalid object URL" );
152 OUString aURLNoPar
= _aURLNoPar
;
154 sal_Int32 _nPos
= aURLNoPar
.lastIndexOf( '/' );
157 rContainerStorageName
.clear();
158 rObjectStorageName
= aURLNoPar
;
162 //eliminate 'superfluous' slashes at start and end
163 //#i103076# load objects with all allowed xlink:href syntaxes
165 //eliminate './' at start
166 sal_Int32 nStart
= 0;
167 sal_Int32 nCount
= aURLNoPar
.getLength();
168 if( aURLNoPar
.startsWith( "./" ) )
174 //eliminate '/' at end
175 sal_Int32 nEnd
= aURLNoPar
.lastIndexOf( '/' );
176 if( nEnd
== aURLNoPar
.getLength()-1 && nEnd
!= (nStart
-1) )
179 aURLNoPar
= aURLNoPar
.copy( nStart
, nCount
);
182 _nPos
= aURLNoPar
.lastIndexOf( '/' );
184 rContainerStorageName
= aURLNoPar
.copy( 0, _nPos
);
185 rObjectStorageName
= aURLNoPar
.copy( _nPos
+1 );
189 bool SvXMLEmbeddedObjectHelper::ImplGetStorageNames(
190 const OUString
& rURLStr
,
191 OUString
& rContainerStorageName
,
192 OUString
& rObjectStorageName
,
193 bool bInternalToExternal
,
195 bool *pOasisFormat
) const
197 // internal URL: vnd.sun.star.EmbeddedObject:<object-name>
198 // or: vnd.sun.star.EmbeddedObject:<path>/<object-name>
199 // internal replacement images:
200 // vnd.sun.star.EmbeddedObjectGraphic:<object-name>
201 // or: vnd.sun.star.EmbeddedObjectGraphic:<path>/<object-name>
202 // external URL: ./<path>/<object-name>
203 // or: <path>/<object-name>
205 // currently, path may only consist of a single directory name
206 // it is also possible to have additional arguments at the end of URL: <main URL>[?<name>=<value>[,<name>=<value>]*]
209 *pGraphicRepl
= false;
212 *pOasisFormat
= true; // the default value
214 if( rURLStr
.isEmpty() )
217 // get rid of arguments
218 sal_Int32 nPos
= rURLStr
.indexOf( '?' );
224 aURLNoPar
= rURLStr
.copy( 0, nPos
);
226 // check the arguments
228 while( nPos
>= 0 && nPos
< rURLStr
.getLength() )
230 OUString aToken
= rURLStr
.getToken( 0, ',', nPos
);
231 if ( aToken
.equalsIgnoreAsciiCase( "oasis=false" ) )
234 *pOasisFormat
= false;
239 SAL_WARN( "svx", "invalid arguments was found in URL!" );
244 if( bInternalToExternal
)
246 nPos
= aURLNoPar
.indexOf( ':' );
249 bool bObjUrl
= aURLNoPar
.startsWith( XML_EMBEDDEDOBJECT_URL_BASE
);
250 bool bGrUrl
= !bObjUrl
&&
251 aURLNoPar
.startsWith( XML_EMBEDDEDOBJECTGRAPHIC_URL_BASE
);
252 if( !(bObjUrl
|| bGrUrl
) )
255 sal_Int32 nPathStart
= nPos
+ 1;
256 nPos
= aURLNoPar
.lastIndexOf( '/' );
259 rContainerStorageName
.clear();
260 rObjectStorageName
= aURLNoPar
.copy( nPathStart
);
262 else if( nPos
> nPathStart
)
264 rContainerStorageName
= aURLNoPar
.copy( nPathStart
, nPos
-nPathStart
);
265 rObjectStorageName
= aURLNoPar
.copy( nPos
+1 );
272 bool bOASIS
= mxRootStorage
.is() &&
273 ( SotStorage::GetVersion( mxRootStorage
) > SOFFICE_FILEFORMAT_60
);
275 rContainerStorageName
= XML_CONTAINERSTORAGE_NAME
;
277 rContainerStorageName
= XML_CONTAINERSTORAGE_NAME_60
;
280 *pGraphicRepl
= true;
287 splitObjectURL(aURLNoPar
, rContainerStorageName
, rObjectStorageName
);
290 if( -1 != rContainerStorageName
.indexOf( '/' ) )
292 OSL_FAIL( "SvXMLEmbeddedObjectHelper: invalid path name" );
299 uno::Reference
< embed::XStorage
> const & SvXMLEmbeddedObjectHelper::ImplGetContainerStorage(
300 const OUString
& rStorageName
)
302 DBG_ASSERT( -1 == rStorageName
.indexOf( '/' ) &&
303 -1 == rStorageName
.indexOf( '\\' ),
304 "nested embedded storages aren't supported" );
305 if( !mxContainerStorage
.is() ||
306 ( rStorageName
!= maCurContainerStorageName
) )
308 if( mxContainerStorage
.is() &&
309 !maCurContainerStorageName
.isEmpty() &&
310 SvXMLEmbeddedObjectHelperMode::Write
== meCreateMode
)
312 uno::Reference
< embed::XTransactedObject
> xTrans( mxContainerStorage
, uno::UNO_QUERY
);
317 if( !rStorageName
.isEmpty() && mxRootStorage
.is() )
319 sal_Int32 nMode
= SvXMLEmbeddedObjectHelperMode::Write
== meCreateMode
320 ? ::embed::ElementModes::READWRITE
321 : ::embed::ElementModes::READ
;
322 mxContainerStorage
= mxRootStorage
->openStorageElement( rStorageName
,
327 mxContainerStorage
= mxRootStorage
;
329 maCurContainerStorageName
= rStorageName
;
332 return mxContainerStorage
;
335 void SvXMLEmbeddedObjectHelper::ImplReadObject(
336 const OUString
& rContainerStorageName
,
338 const SvGlobalName
*, // pClassId, see "TODO/LATER" below
341 uno::Reference
< embed::XStorage
> xDocStor( mpDocPersist
->getStorage() );
342 uno::Reference
< embed::XStorage
> xCntnrStor( ImplGetContainerStorage( rContainerStorageName
) );
344 if( !xCntnrStor
.is() && !pTemp
)
347 OUString
aSrcObjName( rObjName
);
348 comphelper::EmbeddedObjectContainer
& rContainer
= mpDocPersist
->getEmbeddedObjectContainer();
350 // Is the object name unique?
351 // if the object is already instantiated by GetEmbeddedObject
352 // that means that the duplication is being loaded
353 bool bDuplicate
= rContainer
.HasInstantiatedEmbeddedObject( rObjName
);
354 DBG_ASSERT( !bDuplicate
, "An object in the document is referenced twice!" );
356 if( xDocStor
!= xCntnrStor
|| pTemp
|| bDuplicate
)
358 // TODO/LATER: make this altogether a method in the EmbeddedObjectContainer
360 // create a unique name for the duplicate object
362 rObjName
= rContainer
.CreateUniqueObjectName();
369 uno::Reference
< io::XStream
> xStm
= xDocStor
->openStreamElement( rObjName
,
370 embed::ElementModes::READWRITE
| embed::ElementModes::TRUNCATE
);
371 std::unique_ptr
<SvStream
> pStream(::utl::UcbStreamHelper::CreateStream( xStm
));
372 pTemp
->ReadStream( *pStream
);
375 // TODO/LATER: what to do when other types of objects are based on substream persistence?
376 // This is an ole object
377 uno::Reference
< beans::XPropertySet
> xProps( xStm
, uno::UNO_QUERY_THROW
);
378 xProps
->setPropertyValue(
380 uno::Any( OUString( "application/vnd.sun.star.oleobject" ) ) );
382 xStm
->getOutputStream()->closeOutput();
384 catch ( uno::Exception
& )
393 xCntnrStor
->copyElementTo( aSrcObjName
, xDocStor
, rObjName
);
395 catch ( uno::Exception
& )
402 // make object known to the container
403 // TODO/LATER: could be done a little bit more efficient!
404 OUString
aName( rObjName
);
406 // TODO/LATER: The provided pClassId is ignored for now.
407 // The stream contains OLE storage internally and this storage already has a class id specifying the
408 // server that was used to create the object. pClassId could be used to specify the server that should
409 // be used for the next opening, but this information seems to be out of the file format responsibility
411 OUString
const baseURL(mpDocPersist
->getDocumentBaseURL());
412 rContainer
.GetEmbeddedObject(aName
, &baseURL
);
415 OUString
SvXMLEmbeddedObjectHelper::ImplInsertEmbeddedObjectURL(
416 const OUString
& rURLStr
)
420 OUString aContainerStorageName
, aObjectStorageName
;
421 if( !ImplGetStorageNames( rURLStr
, aContainerStorageName
,
423 SvXMLEmbeddedObjectHelperMode::Write
== meCreateMode
) )
426 if( SvXMLEmbeddedObjectHelperMode::Read
== meCreateMode
)
428 OutputStorageWrapper_Impl
*pOut
= nullptr;
429 std::map
< OUString
, rtl::Reference
<OutputStorageWrapper_Impl
> >::iterator aIter
;
433 aIter
= mxStreamMap
->find( rURLStr
);
434 if( aIter
!= mxStreamMap
->end() && aIter
->second
.is() )
435 pOut
= aIter
->second
.get();
438 SvGlobalName aClassId
, *pClassId
= nullptr;
439 sal_Int32 nPos
= aObjectStorageName
.lastIndexOf( '!' );
440 if( -1 != nPos
&& aClassId
.MakeId( aObjectStorageName
.subView( nPos
+1 ) ) )
442 aObjectStorageName
= aObjectStorageName
.copy( 0, nPos
);
443 pClassId
= &aClassId
;
446 ImplReadObject( aContainerStorageName
, aObjectStorageName
, pClassId
, pOut
? pOut
->GetStream() : nullptr );
447 sRetURL
= XML_EMBEDDEDOBJECT_URL_BASE
+ aObjectStorageName
;
451 mxStreamMap
->erase( aIter
);
456 // Objects are written using ::comphelper::IEmbeddedHelper::SaveAs
458 if( !aContainerStorageName
.isEmpty() )
460 sRetURL
+= aContainerStorageName
+ "/";
462 sRetURL
+= aObjectStorageName
;
468 uno::Reference
< io::XInputStream
> SvXMLEmbeddedObjectHelper::ImplGetReplacementImage(
469 const uno::Reference
< embed::XEmbeddedObject
>& xObj
)
471 uno::Reference
< io::XInputStream
> xStream
;
477 bool bSwitchBackToLoaded
= false;
478 sal_Int32 nCurState
= xObj
->getCurrentState();
479 if ( nCurState
== embed::EmbedStates::LOADED
|| nCurState
== embed::EmbedStates::RUNNING
)
481 // means that the object is not active
482 // copy replacement image from old to new container
484 xStream
= mpDocPersist
->getEmbeddedObjectContainer().GetGraphicStream( xObj
, &aMediaType
);
489 // the image must be regenerated
490 // TODO/LATER: another aspect could be used
491 if ( nCurState
== embed::EmbedStates::LOADED
)
492 bSwitchBackToLoaded
= true;
495 xStream
= svt::EmbeddedObjectRef::GetGraphicReplacementStream(
496 embed::Aspects::MSOLE_CONTENT
,
501 if ( bSwitchBackToLoaded
)
502 // switch back to loaded state; that way we have a minimum cache confusion
503 xObj
->changeState( embed::EmbedStates::LOADED
);
505 catch( uno::Exception
& )
512 void SvXMLEmbeddedObjectHelper::Init(
513 const uno::Reference
< embed::XStorage
>& rRootStorage
,
514 ::comphelper::IEmbeddedHelper
& rPersist
,
515 SvXMLEmbeddedObjectHelperMode eCreateMode
)
517 mxRootStorage
= rRootStorage
;
518 mpDocPersist
= &rPersist
;
519 meCreateMode
= eCreateMode
;
522 rtl::Reference
<SvXMLEmbeddedObjectHelper
> SvXMLEmbeddedObjectHelper::Create(
523 const uno::Reference
< embed::XStorage
>& rRootStorage
,
524 ::comphelper::IEmbeddedHelper
& rDocPersist
,
525 SvXMLEmbeddedObjectHelperMode eCreateMode
)
527 rtl::Reference
<SvXMLEmbeddedObjectHelper
> pThis(new SvXMLEmbeddedObjectHelper
);
529 pThis
->Init( rRootStorage
, rDocPersist
, eCreateMode
);
534 rtl::Reference
<SvXMLEmbeddedObjectHelper
> SvXMLEmbeddedObjectHelper::Create(
535 ::comphelper::IEmbeddedHelper
& rDocPersist
,
536 SvXMLEmbeddedObjectHelperMode eCreateMode
)
538 rtl::Reference
<SvXMLEmbeddedObjectHelper
> pThis(new SvXMLEmbeddedObjectHelper
);
540 pThis
->Init( nullptr, rDocPersist
, eCreateMode
);
545 OUString SAL_CALL
SvXMLEmbeddedObjectHelper::resolveEmbeddedObjectURL(const OUString
& rURL
)
547 std::unique_lock
aGuard( m_aMutex
);
552 sRet
= ImplInsertEmbeddedObjectURL(rURL
);
554 catch (const RuntimeException
&)
558 catch (const Exception
&)
560 css::uno::Any anyEx
= cppu::getCaughtException();
561 throw WrappedTargetRuntimeException(
562 "SvXMLEmbeddedObjectHelper::resolveEmbeddedObjectURL non-RuntimeException",
563 static_cast<uno::XWeak
*>(this), anyEx
);
568 // XNameAccess: alien objects!
569 Any SAL_CALL
SvXMLEmbeddedObjectHelper::getByName(
570 const OUString
& rURLStr
)
572 std::unique_lock
aGuard( m_aMutex
);
574 if( SvXMLEmbeddedObjectHelperMode::Read
== meCreateMode
)
576 Reference
< XOutputStream
> xStrm
;
579 auto aIter
= mxStreamMap
->find( rURLStr
);
580 if( aIter
!= mxStreamMap
->end() && aIter
->second
.is() )
581 xStrm
= aIter
->second
.get();
585 rtl::Reference
<OutputStorageWrapper_Impl
> xOut
= new OutputStorageWrapper_Impl
;
587 mxStreamMap
.emplace();
588 (*mxStreamMap
)[rURLStr
] = xOut
;
596 bool bGraphicRepl
= false;
597 bool bOasisFormat
= true;
598 Reference
< XInputStream
> xStrm
;
599 OUString aContainerStorageName
, aObjectStorageName
;
600 if( ImplGetStorageNames( rURLStr
, aContainerStorageName
,
608 comphelper::EmbeddedObjectContainer
& rContainer
=
609 mpDocPersist
->getEmbeddedObjectContainer();
611 Reference
< embed::XEmbeddedObject
> xObj
= rContainer
.GetEmbeddedObject( aObjectStorageName
);
612 DBG_ASSERT( xObj
.is(), "Didn't get object" );
618 xStrm
= ImplGetReplacementImage( xObj
);
622 Reference
< embed::XEmbedPersist
> xPersist( xObj
, UNO_QUERY
);
625 if( !mxTempStorage
.is() )
627 comphelper::OStorageHelper::GetTemporaryStorage();
628 Sequence
< beans::PropertyValue
> aDummy
,
629 aEmbDescr
{ comphelper::makePropertyValue("StoreVisualReplacement",
633 uno::Reference
< io::XInputStream
> xGrInStream
= ImplGetReplacementImage( xObj
);
634 if ( xGrInStream
.is() )
636 aEmbDescr
.realloc( 2 );
637 auto pEmbDescr
= aEmbDescr
.getArray();
638 pEmbDescr
[1].Name
= "VisualReplacement";
639 pEmbDescr
[1].Value
<<= xGrInStream
;
643 xPersist
->storeToEntry( mxTempStorage
, aObjectStorageName
,
645 Reference
< io::XStream
> xStream
=
646 mxTempStorage
->openStreamElement(
648 embed::ElementModes::READ
);
650 xStrm
= xStream
->getInputStream();
655 catch ( uno::Exception
& )
666 Sequence
< OUString
> SAL_CALL
SvXMLEmbeddedObjectHelper::getElementNames()
671 sal_Bool SAL_CALL
SvXMLEmbeddedObjectHelper::hasByName( const OUString
& rURLStr
)
673 std::unique_lock
aGuard( m_aMutex
);
674 if( SvXMLEmbeddedObjectHelperMode::Read
== meCreateMode
)
680 OUString aContainerStorageName
, aObjectStorageName
;
681 if( !ImplGetStorageNames( rURLStr
, aContainerStorageName
,
686 comphelper::EmbeddedObjectContainer
& rContainer
= mpDocPersist
->getEmbeddedObjectContainer();
687 return !aObjectStorageName
.isEmpty() &&
688 rContainer
.HasEmbeddedObject( aObjectStorageName
);
693 Type SAL_CALL
SvXMLEmbeddedObjectHelper::getElementType()
695 std::unique_lock
aGuard( m_aMutex
);
696 if( SvXMLEmbeddedObjectHelperMode::Read
== meCreateMode
)
697 return cppu::UnoType
<XOutputStream
>::get();
699 return cppu::UnoType
<XInputStream
>::get();
702 sal_Bool SAL_CALL
SvXMLEmbeddedObjectHelper::hasElements()
704 std::unique_lock
aGuard( m_aMutex
);
705 if( SvXMLEmbeddedObjectHelperMode::Read
== meCreateMode
)
711 comphelper::EmbeddedObjectContainer
& rContainer
= mpDocPersist
->getEmbeddedObjectContainer();
712 return rContainer
.HasEmbeddedObjects();
716 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */