update credits
[LibreOffice.git] / starmath / source / smdetect.cxx
blob39b67b7da5f03fcdb34b8ed451c5ce8bfea515f3
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 "smdetect.hxx"
22 #include <com/sun/star/lang/XMultiServiceFactory.hpp>
23 #include <com/sun/star/beans/PropertyValue.hpp>
24 #include <com/sun/star/frame/XFrame.hpp>
25 #include <com/sun/star/frame/XModel.hpp>
26 #include <com/sun/star/awt/XWindow.hpp>
27 #include <com/sun/star/lang/XUnoTunnel.hpp>
28 #include <comphelper/processfactory.hxx>
29 #include <com/sun/star/io/XInputStream.hpp>
30 #include <com/sun/star/task/XInteractionHandler.hpp>
31 #include <com/sun/star/lang/WrappedTargetRuntimeException.hpp>
32 #include <com/sun/star/ucb/CommandAbortedException.hpp>
33 #include <com/sun/star/ucb/InteractiveAppException.hpp>
34 #include <com/sun/star/ucb/XContent.hpp>
35 #include <com/sun/star/packages/zip/ZipIOException.hpp>
36 #include <toolkit/helper/vclunohelper.hxx>
37 #include <ucbhelper/simpleinteractionrequest.hxx>
38 #include <rtl/ustring.h>
39 #include <rtl/logfile.hxx>
40 #include <svl/itemset.hxx>
41 #include <vcl/window.hxx>
42 #include <svl/eitem.hxx>
43 #include <svl/stritem.hxx>
44 #include <tools/urlobj.hxx>
45 #include <osl/mutex.hxx>
46 #include <svtools/sfxecode.hxx>
47 #include <svtools/ehdl.hxx>
48 #include <sot/storinfo.hxx>
49 #include <vcl/svapp.hxx>
50 #include <sfx2/app.hxx>
51 #include <sfx2/sfxsids.hrc>
52 #include <sfx2/request.hxx>
53 #include <sfx2/docfile.hxx>
54 #include <sfx2/docfilt.hxx>
55 #include <sfx2/fcontnr.hxx>
56 #include <sfx2/brokenpackageint.hxx>
58 #include "document.hxx"
59 #include "eqnolefilehdr.hxx"
61 using namespace ::com::sun::star;
62 using namespace ::com::sun::star::uno;
63 using namespace ::com::sun::star::io;
64 using namespace ::com::sun::star::frame;
65 using namespace ::com::sun::star::task;
66 using namespace ::com::sun::star::beans;
67 using namespace ::com::sun::star::lang;
68 using namespace ::com::sun::star::ucb;
70 SmFilterDetect::SmFilterDetect( const Reference < XMultiServiceFactory >& /*xFactory*/ )
74 SmFilterDetect::~SmFilterDetect()
78 OUString SAL_CALL SmFilterDetect::detect( Sequence< PropertyValue >& lDescriptor ) throw( RuntimeException )
80 Reference< XInputStream > xStream;
81 Reference< XContent > xContent;
82 Reference< XInteractionHandler > xInteraction;
83 String aURL;
84 OUString sTemp;
85 String aTypeName; // a name describing the type (from MediaDescriptor, usually from flat detection)
86 String aPreselectedFilterName; // a name describing the filter to use (from MediaDescriptor, usually from UI action)
88 OUString aDocumentTitle; // interesting only if set in this method
90 // opening as template is done when a parameter tells to do so and a template filter can be detected
91 // (otherwise no valid filter would be found) or if the detected filter is a template filter and
92 // there is no parameter that forbids to open as template
93 sal_Bool bOpenAsTemplate = sal_False;
94 sal_Bool bWasReadOnly = sal_False, bReadOnly = sal_False;
96 sal_Bool bRepairPackage = sal_False;
97 sal_Bool bRepairAllowed = sal_False;
99 // now some parameters that can already be in the array, but may be overwritten or new inserted here
100 // remember their indices in the case new values must be added to the array
101 sal_Int32 nPropertyCount = lDescriptor.getLength();
102 sal_Int32 nIndexOfInputStream = -1;
103 sal_Int32 nIndexOfContent = -1;
104 sal_Int32 nIndexOfReadOnlyFlag = -1;
105 sal_Int32 nIndexOfTemplateFlag = -1;
106 sal_Int32 nIndexOfDocumentTitle = -1;
108 for( sal_Int32 nProperty=0; nProperty<nPropertyCount; ++nProperty )
110 // extract properties
111 if( lDescriptor[nProperty].Name == "URL" )
113 lDescriptor[nProperty].Value >>= sTemp;
114 aURL = sTemp;
116 else if( !aURL.Len() && lDescriptor[nProperty].Name == "FileName" )
118 lDescriptor[nProperty].Value >>= sTemp;
119 aURL = sTemp;
121 else if( lDescriptor[nProperty].Name == "TypeName" )
123 lDescriptor[nProperty].Value >>= sTemp;
124 aTypeName = sTemp;
126 else if( lDescriptor[nProperty].Name == "FilterName" )
128 lDescriptor[nProperty].Value >>= sTemp;
129 aPreselectedFilterName = sTemp;
131 else if( lDescriptor[nProperty].Name == "InputStream" )
132 nIndexOfInputStream = nProperty;
133 else if( lDescriptor[nProperty].Name == "ReadOnly" )
134 nIndexOfReadOnlyFlag = nProperty;
135 else if( lDescriptor[nProperty].Name == "UCBContent" )
136 nIndexOfContent = nProperty;
137 else if( lDescriptor[nProperty].Name == "AsTemplate" )
139 lDescriptor[nProperty].Value >>= bOpenAsTemplate;
140 nIndexOfTemplateFlag = nProperty;
142 else if( lDescriptor[nProperty].Name == "InteractionHandler" )
143 lDescriptor[nProperty].Value >>= xInteraction;
144 else if( lDescriptor[nProperty].Name == "RepairPackage" )
145 lDescriptor[nProperty].Value >>= bRepairPackage;
146 else if( lDescriptor[nProperty].Name == "DocumentTitle" )
147 nIndexOfDocumentTitle = nProperty;
150 // can't check the type for external filters, so set the "dont" flag accordingly
151 SolarMutexGuard aGuard;
153 SfxApplication* pApp = SFX_APP();
154 SfxAllItemSet *pSet = new SfxAllItemSet( pApp->GetPool() );
155 TransformParameters( SID_OPENDOC, lDescriptor, *pSet );
156 SFX_ITEMSET_ARG( pSet, pItem, SfxBoolItem, SID_DOC_READONLY, sal_False );
158 bWasReadOnly = pItem && pItem->GetValue();
160 String aFilterName;
161 String aPrefix = OUString( "private:factory/" );
162 if( aURL.Match( aPrefix ) == aPrefix.Len() )
164 const SfxFilter* pFilter = 0;
165 String aPattern( aPrefix );
166 aPattern += OUString("smath");
167 if ( aURL.Match( aPattern ) >= aPattern.Len() )
169 pFilter = SfxFilter::GetDefaultFilterFromFactory( aURL );
170 aTypeName = pFilter->GetTypeName();
171 aFilterName = pFilter->GetName();
174 else
176 // ctor of SfxMedium uses owner transition of ItemSet
177 SfxMedium aMedium( aURL, bWasReadOnly ? STREAM_STD_READ : STREAM_STD_READWRITE, NULL, pSet );
178 aMedium.UseInteractionHandler( true );
180 bool bIsStorage = aMedium.IsStorage();
181 if ( aMedium.GetErrorCode() == ERRCODE_NONE )
183 // remember input stream and content and put them into the descriptor later
184 // should be done here since later the medium can switch to a version
185 xStream = aMedium.GetInputStream();
186 xContent = aMedium.GetContent();
187 bReadOnly = aMedium.IsReadOnly();
189 if ( bIsStorage )
191 //TODO/LATER: factor this out!
192 Reference < embed::XStorage > xStorage = aMedium.GetStorage( sal_False );
193 if ( aMedium.GetLastStorageCreationState() != ERRCODE_NONE )
195 // error during storage creation means _here_ that the medium
196 // is broken, but we can not handle it in medium since unpossibility
197 // to create a storage does not _always_ means that the medium is broken
198 aMedium.SetError( aMedium.GetLastStorageCreationState(), OSL_LOG_PREFIX );
199 if ( xInteraction.is() )
201 OUString empty;
204 InteractiveAppException xException( empty,
205 Reference< XInterface >(),
206 InteractionClassification_ERROR,
207 aMedium.GetError() );
209 Reference< XInteractionRequest > xRequest(
210 new ucbhelper::SimpleInteractionRequest( makeAny( xException ),
211 ucbhelper::CONTINUATION_APPROVE ) );
212 xInteraction->handle( xRequest );
214 catch ( Exception & ) {};
217 else
219 aFilterName.Erase();
223 const SfxFilter* pFilter = aPreselectedFilterName.Len() ?
224 SfxFilterMatcher().GetFilter4FilterName( aPreselectedFilterName ) : aTypeName.Len() ?
225 SfxFilterMatcher(OUString("smath")).GetFilter4EA( aTypeName ) : 0;
226 OUString aTmpFilterName;
227 if ( pFilter )
228 aTmpFilterName = pFilter->GetName();
229 aTypeName = SfxFilter::GetTypeFromStorage( xStorage, pFilter ? pFilter->IsAllowedAsTemplate() : sal_False, &aTmpFilterName );
231 catch( const WrappedTargetException& aWrap )
233 packages::zip::ZipIOException aZipException;
235 // repairing is done only if this type is requested from outside
236 if ( ( aWrap.TargetException >>= aZipException ) && aTypeName.Len() )
238 if ( xInteraction.is() )
240 // the package is broken one
241 aDocumentTitle = aMedium.GetURLObject().getName(
242 INetURLObject::LAST_SEGMENT,
243 true,
244 INetURLObject::DECODE_WITH_CHARSET );
246 if ( !bRepairPackage )
248 // ask the user whether he wants to try to repair
249 RequestPackageReparation aRequest( aDocumentTitle );
250 xInteraction->handle( aRequest.GetRequest() );
251 bRepairAllowed = aRequest.isApproved();
254 if ( !bRepairAllowed )
256 // repair either not allowed or not successful
257 NotifyBrokenPackage aNotifyRequest( aDocumentTitle );
258 xInteraction->handle( aNotifyRequest.GetRequest() );
262 if ( !bRepairAllowed )
263 aTypeName.Erase();
266 catch( RuntimeException& )
268 throw;
270 catch( Exception& )
272 aTypeName.Erase();
275 if ( aTypeName.Len() )
277 const SfxFilter* pFilter =
278 SfxFilterMatcher( OUString("smath") ).GetFilter4EA( aTypeName );
279 if ( pFilter )
280 aFilterName = pFilter->GetName();
284 else
286 //Test to see if this begins with xml and if so run it through
287 //the MathML filter. There are all sorts of things wrong with
288 //this approach, to be fixed at a better level than here
289 SvStream *pStrm = aMedium.GetInStream();
290 aTypeName.Erase();
291 if (pStrm && !pStrm->GetError())
293 SotStorageRef aStorage = new SotStorage ( pStrm, sal_False );
294 if ( !aStorage->GetError() )
296 if (aStorage->IsStream(OUString("Equation Native")))
298 sal_uInt8 nVersion;
299 if (GetMathTypeVersion( aStorage, nVersion ) && nVersion <=3)
300 aTypeName.AssignAscii( "math_MathType_3x" );
303 else
305 const sal_uInt16 nSize = 5;
306 sal_Char aBuffer[nSize+1];
307 aBuffer[nSize] = 0;
308 pStrm->Seek( STREAM_SEEK_TO_BEGIN );
309 sal_uLong nBytesRead = pStrm->Read( aBuffer, nSize );
310 if (nBytesRead == nSize)
312 if (0 == strncmp( "<?xml",aBuffer,nSize))
314 // 200 should be enough for the XML
315 // version, encoding and !DOCTYPE
316 // stuff I hope?
317 sal_Char aBuffer2[200];
318 nBytesRead = pStrm->Read( aBuffer2, sizeof(aBuffer2) - 1);
319 aBuffer2[nBytesRead] = 0;
320 if (strstr( aBuffer2, "<math>" ) ||
321 strstr( aBuffer2, "<math " ) ||
322 strstr( aBuffer2, "<math:math " ))
324 static const sal_Char sFltrNm_2[] = MATHML_XML;
325 static const sal_Char sTypeNm_2[] = "math_MathML_XML_Math";
326 aFilterName.AssignAscii( sFltrNm_2 );
327 aTypeName.AssignAscii( sTypeNm_2 );
333 if ( aTypeName.Len() )
335 const SfxFilter* pFilt = SfxFilterMatcher( OUString("smath") ).GetFilter4EA( aTypeName );
336 if ( pFilt )
337 aFilterName = pFilt->GetName();
344 if ( nIndexOfInputStream == -1 && xStream.is() )
346 // if input stream wasn't part of the descriptor, now it should be, otherwise the content would be opend twice
347 lDescriptor.realloc( nPropertyCount + 1 );
348 lDescriptor[nPropertyCount].Name = "InputStream";
349 lDescriptor[nPropertyCount].Value <<= xStream;
350 nPropertyCount++;
353 if ( nIndexOfContent == -1 && xContent.is() )
355 // if input stream wasn't part of the descriptor, now it should be, otherwise the content would be opend twice
356 lDescriptor.realloc( nPropertyCount + 1 );
357 lDescriptor[nPropertyCount].Name = "UCBContent";
358 lDescriptor[nPropertyCount].Value <<= xContent;
359 nPropertyCount++;
362 if ( bReadOnly != bWasReadOnly )
364 if ( nIndexOfReadOnlyFlag == -1 )
366 lDescriptor.realloc( nPropertyCount + 1 );
367 lDescriptor[nPropertyCount].Name = "ReadOnly";
368 lDescriptor[nPropertyCount].Value <<= bReadOnly;
369 nPropertyCount++;
371 else
372 lDescriptor[nIndexOfReadOnlyFlag].Value <<= bReadOnly;
375 if ( !bRepairPackage && bRepairAllowed )
377 lDescriptor.realloc( nPropertyCount + 1 );
378 lDescriptor[nPropertyCount].Name = "RepairPackage";
379 lDescriptor[nPropertyCount].Value <<= bRepairAllowed;
380 nPropertyCount++;
382 bOpenAsTemplate = sal_True;
384 // TODO/LATER: set progress bar that should be used
387 if ( bOpenAsTemplate )
389 if ( nIndexOfTemplateFlag == -1 )
391 lDescriptor.realloc( nPropertyCount + 1 );
392 lDescriptor[nPropertyCount].Name = "AsTemplate";
393 lDescriptor[nPropertyCount].Value <<= bOpenAsTemplate;
394 nPropertyCount++;
396 else
397 lDescriptor[nIndexOfTemplateFlag].Value <<= bOpenAsTemplate;
400 if ( !aDocumentTitle.isEmpty() )
402 // the title was set here
403 if ( nIndexOfDocumentTitle == -1 )
405 lDescriptor.realloc( nPropertyCount + 1 );
406 lDescriptor[nPropertyCount].Name = "DocumentTitle";
407 lDescriptor[nPropertyCount].Value <<= aDocumentTitle;
408 nPropertyCount++;
410 else
411 lDescriptor[nIndexOfDocumentTitle].Value <<= aDocumentTitle;
414 if ( !aFilterName.Len() )
415 aTypeName.Erase();
417 return aTypeName;
420 /* XServiceInfo */
421 OUString SAL_CALL SmFilterDetect::getImplementationName() throw( RuntimeException )
423 return impl_getStaticImplementationName();
426 /* XServiceInfo */
427 sal_Bool SAL_CALL SmFilterDetect::supportsService( const OUString& sServiceName ) throw( RuntimeException )
429 Sequence< OUString > seqServiceNames = getSupportedServiceNames();
430 const OUString* pArray = seqServiceNames.getConstArray();
431 for ( sal_Int32 nCounter=0; nCounter<seqServiceNames.getLength(); nCounter++ )
433 if ( pArray[nCounter] == sServiceName )
435 return sal_True ;
438 return sal_False ;
441 /* XServiceInfo */
442 Sequence< OUString > SAL_CALL SmFilterDetect::getSupportedServiceNames() throw( RuntimeException )
444 return impl_getStaticSupportedServiceNames();
447 /* Helper for XServiceInfo */
448 Sequence< OUString > SmFilterDetect::impl_getStaticSupportedServiceNames()
450 Sequence< OUString > seqServiceNames( 1 );
451 seqServiceNames.getArray() [0] = "com.sun.star.frame.ExtendedTypeDetection";
452 return seqServiceNames ;
455 /* Helper for XServiceInfo */
456 OUString SmFilterDetect::impl_getStaticImplementationName()
458 return OUString("com.sun.star.comp.math.FormatDetector");
461 /* Helper for registry */
462 Reference< XInterface > SAL_CALL SmFilterDetect::impl_createInstance( const Reference< XMultiServiceFactory >& xServiceManager ) throw( Exception )
464 return Reference< XInterface >( *new SmFilterDetect( xServiceManager ) );
467 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */