bump product version to 4.1.6.2
[LibreOffice.git] / sd / source / ui / unoidl / sddetect.cxx
blob66fab30fedcdf385133d0097b1471ae2389fb4e9
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
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 "sddetect.hxx"
23 #include <framework/interaction.hxx>
24 #include <com/sun/star/lang/XMultiServiceFactory.hpp>
25 #include <com/sun/star/beans/PropertyValue.hpp>
26 #include <com/sun/star/frame/XFrame.hpp>
27 #include <com/sun/star/frame/XModel.hpp>
28 #include <com/sun/star/awt/XWindow.hpp>
29 #include <com/sun/star/lang/XUnoTunnel.hpp>
30 #include <comphelper/processfactory.hxx>
31 #include <com/sun/star/container/XNameAccess.hpp>
32 #include <com/sun/star/io/XInputStream.hpp>
33 #include <com/sun/star/task/XInteractionHandler.hpp>
34 #include <com/sun/star/lang/WrappedTargetRuntimeException.hpp>
35 #include <com/sun/star/ucb/CommandAbortedException.hpp>
36 #include <com/sun/star/ucb/InteractiveAppException.hpp>
37 #include <com/sun/star/ucb/XContent.hpp>
38 #include <com/sun/star/packages/zip/ZipIOException.hpp>
39 #include <toolkit/helper/vclunohelper.hxx>
40 #include <ucbhelper/simpleinteractionrequest.hxx>
41 #include <vcl/graphicfilter.hxx>
42 #include <rtl/ustring.h>
43 #include <rtl/logfile.hxx>
44 #include <svl/itemset.hxx>
45 #include <vcl/window.hxx>
46 #include <svl/eitem.hxx>
47 #include <svl/stritem.hxx>
48 #include <tools/urlobj.hxx>
49 #include <osl/mutex.hxx>
50 #include <svtools/sfxecode.hxx>
51 #include <svtools/ehdl.hxx>
52 #include <sot/storinfo.hxx>
53 #include <vcl/svapp.hxx>
54 #include <sfx2/app.hxx>
55 #include <sfx2/sfxsids.hrc>
56 #include <sfx2/request.hxx>
57 #include <sfx2/docfile.hxx>
58 #include <sfx2/docfilt.hxx>
59 #include <sfx2/fcontnr.hxx>
60 #include <sfx2/brokenpackageint.hxx>
61 #include <vcl/FilterConfigItem.hxx>
62 #include <sot/storage.hxx>
63 #include <unotools/moduleoptions.hxx>
65 #include "strmname.h"
67 using namespace ::com::sun::star;
68 using namespace ::com::sun::star::uno;
69 using namespace ::com::sun::star::io;
70 using namespace ::com::sun::star::frame;
71 using namespace ::com::sun::star::task;
72 using namespace ::com::sun::star::beans;
73 using namespace ::com::sun::star::lang;
74 using namespace ::com::sun::star::ucb;
76 namespace {
78 bool isZipStorageType(const OUString& rTypeName)
80 if (rTypeName == "impress8" || rTypeName == "impress8_template")
81 return true;
83 if (rTypeName == "draw8" || rTypeName == "draw8_template")
84 return true;
86 if (rTypeName == "impress_StarOffice_XML_Impress" || rTypeName == "impress_StarOffice_XML_Impress_Template")
87 return true;
89 if (rTypeName == "draw_StarOffice_XML_Draw" || rTypeName == "draw_StarOffice_XML_Draw_Template")
90 return true;
92 return false;
97 SdFilterDetect::SdFilterDetect( const Reference < XMultiServiceFactory >& )
101 SdFilterDetect::~SdFilterDetect()
105 OUString SAL_CALL SdFilterDetect::detect( Sequence< beans::PropertyValue >& lDescriptor ) throw( RuntimeException )
107 Reference< XInputStream > xStream;
108 Reference< XContent > xContent;
109 Reference< XInteractionHandler > xInteraction;
110 String aURL;
111 OUString sTemp;
112 OUString aTypeName; // a name describing the type (from MediaDescriptor, usually from flat detection)
113 String aPreselectedFilterName; // a name describing the filter to use (from MediaDescriptor, usually from UI action)
115 OUString aDocumentTitle; // interesting only if set in this method
117 // opening as template is done when a parameter tells to do so and a template filter can be detected
118 // (otherwise no valid filter would be found) or if the detected filter is a template filter and
119 // there is no parameter that forbids to open as template
120 sal_Bool bOpenAsTemplate = sal_False;
121 sal_Bool bWasReadOnly = sal_False, bReadOnly = sal_False;
123 sal_Bool bRepairPackage = sal_False;
124 sal_Bool bRepairAllowed = sal_False;
125 bool bDeepDetection = false;
127 // now some parameters that can already be in the array, but may be overwritten or new inserted here
128 // remember their indices in the case new values must be added to the array
129 sal_Int32 nPropertyCount = lDescriptor.getLength();
130 sal_Int32 nIndexOfInputStream = -1;
131 sal_Int32 nIndexOfContent = -1;
132 sal_Int32 nIndexOfReadOnlyFlag = -1;
133 sal_Int32 nIndexOfTemplateFlag = -1;
134 sal_Int32 nIndexOfDocumentTitle = -1;
136 for( sal_Int32 nProperty=0; nProperty<nPropertyCount; ++nProperty )
138 // extract properties
139 if ( lDescriptor[nProperty].Name == "URL" )
141 lDescriptor[nProperty].Value >>= sTemp;
142 aURL = sTemp;
144 else if( !aURL.Len() && lDescriptor[nProperty].Name.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("FileName")) )
146 lDescriptor[nProperty].Value >>= sTemp;
147 aURL = sTemp;
149 else if ( lDescriptor[nProperty].Name == "TypeName" )
151 lDescriptor[nProperty].Value >>= sTemp;
152 aTypeName = sTemp;
154 else if ( lDescriptor[nProperty].Name == "FilterName" )
156 lDescriptor[nProperty].Value >>= sTemp;
157 aPreselectedFilterName = sTemp;
159 else if ( lDescriptor[nProperty].Name == "InputStream" )
160 nIndexOfInputStream = nProperty;
161 else if ( lDescriptor[nProperty].Name == "ReadOnly" )
162 nIndexOfReadOnlyFlag = nProperty;
163 else if ( lDescriptor[nProperty].Name == "UCBContent" )
164 nIndexOfContent = nProperty;
165 else if ( lDescriptor[nProperty].Name == "AsTemplate" )
167 lDescriptor[nProperty].Value >>= bOpenAsTemplate;
168 nIndexOfTemplateFlag = nProperty;
170 else if ( lDescriptor[nProperty].Name == "InteractionHandler" )
171 lDescriptor[nProperty].Value >>= xInteraction;
172 else if ( lDescriptor[nProperty].Name == "RepairPackage" )
173 lDescriptor[nProperty].Value >>= bRepairPackage;
174 else if ( lDescriptor[nProperty].Name == "DocumentTitle" )
175 nIndexOfDocumentTitle = nProperty;
176 else if (lDescriptor[nProperty].Name == "DeepDetection")
177 bDeepDetection = lDescriptor[nProperty].Value.get<sal_Bool>();
180 // can't check the type for external filters, so set the "dont" flag accordingly
181 SolarMutexGuard aGuard;
182 //SfxFilterFlags nMust = SFX_FILTER_IMPORT, nDont = SFX_FILTER_NOTINSTALLED;
184 SfxApplication* pApp = SFX_APP();
185 SfxAllItemSet *pSet = new SfxAllItemSet( pApp->GetPool() );
186 TransformParameters( SID_OPENDOC, lDescriptor, *pSet );
187 SFX_ITEMSET_ARG( pSet, pItem, SfxBoolItem, SID_DOC_READONLY, sal_False );
189 bWasReadOnly = pItem && pItem->GetValue();
191 const SfxFilter* pFilter = 0;
192 String aPrefix = OUString("private:factory/");
193 if( aURL.Match( aPrefix ) == aPrefix.Len() )
195 if( SvtModuleOptions().IsImpress() )
197 String aPattern( aPrefix );
198 aPattern += OUString("simpress");
199 if ( aURL.Match( aPattern ) >= aPattern.Len() )
200 pFilter = SfxFilter::GetDefaultFilterFromFactory( aURL );
203 if( !pFilter && SvtModuleOptions().IsDraw() )
205 String aPattern( aPrefix );
206 aPattern += OUString("sdraw");
207 if ( aURL.Match( aPattern ) >= aPattern.Len() )
208 pFilter = SfxFilter::GetDefaultFilterFromFactory( aURL );
211 else
213 // ctor of SfxMedium uses owner transition of ItemSet
214 SfxMedium aMedium( aURL, bWasReadOnly ? STREAM_STD_READ : STREAM_STD_READWRITE, NULL, pSet );
215 aMedium.UseInteractionHandler( sal_True );
216 if ( aPreselectedFilterName.Len() )
217 pFilter = SfxFilter::GetFilterByName( aPreselectedFilterName );
218 else if (!aTypeName.isEmpty())
220 SfxFilterMatcher aMatch;
221 pFilter = aMatch.GetFilter4EA( aTypeName );
224 if ( aMedium.GetErrorCode() == ERRCODE_NONE )
226 // remember input stream and content and put them into the descriptor later
227 // should be done here since later the medium can switch to a version
228 xStream = aMedium.GetInputStream();
229 xContent = aMedium.GetContent();
230 bReadOnly = aMedium.IsReadOnly();
231 bool bIsZipStorage = aMedium.IsStorage();
233 if (aMedium.GetError() == SVSTREAM_OK)
235 if (bIsZipStorage)
237 // PowerPoint needs to be detected via StreamName, all other storage based formats are our own and can
238 // be detected by the ClipboardId, so except for the PPT filter all filters must have a ClipboardId set
239 Reference < embed::XStorage > xStorage = aMedium.GetStorage( sal_False );
241 //TODO/LATER: move error handling to central place! (maybe even complete own filters)
242 if ( aMedium.GetLastStorageCreationState() != ERRCODE_NONE )
244 // error during storage creation means _here_ that the medium
245 // is broken, but we can not handle it in medium since unpossibility
246 // to create a storage does not _always_ means that the medium is broken
247 aMedium.SetError( aMedium.GetLastStorageCreationState(), OSL_LOG_PREFIX );
248 if ( xInteraction.is() )
250 OUString empty;
253 InteractiveAppException xException( empty,
254 Reference< XInterface >(),
255 InteractionClassification_ERROR,
256 aMedium.GetError() );
258 Reference< XInteractionRequest > xRequest(
259 new ucbhelper::SimpleInteractionRequest( makeAny( xException ),
260 ucbhelper::CONTINUATION_APPROVE ) );
261 xInteraction->handle( xRequest );
263 catch ( Exception & ) {};
266 else
268 if ( pFilter && !pFilter->GetFormat() )
269 // preselected Filter has no ClipboardId -> doesn't match (see comment above)
270 pFilter = 0;
272 // the storage must be checked even if filter is already found, since it is deep type detection
273 // the storage can be corrupted and it will be detected here
276 OUString sFilterName;
277 if ( pFilter )
278 sFilterName = pFilter->GetName();
279 aTypeName = SfxFilter::GetTypeFromStorage( xStorage, pFilter ? pFilter->IsOwnTemplateFormat() : sal_False, &sFilterName );
281 catch( const WrappedTargetException& aWrap )
283 if (!bDeepDetection)
284 // Bail out early unless it's a deep detection.
285 return OUString();
287 packages::zip::ZipIOException aZipException;
288 if ((aWrap.TargetException >>= aZipException) && !aTypeName.isEmpty())
290 if ( xInteraction.is() )
292 // the package is broken one
293 aDocumentTitle = aMedium.GetURLObject().getName(
294 INetURLObject::LAST_SEGMENT,
295 true,
296 INetURLObject::DECODE_WITH_CHARSET );
298 if ( !bRepairPackage )
300 // ask the user whether he wants to try to repair
301 RequestPackageReparation aRequest( aDocumentTitle );
302 xInteraction->handle( aRequest.GetRequest() );
303 bRepairAllowed = aRequest.isApproved();
306 if ( !bRepairAllowed )
308 // repair either not allowed or not successful
309 NotifyBrokenPackage aNotifyRequest( aDocumentTitle );
310 xInteraction->handle( aNotifyRequest.GetRequest() );
314 if ( !bRepairAllowed )
316 aTypeName = OUString();
317 pFilter = 0;
321 catch( RuntimeException& )
323 throw;
325 catch( Exception& )
327 aTypeName = OUString();
328 pFilter = 0;
331 if (!pFilter && !aTypeName.isEmpty())
333 //TODO/LATER: using this method impress is always preferred if no flat detecion has been made
334 // this should been discussed!
335 if ( SvtModuleOptions().IsImpress() )
336 pFilter = SfxFilterMatcher( OUString("simpress") ).GetFilter4EA( aTypeName );
337 else if ( SvtModuleOptions().IsDraw() )
338 pFilter = SfxFilterMatcher( OUString("sdraw") ).GetFilter4EA( aTypeName );
342 else
344 if (isZipStorageType(aTypeName))
345 // This stream is a not zip archive, but a zip archive type is specified.
346 pFilter = NULL;
348 SvStream* pStm = NULL;
349 if (pFilter)
351 pStm = aMedium.GetInStream();
352 if (!pStm)
353 pFilter = NULL;
356 if (pFilter && pStm)
358 SotStorageRef aStorage = new SotStorage ( pStm, sal_False );
359 if ( !aStorage->GetError() )
361 OUString aStreamName("PowerPoint Document");
362 if ( aStorage->IsStream( aStreamName ) && SvtModuleOptions().IsImpress() )
364 String aFileName(aMedium.GetName());
365 aFileName.ToUpperAscii();
367 if( aFileName.SearchAscii( ".POT" ) != STRING_NOTFOUND )
368 pFilter = SfxFilter::GetFilterByName( pFilterPowerPoint97Template );
369 else if( aFileName.SearchAscii( ".PPS" ) != STRING_NOTFOUND )
370 pFilter = SfxFilter::GetFilterByName( pFilterPowerPoint97AutoPlay );
371 else
372 pFilter = SfxFilter::GetFilterByName( pFilterPowerPoint97);
374 else
376 pFilter = 0;
379 else
381 // vector graphic?
382 pStm->Seek( STREAM_SEEK_TO_BEGIN );
384 const String aFileName( aMedium.GetURLObject().GetMainURL( INetURLObject::NO_DECODE ) );
385 GraphicDescriptor aDesc( *pStm, &aFileName );
386 if( !aDesc.Detect( sal_False ) )
388 pFilter = 0;
389 if( SvtModuleOptions().IsImpress() )
391 INetURLObject aCheckURL( aFileName );
392 if( aCheckURL.getExtension().equalsIgnoreAsciiCase("cgm") )
394 sal_uInt8 n8;
395 pStm->Seek( STREAM_SEEK_TO_BEGIN );
396 *pStm >> n8;
397 if ( ( n8 & 0xf0 ) == 0 ) // we are supporting binary cgm format only, so
398 { // this is a small test to exclude cgm text
399 SfxFilterMatcher aMatch(OUString("simpress"));
400 pFilter = aMatch.GetFilter4FilterName(OUString("CGM - Computer Graphics Metafile"));
405 else
407 String aShortName( aDesc.GetImportFormatShortName( aDesc.GetFileFormat() ) );
408 GraphicFilter &rGrfFilter = GraphicFilter::GetGraphicFilter();
409 const String aName( rGrfFilter.GetImportFormatTypeName( rGrfFilter.GetImportFormatNumberForShortName( aShortName ) ) );
411 if ( pFilter && aShortName.EqualsIgnoreCaseAscii( "PCD" ) ) // there is a multiple pcd selection possible
413 sal_Int32 nBase = 2; // default Base0
414 String aFilterTypeName( pFilter->GetRealTypeName() );
415 if ( aFilterTypeName.CompareToAscii( "pcd_Photo_CD_Base4" ) == COMPARE_EQUAL )
416 nBase = 1;
417 else if ( aFilterTypeName.CompareToAscii( "pcd_Photo_CD_Base16" ) == COMPARE_EQUAL )
418 nBase = 0;
419 FilterConfigItem aFilterConfigItem( "Office.Common/Filter/Graphic/Import/PCD" );
420 aFilterConfigItem.WriteInt32( "Resolution" , nBase );
423 SfxFilterMatcher aMatch(OUString("sdraw"));
424 pFilter = aMatch.GetFilter4FilterName( aName );
430 else
432 pFilter = 0;
437 if ( nIndexOfInputStream == -1 && xStream.is() )
439 // if input stream wasn't part of the descriptor, now it should be, otherwise the content would be opend twice
440 lDescriptor.realloc( nPropertyCount + 1 );
441 lDescriptor[nPropertyCount].Name = "InputStream";
442 lDescriptor[nPropertyCount].Value <<= xStream;
443 nPropertyCount++;
446 if ( nIndexOfContent == -1 && xContent.is() )
448 // if input stream wasn't part of the descriptor, now it should be, otherwise the content would be opend twice
449 lDescriptor.realloc( nPropertyCount + 1 );
450 lDescriptor[nPropertyCount].Name = "UCBContent";
451 lDescriptor[nPropertyCount].Value <<= xContent;
452 nPropertyCount++;
455 if ( bReadOnly != bWasReadOnly )
457 if ( nIndexOfReadOnlyFlag == -1 )
459 lDescriptor.realloc( nPropertyCount + 1 );
460 lDescriptor[nPropertyCount].Name = "ReadOnly";
461 lDescriptor[nPropertyCount].Value <<= bReadOnly;
462 nPropertyCount++;
464 else
465 lDescriptor[nIndexOfReadOnlyFlag].Value <<= bReadOnly;
468 if ( !bRepairPackage && bRepairAllowed )
470 lDescriptor.realloc( nPropertyCount + 1 );
471 lDescriptor[nPropertyCount].Name = "RepairPackage";
472 lDescriptor[nPropertyCount].Value <<= bRepairAllowed;
473 nPropertyCount++;
475 bOpenAsTemplate = sal_True;
477 // TODO/LATER: set progress bar that should be used
480 if ( bOpenAsTemplate )
482 if ( nIndexOfTemplateFlag == -1 )
484 lDescriptor.realloc( nPropertyCount + 1 );
485 lDescriptor[nPropertyCount].Name = "AsTemplate";
486 lDescriptor[nPropertyCount].Value <<= bOpenAsTemplate;
487 nPropertyCount++;
489 else
490 lDescriptor[nIndexOfTemplateFlag].Value <<= bOpenAsTemplate;
493 if ( !aDocumentTitle.isEmpty() )
495 // the title was set here
496 if ( nIndexOfDocumentTitle == -1 )
498 lDescriptor.realloc( nPropertyCount + 1 );
499 lDescriptor[nPropertyCount].Name = "DocumentTitle";
500 lDescriptor[nPropertyCount].Value <<= aDocumentTitle;
501 nPropertyCount++;
503 else
504 lDescriptor[nIndexOfDocumentTitle].Value <<= aDocumentTitle;
507 if (!pFilter)
508 aTypeName = OUString();
510 return aTypeName;
513 /* XServiceInfo */
514 OUString SAL_CALL SdFilterDetect::getImplementationName() throw( RuntimeException )
516 return impl_getStaticImplementationName();
519 /* XServiceInfo */
520 sal_Bool SAL_CALL SdFilterDetect::supportsService( const OUString& sServiceName ) throw( RuntimeException )
522 Sequence< OUString > seqServiceNames = getSupportedServiceNames();
523 const OUString* pArray = seqServiceNames.getConstArray();
524 for ( sal_Int32 nCounter=0; nCounter<seqServiceNames.getLength(); nCounter++ )
526 if ( pArray[nCounter] == sServiceName )
528 return sal_True ;
531 return sal_False ;
534 /* XServiceInfo */
535 Sequence< OUString > SAL_CALL SdFilterDetect::getSupportedServiceNames() throw( RuntimeException )
537 return impl_getStaticSupportedServiceNames();
540 /* Helper for XServiceInfo */
541 Sequence< OUString > SdFilterDetect::impl_getStaticSupportedServiceNames()
543 Sequence< OUString > seqServiceNames( 1 );
544 seqServiceNames.getArray() [0] = "com.sun.star.frame.ExtendedTypeDetection" ;
545 return seqServiceNames ;
548 /* Helper for XServiceInfo */
549 OUString SdFilterDetect::impl_getStaticImplementationName()
551 return OUString( "com.sun.star.comp.draw.FormatDetector" );
554 /* Helper for registry */
555 Reference< XInterface > SAL_CALL SdFilterDetect::impl_createInstance( const Reference< XMultiServiceFactory >& xServiceManager ) throw( Exception )
557 return static_cast< cppu::OWeakObject * >(
558 new SdFilterDetect( xServiceManager ) );
561 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */