Update ooo320-m1
[ooovba.git] / sc / source / ui / unoobj / scdetect.cxx
blobeb1e27380f935ce3dcfeaef6e80ff987ca382751
1 /*************************************************************************
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * Copyright 2008 by Sun Microsystems, Inc.
7 * OpenOffice.org - a multi-platform office productivity suite
9 * $RCSfile: scdetect.cxx,v $
10 * $Revision: 1.24 $
12 * This file is part of OpenOffice.org.
14 * OpenOffice.org is free software: you can redistribute it and/or modify
15 * it under the terms of the GNU Lesser General Public License version 3
16 * only, as published by the Free Software Foundation.
18 * OpenOffice.org is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU Lesser General Public License version 3 for more details
22 * (a copy is included in the LICENSE file that accompanied this code).
24 * You should have received a copy of the GNU Lesser General Public License
25 * version 3 along with OpenOffice.org. If not, see
26 * <http://www.openoffice.org/license.html>
27 * for a copy of the LGPLv3 License.
29 ************************************************************************/
31 // MARKER(update_precomp.py): autogen include statement, do not remove
32 #include "precompiled_sc.hxx"
34 #include "scdetect.hxx"
36 #include <framework/interaction.hxx>
37 #include <com/sun/star/lang/XMultiServiceFactory.hpp>
38 #include <com/sun/star/beans/PropertyValue.hpp>
39 #include <com/sun/star/frame/XFrame.hpp>
40 #include <com/sun/star/frame/XModel.hpp>
41 #include <com/sun/star/awt/XWindow.hpp>
42 #include <com/sun/star/lang/XUnoTunnel.hpp>
43 #ifndef _UNOTOOLS_PROCESSFACTORY_HXX
44 #include <comphelper/processfactory.hxx>
45 #endif
46 #include <com/sun/star/beans/PropertyValue.hpp>
47 #include <com/sun/star/container/XNameAccess.hpp>
48 #include <com/sun/star/io/XInputStream.hpp>
49 #include <com/sun/star/task/XInteractionHandler.hpp>
50 #include <com/sun/star/lang/WrappedTargetRuntimeException.hpp>
51 #include <com/sun/star/ucb/CommandAbortedException.hpp>
52 #include <com/sun/star/ucb/InteractiveAppException.hpp>
53 #include <com/sun/star/ucb/XContent.hpp>
54 #include <com/sun/star/packages/zip/ZipIOException.hpp>
57 #include <framework/interaction.hxx>
59 #ifndef _TOOLKIT_UNOHLP_HXX
60 #include <toolkit/helper/vclunohelper.hxx>
61 #endif
62 #include <ucbhelper/simpleinteractionrequest.hxx>
64 #include <svtools/parhtml.hxx>
65 #include <rtl/ustring.h>
66 #include <rtl/logfile.hxx>
67 #include <svtools/itemset.hxx>
68 #include <vcl/window.hxx>
69 #include <svtools/eitem.hxx>
70 #include <svtools/stritem.hxx>
71 #include <tools/urlobj.hxx>
72 #include <vos/mutex.hxx>
73 #include <svtools/sfxecode.hxx>
74 #include <svtools/ehdl.hxx>
75 #include <sot/storinfo.hxx>
76 #include <vcl/svapp.hxx>
77 #include <sfx2/sfxsids.hrc>
78 #include <sfx2/request.hxx>
79 #include <sfx2/docfile.hxx>
80 #include <sfx2/docfilt.hxx>
81 #include <sfx2/fcontnr.hxx>
82 #include <sfx2/app.hxx>
83 #include <sfx2/brokenpackageint.hxx>
84 #include <sot/storage.hxx>
86 using namespace ::com::sun::star;
87 using namespace ::com::sun::star::uno;
88 using namespace ::com::sun::star::io;
89 using namespace ::com::sun::star::frame;
90 using namespace ::com::sun::star::task;
91 using namespace ::com::sun::star::beans;
92 using namespace ::com::sun::star::lang;
93 using namespace ::com::sun::star::ucb;
94 using ::rtl::OUString;
96 ScFilterDetect::ScFilterDetect( const REFERENCE < ::com::sun::star::lang::XMultiServiceFactory >& /* xFactory */ )
100 ScFilterDetect::~ScFilterDetect()
104 static const sal_Char __FAR_DATA pFilterSc50[] = "StarCalc 5.0";
105 static const sal_Char __FAR_DATA pFilterSc50Temp[] = "StarCalc 5.0 Vorlage/Template";
106 static const sal_Char __FAR_DATA pFilterSc40[] = "StarCalc 4.0";
107 static const sal_Char __FAR_DATA pFilterSc40Temp[] = "StarCalc 4.0 Vorlage/Template";
108 static const sal_Char __FAR_DATA pFilterSc30[] = "StarCalc 3.0";
109 static const sal_Char __FAR_DATA pFilterSc30Temp[] = "StarCalc 3.0 Vorlage/Template";
110 static const sal_Char __FAR_DATA pFilterSc10[] = "StarCalc 1.0";
111 static const sal_Char __FAR_DATA pFilterXML[] = "StarOffice XML (Calc)";
112 static const sal_Char __FAR_DATA pFilterAscii[] = "Text - txt - csv (StarCalc)";
113 static const sal_Char __FAR_DATA pFilterLotus[] = "Lotus";
114 static const sal_Char __FAR_DATA pFilterQPro6[] = "Quattro Pro 6.0";
115 static const sal_Char __FAR_DATA pFilterExcel4[] = "MS Excel 4.0";
116 static const sal_Char __FAR_DATA pFilterEx4Temp[] = "MS Excel 4.0 Vorlage/Template";
117 static const sal_Char __FAR_DATA pFilterExcel5[] = "MS Excel 5.0/95";
118 static const sal_Char __FAR_DATA pFilterEx5Temp[] = "MS Excel 5.0/95 Vorlage/Template";
119 static const sal_Char __FAR_DATA pFilterExcel95[] = "MS Excel 95";
120 static const sal_Char __FAR_DATA pFilterEx95Temp[] = "MS Excel 95 Vorlage/Template";
121 static const sal_Char __FAR_DATA pFilterExcel97[] = "MS Excel 97";
122 static const sal_Char __FAR_DATA pFilterEx97Temp[] = "MS Excel 97 Vorlage/Template";
123 static const sal_Char __FAR_DATA pFilterDBase[] = "dBase";
124 static const sal_Char __FAR_DATA pFilterDif[] = "DIF";
125 static const sal_Char __FAR_DATA pFilterSylk[] = "SYLK";
126 static const sal_Char __FAR_DATA pFilterHtml[] = "HTML (StarCalc)";
127 static const sal_Char __FAR_DATA pFilterHtmlWeb[] = "calc_HTML_WebQuery";
128 static const sal_Char __FAR_DATA pFilterRtf[] = "Rich Text Format (StarCalc)";
131 static BOOL lcl_MayBeAscii( SvStream& rStream )
133 // ASCII/CSV is considered possible if there are no null bytes, or a Byte
134 // Order Mark is present, or if, for Unicode UCS2/UTF-16, all null bytes
135 // are on either even or uneven byte positions.
137 rStream.Seek(STREAM_SEEK_TO_BEGIN);
139 const size_t nBufSize = 2048;
140 sal_uInt16 aBuffer[ nBufSize ];
141 sal_uInt8* pByte = reinterpret_cast<sal_uInt8*>(aBuffer);
142 ULONG nBytesRead = rStream.Read( pByte, nBufSize*2);
144 if ( nBytesRead >= 2 && (aBuffer[0] == 0xfffe || aBuffer[0] == 0xfeff) )
146 // Unicode BOM file may contain null bytes.
147 return TRUE;
150 const sal_uInt16* p = aBuffer;
151 sal_uInt16 nMask = 0xffff;
152 nBytesRead /= 2;
153 while( nBytesRead-- && nMask )
155 sal_uInt16 nVal = *p++ & nMask;
156 if (!(nVal & 0x00ff))
157 nMask &= 0xff00;
158 if (!(nVal & 0xff00))
159 nMask &= 0x00ff;
162 return nMask != 0;
165 static BOOL lcl_MayBeDBase( SvStream& rStream )
167 // Look for dbf marker, see connectivity/source/inc/dbase/DTable.hxx
168 // DBFType for values.
169 const BYTE nValidMarks[] = {
170 0x03, 0x04, 0x05, 0x30, 0x43, 0xB3, 0x83, 0x8b, 0x8e, 0xf5 };
171 BYTE nMark;
172 rStream.Seek(STREAM_SEEK_TO_BEGIN);
173 rStream >> nMark;
174 bool bValidMark = false;
175 for (size_t i=0; i < sizeof(nValidMarks)/sizeof(nValidMarks[0]) && !bValidMark; ++i)
177 if (nValidMarks[i] == nMark)
178 bValidMark = true;
180 if ( !bValidMark )
181 return FALSE;
183 const size_t nHeaderBlockSize = 32;
184 // Empty dbf is >= 32*2+1 bytes in size.
185 const size_t nEmptyDbf = nHeaderBlockSize * 2 + 1;
187 rStream.Seek(STREAM_SEEK_TO_END);
188 ULONG nSize = rStream.Tell();
189 if ( nSize < nEmptyDbf )
190 return FALSE;
192 // length of header starts at 8
193 rStream.Seek(8);
194 USHORT nHeaderLen;
195 rStream >> nHeaderLen;
197 if ( nHeaderLen < nEmptyDbf || nSize < nHeaderLen )
198 return FALSE;
200 // Last byte of header must be 0x0d, this is how it's specified.
201 // #i9581#,#i26407# but some applications don't follow the specification
202 // and pad the header with one byte 0x00 to reach an
203 // even boundary. Some (#i88577# ) even pad more or pad using a 0x1a ^Z
204 // control character (#i8857#). This results in:
205 // Last byte of header must be 0x0d on 32 bytes boundary.
206 USHORT nBlocks = (nHeaderLen - 1) / nHeaderBlockSize;
207 BYTE nEndFlag = 0;
208 while ( nBlocks > 1 && nEndFlag != 0x0d ) {
209 rStream.Seek( nBlocks-- * nHeaderBlockSize );
210 rStream >> nEndFlag;
213 return ( 0x0d == nEndFlag );
216 #if 0
217 static BOOL lcl_IsAnyXMLFilter( const SfxFilter* pFilter )
219 if ( !pFilter )
220 return FALSE;
222 // TRUE for XML file or template
223 // (template filter has no internal name -> allow configuration key names)
225 String aName(pFilter->GetFilterName());
226 return aName.EqualsAscii(pFilterXML) ||
227 aName.EqualsAscii("calc_StarOffice_XML_Calc") ||
228 aName.EqualsAscii("calc_StarOffice_XML_Calc_Template");
230 #endif
232 ::rtl::OUString SAL_CALL ScFilterDetect::detect( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lDescriptor ) throw( ::com::sun::star::uno::RuntimeException )
234 REFERENCE< XInputStream > xStream;
235 REFERENCE< XContent > xContent;
236 REFERENCE< XInteractionHandler > xInteraction;
237 String aURL;
238 ::rtl::OUString sTemp;
239 String aTypeName; // a name describing the type (from MediaDescriptor, usually from flat detection)
240 String aPreselectedFilterName; // a name describing the filter to use (from MediaDescriptor, usually from UI action)
242 ::rtl::OUString aDocumentTitle; // interesting only if set in this method
244 // opening as template is done when a parameter tells to do so and a template filter can be detected
245 // (otherwise no valid filter would be found) or if the detected filter is a template filter and
246 // there is no parameter that forbids to open as template
247 sal_Bool bOpenAsTemplate = sal_False;
248 sal_Bool bWasReadOnly = sal_False, bReadOnly = sal_False;
250 sal_Bool bRepairPackage = sal_False;
251 sal_Bool bRepairAllowed = sal_False;
253 // now some parameters that can already be in the array, but may be overwritten or new inserted here
254 // remember their indices in the case new values must be added to the array
255 sal_Int32 nPropertyCount = lDescriptor.getLength();
256 sal_Int32 nIndexOfFilterName = -1;
257 sal_Int32 nIndexOfInputStream = -1;
258 sal_Int32 nIndexOfContent = -1;
259 sal_Int32 nIndexOfReadOnlyFlag = -1;
260 sal_Int32 nIndexOfTemplateFlag = -1;
261 sal_Int32 nIndexOfDocumentTitle = -1;
263 for( sal_Int32 nProperty=0; nProperty<nPropertyCount; ++nProperty )
265 // extract properties
266 if( lDescriptor[nProperty].Name == OUString(RTL_CONSTASCII_USTRINGPARAM("URL")) )
268 lDescriptor[nProperty].Value >>= sTemp;
269 aURL = sTemp;
271 else if( !aURL.Len() && lDescriptor[nProperty].Name == OUString(RTL_CONSTASCII_USTRINGPARAM("FileName")) )
273 lDescriptor[nProperty].Value >>= sTemp;
274 aURL = sTemp;
276 else if( lDescriptor[nProperty].Name == OUString(RTL_CONSTASCII_USTRINGPARAM("TypeName")) )
278 lDescriptor[nProperty].Value >>= sTemp;
279 aTypeName = sTemp;
281 else if( lDescriptor[nProperty].Name == OUString(RTL_CONSTASCII_USTRINGPARAM("FilterName")) )
283 lDescriptor[nProperty].Value >>= sTemp;
284 aPreselectedFilterName = sTemp;
286 // if the preselected filter name is not correct, it must be erased after detection
287 // remember index of property to get access to it later
288 nIndexOfFilterName = nProperty;
290 else if( lDescriptor[nProperty].Name == OUString(RTL_CONSTASCII_USTRINGPARAM("InputStream")) )
291 nIndexOfInputStream = nProperty;
292 else if( lDescriptor[nProperty].Name == OUString(RTL_CONSTASCII_USTRINGPARAM("ReadOnly")) )
293 nIndexOfReadOnlyFlag = nProperty;
294 else if( lDescriptor[nProperty].Name == OUString(RTL_CONSTASCII_USTRINGPARAM("UCBContent")) )
295 nIndexOfContent = nProperty;
296 else if( lDescriptor[nProperty].Name == OUString(RTL_CONSTASCII_USTRINGPARAM("AsTemplate")) )
298 lDescriptor[nProperty].Value >>= bOpenAsTemplate;
299 nIndexOfTemplateFlag = nProperty;
301 else if( lDescriptor[nProperty].Name == OUString(RTL_CONSTASCII_USTRINGPARAM("InteractionHandler")) )
302 lDescriptor[nProperty].Value >>= xInteraction;
303 else if( lDescriptor[nProperty].Name == OUString(RTL_CONSTASCII_USTRINGPARAM("RapairPackage")) )
304 lDescriptor[nProperty].Value >>= bRepairPackage;
305 else if( lDescriptor[nProperty].Name == OUString(RTL_CONSTASCII_USTRINGPARAM("DocumentTitle")) )
306 nIndexOfDocumentTitle = nProperty;
309 // can't check the type for external filters, so set the "dont" flag accordingly
310 ::vos::OGuard aGuard( Application::GetSolarMutex() );
311 //SfxFilterFlags nMust = SFX_FILTER_IMPORT, nDont = SFX_FILTER_NOTINSTALLED;
313 SfxAllItemSet *pSet = new SfxAllItemSet( SFX_APP()->GetPool() );
314 TransformParameters( SID_OPENDOC, lDescriptor, *pSet );
315 SFX_ITEMSET_ARG( pSet, pItem, SfxBoolItem, SID_DOC_READONLY, FALSE );
317 bWasReadOnly = pItem && pItem->GetValue();
319 const SfxFilter* pFilter = 0;
320 String aPrefix = String::CreateFromAscii( "private:factory/" );
321 if( aURL.Match( aPrefix ) == aPrefix.Len() )
323 String aPattern( aPrefix );
324 aPattern += String::CreateFromAscii("scalc");
325 if ( aURL.Match( aPattern ) >= aPattern.Len() )
326 pFilter = SfxFilter::GetDefaultFilterFromFactory( aURL );
328 else
330 // container for Calc filters
331 SfxFilterMatcher aMatcher( String::CreateFromAscii("scalc") );
332 if ( aPreselectedFilterName.Len() )
333 pFilter = SfxFilter::GetFilterByName( aPreselectedFilterName );
334 else if( aTypeName.Len() )
335 pFilter = aMatcher.GetFilter4EA( aTypeName );
337 // ctor of SfxMedium uses owner transition of ItemSet
338 SfxMedium aMedium( aURL, bWasReadOnly ? STREAM_STD_READ : STREAM_STD_READWRITE, FALSE, NULL, pSet );
339 aMedium.UseInteractionHandler( TRUE );
341 BOOL bIsStorage = aMedium.IsStorage();
342 if ( aMedium.GetErrorCode() == ERRCODE_NONE )
344 // remember input stream and content and put them into the descriptor later
345 // should be done here since later the medium can switch to a version
346 xStream.set(aMedium.GetInputStream());
347 xContent.set(aMedium.GetContent());
348 bReadOnly = aMedium.IsReadOnly();
350 // maybe that IsStorage() already created an error!
351 if ( bIsStorage )
353 uno::Reference < embed::XStorage > xStorage(aMedium.GetStorage( sal_False ));
354 if ( aMedium.GetLastStorageCreationState() != ERRCODE_NONE )
356 // error during storage creation means _here_ that the medium
357 // is broken, but we can not handle it in medium since unpossibility
358 // to create a storage does not _always_ means that the medium is broken
359 aMedium.SetError( aMedium.GetLastStorageCreationState(), ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX ) ) );
360 if ( xInteraction.is() )
362 OUString empty;
365 InteractiveAppException xException( empty,
366 REFERENCE< XInterface >(),
367 InteractionClassification_ERROR,
368 aMedium.GetError() );
370 REFERENCE< XInteractionRequest > xRequest(
371 new ucbhelper::SimpleInteractionRequest( makeAny( xException ),
372 ucbhelper::CONTINUATION_APPROVE ) );
373 xInteraction->handle( xRequest );
375 catch ( Exception & ) {};
378 else if ( xStorage.is() )
382 String aFilterName;
383 if ( pFilter )
384 aFilterName = pFilter->GetName();
385 aTypeName = SfxFilter::GetTypeFromStorage( xStorage, pFilter ? pFilter->IsOwnTemplateFormat() : FALSE, &aFilterName );
387 catch( lang::WrappedTargetException& aWrap )
389 packages::zip::ZipIOException aZipException;
391 // repairing is done only if this type is requested from outside
392 if ( ( aWrap.TargetException >>= aZipException ) && aTypeName.Len() )
394 if ( xInteraction.is() )
396 // the package is broken one
397 aDocumentTitle = aMedium.GetURLObject().getName(
398 INetURLObject::LAST_SEGMENT,
399 true,
400 INetURLObject::DECODE_WITH_CHARSET );
402 if ( !bRepairPackage )
404 // ask the user whether he wants to try to repair
405 RequestPackageReparation* pRequest = new RequestPackageReparation( aDocumentTitle );
406 uno::Reference< task::XInteractionRequest > xRequest ( pRequest );
408 xInteraction->handle( xRequest );
410 bRepairAllowed = pRequest->isApproved();
413 if ( !bRepairAllowed )
415 // repair either not allowed or not successful
416 NotifyBrokenPackage* pNotifyRequest = new NotifyBrokenPackage( aDocumentTitle );
417 uno::Reference< task::XInteractionRequest > xRequest ( pNotifyRequest );
418 xInteraction->handle( xRequest );
422 if ( !bRepairAllowed )
423 aTypeName.Erase();
426 catch( uno::RuntimeException& )
428 throw;
430 catch( uno::Exception& )
432 aTypeName.Erase();
435 if ( aTypeName.Len() )
436 pFilter = SfxFilterMatcher( String::CreateFromAscii("scalc") ).GetFilter4EA( aTypeName );
440 else
442 SvStream* pStream = aMedium.GetInStream();
443 const SfxFilter* pPreselectedFilter = pFilter;
444 pFilter = 0;
445 if ( pStream )
447 SotStorageRef aStorage = new SotStorage ( pStream, FALSE );
448 if ( !aStorage->GetError() )
450 // Excel-5: detect through contained streams
451 // there are some "excel" formats from 3rd party vendors that need to be distinguished
452 String aStreamName(RTL_CONSTASCII_STRINGPARAM("Workbook"));
453 BOOL bExcel97Stream = ( aStorage->IsStream( aStreamName ) );
455 aStreamName = String(RTL_CONSTASCII_STRINGPARAM("Book"));
456 BOOL bExcel5Stream = ( aStorage->IsStream( aStreamName ) );
457 if ( bExcel97Stream || bExcel5Stream )
459 if ( bExcel97Stream )
461 String aOldName;
462 BOOL bIsCalcFilter = TRUE;
463 if ( pPreselectedFilter )
465 // cross filter; now this should be a type detection only, not a filter detection
466 // we can simulate it by preserving the preselected filter if the type matches
467 // example: Excel filters for Writer
468 aOldName = pPreselectedFilter->GetFilterName();
469 bIsCalcFilter = pPreselectedFilter->GetServiceName().EqualsAscii("com.sun.star.sheet.SpreadsheetDocument");
472 if ( aOldName.EqualsAscii(pFilterEx97Temp) || !bIsCalcFilter )
474 // Excel 97 template selected -> keep selection
476 else if ( bExcel5Stream &&
477 ( aOldName.EqualsAscii(pFilterExcel5) || aOldName.EqualsAscii(pFilterEx5Temp) ||
478 aOldName.EqualsAscii(pFilterExcel95) || aOldName.EqualsAscii(pFilterEx95Temp) ) )
480 // dual format file and Excel 5 selected -> keep selection
482 else
484 // else use Excel 97 filter
485 pFilter = aMatcher.GetFilter4FilterName( String::CreateFromAscii(pFilterExcel97) );
488 else if ( bExcel5Stream )
490 String aOldName;
491 BOOL bIsCalcFilter = TRUE;
492 if ( pPreselectedFilter )
494 // cross filter; now this should be a type detection only, not a filter detection
495 // we can simulate it by preserving the preselected filter if the type matches
496 // example: Excel filters for Writer
497 aOldName = pPreselectedFilter->GetFilterName();
498 bIsCalcFilter = pPreselectedFilter->GetServiceName().EqualsAscii("com.sun.star.sheet.SpreadsheetDocument");
501 if ( aOldName.EqualsAscii(pFilterExcel95) || aOldName.EqualsAscii(pFilterEx95Temp) ||
502 aOldName.EqualsAscii(pFilterEx5Temp) || !bIsCalcFilter )
504 // Excel 95 oder Vorlage (5 oder 95) eingestellt -> auch gut
506 else if ( aOldName.EqualsAscii(pFilterEx97Temp) )
508 // #101923# auto detection has found template -> return Excel5 template
509 pFilter = aMatcher.GetFilter4FilterName( String::CreateFromAscii(pFilterEx5Temp) );
511 else
513 // sonst wird als Excel 5-Datei erkannt
514 pFilter = aMatcher.GetFilter4FilterName( String::CreateFromAscii(pFilterExcel5) );
519 else
521 SvStream &rStr = *pStream;
523 // Tabelle mit Suchmustern
524 // Bedeutung der Sequenzen
525 // 0x00??: genau Byte 0x?? muss an dieser Stelle stehen
526 // 0x0100: ein Byte ueberlesen (don't care)
527 // 0x02nn: ein Byte aus 0xnn Alternativen folgt
528 // 0x8000: Erkennung abgeschlossen
531 #define M_DC 0x0100
532 #define M_ALT(ANZ) (0x0200+(ANZ))
533 #define M_ENDE 0x8000
535 static const UINT16 pLotus[] = // Lotus 1/1A/2
536 { 0x0000, 0x0000, 0x0002, 0x0000,
537 M_ALT(2), 0x0004, 0x0006,
538 0x0004, M_ENDE };
540 static const UINT16 pLotusNew[] = // Lotus >= 9.7
541 { 0x0000, 0x0000, M_DC, 0x0000, // Rec# + Len (0x1a)
542 M_ALT(3), 0x0003, 0x0004, 0x0005, // File Revision Code 97->ME
543 0x0010, 0x0004, 0x0000, 0x0000,
544 M_ENDE };
546 static const UINT16 pExcel1[] = // Excel BIFF2, BIFF3, BIFF4
547 { 0x09, // lobyte of BOF rec ID (0x0009, 0x0209, 0x0409)
548 M_ALT(3), 0x00, 0x02, 0x04, // hibyte of BOF rec ID (0x0009, 0x0209, 0x0409)
549 M_ALT(3), 4, 6, 8, // lobyte of BOF rec size (4, 6, 8, 16)
550 0x00, // hibyte of BOF rec size (4, 6, 8, 16)
551 M_DC, M_DC, // any version
552 M_ALT(3), 0x10, 0x20, 0x40, // lobyte of data type (0x0010, 0x0020, 0x0040)
553 0x00, // hibyte of data type (0x0010, 0x0020, 0x0040)
554 M_ENDE };
556 static const UINT16 pExcel2[] = // Excel BIFF4 Workspace
557 { 0x09, // lobyte of BOF rec ID (0x0409)
558 0x04, // hibyte of BOF rec ID (0x0409)
559 M_ALT(3), 4, 6, 8, // lobyte of BOF rec size (4, 6, 8, 16)
560 0x00, // hibyte of BOF rec size (4, 6, 8, 16)
561 M_DC, M_DC, // any version
562 0x00, // lobyte of data type (0x0100)
563 0x01, // hibyte of data type (0x0100)
564 M_ENDE };
566 static const UINT16 pExcel3[] = // #i23425# Excel BIFF5, BIFF7, BIFF8 (simple book stream)
567 { 0x09, // lobyte of BOF rec ID (0x0809)
568 0x08, // hibyte of BOF rec ID (0x0809)
569 M_ALT(4), 4, 6, 8, 16, // lobyte of BOF rec size
570 0x00, // hibyte of BOF rec size
571 M_DC, M_DC, // any version
572 M_ALT(5), 0x05, 0x06, 0x10, 0x20, 0x40, // lobyte of data type
573 0x00, // hibyte of data type
574 M_ENDE };
576 static const UINT16 pSc10[] = // StarCalc 1.0 Dokumente
577 { 'B', 'l', 'a', 'i', 's', 'e', '-', 'T', 'a', 'b', 'e', 'l', 'l',
578 'e', 0x000A, 0x000D, 0x0000, // Sc10CopyRight[16]
579 M_DC, M_DC, M_DC, M_DC, M_DC, M_DC, M_DC, M_DC, M_DC, M_DC, M_DC,
580 M_DC, M_DC, // Sc10CopyRight[29]
581 M_ALT(2), 0x0065, 0x0066, // Versionsnummer 101 oder 102
582 0x0000,
583 M_ENDE };
585 static const UINT16 pLotus2[] = // Lotus >3
586 { 0x0000, 0x0000, 0x001A, 0x0000, // Rec# + Len (26)
587 M_ALT(2), 0x0000, 0x0002, // File Revision Code
588 0x0010,
589 0x0004, 0x0000, // File Revision Subcode
590 M_ENDE };
592 static const UINT16 pQPro[] =
593 { 0x0000, 0x0000, 0x0002, 0x0000,
594 M_ALT(4), 0x0001, 0x0002, // WB1, WB2
595 0x0006, 0x0007, // QPro 6/7 (?)
596 0x0010,
597 M_ENDE };
599 static const UINT16 pDIF1[] = // DIF mit CR-LF
601 'T', 'A', 'B', 'L', 'E',
602 M_DC, M_DC,
603 '0', ',', '1',
604 M_DC, M_DC,
605 '\"',
606 M_ENDE };
608 static const UINT16 pDIF2[] = // DIF mit CR oder LF
610 'T', 'A', 'B', 'L', 'E',
611 M_DC,
612 '0', ',', '1',
613 M_DC,
614 '\"',
615 M_ENDE };
617 static const UINT16 pSylk[] = // Sylk
619 'I', 'D', ';',
620 M_ALT(3), 'P', 'N', 'E', // 'P' plus undocumented Excel extensions 'N' and 'E'
621 M_ENDE };
623 static const UINT16 *ppFilterPatterns[] = // Arrays mit Suchmustern
625 pLotus,
626 pExcel1,
627 pExcel2,
628 pExcel3,
629 pSc10,
630 pDIF1,
631 pDIF2,
632 pSylk,
633 pLotusNew,
634 pLotus2,
635 pQPro
637 const UINT16 nFilterCount = sizeof(ppFilterPatterns) / sizeof(ppFilterPatterns[0]);
639 static const sal_Char* const pFilterName[] = // zugehoerige Filter
641 pFilterLotus,
642 pFilterExcel4,
643 pFilterExcel4,
644 pFilterExcel4,
645 pFilterSc10,
646 pFilterDif,
647 pFilterDif,
648 pFilterSylk,
649 pFilterLotus,
650 pFilterLotus,
651 pFilterQPro6
654 // const UINT16 nByteMask = 0xFF;
656 // suchen Sie jetzt!
657 // ... realisiert ueber 'Mustererkennung'
659 BYTE nAkt;
660 BOOL bSync; // Datei und Muster stimmen ueberein
661 USHORT nFilter; // Zaehler ueber alle Filter
662 const UINT16 *pSearch; // aktuelles Musterwort
664 for ( nFilter = 0 ; nFilter < nFilterCount ; nFilter++ )
666 rStr.Seek( 0 ); // am Anfang war alles Uebel...
667 rStr >> nAkt;
668 pSearch = ppFilterPatterns[ nFilter ];
669 bSync = TRUE;
670 while( !rStr.IsEof() && bSync )
672 register UINT16 nMuster = *pSearch;
674 if( nMuster < 0x0100 )
675 { // direkter Byte-Vergleich
676 if( ( BYTE ) nMuster != nAkt )
677 bSync = FALSE;
679 else if( nMuster & M_DC )
680 { // don't care
682 else if( nMuster & M_ALT(0) )
683 { // alternative Bytes
684 BYTE nAnzAlt = ( BYTE ) nMuster;
685 bSync = FALSE; // zunaechst unsynchron
686 while( nAnzAlt > 0 )
688 pSearch++;
689 if( ( BYTE ) *pSearch == nAkt )
690 bSync = TRUE; // jetzt erst Synchronisierung
691 nAnzAlt--;
694 else if( nMuster & M_ENDE )
695 { // Format detected
696 if ( pFilterName[nFilter] == pFilterExcel4 && pPreselectedFilter &&
697 ( (pPreselectedFilter)->GetFilterName().EqualsAscii(pFilterEx4Temp) || pPreselectedFilter->GetTypeName().EqualsAscii("calc_MS_Excel_40") ) )
699 // Excel 4 erkannt, Excel 4 Vorlage eingestellt -> auch gut
700 // oder Excel 4 Filter anderer Applikation (simulated type detection!)
702 else
703 { // gefundenen Filter einstellen
704 pFilter = aMatcher.GetFilter4FilterName( String::CreateFromAscii(pFilterName[ nFilter ]) );
706 bSync = FALSE; // leave inner loop
707 nFilter = nFilterCount; // leave outer loop
709 else
710 { // Tabellenfehler
711 DBG_ERROR( "-ScApplication::DetectFilter(): Fehler in Mustertabelle");
714 pSearch++;
715 rStr >> nAkt;
719 if ( pPreselectedFilter && !pFilter )
721 // further checks for filters only if they are preselected: ASCII, HTML, RTF, DBase
722 // without the preselection other filters (Writer) take precedence
723 // DBase can't be detected reliably, so it also needs preselection
724 if ( pPreselectedFilter->GetFilterName().EqualsAscii(pFilterAscii) && lcl_MayBeAscii( rStr ) )
726 // Text filter is accepted if preselected
727 pFilter = pPreselectedFilter;
729 else
731 // get file header
732 rStr.Seek( 0 );
733 const int nTrySize = 80;
734 ByteString aHeader;
735 for ( int j = 0; j < nTrySize && !rStr.IsEof(); j++ )
737 sal_Char c;
738 rStr >> c;
739 aHeader += c;
741 aHeader += '\0';
743 if ( HTMLParser::IsHTMLFormat( aHeader.GetBuffer() ) )
745 // test for HTML
746 if ( pPreselectedFilter->GetName().EqualsAscii(pFilterHtml) )
748 pFilter = pPreselectedFilter;
750 else
752 pFilter = aMatcher.GetFilter4FilterName( String::CreateFromAscii(pFilterHtmlWeb) );
755 else if ( aHeader.CompareTo( "{\\rtf", 5 ) == COMPARE_EQUAL )
757 // test for RTF
758 pFilter = aMatcher.GetFilter4FilterName( String::CreateFromAscii(pFilterRtf) );
760 else if ( pPreselectedFilter->GetName().EqualsAscii(pFilterDBase) && lcl_MayBeDBase( rStr ) )
761 pFilter = pPreselectedFilter;
770 if ( nIndexOfInputStream == -1 && xStream.is() )
772 // if input stream wasn't part of the descriptor, now it should be, otherwise the content would be opend twice
773 lDescriptor.realloc( nPropertyCount + 1 );
774 lDescriptor[nPropertyCount].Name = ::rtl::OUString::createFromAscii("InputStream");
775 lDescriptor[nPropertyCount].Value <<= xStream;
776 nPropertyCount++;
779 if ( nIndexOfContent == -1 && xContent.is() )
781 // if input stream wasn't part of the descriptor, now it should be, otherwise the content would be opend twice
782 lDescriptor.realloc( nPropertyCount + 1 );
783 lDescriptor[nPropertyCount].Name = ::rtl::OUString::createFromAscii("UCBContent");
784 lDescriptor[nPropertyCount].Value <<= xContent;
785 nPropertyCount++;
788 if ( bReadOnly != bWasReadOnly )
790 if ( nIndexOfReadOnlyFlag == -1 )
792 lDescriptor.realloc( nPropertyCount + 1 );
793 lDescriptor[nPropertyCount].Name = ::rtl::OUString::createFromAscii("ReadOnly");
794 lDescriptor[nPropertyCount].Value <<= bReadOnly;
795 nPropertyCount++;
797 else
798 lDescriptor[nIndexOfReadOnlyFlag].Value <<= bReadOnly;
801 if ( !bRepairPackage && bRepairAllowed )
803 lDescriptor.realloc( nPropertyCount + 1 );
804 lDescriptor[nPropertyCount].Name = ::rtl::OUString::createFromAscii("RepairPackage");
805 lDescriptor[nPropertyCount].Value <<= bRepairAllowed;
806 nPropertyCount++;
808 bOpenAsTemplate = sal_True;
810 // TODO/LATER: set progress bar that should be used
813 if ( bOpenAsTemplate )
815 if ( nIndexOfTemplateFlag == -1 )
817 lDescriptor.realloc( nPropertyCount + 1 );
818 lDescriptor[nPropertyCount].Name = ::rtl::OUString::createFromAscii("AsTemplate");
819 lDescriptor[nPropertyCount].Value <<= bOpenAsTemplate;
820 nPropertyCount++;
822 else
823 lDescriptor[nIndexOfTemplateFlag].Value <<= bOpenAsTemplate;
826 if ( aDocumentTitle.getLength() )
828 // the title was set here
829 if ( nIndexOfDocumentTitle == -1 )
831 lDescriptor.realloc( nPropertyCount + 1 );
832 lDescriptor[nPropertyCount].Name = ::rtl::OUString::createFromAscii("DocumentTitle");
833 lDescriptor[nPropertyCount].Value <<= aDocumentTitle;
834 nPropertyCount++;
836 else
837 lDescriptor[nIndexOfDocumentTitle].Value <<= aDocumentTitle;
840 if ( pFilter )
841 aTypeName = pFilter->GetTypeName();
842 else
843 aTypeName.Erase();
844 return aTypeName;
847 SFX_IMPL_SINGLEFACTORY( ScFilterDetect )
849 /* XServiceInfo */
850 UNOOUSTRING SAL_CALL ScFilterDetect::getImplementationName() throw( UNORUNTIMEEXCEPTION )
852 return impl_getStaticImplementationName();
855 /* XServiceInfo */
856 sal_Bool SAL_CALL ScFilterDetect::supportsService( const UNOOUSTRING& sServiceName ) throw( UNORUNTIMEEXCEPTION )
858 UNOSEQUENCE< UNOOUSTRING > seqServiceNames(getSupportedServiceNames());
859 const UNOOUSTRING* pArray = seqServiceNames.getConstArray();
860 for ( sal_Int32 nCounter=0; nCounter<seqServiceNames.getLength(); nCounter++ )
862 if ( pArray[nCounter] == sServiceName )
864 return sal_True ;
867 return sal_False ;
870 /* XServiceInfo */
871 UNOSEQUENCE< UNOOUSTRING > SAL_CALL ScFilterDetect::getSupportedServiceNames() throw( UNORUNTIMEEXCEPTION )
873 return impl_getStaticSupportedServiceNames();
876 /* Helper for XServiceInfo */
877 UNOSEQUENCE< UNOOUSTRING > ScFilterDetect::impl_getStaticSupportedServiceNames()
879 UNOMUTEXGUARD aGuard( UNOMUTEX::getGlobalMutex() );
880 UNOSEQUENCE< UNOOUSTRING > seqServiceNames( 1 );
881 seqServiceNames.getArray() [0] = UNOOUSTRING::createFromAscii( "com.sun.star.frame.ExtendedTypeDetection" );
882 return seqServiceNames ;
885 /* Helper for XServiceInfo */
886 UNOOUSTRING ScFilterDetect::impl_getStaticImplementationName()
888 return UNOOUSTRING::createFromAscii( "com.sun.star.comp.calc.FormatDetector" );
891 /* Helper for registry */
892 UNOREFERENCE< UNOXINTERFACE > SAL_CALL ScFilterDetect::impl_createInstance( const UNOREFERENCE< UNOXMULTISERVICEFACTORY >& xServiceManager ) throw( UNOEXCEPTION )
894 return UNOREFERENCE< UNOXINTERFACE >( *new ScFilterDetect( xServiceManager ) );