LibreOffice Module comphelper (master)  1
embeddedobjectcontainer.cxx
Go to the documentation of this file.
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3  * This file is part of the LibreOffice project.
4  *
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/.
8  *
9  * This file incorporates work covered by the following license notice:
10  *
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 .
18  */
19 
20 #include <com/sun/star/container/XChild.hpp>
21 #include <com/sun/star/container/XNameAccess.hpp>
22 #include <com/sun/star/embed/EmbeddedObjectCreator.hpp>
23 #include <com/sun/star/embed/WrongStateException.hpp>
24 #include <com/sun/star/embed/XEmbeddedObject.hpp>
25 #include <com/sun/star/embed/XEmbedPersist.hpp>
26 #include <com/sun/star/embed/XLinkageSupport.hpp>
27 #include <com/sun/star/embed/XTransactedObject.hpp>
28 #include <com/sun/star/embed/XOptimizedStorage.hpp>
29 #include <com/sun/star/embed/EntryInitModes.hpp>
30 #include <com/sun/star/io/IOException.hpp>
31 #include <com/sun/star/util/XCloseable.hpp>
32 #include <com/sun/star/util/XModifiable.hpp>
33 #include <com/sun/star/embed/EmbedStates.hpp>
34 #include <com/sun/star/beans/XPropertySetInfo.hpp>
35 #include <com/sun/star/beans/XPropertySet.hpp>
36 #include <com/sun/star/embed/Aspects.hpp>
37 #include <com/sun/star/embed/EmbedMisc.hpp>
38 
39 #include <comphelper/seqstream.hxx>
43 #include <comphelper/sequence.hxx>
45 #include <cppuhelper/weakref.hxx>
46 #include <sal/log.hxx>
47 
48 #include <algorithm>
49 #include <unordered_map>
50 
51 
52 using namespace ::com::sun::star;
53 
54 namespace comphelper {
55 
56 typedef std::unordered_map<OUString, uno::Reference<embed::XEmbeddedObject>> EmbeddedObjectContainerNameMap;
57 struct EmbedImpl
58 {
59  // TODO/LATER: remove objects from temp. Container storage when object is disposed
60  EmbeddedObjectContainerNameMap maNameToObjectMap;
61  // to speed up lookup by Reference
62  std::unordered_map<uno::Reference<embed::XEmbeddedObject>, OUString> maObjectToNameMap;
63  uno::Reference < embed::XStorage > mxStorage;
65  uno::Reference < embed::XStorage > mxImageStorage;
66  uno::WeakReference < uno::XInterface > m_xModel;
67 
68  bool mbOwnsStorage : 1;
70 
71  const uno::Reference < embed::XStorage >& GetReplacements();
72 };
73 
74 const uno::Reference < embed::XStorage >& EmbedImpl::GetReplacements()
75 {
76  if ( !mxImageStorage.is() )
77  {
78  try
79  {
80  mxImageStorage = mxStorage->openStorageElement(
81  "ObjectReplacements", embed::ElementModes::READWRITE );
82  }
83  catch (const uno::Exception&)
84  {
85  mxImageStorage = mxStorage->openStorageElement(
86  "ObjectReplacements", embed::ElementModes::READ );
87  }
88  }
89 
90  if ( !mxImageStorage.is() )
91  throw io::IOException();
92 
93  return mxImageStorage;
94 }
95 
97  : pImpl(new EmbedImpl)
98 {
100  pImpl->mbOwnsStorage = true;
101  pImpl->mbUserAllowsLinkUpdate = true;
102  pImpl->mpTempObjectContainer = nullptr;
103 }
104 
105 EmbeddedObjectContainer::EmbeddedObjectContainer( const uno::Reference < embed::XStorage >& rStor )
106  : pImpl(new EmbedImpl)
107 {
108  pImpl->mxStorage = rStor;
109  pImpl->mbOwnsStorage = false;
110  pImpl->mbUserAllowsLinkUpdate = true;
111  pImpl->mpTempObjectContainer = nullptr;
112 }
113 
114 EmbeddedObjectContainer::EmbeddedObjectContainer( const uno::Reference < embed::XStorage >& rStor, const uno::Reference < uno::XInterface >& xModel )
115  : pImpl(new EmbedImpl)
116 {
117  pImpl->mxStorage = rStor;
118  pImpl->mbOwnsStorage = false;
119  pImpl->mbUserAllowsLinkUpdate = true;
120  pImpl->mpTempObjectContainer = nullptr;
121  pImpl->m_xModel = xModel;
122 }
123 
124 void EmbeddedObjectContainer::SwitchPersistence( const uno::Reference < embed::XStorage >& rStor )
125 {
127 
128  if ( pImpl->mbOwnsStorage )
129  pImpl->mxStorage->dispose();
130 
131  pImpl->mxStorage = rStor;
132  pImpl->mbOwnsStorage = false;
133 }
134 
136 {
137  if ( pImpl->mxImageStorage.is() )
138  {
139  try
140  {
141  bool bReadOnlyMode = true;
142  uno::Reference < beans::XPropertySet > xSet(pImpl->mxImageStorage,uno::UNO_QUERY);
143  if ( xSet.is() )
144  {
145  // get the open mode from the parent storage
146  sal_Int32 nMode = 0;
147  uno::Any aAny = xSet->getPropertyValue("OpenMode");
148  if ( aAny >>= nMode )
149  bReadOnlyMode = !(nMode & embed::ElementModes::WRITE );
150  } // if ( xSet.is() )
151  if ( !bReadOnlyMode )
152  {
153  uno::Reference< embed::XTransactedObject > xTransact( pImpl->mxImageStorage, uno::UNO_QUERY_THROW );
154  xTransact->commit();
155  }
156  }
157  catch (const uno::Exception&)
158  {
159  return false;
160  }
161  }
162 
163  return true;
164 }
165 
167 {
169 
170  if ( pImpl->mxImageStorage.is() )
171  {
172  try
173  {
174  pImpl->mxImageStorage->dispose();
175  pImpl->mxImageStorage.clear();
176  }
177  catch (const uno::Exception&)
178  {
179  SAL_WARN( "comphelper.container", "Problems releasing image substorage!" );
180  }
181  }
182 }
183 
185 {
187 
188  if ( pImpl->mbOwnsStorage )
189  pImpl->mxStorage->dispose();
190 
191  delete pImpl->mpTempObjectContainer;
192 }
193 
195 {
196  for( const auto& rObj : pImpl->maNameToObjectMap )
197  {
198  uno::Reference < util::XCloseable > xClose( rObj.second, uno::UNO_QUERY );
199  if( xClose.is() )
200  {
201  try
202  {
203  xClose->close( true );
204  }
205  catch (const uno::Exception&)
206  {
207  }
208  }
209  }
210 }
211 
213 {
214  OUString aStr;
215  sal_Int32 i=1;
216  do
217  {
218  aStr = "Object " + OUString::number( i++ );
219  }
220  while( HasEmbeddedObject( aStr ) );
221  // TODO/LATER: should we consider deleted objects?
222 
223  return aStr;
224 }
225 
226 uno::Sequence < OUString > EmbeddedObjectContainer::GetObjectNames() const
227 {
228  return comphelper::mapKeysToSequence(pImpl->maNameToObjectMap);
229 }
230 
232 {
233  return !pImpl->maNameToObjectMap.empty();
234 }
235 
236 bool EmbeddedObjectContainer::HasEmbeddedObject( const OUString& rName )
237 {
238  auto aIt = pImpl->maNameToObjectMap.find( rName );
239  if (aIt != pImpl->maNameToObjectMap.end())
240  return true;
241  if (!pImpl->mxStorage.is())
242  return false;
243  return pImpl->mxStorage->hasByName(rName);
244 }
245 
246 bool EmbeddedObjectContainer::HasEmbeddedObject( const uno::Reference < embed::XEmbeddedObject >& xObj ) const
247 {
248  return pImpl->maObjectToNameMap.find(xObj) != pImpl->maObjectToNameMap.end();
249 }
250 
252 {
253  // allows to detect whether the object was already instantiated
254  // currently the filter instantiate it on loading, so this method allows
255  // to avoid objects pointing to the same persistence
256  auto aIt = pImpl->maNameToObjectMap.find( rName );
257  return ( aIt != pImpl->maNameToObjectMap.end() );
258 }
259 
260 OUString EmbeddedObjectContainer::GetEmbeddedObjectName( const css::uno::Reference < css::embed::XEmbeddedObject >& xObj ) const
261 {
262  auto it = pImpl->maObjectToNameMap.find(xObj);
263  if (it == pImpl->maObjectToNameMap.end())
264  {
265  SAL_WARN( "comphelper.container", "Unknown object!" );
266  return OUString();
267  }
268  return it->second;
269 }
270 
271 uno::Reference< embed::XEmbeddedObject>
273  const OUString& rName, OUString const*const pBaseURL)
274 {
275  SAL_WARN_IF( rName.isEmpty(), "comphelper.container", "Empty object name!");
276 
277  uno::Reference < embed::XEmbeddedObject > xObj;
278  auto aIt = pImpl->maNameToObjectMap.find( rName );
279 
280 #if OSL_DEBUG_LEVEL > 1
281  uno::Reference < container::XNameAccess > xAccess( pImpl->mxStorage, uno::UNO_QUERY );
282  uno::Sequence< OUString> aSeq = xAccess->getElementNames();
283  const OUString* pIter = aSeq.getConstArray();
284  const OUString* pEnd = pIter + aSeq.getLength();
285  for(;pIter != pEnd;++pIter)
286  {
287  (void)*pIter;
288  }
289  OSL_ENSURE( aIt != pImpl->maNameToObjectMap.end() || xAccess->hasByName(rName), "Could not return object!" );
290 #endif
291 
292  // check if object was already created
293  if ( aIt != pImpl->maNameToObjectMap.end() )
294  xObj = (*aIt).second;
295  else
296  xObj = Get_Impl(rName, uno::Reference<embed::XEmbeddedObject>(), pBaseURL);
297 
298  return xObj;
299 }
300 
301 uno::Reference<embed::XEmbeddedObject> EmbeddedObjectContainer::Get_Impl(
302  const OUString& rName,
303  const uno::Reference<embed::XEmbeddedObject>& xCopy,
304  OUString const*const pBaseURL)
305 {
306  uno::Reference < embed::XEmbeddedObject > xObj;
307  try
308  {
309  // create the object from the storage
310  uno::Reference < beans::XPropertySet > xSet( pImpl->mxStorage, uno::UNO_QUERY );
311  bool bReadOnlyMode = true;
312  if ( xSet.is() )
313  {
314  // get the open mode from the parent storage
315  sal_Int32 nMode = 0;
316  uno::Any aAny = xSet->getPropertyValue("OpenMode");
317  if ( aAny >>= nMode )
318  bReadOnlyMode = !(nMode & embed::ElementModes::WRITE );
319  }
320 
321  // object was not added until now - should happen only by calling this method from "inside"
322  //TODO/LATER: it would be good to detect an error when an object should be created already, but isn't (not an "inside" call)
323  uno::Reference < embed::XEmbeddedObjectCreator > xFactory = embed::EmbeddedObjectCreator::create( ::comphelper::getProcessComponentContext() );
324  uno::Sequence< beans::PropertyValue > aObjDescr(1 + (xCopy.is() ? 1 : 0) + (pBaseURL ? 1 : 0));
325  aObjDescr[0].Name = "Parent";
326  aObjDescr[0].Value <<= pImpl->m_xModel.get();
327  sal_Int32 i = 1;
328  if (pBaseURL)
329  {
330  aObjDescr[i].Name = "DefaultParentBaseURL";
331  aObjDescr[i].Value <<= *pBaseURL;
332  ++i;
333  }
334  if ( xCopy.is() )
335  {
336  aObjDescr[i].Name = "CloneFrom";
337  aObjDescr[i].Value <<= xCopy;
338  }
339 
340  uno::Sequence< beans::PropertyValue > aMediaDescr( 1 );
341  aMediaDescr[0].Name = "ReadOnly";
342  aMediaDescr[0].Value <<= bReadOnlyMode;
343  xObj.set( xFactory->createInstanceInitFromEntry(
344  pImpl->mxStorage, rName,
345  aMediaDescr, aObjDescr ), uno::UNO_QUERY );
346 
347  // insert object into my list
348  AddEmbeddedObject( xObj, rName );
349  }
350  catch (uno::Exception const& e)
351  {
352  SAL_WARN("comphelper.container", "EmbeddedObjectContainer::Get_Impl: exception caught: " << e);
353  }
354 
355  return xObj;
356 }
357 
358 uno::Reference < embed::XEmbeddedObject > EmbeddedObjectContainer::CreateEmbeddedObject( const uno::Sequence < sal_Int8 >& rClassId,
359  const uno::Sequence < beans::PropertyValue >& rArgs, OUString& rNewName, OUString const* pBaseURL )
360 {
361  if ( rNewName.isEmpty() )
362  rNewName = CreateUniqueObjectName();
363 
364  SAL_WARN_IF( HasEmbeddedObject(rNewName), "comphelper.container", "Object to create already exists!");
365 
366  // create object from classid by inserting it into storage
367  uno::Reference < embed::XEmbeddedObject > xObj;
368  try
369  {
370  uno::Reference < embed::XEmbeddedObjectCreator > xFactory = embed::EmbeddedObjectCreator::create( ::comphelper::getProcessComponentContext() );
371 
372  const size_t nExtraArgs = pBaseURL ? 2 : 1;
373  uno::Sequence< beans::PropertyValue > aObjDescr( rArgs.getLength() + nExtraArgs );
374  aObjDescr[0].Name = "Parent";
375  aObjDescr[0].Value <<= pImpl->m_xModel.get();
376  if (pBaseURL)
377  {
378  aObjDescr[1].Name = "DefaultParentBaseURL";
379  aObjDescr[1].Value <<= *pBaseURL;
380  }
381  std::copy( rArgs.begin(), rArgs.end(), aObjDescr.getArray() + nExtraArgs );
382  xObj.set( xFactory->createInstanceInitNew(
383  rClassId, OUString(), pImpl->mxStorage, rNewName,
384  aObjDescr ), uno::UNO_QUERY );
385 
386  AddEmbeddedObject( xObj, rNewName );
387 
388  OSL_ENSURE( !xObj.is() || xObj->getCurrentState() != embed::EmbedStates::LOADED,
389  "A freshly create object should be running always!" );
390  }
391  catch (uno::Exception const& e)
392  {
393  SAL_WARN("comphelper.container", "EmbeddedObjectContainer::CreateEmbeddedObject: exception caught: " << e);
394  }
395 
396  return xObj;
397 }
398 
399 uno::Reference < embed::XEmbeddedObject > EmbeddedObjectContainer::CreateEmbeddedObject( const uno::Sequence < sal_Int8 >& rClassId, OUString& rNewName, OUString const* pBaseURL )
400 {
401  return CreateEmbeddedObject( rClassId, uno::Sequence < beans::PropertyValue >(), rNewName, pBaseURL );
402 }
403 
404 void EmbeddedObjectContainer::AddEmbeddedObject( const css::uno::Reference < css::embed::XEmbeddedObject >& xObj, const OUString& rName )
405 {
406 #if OSL_DEBUG_LEVEL > 1
407  SAL_WARN_IF( rName.isEmpty(), "comphelper.container", "Added object doesn't have a name!");
408  uno::Reference < container::XNameAccess > xAccess( pImpl->mxStorage, uno::UNO_QUERY );
409  uno::Reference < embed::XEmbedPersist > xEmb( xObj, uno::UNO_QUERY );
410  uno::Reference < embed::XLinkageSupport > xLink( xEmb, uno::UNO_QUERY );
411  // if the object has a persistence and the object is not a link than it must have persistence entry in the storage
412  OSL_ENSURE( !( xEmb.is() && ( !xLink.is() || !xLink->isLink() ) ) || xAccess->hasByName(rName),
413  "Added element not in storage!" );
414 #endif
415 
416  // remember object - it needs to be in storage already
417  auto aIt = pImpl->maNameToObjectMap.find( rName );
418  OSL_ENSURE( aIt == pImpl->maNameToObjectMap.end(), "Element already inserted!" );
419  pImpl->maNameToObjectMap[ rName ] = xObj;
420  pImpl->maObjectToNameMap[ xObj ] = rName;
421  uno::Reference < container::XChild > xChild( xObj, uno::UNO_QUERY );
422  if ( xChild.is() && xChild->getParent() != pImpl->m_xModel.get() )
423  xChild->setParent( pImpl->m_xModel.get() );
424 
425  // look for object in temporary container
426  if ( pImpl->mpTempObjectContainer )
427  {
428  auto& rObjectContainer = pImpl->mpTempObjectContainer->pImpl->maNameToObjectMap;
429  auto aIter = std::find_if(rObjectContainer.begin(), rObjectContainer.end(),
430  [&xObj](const EmbeddedObjectContainerNameMap::value_type& rEntry) { return rEntry.second == xObj; });
431  if (aIter != rObjectContainer.end())
432  {
433  // copy replacement image from temporary container (if there is any)
434  OUString aTempName = aIter->first;
435  OUString aMediaType;
436  uno::Reference < io::XInputStream > xStream = pImpl->mpTempObjectContainer->GetGraphicStream( xObj, &aMediaType );
437  if ( xStream.is() )
438  {
439  InsertGraphicStream( xStream, rName, aMediaType );
440  xStream = nullptr;
441  pImpl->mpTempObjectContainer->RemoveGraphicStream( aTempName );
442  }
443 
444  // remove object from storage of temporary container
445  uno::Reference < embed::XEmbedPersist > xPersist( xObj, uno::UNO_QUERY );
446  if ( xPersist.is() )
447  {
448  try
449  {
450  pImpl->mpTempObjectContainer->pImpl->mxStorage->removeElement( aTempName );
451  }
452  catch (const uno::Exception&)
453  {
454  }
455  }
456 
457  // temp. container needs to forget the object
458  pImpl->mpTempObjectContainer->pImpl->maObjectToNameMap.erase( aIter->second );
459  pImpl->mpTempObjectContainer->pImpl->maNameToObjectMap.erase( aIter );
460  }
461  }
462 }
463 
465  const uno::Reference < embed::XEmbeddedObject >& xObj, OUString& rName, bool bCopy,
466  const OUString& rSrcShellID, const OUString& rDestShellID )
467 {
468  uno::Reference < embed::XEmbedPersist > xPersist( xObj, uno::UNO_QUERY );
469  if ( rName.isEmpty() )
470  rName = CreateUniqueObjectName();
471 
472 #if OSL_DEBUG_LEVEL > 1
473  uno::Reference < container::XNameAccess > xAccess( pImpl->mxStorage, uno::UNO_QUERY );
474  OSL_ENSURE( !xPersist.is() || !xAccess->hasByName(rName), "Inserting element already present in storage!" );
475  OSL_ENSURE( xPersist.is() || xObj->getCurrentState() == embed::EmbedStates::RUNNING, "Non persistent object inserted!");
476 #endif
477 
478  // insert objects' storage into the container storage (if object has one)
479  try
480  {
481  if ( xPersist.is() )
482  {
483  uno::Sequence < beans::PropertyValue > aSeq;
484  if ( bCopy )
485  {
486  auto aObjArgs(::comphelper::InitPropertySequence({
487  { "SourceShellID", uno::Any(rSrcShellID) },
488  { "DestinationShellID", uno::Any(rDestShellID) }
489  }));
490  xPersist->storeToEntry(pImpl->mxStorage, rName, aSeq, aObjArgs);
491  }
492  else
493  {
494  //TODO/LATER: possible optimization, don't store immediately
495  //xPersist->setPersistentEntry( pImpl->mxStorage, rName, embed::EntryInitModes::ENTRY_NO_INIT, aSeq, aSeq );
496  xPersist->storeAsEntry( pImpl->mxStorage, rName, aSeq, aSeq );
497  xPersist->saveCompleted( true );
498  }
499  }
500  }
501  catch (uno::Exception const& e)
502  {
503  SAL_WARN("comphelper.container", "EmbeddedObjectContainer::StoreEmbeddedObject: exception caught: " << e);
504  // TODO/LATER: better error recovery should keep storage intact
505  return false;
506  }
507 
508  return true;
509 }
510 
511 bool EmbeddedObjectContainer::InsertEmbeddedObject( const uno::Reference < embed::XEmbeddedObject >& xObj, OUString& rName )
512 {
513  // store it into the container storage
514  if (StoreEmbeddedObject(xObj, rName, false, OUString(), OUString()))
515  {
516  // remember object
517  AddEmbeddedObject( xObj, rName );
518  return true;
519  }
520  else
521  return false;
522 }
523 
524 uno::Reference < embed::XEmbeddedObject > EmbeddedObjectContainer::InsertEmbeddedObject( const uno::Reference < io::XInputStream >& xStm, OUString& rNewName )
525 {
526  if ( rNewName.isEmpty() )
527  rNewName = CreateUniqueObjectName();
528 
529  // store it into the container storage
530  bool bIsStorage = false;
531  try
532  {
533  // first try storage persistence
534  uno::Reference < embed::XStorage > xStore = ::comphelper::OStorageHelper::GetStorageFromInputStream( xStm );
535 
536  // storage was created from stream successfully
537  bIsStorage = true;
538 
539  uno::Reference < embed::XStorage > xNewStore = pImpl->mxStorage->openStorageElement( rNewName, embed::ElementModes::READWRITE );
540  xStore->copyToStorage( xNewStore );
541  }
542  catch (const uno::Exception&)
543  {
544  if ( bIsStorage )
545  // it is storage persistence, but opening of new substorage or copying to it failed
546  return uno::Reference < embed::XEmbeddedObject >();
547 
548  // stream didn't contain a storage, now try stream persistence
549  try
550  {
551  uno::Reference < io::XStream > xNewStream = pImpl->mxStorage->openStreamElement( rNewName, embed::ElementModes::READWRITE );
552  ::comphelper::OStorageHelper::CopyInputToOutput( xStm, xNewStream->getOutputStream() );
553 
554  // No mediatype is provided so the default for OLE objects value is used
555  // it is correct so for now, but what if somebody introduces a new stream based embedded object?
556  // Probably introducing of such an object must be restricted ( a storage must be used! ).
557  uno::Reference< beans::XPropertySet > xProps( xNewStream, uno::UNO_QUERY_THROW );
558  xProps->setPropertyValue("MediaType",
559  uno::Any( OUString( "application/vnd.sun.star.oleobject" ) ) );
560  }
561  catch (uno::Exception const& e)
562  {
563  // complete disaster!
564  SAL_WARN("comphelper.container", "EmbeddedObjectContainer::InsertEmbeddedObject: exception caught: " << e);
565  return uno::Reference < embed::XEmbeddedObject >();
566  }
567  }
568 
569  // stream was copied into the container storage in either way, now try to open something form it
570  uno::Reference < embed::XEmbeddedObject > xRet = GetEmbeddedObject( rNewName );
571  try
572  {
573  if ( !xRet.is() )
574  // no object could be created, so withdraw insertion
575  pImpl->mxStorage->removeElement( rNewName );
576  }
577  catch (const uno::Exception&)
578  {
579  }
580 
581  return xRet;
582 }
583 
584 uno::Reference < embed::XEmbeddedObject > EmbeddedObjectContainer::InsertEmbeddedObject( const css::uno::Sequence < css::beans::PropertyValue >& aMedium, OUString& rNewName, OUString const* pBaseURL )
585 {
586  if ( rNewName.isEmpty() )
587  rNewName = CreateUniqueObjectName();
588 
589  uno::Reference < embed::XEmbeddedObject > xObj;
590  try
591  {
592  uno::Reference < embed::XEmbeddedObjectCreator > xFactory = embed::EmbeddedObjectCreator::create( ::comphelper::getProcessComponentContext() );
593  uno::Sequence< beans::PropertyValue > aObjDescr(pBaseURL ? 2 : 1);
594  aObjDescr[0].Name = "Parent";
595  aObjDescr[0].Value <<= pImpl->m_xModel.get();
596  if (pBaseURL)
597  {
598  aObjDescr[1].Name = "DefaultParentBaseURL";
599  aObjDescr[1].Value <<= *pBaseURL;
600  }
601  xObj.set( xFactory->createInstanceInitFromMediaDescriptor(
602  pImpl->mxStorage, rNewName, aMedium, aObjDescr ), uno::UNO_QUERY );
603  uno::Reference < embed::XEmbedPersist > xPersist( xObj, uno::UNO_QUERY );
604 
605  OSL_ENSURE( !xObj.is() || xObj->getCurrentState() != embed::EmbedStates::LOADED,
606  "A freshly create object should be running always!" );
607 
608  // possible optimization: store later!
609  if ( xPersist.is())
610  xPersist->storeOwn();
611 
612  AddEmbeddedObject( xObj, rNewName );
613  }
614  catch (const uno::Exception&)
615  {
616  }
617 
618  return xObj;
619 }
620 
621 uno::Reference < embed::XEmbeddedObject > EmbeddedObjectContainer::InsertEmbeddedLink( const css::uno::Sequence < css::beans::PropertyValue >& aMedium, OUString& rNewName )
622 {
623  if ( rNewName.isEmpty() )
624  rNewName = CreateUniqueObjectName();
625 
626  uno::Reference < embed::XEmbeddedObject > xObj;
627  try
628  {
629  uno::Reference < embed::XEmbeddedObjectCreator > xFactory = embed::EmbeddedObjectCreator::create(::comphelper::getProcessComponentContext());
630  uno::Sequence< beans::PropertyValue > aObjDescr( 1 );
631  aObjDescr[0].Name = "Parent";
632  aObjDescr[0].Value <<= pImpl->m_xModel.get();
633  xObj.set( xFactory->createInstanceLink( pImpl->mxStorage, rNewName, aMedium, aObjDescr ), uno::UNO_QUERY );
634 
635  uno::Reference < embed::XEmbedPersist > xPersist( xObj, uno::UNO_QUERY );
636 
637  OSL_ENSURE( !xObj.is() || xObj->getCurrentState() != embed::EmbedStates::LOADED,
638  "A freshly create object should be running always!" );
639 
640  // possible optimization: store later!
641  if ( xPersist.is())
642  xPersist->storeOwn();
643 
644  AddEmbeddedObject( xObj, rNewName );
645  }
646  catch (uno::Exception const& e)
647  {
648  SAL_WARN("comphelper.container", "EmbeddedObjectContainer::InsertEmbeddedLink: "
649  "exception caught: " << e);
650  }
651 
652  return xObj;
653 }
654 
656  const OUString& aOrigName,
657  const OUString& aTargetName )
658 {
659  bool bResult = false;
660 
661  if ( ( &rSrc != this || aOrigName != aTargetName ) && !aOrigName.isEmpty() && !aTargetName.isEmpty() )
662  {
663  OUString aMediaType;
664  uno::Reference < io::XInputStream > xGrStream = rSrc.GetGraphicStream( aOrigName, &aMediaType );
665  if ( xGrStream.is() )
666  bResult = InsertGraphicStream( xGrStream, aTargetName, aMediaType );
667  }
668 
669  return bResult;
670 }
671 
672 uno::Reference < embed::XEmbeddedObject > EmbeddedObjectContainer::CopyAndGetEmbeddedObject(
673  EmbeddedObjectContainer& rSrc, const uno::Reference <embed::XEmbeddedObject>& xObj, OUString& rName,
674  const OUString& rSrcShellID, const OUString& rDestShellID )
675 {
676  uno::Reference< embed::XEmbeddedObject > xResult;
677 
678  // TODO/LATER: For now only objects that implement XEmbedPersist have a replacement image, it might change in future
679  // do an incompatible change so that object name is provided in all the move and copy methods
680  OUString aOrigName;
681  try
682  {
683  uno::Reference < embed::XEmbedPersist > xPersist( xObj, uno::UNO_QUERY_THROW );
684  aOrigName = xPersist->getEntryName();
685  }
686  catch (const uno::Exception&)
687  {
688  }
689 
690  if ( rName.isEmpty() )
691  rName = CreateUniqueObjectName();
692 
693  // objects without persistence are not really stored by the method
694  if (xObj.is() && StoreEmbeddedObject(xObj, rName, true, rSrcShellID, rDestShellID))
695  {
696  SAL_INFO_IF(rDestShellID.isEmpty(), "comphelper.container",
697  "SfxObjectShell with no base URL?"); // every shell has a base URL, except the clipboard SwDocShell
698  xResult = Get_Impl(rName, xObj, &rDestShellID);
699  if ( !xResult.is() )
700  {
701  // this is a case when object has no real persistence
702  // in such cases a new object should be explicitly created and initialized with the data of the old one
703  try
704  {
705  uno::Reference< embed::XLinkageSupport > xOrigLinkage( xObj, uno::UNO_QUERY );
706  if ( xOrigLinkage.is() && xOrigLinkage->isLink() )
707  {
708  // this is an OOo link, it has no persistence
709  OUString aURL = xOrigLinkage->getLinkURL();
710  if ( aURL.isEmpty() )
711  throw uno::RuntimeException();
712 
713  // create new linked object from the URL the link is based on
714  uno::Reference < embed::XEmbeddedObjectCreator > xCreator =
715  embed::EmbeddedObjectCreator::create( ::comphelper::getProcessComponentContext() );
716 
717  uno::Sequence< beans::PropertyValue > aMediaDescr( 1 );
718  aMediaDescr[0].Name = "URL";
719  aMediaDescr[0].Value <<= aURL;
720  uno::Sequence< beans::PropertyValue > aObjDescr( 1 );
721  aObjDescr[0].Name = "Parent";
722  aObjDescr[0].Value <<= pImpl->m_xModel.get();
723  xResult.set(xCreator->createInstanceLink(
724  pImpl->mxStorage,
725  rName,
726  aMediaDescr,
727  aObjDescr ),
728  uno::UNO_QUERY_THROW );
729  }
730  else
731  {
732  // the component is required for copying of this object
733  if ( xObj->getCurrentState() == embed::EmbedStates::LOADED )
734  xObj->changeState( embed::EmbedStates::RUNNING );
735 
736  // this must be an object based on properties, otherwise we can not copy it currently
737  uno::Reference< beans::XPropertySet > xOrigProps( xObj->getComponent(), uno::UNO_QUERY_THROW );
738 
739  // use object class ID to create a new one and transfer all the properties
740  uno::Reference < embed::XEmbeddedObjectCreator > xCreator =
741  embed::EmbeddedObjectCreator::create( ::comphelper::getProcessComponentContext() );
742 
743  uno::Sequence< beans::PropertyValue > aObjDescr( 1 );
744  aObjDescr[0].Name = "Parent";
745  aObjDescr[0].Value <<= pImpl->m_xModel.get();
746  xResult.set(xCreator->createInstanceInitNew(
747  xObj->getClassID(),
748  xObj->getClassName(),
749  pImpl->mxStorage,
750  rName,
751  aObjDescr ),
752  uno::UNO_QUERY_THROW );
753 
754  if ( xResult->getCurrentState() == embed::EmbedStates::LOADED )
755  xResult->changeState( embed::EmbedStates::RUNNING );
756 
757  uno::Reference< beans::XPropertySet > xTargetProps( xResult->getComponent(), uno::UNO_QUERY_THROW );
758 
759  // copy all the properties from xOrigProps to xTargetProps
760  uno::Reference< beans::XPropertySetInfo > xOrigInfo = xOrigProps->getPropertySetInfo();
761  if ( !xOrigInfo.is() )
762  throw uno::RuntimeException();
763 
764  uno::Sequence< beans::Property > aPropertiesList = xOrigInfo->getProperties();
765  for ( sal_Int32 nInd = 0; nInd < aPropertiesList.getLength(); nInd++ )
766  {
767  try
768  {
769  xTargetProps->setPropertyValue(
770  aPropertiesList[nInd].Name,
771  xOrigProps->getPropertyValue( aPropertiesList[nInd].Name ) );
772  }
773  catch (const beans::PropertyVetoException&)
774  {
775  // impossibility to copy readonly property is not treated as an error for now
776  // but the assertion is helpful to detect such scenarios and review them
777  SAL_WARN( "comphelper.container", "Could not copy readonly property!" );
778  }
779  }
780  }
781 
782  if ( xResult.is() )
783  AddEmbeddedObject( xResult, rName );
784  }
785  catch (const uno::Exception&)
786  {
787  if ( xResult.is() )
788  {
789  try
790  {
791  xResult->close( true );
792  }
793  catch (const uno::Exception&)
794  {
795  }
796  xResult.clear();
797  }
798  }
799  }
800  }
801 
802  SAL_WARN_IF( !xResult.is(), "comphelper.container", "Can not copy embedded object that has no persistence!" );
803 
804  if ( xResult.is() )
805  {
806  // the object is successfully copied, try to copy graphical replacement
807  if ( !aOrigName.isEmpty() )
808  TryToCopyGraphReplacement( rSrc, aOrigName, rName );
809 
810  // the object might need the size to be set
811  try
812  {
813  if ( xResult->getStatus( embed::Aspects::MSOLE_CONTENT ) & embed::EmbedMisc::EMBED_NEEDSSIZEONLOAD )
814  xResult->setVisualAreaSize( embed::Aspects::MSOLE_CONTENT,
815  xObj->getVisualAreaSize( embed::Aspects::MSOLE_CONTENT ) );
816  }
817  catch (const uno::Exception&)
818  {
819  }
820  }
821 
822  return xResult;
823 }
824 
825 // #i119941, bKeepToTempStorage: use to specify whether store the removed object to temporary storage+
826 void EmbeddedObjectContainer::RemoveEmbeddedObject( const OUString& rName, bool bKeepToTempStorage )
827 {
828  uno::Reference < embed::XEmbeddedObject > xObj = GetEmbeddedObject( rName );
829  if ( xObj.is() )
830  RemoveEmbeddedObject( xObj, bKeepToTempStorage );
831 }
832 
834 {
835  // find object entry
836  auto aIt2 = rCnt.pImpl->maNameToObjectMap.find( rName );
837  OSL_ENSURE( aIt2 == rCnt.pImpl->maNameToObjectMap.end(), "Object does already exist in target container!" );
838 
839  if ( aIt2 != rCnt.pImpl->maNameToObjectMap.end() )
840  return false;
841 
842  uno::Reference < embed::XEmbeddedObject > xObj;
843  auto aIt = pImpl->maNameToObjectMap.find( rName );
844  if ( aIt != pImpl->maNameToObjectMap.end() )
845  {
846  xObj = (*aIt).second;
847  try
848  {
849  if ( xObj.is() )
850  {
851  // move object
852  OUString aName( rName );
853  rCnt.InsertEmbeddedObject( xObj, aName );
854  pImpl->maObjectToNameMap.erase( aIt->second );
855  pImpl->maNameToObjectMap.erase( aIt );
856  uno::Reference < embed::XEmbedPersist > xPersist( xObj, uno::UNO_QUERY );
857  if ( xPersist.is() )
858  pImpl->mxStorage->removeElement( rName );
859  }
860  else
861  {
862  // copy storages; object *must* have persistence!
863  uno::Reference < embed::XStorage > xOld = pImpl->mxStorage->openStorageElement( rName, embed::ElementModes::READ );
864  uno::Reference < embed::XStorage > xNew = rCnt.pImpl->mxStorage->openStorageElement( rName, embed::ElementModes::READWRITE );
865  xOld->copyToStorage( xNew );
866  }
867 
868  rCnt.TryToCopyGraphReplacement( *this, rName, rName );
869  // RemoveGraphicStream( rName );
870 
871  return true;
872  }
873  catch (const uno::Exception&)
874  {
875  SAL_WARN( "comphelper.container", "Could not move object!");
876  return false;
877  }
878 
879  }
880  else
881  SAL_WARN( "comphelper.container", "Unknown object!");
882  return false;
883 }
884 
885 // #i119941, bKeepToTempStorage: use to specify whether store the removed object to temporary storage+
886 bool EmbeddedObjectContainer::RemoveEmbeddedObject( const uno::Reference < embed::XEmbeddedObject >& xObj, bool bKeepToTempStorage )
887 {
888  uno::Reference < embed::XEmbedPersist > xPersist( xObj, uno::UNO_QUERY );
889  OUString aName;
890  if ( xPersist.is() )
891  aName = xPersist->getEntryName();
892 
893 #if OSL_DEBUG_LEVEL > 1
894  uno::Reference < container::XNameAccess > xAccess( pImpl->mxStorage, uno::UNO_QUERY );
895  uno::Reference < embed::XLinkageSupport > xLink( xPersist, uno::UNO_QUERY );
896  sal_Bool bIsNotEmbedded = !xPersist.is() || ( xLink.is() && xLink->isLink() );
897 
898  // if the object has a persistence and the object is not a link than it must have persistence entry in the storage
899  OSL_ENSURE( bIsNotEmbedded || xAccess->hasByName(aName), "Removing element not present in storage!" );
900 #endif
901 
902  // somebody still needs the object, so we must assign a temporary persistence
903  try
904  {
905  if ( xPersist.is() && bKeepToTempStorage ) // #i119941
906  {
907 
908  if ( !pImpl->mpTempObjectContainer )
909  {
910  pImpl->mpTempObjectContainer = new EmbeddedObjectContainer();
911  try
912  {
913  // TODO/LATER: in future probably the temporary container will have two storages ( of two formats )
914  // the media type will be provided with object insertion
915  OUString aOrigStorMediaType;
916  uno::Reference< beans::XPropertySet > xStorProps( pImpl->mxStorage, uno::UNO_QUERY_THROW );
917  static const OUStringLiteral s_sMediaType("MediaType");
918  xStorProps->getPropertyValue( s_sMediaType ) >>= aOrigStorMediaType;
919 
920  SAL_WARN_IF( aOrigStorMediaType.isEmpty(), "comphelper.container", "No valuable media type in the storage!" );
921 
922  uno::Reference< beans::XPropertySet > xTargetStorProps(
923  pImpl->mpTempObjectContainer->pImpl->mxStorage,
924  uno::UNO_QUERY_THROW );
925  xTargetStorProps->setPropertyValue( s_sMediaType,uno::Any( aOrigStorMediaType ) );
926  }
927  catch (const uno::Exception&)
928  {
929  SAL_WARN( "comphelper.container", "Can not set the new media type to a storage!" );
930  }
931  }
932 
933  OUString aTempName, aMediaType;
934  pImpl->mpTempObjectContainer->InsertEmbeddedObject( xObj, aTempName );
935 
936  uno::Reference < io::XInputStream > xStream = GetGraphicStream( xObj, &aMediaType );
937  if ( xStream.is() )
938  pImpl->mpTempObjectContainer->InsertGraphicStream( xStream, aTempName, aMediaType );
939 
940  // object is stored, so at least it can be set to loaded state
941  xObj->changeState( embed::EmbedStates::LOADED );
942  }
943  else
944  // objects without persistence need to stay in running state if they shall not be closed
945  xObj->changeState( embed::EmbedStates::RUNNING );
946  }
947  catch (const uno::Exception&)
948  {
949  return false;
950  }
951 
952  auto aIter = std::find_if(pImpl->maNameToObjectMap.begin(), pImpl->maNameToObjectMap.end(),
953  [&xObj](const EmbeddedObjectContainerNameMap::value_type& rEntry) { return rEntry.second == xObj; });
954  if (aIter != pImpl->maNameToObjectMap.end())
955  {
956  pImpl->maObjectToNameMap.erase( aIter->second );
957  pImpl->maNameToObjectMap.erase( aIter );
958  uno::Reference < container::XChild > xChild( xObj, uno::UNO_QUERY );
959  if ( xChild.is() )
960  xChild->setParent( uno::Reference < uno::XInterface >() );
961  }
962  else
963  SAL_WARN( "comphelper.container", "Object not found for removal!" );
964 
965  if ( xPersist.is() && bKeepToTempStorage ) // #i119941#
966  {
967  // remove replacement image (if there is one)
968  RemoveGraphicStream( aName );
969 
970  // now it's time to remove the storage from the container storage
971  try
972  {
973 #if OSL_DEBUG_LEVEL > 1
974  // if the object has a persistence and the object is not a link than it must have persistence entry in storage
975  OSL_ENSURE( bIsNotEmbedded || pImpl->mxStorage->hasByName( aName ), "The object has no persistence entry in the storage!" );
976 #endif
977  if ( xPersist.is() && pImpl->mxStorage->hasByName( aName ) )
978  pImpl->mxStorage->removeElement( aName );
979  }
980  catch (const uno::Exception&)
981  {
982  SAL_WARN( "comphelper.container", "Failed to remove object from storage!" );
983  return false;
984  }
985  }
986 
987  return true;
988 }
989 
990 void EmbeddedObjectContainer::CloseEmbeddedObject( const uno::Reference < embed::XEmbeddedObject >& xObj )
991 {
992  // disconnect the object from the container and close it if possible
993 
994  auto aIter = std::find_if(pImpl->maNameToObjectMap.begin(), pImpl->maNameToObjectMap.end(),
995  [&xObj](const EmbeddedObjectContainerNameMap::value_type& rEntry) { return rEntry.second == xObj; });
996  if (aIter != pImpl->maNameToObjectMap.end())
997  {
998  pImpl->maObjectToNameMap.erase( aIter->second );
999  pImpl->maNameToObjectMap.erase( aIter );
1000 
1001  try
1002  {
1003  xObj->close( true );
1004  }
1005  catch (const uno::Exception&)
1006  {
1007  // it is no problem if the object is already closed
1008  // TODO/LATER: what if the object can not be closed?
1009  }
1010  }
1011 }
1012 
1013 uno::Reference < io::XInputStream > EmbeddedObjectContainer::GetGraphicStream( const OUString& aName, OUString* pMediaType )
1014 {
1015  uno::Reference < io::XInputStream > xStream;
1016 
1017  SAL_WARN_IF( aName.isEmpty(), "comphelper.container", "Retrieving graphic for unknown object!" );
1018  if ( !aName.isEmpty() )
1019  {
1020  try
1021  {
1022  uno::Reference < embed::XStorage > xReplacements = pImpl->GetReplacements();
1023  uno::Reference < io::XStream > xGraphicStream = xReplacements->openStreamElement( aName, embed::ElementModes::READ );
1024  xStream = xGraphicStream->getInputStream();
1025  if ( pMediaType )
1026  {
1027  uno::Reference < beans::XPropertySet > xSet( xStream, uno::UNO_QUERY );
1028  if ( xSet.is() )
1029  {
1030  uno::Any aAny = xSet->getPropertyValue("MediaType");
1031  aAny >>= *pMediaType;
1032  }
1033  }
1034  }
1035  catch (uno::Exception const& e)
1036  {
1037  SAL_INFO("comphelper.container",
1038  "EmbeddedObjectContainer::GetGraphicStream(): " << e);
1039  }
1040  }
1041 
1042  return xStream;
1043 }
1044 
1045 uno::Reference < io::XInputStream > EmbeddedObjectContainer::GetGraphicStream( const css::uno::Reference < css::embed::XEmbeddedObject >& xObj, OUString* pMediaType )
1046 {
1047  // try to load it from the container storage
1048  return GetGraphicStream( GetEmbeddedObjectName( xObj ), pMediaType );
1049 }
1050 
1051 bool EmbeddedObjectContainer::InsertGraphicStream( const css::uno::Reference < css::io::XInputStream >& rStream, const OUString& rObjectName, const OUString& rMediaType )
1052 {
1053  try
1054  {
1055  uno::Reference < embed::XStorage > xReplacements = pImpl->GetReplacements();
1056 
1057  // store it into the subfolder
1058  uno::Reference < io::XOutputStream > xOutStream;
1059  uno::Reference < io::XStream > xGraphicStream = xReplacements->openStreamElement( rObjectName,
1060  embed::ElementModes::READWRITE | embed::ElementModes::TRUNCATE );
1061  xOutStream = xGraphicStream->getOutputStream();
1062  ::comphelper::OStorageHelper::CopyInputToOutput( rStream, xOutStream );
1063  xOutStream->flush();
1064 
1065  uno::Reference< beans::XPropertySet > xPropSet( xGraphicStream, uno::UNO_QUERY_THROW );
1066 
1067  xPropSet->setPropertyValue("UseCommonStoragePasswordEncryption",
1068  uno::Any( true ) );
1069  xPropSet->setPropertyValue("MediaType", uno::Any(rMediaType) );
1070 
1071  xPropSet->setPropertyValue("Compressed",
1072  uno::Any( true ) );
1073  }
1074  catch (const uno::Exception&)
1075  {
1076  return false;
1077  }
1078 
1079  return true;
1080 }
1081 
1082 bool EmbeddedObjectContainer::InsertGraphicStreamDirectly( const css::uno::Reference < css::io::XInputStream >& rStream, const OUString& rObjectName, const OUString& rMediaType )
1083 {
1084  try
1085  {
1086  uno::Reference < embed::XStorage > xReplacement = pImpl->GetReplacements();
1087  uno::Reference < embed::XOptimizedStorage > xOptRepl( xReplacement, uno::UNO_QUERY_THROW );
1088 
1089  // store it into the subfolder
1090  uno::Sequence< beans::PropertyValue > aProps( 3 );
1091  aProps[0].Name = "MediaType";
1092  aProps[0].Value <<= rMediaType;
1093  aProps[1].Name = "UseCommonStoragePasswordEncryption";
1094  aProps[1].Value <<= true;
1095  aProps[2].Name = "Compressed";
1096  aProps[2].Value <<= true;
1097 
1098  if ( xReplacement->hasByName( rObjectName ) )
1099  xReplacement->removeElement( rObjectName );
1100 
1101  xOptRepl->insertStreamElementDirect( rObjectName, rStream, aProps );
1102  }
1103  catch (const uno::Exception&)
1104  {
1105  return false;
1106  }
1107 
1108  return true;
1109 }
1110 
1111 
1112 void EmbeddedObjectContainer::RemoveGraphicStream( const OUString& rObjectName )
1113 {
1114  try
1115  {
1116  uno::Reference < embed::XStorage > xReplacements = pImpl->GetReplacements();
1117  xReplacements->removeElement( rObjectName );
1118  }
1119  catch (const uno::Exception&)
1120  {
1121  }
1122 }
1123 namespace {
1124  void InsertStreamIntoPicturesStorage_Impl( const uno::Reference< embed::XStorage >& xDocStor,
1125  const uno::Reference< io::XInputStream >& xInStream,
1126  const OUString& aStreamName )
1127  {
1128  OSL_ENSURE( !aStreamName.isEmpty() && xInStream.is() && xDocStor.is(), "Misuse of the method!" );
1129 
1130  try
1131  {
1132  uno::Reference< embed::XStorage > xPictures = xDocStor->openStorageElement(
1133  "Pictures",
1134  embed::ElementModes::READWRITE );
1135  uno::Reference< io::XStream > xObjReplStr = xPictures->openStreamElement(
1136  aStreamName,
1137  embed::ElementModes::READWRITE | embed::ElementModes::TRUNCATE );
1138  uno::Reference< io::XOutputStream > xOutStream(
1139  xObjReplStr->getInputStream(), uno::UNO_QUERY_THROW );
1140 
1141  ::comphelper::OStorageHelper::CopyInputToOutput( xInStream, xOutStream );
1142  xOutStream->closeOutput();
1143 
1144  uno::Reference< embed::XTransactedObject > xTransact( xPictures, uno::UNO_QUERY );
1145  if ( xTransact.is() )
1146  xTransact->commit();
1147  }
1148  catch (const uno::Exception&)
1149  {
1150  SAL_WARN( "comphelper.container", "The images storage is not available!" );
1151  }
1152  }
1153 
1154 }
1155 
1156 bool EmbeddedObjectContainer::StoreAsChildren(bool _bOasisFormat,bool _bCreateEmbedded,const uno::Reference < embed::XStorage >& _xStorage)
1157 {
1158  bool bResult = false;
1159  try
1160  {
1161  comphelper::EmbeddedObjectContainer aCnt( _xStorage );
1162  const uno::Sequence < OUString > aNames = GetObjectNames();
1163  const OUString* pIter = aNames.getConstArray();
1164  const OUString* pEnd = pIter + aNames.getLength();
1165  for(;pIter != pEnd;++pIter)
1166  {
1167  uno::Reference < embed::XEmbeddedObject > xObj = GetEmbeddedObject( *pIter );
1168  SAL_WARN_IF( !xObj.is(), "comphelper.container", "An empty entry in the embedded objects list!" );
1169  if ( xObj.is() )
1170  {
1171  bool bSwitchBackToLoaded = false;
1172  uno::Reference< embed::XLinkageSupport > xLink( xObj, uno::UNO_QUERY );
1173 
1174  uno::Reference < io::XInputStream > xStream;
1175  OUString aMediaType;
1176 
1177  sal_Int32 nCurState = xObj->getCurrentState();
1178  if ( nCurState == embed::EmbedStates::LOADED || nCurState == embed::EmbedStates::RUNNING )
1179  {
1180  // means that the object is not active
1181  // copy replacement image from old to new container
1182  xStream = GetGraphicStream( xObj, &aMediaType );
1183  }
1184 
1185  if ( !xStream.is() && getUserAllowsLinkUpdate() )
1186  {
1187  // the image must be regenerated
1188  // TODO/LATER: another aspect could be used
1189  if ( xObj->getCurrentState() == embed::EmbedStates::LOADED )
1190  bSwitchBackToLoaded = true;
1191 
1192  xStream = GetGraphicReplacementStream(
1193  embed::Aspects::MSOLE_CONTENT,
1194  xObj,
1195  &aMediaType );
1196  }
1197 
1198  if ( _bOasisFormat || (xLink.is() && xLink->isLink()) )
1199  {
1200  if ( xStream.is() )
1201  {
1202  if ( _bOasisFormat )
1203  {
1204  // if it is an embedded object or the optimized inserting fails the normal inserting should be done
1205  if ( _bCreateEmbedded
1206  || !aCnt.InsertGraphicStreamDirectly( xStream, *pIter, aMediaType ) )
1207  aCnt.InsertGraphicStream( xStream, *pIter, aMediaType );
1208  }
1209  else
1210  {
1211  // it is a linked object exported into SO7 format
1212  InsertStreamIntoPicturesStorage_Impl( _xStorage, xStream, *pIter );
1213  }
1214  }
1215  }
1216 
1217  uno::Reference< embed::XEmbedPersist > xPersist( xObj, uno::UNO_QUERY );
1218  if ( xPersist.is() )
1219  {
1220  uno::Sequence< beans::PropertyValue > aArgs( _bOasisFormat ? 2 : 3 );
1221  aArgs[0].Name = "StoreVisualReplacement";
1222  aArgs[0].Value <<= !_bOasisFormat;
1223 
1224  // if it is an embedded object or the optimized inserting fails the normal inserting should be done
1225  aArgs[1].Name = "CanTryOptimization";
1226  aArgs[1].Value <<= !_bCreateEmbedded;
1227  if ( !_bOasisFormat )
1228  {
1229  // if object has no cached replacement it will use this one
1230  aArgs[2].Name = "VisualReplacement";
1231  aArgs[2].Value <<= xStream;
1232  }
1233 
1234  try
1235  {
1236  xPersist->storeAsEntry( _xStorage, xPersist->getEntryName(), uno::Sequence< beans::PropertyValue >(), aArgs );
1237  }
1238  catch (const embed::WrongStateException&)
1239  {
1240  SAL_WARN("comphelper.container", "failed to store '" << *pIter << "'");
1241  }
1242  }
1243 
1244  if ( bSwitchBackToLoaded )
1245  // switch back to loaded state; that way we have a minimum cache confusion
1246  xObj->changeState( embed::EmbedStates::LOADED );
1247  }
1248  }
1249 
1250  bResult = aCnt.CommitImageSubStorage();
1251 
1252  }
1253  catch (const uno::Exception& e)
1254  {
1255  // TODO/LATER: error handling
1256  bResult = false;
1257  SAL_WARN("comphelper.container", "failed. Message: " << e);
1258  }
1259 
1260  // the old SO6 format does not store graphical replacements
1261  if ( !_bOasisFormat && bResult )
1262  {
1263  try
1264  {
1265  // the substorage still can not be locked by the embedded object container
1266  OUString aObjReplElement( "ObjectReplacements" );
1267  if ( _xStorage->hasByName( aObjReplElement ) && _xStorage->isStorageElement( aObjReplElement ) )
1268  _xStorage->removeElement( aObjReplElement );
1269  }
1270  catch (const uno::Exception&)
1271  {
1272  // TODO/LATER: error handling;
1273  bResult = false;
1274  }
1275  }
1276  return bResult;
1277 }
1278 
1279 bool EmbeddedObjectContainer::StoreChildren(bool _bOasisFormat,bool _bObjectsOnly)
1280 {
1281  bool bResult = true;
1282  const uno::Sequence < OUString > aNames = GetObjectNames();
1283  const OUString* pIter = aNames.getConstArray();
1284  const OUString* pEnd = pIter + aNames.getLength();
1285  for(;pIter != pEnd;++pIter)
1286  {
1287  uno::Reference < embed::XEmbeddedObject > xObj = GetEmbeddedObject( *pIter );
1288  SAL_WARN_IF( !xObj.is(), "comphelper.container", "An empty entry in the embedded objects list!" );
1289  if ( xObj.is() )
1290  {
1291  sal_Int32 nCurState = xObj->getCurrentState();
1292  if ( _bOasisFormat && nCurState != embed::EmbedStates::LOADED && nCurState != embed::EmbedStates::RUNNING )
1293  {
1294  // means that the object is active
1295  // the image must be regenerated
1296  OUString aMediaType;
1297 
1298  // TODO/LATER: another aspect could be used
1299  uno::Reference < io::XInputStream > xStream =
1301  embed::Aspects::MSOLE_CONTENT,
1302  xObj,
1303  &aMediaType );
1304  if ( xStream.is() )
1305  {
1306  if ( !InsertGraphicStreamDirectly( xStream, *pIter, aMediaType ) )
1307  InsertGraphicStream( xStream, *pIter, aMediaType );
1308  }
1309  }
1310 
1311  // TODO/LATER: currently the object by default does not cache replacement image
1312  // that means that if somebody loads SO7 document and store its objects using
1313  // this method the images might be lost.
1314  // Currently this method is only used on storing to alien formats, that means
1315  // that SO7 documents storing does not use it, and all other filters are
1316  // based on OASIS format. But if it changes the method must be fixed. The fix
1317  // must be done only on demand since it can affect performance.
1318 
1319  uno::Reference< embed::XEmbedPersist > xPersist( xObj, uno::UNO_QUERY );
1320  if ( xPersist.is() )
1321  {
1322  try
1323  {
1324  //TODO/LATER: only storing if changed!
1325  //xPersist->storeOwn(); //commented, i120168
1326 
1327  // begin:all charts will be persisted as xml format on disk when saving, which is time consuming.
1328  // '_bObjectsOnly' mean we are storing to alien formats.
1329  // 'isStorageElement' mean current object is NOT a MS OLE format. (may also include in future), i120168
1330  if (_bObjectsOnly && (nCurState == embed::EmbedStates::LOADED || nCurState == embed::EmbedStates::RUNNING)
1331  && (pImpl->mxStorage->isStorageElement( *pIter ) ))
1332  {
1333  uno::Reference< util::XModifiable > xModifiable( xObj->getComponent(), uno::UNO_QUERY );
1334  if ( xModifiable.is() && xModifiable->isModified())
1335  {
1336  xPersist->storeOwn();
1337  }
1338  else
1339  {
1340  //do nothing. Embedded model is not modified, no need to persist.
1341  }
1342  }
1343  else //the embedded object is in active status, always store back it.
1344  {
1345  xPersist->storeOwn();
1346  }
1347  //end i120168
1348  }
1349  catch (const uno::Exception&)
1350  {
1351  // TODO/LATER: error handling
1352  bResult = false;
1353  break;
1354  }
1355  }
1356 
1357  if ( !_bOasisFormat && !_bObjectsOnly )
1358  {
1359  // copy replacement images for linked objects
1360  try
1361  {
1362  uno::Reference< embed::XLinkageSupport > xLink( xObj, uno::UNO_QUERY );
1363  if ( xLink.is() && xLink->isLink() )
1364  {
1365  OUString aMediaType;
1366  uno::Reference < io::XInputStream > xInStream = GetGraphicStream( xObj, &aMediaType );
1367  if ( xInStream.is() )
1368  InsertStreamIntoPicturesStorage_Impl( pImpl->mxStorage, xInStream, *pIter );
1369  }
1370  }
1371  catch (const uno::Exception&)
1372  {
1373  }
1374  }
1375  }
1376  }
1377 
1378  if ( bResult && _bOasisFormat )
1379  bResult = CommitImageSubStorage();
1380 
1381  if ( bResult && !_bObjectsOnly )
1382  {
1383  try
1384  {
1386  OUString aObjReplElement( "ObjectReplacements" );
1387  if ( !_bOasisFormat && pImpl->mxStorage->hasByName( aObjReplElement ) && pImpl->mxStorage->isStorageElement( aObjReplElement ) )
1388  pImpl->mxStorage->removeElement( aObjReplElement );
1389  }
1390  catch (const uno::Exception&)
1391  {
1392  // TODO/LATER: error handling
1393  bResult = false;
1394  }
1395  }
1396  return bResult;
1397 }
1398 
1399 uno::Reference< io::XInputStream > EmbeddedObjectContainer::GetGraphicReplacementStream(
1400  sal_Int64 nViewAspect,
1401  const uno::Reference< embed::XEmbeddedObject >& xObj,
1402  OUString* pMediaType )
1403 {
1404  uno::Reference< io::XInputStream > xInStream;
1405  if ( xObj.is() )
1406  {
1407  try
1408  {
1409  // retrieving of the visual representation can switch object to running state
1410  embed::VisualRepresentation aRep = xObj->getPreferredVisualRepresentation( nViewAspect );
1411  if ( pMediaType )
1412  *pMediaType = aRep.Flavor.MimeType;
1413 
1414  uno::Sequence < sal_Int8 > aSeq;
1415  aRep.Data >>= aSeq;
1416  xInStream = new ::comphelper::SequenceInputStream( aSeq );
1417  }
1418  catch (const uno::Exception&)
1419  {
1420  }
1421  }
1422 
1423  return xInStream;
1424 }
1425 
1426 bool EmbeddedObjectContainer::SetPersistentEntries(const uno::Reference< embed::XStorage >& _xStorage,bool _bClearModifedFlag)
1427 {
1428  bool bError = false;
1429  const uno::Sequence < OUString > aNames = GetObjectNames();
1430  const OUString* pIter = aNames.getConstArray();
1431  const OUString* pEnd = pIter + aNames.getLength();
1432  for(;pIter != pEnd;++pIter)
1433  {
1434  uno::Reference < embed::XEmbeddedObject > xObj = GetEmbeddedObject( *pIter );
1435  SAL_WARN_IF( !xObj.is(), "comphelper.container", "An empty entry in the embedded objects list!" );
1436  if ( xObj.is() )
1437  {
1438  uno::Reference< embed::XEmbedPersist > xPersist( xObj, uno::UNO_QUERY );
1439  if ( xPersist.is() )
1440  {
1441  try
1442  {
1443  xPersist->setPersistentEntry( _xStorage,
1444  *pIter,
1445  embed::EntryInitModes::NO_INIT,
1446  uno::Sequence< beans::PropertyValue >(),
1447  uno::Sequence< beans::PropertyValue >() );
1448 
1449  }
1450  catch (const uno::Exception&)
1451  {
1452  // TODO/LATER: error handling
1453  bError = true;
1454  break;
1455  }
1456  }
1457  if ( _bClearModifedFlag )
1458  {
1459  // if this method is used as part of SaveCompleted the object must stay unmodified after execution
1460  try
1461  {
1462  uno::Reference< util::XModifiable > xModif( xObj->getComponent(), uno::UNO_QUERY_THROW );
1463  if ( xModif->isModified() )
1464  xModif->setModified( false );
1465  }
1466  catch (const uno::Exception&)
1467  {
1468  }
1469  }
1470  }
1471  }
1472  return bError;
1473 }
1474 
1476 {
1477  return pImpl->mbUserAllowsLinkUpdate;
1478 }
1479 
1481 {
1482  if(pImpl->mbUserAllowsLinkUpdate != bNew)
1483  {
1484  pImpl->mbUserAllowsLinkUpdate = bNew;
1485  }
1486 }
1487 
1488 }
1489 
1490 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
css::uno::Reference< css::embed::XEmbeddedObject > CreateEmbeddedObject(const css::uno::Sequence< sal_Int8 > &, OUString &, OUString const *pBaseURL=nullptr)
static css::uno::Reference< css::embed::XStorage > GetStorageFromInputStream(const css::uno::Reference< css::io::XInputStream > &xStream, const css::uno::Reference< css::uno::XComponentContext > &rxContext=css::uno::Reference< css::uno::XComponentContext >())
EmbeddedObjectContainerNameMap maNameToObjectMap
static void CopyInputToOutput(const css::uno::Reference< css::io::XInputStream > &xInput, const css::uno::Reference< css::io::XOutputStream > &xOutput)
#define SAL_INFO_IF(condition, area, stream)
bool StoreAsChildren(bool _bOasisFormat, bool _bCreateEmbedded, const css::uno::Reference< css::embed::XStorage > &_xStorage)
void CloseEmbeddedObject(const css::uno::Reference< css::embed::XEmbeddedObject > &)
void AddEmbeddedObject(const css::uno::Reference< css::embed::XEmbeddedObject > &, const OUString &)
EmbeddedObjectContainer * mpTempObjectContainer
css::uno::Reference< css::embed::XEmbeddedObject > InsertEmbeddedLink(const css::uno::Sequence< css::beans::PropertyValue > &, OUString &)
css::uno::Reference< css::embed::XEmbeddedObject > Get_Impl(const OUString &, const css::uno::Reference< css::embed::XEmbeddedObject > &xCopy, OUString const *pBaseURL)
OUString Name
css::uno::Reference< css::io::XInputStream > GetGraphicStream(const css::uno::Reference< css::embed::XEmbeddedObject > &, OUString *pMediaType=nullptr)
Reference< XInputStream > xStream
void SwitchPersistence(const css::uno::Reference< css::embed::XStorage > &)
css::uno::Sequence< css::beans::PropertyValue > InitPropertySequence(::std::initializer_list< ::std::pair< OUString, css::uno::Any > > vInit)
Init list for property sequences.
std::unordered_map< uno::Reference< embed::XEmbeddedObject >, OUString > maObjectToNameMap
static css::uno::Reference< css::embed::XStorage > GetTemporaryStorage(const css::uno::Reference< css::uno::XComponentContext > &rxContext=css::uno::Reference< css::uno::XComponentContext >())
bool InsertGraphicStream(const css::uno::Reference< css::io::XInputStream > &rStream, const OUString &rObjectName, const OUString &rMediaType)
uno::Reference< embed::XStorage > mxStorage
int i
unsigned char sal_Bool
bool StoreChildren(bool _bOasisFormat, bool _bObjectsOnly)
uno::WeakReference< uno::XInterface > m_xModel
uno::Reference< embed::XStorage > mxImageStorage
OUString GetEmbeddedObjectName(const css::uno::Reference< css::embed::XEmbeddedObject > &) const
css::uno::Reference< css::embed::XEmbeddedObject > GetEmbeddedObject(const OUString &, OUString const *pBaseURL=nullptr)
void RemoveEmbeddedObject(const OUString &rName, bool bKeepToTempStorage=true)
#define SAL_WARN_IF(condition, area, stream)
const uno::Reference< embed::XStorage > & GetReplacements()
bool InsertGraphicStreamDirectly(const css::uno::Reference< css::io::XInputStream > &rStream, const OUString &rObjectName, const OUString &rMediaType)
#define SAL_INFO(area, stream)
bool SetPersistentEntries(const css::uno::Reference< css::embed::XStorage > &_xStorage, bool _bClearModifedFlag=true)
call setPersistentEntry for each embedded object in the container
Reference< XComponentContext > getProcessComponentContext()
This function gets the process service factory's default component context.
bool InsertEmbeddedObject(const css::uno::Reference< css::embed::XEmbeddedObject > &, OUString &)
OString const aName
css::uno::Reference< css::embed::XEmbeddedObject > CopyAndGetEmbeddedObject(EmbeddedObjectContainer &rSrc, const css::uno::Reference< css::embed::XEmbeddedObject > &xObj, OUString &rName, const OUString &rSrcShellID, const OUString &rDestShellID)
bool StoreEmbeddedObject(const css::uno::Reference< css::embed::XEmbeddedObject > &xObj, OUString &rName, bool bCopy, const OUString &rSrcShellID, const OUString &rDestShellID)
#define SAL_WARN(area, stream)
static css::uno::Reference< css::io::XInputStream > GetGraphicReplacementStream(sal_Int64 nViewAspect, const css::uno::Reference< css::embed::XEmbeddedObject > &, OUString *pMediaType)
std::unordered_map< OUString, uno::Reference< embed::XEmbeddedObject > > EmbeddedObjectContainerNameMap
void RemoveGraphicStream(const OUString &rObjectName)
bool TryToCopyGraphReplacement(EmbeddedObjectContainer &rSrc, const OUString &aOrigName, const OUString &aTargetName)
aStr
bool MoveEmbeddedObject(const OUString &rName, EmbeddedObjectContainer &)
css::uno::Sequence< OUString > GetObjectNames() const
css::uno::Sequence< typename M::key_type > mapKeysToSequence(M const &map)
Copy (keys or values) from an associate container into a Sequence.
Definition: sequence.hxx:293
typedef void(CALLTYPE *GetFuncDataPtr)(sal_uInt16 &nNo