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 .
20 #include "swdetect.hxx"
22 #include <framework/interaction.hxx>
23 #include <com/sun/star/frame/XFrame.hpp>
24 #include <com/sun/star/frame/XModel.hpp>
25 #include <com/sun/star/lang/XUnoTunnel.hpp>
26 #include <comphelper/processfactory.hxx>
27 #include <com/sun/star/container/XNameAccess.hpp>
28 #include <com/sun/star/io/XInputStream.hpp>
29 #include <com/sun/star/task/XInteractionHandler.hpp>
30 #include <com/sun/star/lang/WrappedTargetRuntimeException.hpp>
31 #include <com/sun/star/ucb/CommandAbortedException.hpp>
32 #include <com/sun/star/ucb/InteractiveAppException.hpp>
33 #include <com/sun/star/ucb/XContent.hpp>
34 #include <com/sun/star/packages/zip/ZipIOException.hpp>
35 #include <toolkit/helper/vclunohelper.hxx>
36 #include <ucbhelper/simpleinteractionrequest.hxx>
37 #include <rtl/ustring.h>
38 #include <rtl/logfile.hxx>
39 #include <svl/itemset.hxx>
40 #include <vcl/window.hxx>
41 #include <svl/eitem.hxx>
42 #include <svl/stritem.hxx>
43 #include <tools/urlobj.hxx>
44 #include <osl/mutex.hxx>
45 #include <svtools/sfxecode.hxx>
46 #include <svtools/ehdl.hxx>
47 #include <sot/storinfo.hxx>
48 #include <vcl/svapp.hxx>
49 #include <sfx2/app.hxx>
50 #include <sfx2/sfxsids.hrc>
51 #include <sfx2/request.hxx>
52 #include <sfx2/docfile.hxx>
53 #include <sfx2/docfilt.hxx>
54 #include <sfx2/fcontnr.hxx>
55 #include <sfx2/brokenpackageint.hxx>
56 #include <vcl/FilterConfigItem.hxx>
57 #include <unotools/moduleoptions.hxx>
58 #include <comphelper/ihwrapnofilter.hxx>
62 using namespace ::com::sun::star
;
63 using namespace ::com::sun::star::uno
;
64 using namespace ::com::sun::star::io
;
65 using namespace ::com::sun::star::frame
;
66 using namespace ::com::sun::star::task
;
67 using namespace ::com::sun::star::beans
;
68 using namespace ::com::sun::star::lang
;
69 using namespace ::com::sun::star::ucb
;
71 SwFilterDetect::SwFilterDetect( const Reference
< XMultiServiceFactory
>& /*xFactory*/ )
75 SwFilterDetect::~SwFilterDetect()
79 OUString SAL_CALL
SwFilterDetect::detect( Sequence
< PropertyValue
>& lDescriptor
) throw( RuntimeException
)
81 Reference
< XInputStream
> xStream
;
82 Reference
< XContent
> xContent
;
83 Reference
< XInteractionHandler
> xInteraction
;
86 String aTypeName
; // a name describing the type (from MediaDescriptor, usually from flat detection)
87 String aPreselectedFilterName
; // a name describing the filter to use (from MediaDescriptor, usually from UI action)
89 OUString aDocumentTitle
; // interesting only if set in this method
91 // opening as template is done when a parameter tells to do so and a template filter can be detected
92 // (otherwise no valid filter would be found) or if the detected filter is a template filter and
93 // there is no parameter that forbids to open as template
94 sal_Bool bOpenAsTemplate
= sal_False
;
95 sal_Bool bWasReadOnly
= sal_False
, bReadOnly
= sal_False
;
97 sal_Bool bRepairPackage
= sal_False
;
98 sal_Bool bRepairAllowed
= sal_False
;
99 bool bDeepDetection
= false;
101 // now some parameters that can already be in the array, but may be overwritten or new inserted here
102 // remember their indices in the case new values must be added to the array
103 sal_Int32 nPropertyCount
= lDescriptor
.getLength();
104 sal_Int32 nIndexOfInputStream
= -1;
105 sal_Int32 nIndexOfContent
= -1;
106 sal_Int32 nIndexOfReadOnlyFlag
= -1;
107 sal_Int32 nIndexOfTemplateFlag
= -1;
108 sal_Int32 nIndexOfDocumentTitle
= -1;
109 sal_Int32 nIndexOfInteractionHandler
= -1;
111 for( sal_Int32 nProperty
=0; nProperty
<nPropertyCount
; ++nProperty
)
113 // extract properties
114 if ( lDescriptor
[nProperty
].Name
== "URL" )
116 lDescriptor
[nProperty
].Value
>>= sTemp
;
119 else if( !aURL
.Len() && lDescriptor
[nProperty
].Name
.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM("FileName")) )
121 lDescriptor
[nProperty
].Value
>>= sTemp
;
124 else if ( lDescriptor
[nProperty
].Name
== "TypeName" )
126 lDescriptor
[nProperty
].Value
>>= sTemp
;
129 else if ( lDescriptor
[nProperty
].Name
== "FilterName" )
131 lDescriptor
[nProperty
].Value
>>= sTemp
;
132 aPreselectedFilterName
= sTemp
;
134 else if ( lDescriptor
[nProperty
].Name
== "InputStream" )
135 nIndexOfInputStream
= nProperty
;
136 else if ( lDescriptor
[nProperty
].Name
== "ReadOnly" )
137 nIndexOfReadOnlyFlag
= nProperty
;
138 else if ( lDescriptor
[nProperty
].Name
== "UCBContent" )
139 nIndexOfContent
= nProperty
;
140 else if ( lDescriptor
[nProperty
].Name
== "AsTemplate" )
142 lDescriptor
[nProperty
].Value
>>= bOpenAsTemplate
;
143 nIndexOfTemplateFlag
= nProperty
;
145 else if ( lDescriptor
[nProperty
].Name
== "InteractionHandler" )
147 lDescriptor
[nProperty
].Value
>>= xInteraction
;
148 nIndexOfInteractionHandler
= nProperty
;
150 else if ( lDescriptor
[nProperty
].Name
== "RepairPackage" )
151 lDescriptor
[nProperty
].Value
>>= bRepairPackage
;
152 else if ( lDescriptor
[nProperty
].Name
== "DocumentTitle" )
153 nIndexOfDocumentTitle
= nProperty
;
154 else if (lDescriptor
[nProperty
].Name
== "DeepDetection")
155 bDeepDetection
= lDescriptor
[nProperty
].Value
.get
<sal_Bool
>();
158 SolarMutexGuard aGuard
;
160 SfxApplication
* pApp
= SFX_APP();
161 SfxAllItemSet
*pSet
= new SfxAllItemSet( pApp
->GetPool() );
162 TransformParameters( SID_OPENDOC
, lDescriptor
, *pSet
);
163 SFX_ITEMSET_ARG( pSet
, pItem
, SfxBoolItem
, SID_DOC_READONLY
, sal_False
);
165 bWasReadOnly
= pItem
&& pItem
->GetValue();
167 const SfxFilter
* pFilter
= 0;
168 String aPrefix
= OUString("private:factory/");
169 if( aURL
.Match( aPrefix
) == aPrefix
.Len() )
171 if( SvtModuleOptions().IsWriter() )
173 String
aPattern( aPrefix
);
174 aPattern
+= OUString("swriter");
175 if ( aURL
.Match( aPattern
) >= aPattern
.Len() )
181 // ctor of SfxMedium uses owner transition of ItemSet
182 SfxMedium
aMedium( aURL
, bWasReadOnly
? STREAM_STD_READ
: STREAM_STD_READWRITE
, NULL
, pSet
);
183 aMedium
.UseInteractionHandler( sal_True
);
184 if ( aMedium
.GetErrorCode() == ERRCODE_NONE
)
186 // remember input stream and content and put them into the descriptor later
187 // should be done here since later the medium can switch to a version
188 xStream
= aMedium
.GetInputStream();
189 xContent
= aMedium
.GetContent();
190 bReadOnly
= aMedium
.IsReadOnly();
192 sal_Bool bIsStorage
= aMedium
.IsStorage();
195 Reference
< embed::XStorage
> xStorage
= aMedium
.GetStorage( sal_False
);
196 if ( aMedium
.GetLastStorageCreationState() != ERRCODE_NONE
)
198 // error during storage creation means _here_ that the medium
199 // is broken, but we can not handle it in medium since impossibility
200 // to create a storage does not _always_ means that the medium is broken
201 aMedium
.SetError( aMedium
.GetLastStorageCreationState(), OUString( OSL_LOG_PREFIX
) );
202 if ( xInteraction
.is() )
207 InteractiveAppException
xException( empty
,
208 Reference
< XInterface
>(),
209 InteractionClassification_ERROR
,
210 aMedium
.GetError() );
212 Reference
< XInteractionRequest
> xRequest(
213 new ucbhelper::SimpleInteractionRequest( makeAny( xException
),
214 ucbhelper::CONTINUATION_APPROVE
) );
215 xInteraction
->handle( xRequest
);
217 catch (const Exception
&)
224 OSL_ENSURE( xStorage
.is(), "At this point storage must exist!" );
228 const SfxFilter
* pPreFilter
= aPreselectedFilterName
.Len() ?
229 SfxFilterMatcher().GetFilter4FilterName( aPreselectedFilterName
) : aTypeName
.Len() ?
230 SfxFilterMatcher(OUString("swriter")).GetFilter4EA( aTypeName
) : 0;
232 pPreFilter
= SfxFilterMatcher(OUString("sweb")).GetFilter4EA( aTypeName
);
233 OUString aFilterName
;
236 aFilterName
= pPreFilter
->GetName();
237 aTypeName
= pPreFilter
->GetTypeName();
240 aTypeName
= SfxFilter::GetTypeFromStorage( xStorage
, pPreFilter
? pPreFilter
->IsOwnTemplateFormat() : sal_False
, &aFilterName
);
242 catch (const WrappedTargetException
& aWrap
)
245 // Bail out early unless it's a deep detection.
248 packages::zip::ZipIOException aZipException
;
250 // repairing is done only if this type is requested from outside
251 // we don't do any type detection on broken packages (f.e. because it might be impossible), so any requested
252 // type will be accepted if the user allows to repair the file
253 if ( ( aWrap
.TargetException
>>= aZipException
) && ( aTypeName
.Len() || aPreselectedFilterName
.Len() ) )
255 if ( xInteraction
.is() )
257 // the package is a broken one
258 aDocumentTitle
= aMedium
.GetURLObject().getName(
259 INetURLObject::LAST_SEGMENT
,
261 INetURLObject::DECODE_WITH_CHARSET
);
263 if ( !bRepairPackage
)
265 // ask the user whether he wants to try to repair
266 RequestPackageReparation
aRequest( aDocumentTitle
);
267 xInteraction
->handle( aRequest
.GetRequest() );
268 bRepairAllowed
= aRequest
.isApproved();
271 if ( !bRepairAllowed
)
273 // repair either not allowed or not successful
274 // repair either not allowed or not successful
275 NotifyBrokenPackage
aNotifyRequest( aDocumentTitle
);
276 xInteraction
->handle( aNotifyRequest
.GetRequest() );
278 Reference
< ::comphelper::OIHWrapNoFilterDialog
> xHandler
= new ::comphelper::OIHWrapNoFilterDialog( xInteraction
);
279 if ( nIndexOfInteractionHandler
!= -1 )
280 lDescriptor
[nIndexOfInteractionHandler
].Value
<<= Reference
< XInteractionHandler
>( static_cast< XInteractionHandler
* >( xHandler
.get() ) );
282 aMedium
.SetError( ERRCODE_ABORT
, OUString( OSL_LOG_PREFIX
) );
286 // no interaction, error handling as usual
287 aMedium
.SetError( ERRCODE_IO_BROKENPACKAGE
, OUString( OSL_LOG_PREFIX
) );
289 if ( !bRepairAllowed
)
292 aPreselectedFilterName
.Erase();
296 catch (const RuntimeException
&)
300 catch (const Exception
&)
303 aPreselectedFilterName
.Erase();
309 aMedium
.GetInStream();
310 if ( aMedium
.GetErrorCode() == ERRCODE_NONE
)
312 if ( aPreselectedFilterName
.Len() )
313 pFilter
= SfxFilter::GetFilterByName( aPreselectedFilterName
);
315 pFilter
= SfxFilterMatcher().GetFilter4EA( aTypeName
);
317 bool bTestWriter
= !pFilter
|| pFilter
->GetServiceName() == "com.sun.star.text.TextDocument" ||
318 pFilter
->GetServiceName() == "com.sun.star.text.WebDocument";
319 bool bTestGlobal
= !pFilter
|| pFilter
->GetServiceName() == "com.sun.star.text.GlobalDocument";
321 const SfxFilter
* pOrigFilter
= NULL
;
322 if ( !bTestWriter
&& !bTestGlobal
&& pFilter
)
324 // cross filter; now this should be a type detection only, not a filter detection
325 // we can simulate it by preserving the preselected filter if the type matches
326 // example: HTML filter for Calc
327 pOrigFilter
= pFilter
;
328 pFilter
= SfxFilterMatcher().GetFilter4EA( pFilter
->GetTypeName() );
332 sal_uLong nErr
= ERRCODE_NONE
;
333 if ( pFilter
|| bTestWriter
)
334 nErr
= DetectFilter( aMedium
, &pFilter
);
335 if ( nErr
!= ERRCODE_NONE
)
337 else if ( pOrigFilter
&& pFilter
&& pFilter
->GetTypeName() == pOrigFilter
->GetTypeName() )
338 // cross filter, see above
339 pFilter
= pOrigFilter
;
343 aTypeName
= pFilter
->GetTypeName();
350 if ( nIndexOfInputStream
== -1 && xStream
.is() )
352 // if input stream wasn't part of the descriptor, now it should be, otherwise the content would be opend twice
353 lDescriptor
.realloc( nPropertyCount
+ 1 );
354 lDescriptor
[nPropertyCount
].Name
= OUString("InputStream");
355 lDescriptor
[nPropertyCount
].Value
<<= xStream
;
359 if ( nIndexOfContent
== -1 && xContent
.is() )
361 // if input stream wasn't part of the descriptor, now it should be, otherwise the content would be opend twice
362 lDescriptor
.realloc( nPropertyCount
+ 1 );
363 lDescriptor
[nPropertyCount
].Name
= OUString("UCBContent");
364 lDescriptor
[nPropertyCount
].Value
<<= xContent
;
368 if ( bReadOnly
!= bWasReadOnly
)
370 if ( nIndexOfReadOnlyFlag
== -1 )
372 lDescriptor
.realloc( nPropertyCount
+ 1 );
373 lDescriptor
[nPropertyCount
].Name
= OUString("ReadOnly");
374 lDescriptor
[nPropertyCount
].Value
<<= bReadOnly
;
378 lDescriptor
[nIndexOfReadOnlyFlag
].Value
<<= bReadOnly
;
381 if ( !bRepairPackage
&& bRepairAllowed
)
383 lDescriptor
.realloc( nPropertyCount
+ 1 );
384 lDescriptor
[nPropertyCount
].Name
= OUString("RepairPackage");
385 lDescriptor
[nPropertyCount
].Value
<<= bRepairAllowed
;
387 bOpenAsTemplate
= sal_True
;
388 // TODO/LATER: set progress bar that should be used
391 if ( bOpenAsTemplate
)
393 if ( nIndexOfTemplateFlag
== -1 )
395 lDescriptor
.realloc( nPropertyCount
+ 1 );
396 lDescriptor
[nPropertyCount
].Name
= OUString("AsTemplate");
397 lDescriptor
[nPropertyCount
].Value
<<= bOpenAsTemplate
;
401 lDescriptor
[nIndexOfTemplateFlag
].Value
<<= bOpenAsTemplate
;
404 if ( !aDocumentTitle
.isEmpty() )
406 // the title was set here
407 if ( nIndexOfDocumentTitle
== -1 )
409 lDescriptor
.realloc( nPropertyCount
+ 1 );
410 lDescriptor
[nPropertyCount
].Name
= OUString("DocumentTitle");
411 lDescriptor
[nPropertyCount
].Value
<<= aDocumentTitle
;
415 lDescriptor
[nIndexOfDocumentTitle
].Value
<<= aDocumentTitle
;
423 OUString SAL_CALL
SwFilterDetect::getImplementationName() throw( RuntimeException
)
425 return impl_getStaticImplementationName();
429 sal_Bool SAL_CALL
SwFilterDetect::supportsService( const OUString
& sServiceName
) throw( RuntimeException
)
431 Sequence
< OUString
> seqServiceNames
= getSupportedServiceNames();
432 const OUString
* pArray
= seqServiceNames
.getConstArray();
433 for ( sal_Int32 nCounter
=0; nCounter
<seqServiceNames
.getLength(); nCounter
++ )
435 if ( pArray
[nCounter
] == sServiceName
)
444 Sequence
< OUString
> SAL_CALL
SwFilterDetect::getSupportedServiceNames() throw( RuntimeException
)
446 return impl_getStaticSupportedServiceNames();
449 /* Helper for XServiceInfo */
450 Sequence
< OUString
> SwFilterDetect::impl_getStaticSupportedServiceNames()
452 Sequence
< OUString
> seqServiceNames( 3 );
453 seqServiceNames
.getArray() [0] = OUString("com.sun.star.frame.ExtendedTypeDetection" );
454 seqServiceNames
.getArray() [1] = OUString("com.sun.star.text.FormatDetector" );
455 seqServiceNames
.getArray() [2] = OUString("com.sun.star.text.W4WFormatDetector" );
456 return seqServiceNames
;
459 /* Helper for XServiceInfo */
460 OUString
SwFilterDetect::impl_getStaticImplementationName()
462 return OUString("com.sun.star.comp.writer.FormatDetector" );
465 /* Helper for registry */
466 Reference
< XInterface
> SAL_CALL
SwFilterDetect::impl_createInstance( const Reference
< XMultiServiceFactory
>& xServiceManager
) throw( Exception
)
468 return Reference
< XInterface
>( *new SwFilterDetect( xServiceManager
) );
471 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */