xref: /trunk/main/sw/source/filter/ww8/ww8par.cxx (revision f6c78b21b9451944eb43023c08ad1a3c8ad54ae4)
1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 
23 
24 // MARKER(update_precomp.py): autogen include statement, do not remove
25 #include "precompiled_sw.hxx"
26 
27 #include <com/sun/star/embed/ElementModes.hpp>
28 #include <com/sun/star/embed/XStorage.hpp>
29 
30 #include <unordered_set>
31 #include <unotools/ucbstreamhelper.hxx>
32 #include <tools/solar.h>
33 #include <rtl/tencinfo.h>
34 #include <rtl/random.h>
35 
36 #include <sot/storage.hxx>
37 #include <sfx2/docinf.hxx>
38 #include <sfx2/docfile.hxx>
39 #include <sfx2/request.hxx>
40 #include <sfx2/frame.hxx>
41 #include <tools/urlobj.hxx>
42 #include <unotools/tempfile.hxx>
43 #include <svtools/sfxecode.hxx>
44 
45 #include <comphelper/docpasswordrequest.hxx>
46 #include <hintids.hxx>
47 
48 #include <editeng/tstpitem.hxx>
49 #include <editeng/cscoitem.hxx>
50 #include <svx/svdobj.hxx>
51 #include <svx/svdpage.hxx>
52 #include <editeng/paperinf.hxx>
53 #include <editeng/lrspitem.hxx> // SvxLRSpaceItem
54 #include <editeng/ulspitem.hxx>
55 #include <editeng/langitem.hxx>
56 #include <editeng/opaqitem.hxx>
57 #include <editeng/charhiddenitem.hxx>
58 #include <filter/msfilter/svxmsbas.hxx>
59 #include <svx/unoapi.hxx>
60 #include <svx/svdoole2.hxx>
61 #include <filter/msfilter/msdffimp.hxx>
62 #include <svx/svdoashp.hxx>
63 #include <svx/svxerr.hxx>
64 #include <filter/msfilter/mscodec.hxx>
65 #include <svx/svdmodel.hxx>
66 #include <svx/svdogrp.hxx>
67 #include <svx/xflclit.hxx>
68 
69 #include <unotools/fltrcfg.hxx>
70 #include <fmtfld.hxx>
71 #include <fmturl.hxx>
72 #include <fmtinfmt.hxx>
73 #include <IMark.hxx>
74 #include <reffld.hxx>
75 #include <fmthdft.hxx>
76 #include <fmtcntnt.hxx>
77 #include <fmtcnct.hxx>
78 #include <fmtanchr.hxx>
79 #include <fmtpdsc.hxx>
80 #include <ftninfo.hxx>
81 #include <fmtftn.hxx>
82 #include <txtftn.hxx>
83 #include <pam.hxx>              // fuer SwPam
84 #include <doc.hxx>
85 #include <ndtxt.hxx>            // class SwTxtNode
86 #include <pagedesc.hxx>         // class SwPageDesc
87 #include <paratr.hxx>
88 #include <fmtclds.hxx>
89 #include <fmtclbl.hxx>
90 #include <section.hxx>
91 #include <docsh.hxx>
92 #include <docufld.hxx>
93 #include <swfltopt.hxx>
94 #include <viewsh.hxx>
95 #include <shellres.hxx>
96 #include <mdiexp.hxx>           // Progress
97 #include <statstr.hrc>          // ResId fuer Statusleiste
98 #include <swerror.h>            // ERR_WW8_...
99 #include <swunodef.hxx>
100 #include <unodraw.hxx>
101 #include <swtable.hxx>          // class SwTableLines, ...
102 // #i18732#
103 #include <fmtfollowtextflow.hxx>
104 #include <fchrfmt.hxx>
105 #include <charfmt.hxx>
106 
107 
108 #include <com/sun/star/i18n/ForbiddenCharacters.hpp>
109 #include <comphelper/extract.hxx>
110 #include <comphelper/sequenceashashmap.hxx>
111 #include <fltini.hxx>
112 
113 #include <algorithm>
114 #include <functional>
115 #include "writerhelper.hxx"
116 #include "writerwordglue.hxx"
117 
118 #include "ndgrf.hxx"
119 #include <editeng/brshitem.hxx>
120 #include <editeng/editids.hrc>
121 #include <txtflcnt.hxx>
122 #include <fmtflcnt.hxx>
123 #include <txatbase.hxx>
124 
125 #include "ww8par2.hxx"          // class WW8RStyle, class WW8AnchorPara
126 
127 #include <frmatr.hxx>
128 
129 #include <math.h>
130 #include <com/sun/star/beans/XPropertyContainer.hpp>
131 
132 #include <com/sun/star/beans/PropertyAttribute.hpp>
133 #include <com/sun/star/document/XDocumentPropertiesSupplier.hpp>
134 #include <com/sun/star/document/XDocumentProperties.hpp>
135 #include <svl/itemiter.hxx>  //SfxItemIter
136 
137 #include <stdio.h>
138 
139 #ifdef DEBUG
140 #include <iostream>
141 #include <dbgoutsw.hxx>
142 #endif
143 #include <svx/hlnkitem.hxx>
144 #include "WW8Sttbf.hxx"
145 #include "WW8FibData.hxx"
146 #define MM_250 1417             // WW-Default fuer Hor. Seitenraender: 2.5 cm
147 #define MM_200 1134             // WW-Default fuer u.Seitenrand: 2.0 cm
148 
149 using namespace ::com::sun::star;
150 using namespace sw::util;
151 using namespace sw::types;
152 using namespace nsHdFtFlags;
153 
154 #define VT_EMPTY            0
155 #define VT_I4               3
156 #define VT_LPSTR            30
157 #define VT_LPWSTR           31
158 #define VT_BLOB             65
159 #define VT_TYPEMASK         0xFFF
160 /** Expands to a pointer behind the last element of a STATIC data array (like STL end()). */
161 #define STATIC_TABLE_END( array )   ((array)+STATIC_TABLE_SIZE(array))
162 /** Expands to the size of a STATIC data array. */
163 #define STATIC_TABLE_SIZE( array )  (sizeof(array)/sizeof(*(array)))
164 
GetMacroInfo(SdrObject * pObj,sal_Bool bCreate)165 SwMacroInfo* GetMacroInfo( SdrObject* pObj, sal_Bool bCreate )             // static
166 {
167     if ( pObj )
168     {
169         sal_uInt16 nCount = pObj->GetUserDataCount();
170             for( sal_uInt16 i = 0; i < nCount; i++ )
171             {
172             SdrObjUserData* pData = pObj->GetUserData( i );
173                 if( pData && pData->GetInventor() == SW_DRAWLAYER
174                     && pData->GetId() == SW_UD_IMAPDATA)
175                         return dynamic_cast<SwMacroInfo*>(pData);
176             }
177             if ( bCreate )
178             {
179             SwMacroInfo* pData = new SwMacroInfo;
180                 pObj->InsertUserData( pData, 0 );
181                 return pData;
182             }
183     }
184 
185         return 0;
186 };
187 
lclGetAbsPath(String & rPath,sal_uInt16 nLevel,SwDocShell * pDocShell)188 void lclGetAbsPath( String& rPath, sal_uInt16 nLevel, SwDocShell* pDocShell)
189 {
190     String aTmpStr;
191         while( nLevel )
192         {
193         aTmpStr.AppendAscii( "../" );
194             --nLevel;
195         }
196     if(aTmpStr.Len())
197         aTmpStr += rPath;
198     else
199         aTmpStr = rPath;
200 
201     if(aTmpStr.Len())
202     {
203         bool bWasAbs = false;
204             rPath = pDocShell->GetMedium()->GetURLObject().smartRel2Abs( aTmpStr, bWasAbs ).GetMainURL( INetURLObject::NO_DECODE );
205             // full path as stored in SvxURLField must be encoded
206     }
207 }
208 
lclIgnoreString32(SvMemoryStream & rStrm,bool b16Bit)209 void lclIgnoreString32( SvMemoryStream& rStrm, bool b16Bit )
210 {
211     sal_uInt32 nChars;
212         rStrm >> nChars;
213         if( b16Bit )
214         nChars *= 2;
215         rStrm.SeekRel( nChars );
216 }
217 
ReadRawUniString(SvMemoryStream & rStrm,sal_uInt16 nChars,bool b16Bit)218 String SwWW8ImplReader::ReadRawUniString( SvMemoryStream& rStrm,sal_uInt16 nChars, bool b16Bit )
219 {
220     // Fixed-size characters
221     const sal_uInt8 WW8_NUL_C                   = '\x00';       /// NUL character.
222     const sal_uInt16 WW8_NUL                    = WW8_NUL_C;    /// NUL character (unicode).
223     String aRet;
224     sal_Unicode         mcNulSubst = '\0';
225 
226     sal_uInt16 nCharsLeft = nChars;
227     sal_Unicode* pcBuffer = new sal_Unicode[ nCharsLeft + 1 ];
228 
229     sal_Unicode* pcUniChar = pcBuffer;
230        sal_Unicode* pcEndChar = pcBuffer + nCharsLeft;
231 
232        if( b16Bit )
233        {
234         sal_uInt16 nReadChar;
235                 for( ;  (pcUniChar < pcEndChar); ++pcUniChar )
236                 {
237                 rStrm >> (nReadChar);
238                     (*pcUniChar) = (nReadChar == WW8_NUL) ? mcNulSubst : static_cast< sal_Unicode >( nReadChar );
239                 }
240         }
241         else
242         {
243             sal_uInt8 nReadChar;
244                 for( ; (pcUniChar < pcEndChar); ++pcUniChar )
245                 {
246                 rStrm >> nReadChar ;
247                     (*pcUniChar) = (nReadChar == WW8_NUL_C) ? mcNulSubst : static_cast< sal_Unicode >( nReadChar );
248                 }
249         }
250 
251        *pcEndChar = '\0';
252        aRet.Append( pcBuffer );
253     delete[] pcBuffer;
254     return aRet;
255 }
256 
lclAppendString32(String & rString,SvMemoryStream & rStrm,sal_uInt32 nChars,bool b16Bit)257 void lclAppendString32( String& rString, SvMemoryStream& rStrm, sal_uInt32 nChars, bool b16Bit )
258 {
259     sal_uInt16 nReadChars = ulimit_cast< sal_uInt16 >( nChars );
260     String urlStr = SwWW8ImplReader::ReadRawUniString( rStrm, nReadChars, b16Bit );
261         rString.Append( urlStr );
262 }
263 
lclAppendString32(String & rString,SvMemoryStream & rStrm,bool b16Bit)264 void lclAppendString32( String& rString, SvMemoryStream& rStrm, bool b16Bit )
265 {
266     sal_uInt32 nValue;
267         rStrm >>( nValue );
268         lclAppendString32( rString, rStrm, nValue, b16Bit );
269 }
270 
ReadEmbeddedData(SvMemoryStream & rStrm,SwDocShell * pDocShell,struct HyperLinksTable & hlStr)271 void SwWW8ImplReader::ReadEmbeddedData( SvMemoryStream& rStrm, SwDocShell* pDocShell, struct HyperLinksTable& hlStr)
272 {
273     // (0x01B8) HLINK -------------------------------------------------------------
274     // const sal_uInt16 WW8_ID_HLINK               = 0x01B8;
275     const sal_uInt32 WW8_HLINK_BODY             = 0x00000001;   /// Contains file link or URL.
276     const sal_uInt32 WW8_HLINK_ABS              = 0x00000002;   /// Absolute path.
277     const sal_uInt32 WW8_HLINK_DESCR            = 0x00000014;   /// Description.
278     const sal_uInt32 WW8_HLINK_MARK             = 0x00000008;   /// Text mark.
279     const sal_uInt32 WW8_HLINK_FRAME            = 0x00000080;   /// Target frame.
280     const sal_uInt32 WW8_HLINK_UNC              = 0x00000100;   /// UNC path.
281 
282     //  sal_uInt8 maGuidStdLink[ 16 ] ={
283     //      0xD0, 0xC9, 0xEA, 0x79, 0xF9, 0xBA, 0xCE, 0x11, 0x8C, 0x82, 0x00, 0xAA, 0x00, 0x4B, 0xA9, 0x0B };
284 
285     sal_uInt8 maGuidUrlMoniker[ 16 ] = {
286         0xE0, 0xC9, 0xEA, 0x79, 0xF9, 0xBA, 0xCE, 0x11, 0x8C, 0x82, 0x00, 0xAA, 0x00, 0x4B, 0xA9, 0x0B };
287 
288     sal_uInt8 maGuidFileMoniker[ 16 ] = {
289         0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 };
290 
291     sal_uInt8*  aGuid = new sal_uInt8[ 16 ];
292     sal_uInt32 nFlags;
293 
294 
295         rStrm.Read( aGuid, 16);
296         rStrm.SeekRel( 4 );
297         rStrm >> nFlags;
298 
299         sal_uInt16 nLevel = 0;                  // counter for level to climb down in path
300         ::std::unique_ptr< String > xLongName;    // link / file name
301         ::std::unique_ptr< String > xShortName;   // 8.3-representation of file name
302         ::std::unique_ptr< String > xTextMark;    // text mark
303 
304     // description (ignore)
305         if( ::get_flag( nFlags, WW8_HLINK_DESCR ) )
306         lclIgnoreString32( rStrm, true );
307 
308     // target frame
309         if( ::get_flag( nFlags, WW8_HLINK_FRAME ) )
310     {
311         ::std::unique_ptr< String > FrmName;
312         FrmName.reset( new String );
313         lclAppendString32(*FrmName , rStrm , true);
314         hlStr.tarFrm = *FrmName;
315     }
316 
317         // UNC path
318     if( ::get_flag( nFlags, WW8_HLINK_UNC ) )
319         {
320         xLongName.reset( new String );
321             lclAppendString32( *xLongName, rStrm, true );
322         lclGetAbsPath( *xLongName, 0 , pDocShell);
323         }
324         // file link or URL
325         else if( ::get_flag( nFlags, WW8_HLINK_BODY ) )
326         {
327             rStrm.Read( aGuid, 16);
328 
329             if( (memcmp(aGuid, maGuidFileMoniker, 16) == 0) )
330             {
331                     rStrm >> nLevel;
332                     xShortName.reset( new String );
333             lclAppendString32( *xShortName,rStrm, false );
334             rStrm.SeekRel( 24 );
335 
336                     sal_uInt32 nStrLen;
337                     rStrm >> nStrLen;
338                     if( nStrLen )
339                     {
340                         rStrm >> nStrLen;
341                         nStrLen /= 2;
342                         rStrm.SeekRel( 2 );
343                         xLongName.reset( new String );
344                 lclAppendString32( *xLongName, rStrm,nStrLen, true );
345                 lclGetAbsPath( *xLongName, nLevel, pDocShell);
346                     }
347                     else
348                 lclGetAbsPath( *xShortName, nLevel, pDocShell);
349             }
350             else    if( (memcmp(aGuid, maGuidUrlMoniker, 16) == 0) )
351             {
352             sal_uInt32 nStrLen;
353                     rStrm >> nStrLen;
354                     nStrLen /= 2;
355                     xLongName.reset( new String );
356             lclAppendString32( *xLongName,rStrm, nStrLen, true );
357                     if( !::get_flag( nFlags, WW8_HLINK_ABS ) )
358                 lclGetAbsPath( *xLongName, 0 ,pDocShell);
359             }
360             else
361             {
362                 DBG_ERRORFILE( "WW8Hyperlink::ReadEmbeddedData - unknown content GUID" );
363             }
364     }
365 
366     // text mark
367         if( ::get_flag( nFlags, WW8_HLINK_MARK ) )
368         {
369         xTextMark.reset( new String );
370             lclAppendString32( *xTextMark, rStrm, true );
371         }
372 
373     if( !xLongName.get() && xShortName.get() )
374     {
375         xLongName.reset( new String );
376         xLongName->Append(*xShortName);
377     }
378         else if( !xLongName.get() && xTextMark.get() )
379         xLongName.reset( new String );
380 
381         if( xLongName.get() )
382         {
383         if( xTextMark.get() )
384             {
385                     if( xLongName->Len() == 0 )
386                         xTextMark->SearchAndReplaceAll( '!', '.' );
387                     xLongName->Append( '#' );
388                     xLongName->Append( *xTextMark );
389             }
390         hlStr.hLinkAddr = *xLongName;
391         }
392 }
393 
SwMSDffManager(SwWW8ImplReader & rRdr)394 SwMSDffManager::SwMSDffManager( SwWW8ImplReader& rRdr )
395     : SvxMSDffManager(*rRdr.pTableStream, rRdr.GetBaseURL(), rRdr.pWwFib->fcDggInfo,
396         rRdr.pDataStream, 0, 0, COL_WHITE, 12, rRdr.pStrm,
397         rRdr.maTracer.GetTrace()),
398     rReader(rRdr), pFallbackStream(0), pOldEscherBlipCache(0)
399 {
400     SetSvxMSDffSettings( GetSvxMSDffSettings() );
401     nSvxMSDffOLEConvFlags = SwMSDffManager::GetFilterFlags();
402 }
403 
GetFilterFlags()404 sal_uInt32 SwMSDffManager::GetFilterFlags()
405 {
406     sal_uInt32 nFlags(0);
407     if (const SvtFilterOptions* pOpt = SvtFilterOptions::Get())
408     {
409         if (pOpt->IsMathType2Math())
410             nFlags |= OLE_MATHTYPE_2_STARMATH;
411         if (pOpt->IsExcel2Calc())
412             nFlags |= OLE_EXCEL_2_STARCALC;
413         if (pOpt->IsPowerPoint2Impress())
414             nFlags |= OLE_POWERPOINT_2_STARIMPRESS;
415         if (pOpt->IsWinWord2Writer())
416             nFlags |= OLE_WINWORD_2_STARWRITER;
417     }
418     return nFlags;
419 }
420 
421 /*
422  * I would like to override the default OLE importing to add a test
423  * and conversion of OCX controls from their native OLE type into our
424  * native nonOLE Form Control Objects.
425  *
426  * cmc
427  */
428 // #i32596# - consider new parameter <_nCalledByGroup>
ImportOLE(long nOLEId,const Graphic & rGrf,const Rectangle & rBoundRect,const Rectangle & rVisArea,const int _nCalledByGroup,sal_Int64 nAspect) const429 SdrObject* SwMSDffManager::ImportOLE( long nOLEId,
430                                       const Graphic& rGrf,
431                                       const Rectangle& rBoundRect,
432                                       const Rectangle& rVisArea,
433                                       const int _nCalledByGroup,
434                                       sal_Int64 nAspect ) const
435 {
436     // #i32596# - no import of OLE object, if it's inside a group.
437     // NOTE: This can be undone, if grouping of Writer fly frames is possible or
438     // if drawing OLE objects are allowed in Writer.
439     if ( _nCalledByGroup > 0 )
440     {
441         return 0L;
442     }
443 
444     SdrObject* pRet = 0;
445     String sStorageName;
446     SotStorageRef xSrcStg;
447     uno::Reference < embed::XStorage > xDstStg;
448     if( GetOLEStorageName( nOLEId, sStorageName, xSrcStg, xDstStg ))
449     {
450         SvStorageRef xSrc = xSrcStg->OpenSotStorage( sStorageName,
451             STREAM_READWRITE| STREAM_SHARE_DENYALL );
452         ASSERT(rReader.pFormImpl, "No Form Implementation!");
453         STAR_REFERENCE( drawing::XShape ) xShape;
454         if ( (!(rReader.bIsHeader || rReader.bIsFooter)) &&
455             rReader.pFormImpl->ReadOCXStream(xSrc,&xShape,true))
456         {
457             pRet = GetSdrObjectFromXShape(xShape);
458         }
459         else
460         {
461             ErrCode nError = ERRCODE_NONE;
462             pRet = CreateSdrOLEFromStorage( sStorageName, xSrcStg, xDstStg,
463                 rGrf, rBoundRect, rVisArea, pStData, nError, nSvxMSDffOLEConvFlags, nAspect );
464         }
465     }
466     return pRet;
467 }
468 
DisableFallbackStream()469 void SwMSDffManager::DisableFallbackStream()
470 {
471     ASSERT(!pFallbackStream || !pOldEscherBlipCache,
472         "if you're recursive, you're broken");
473     pFallbackStream = pStData2;
474     pOldEscherBlipCache = pEscherBlipCache;
475     pEscherBlipCache = 0;
476     pStData2 = 0;
477 }
478 
EnableFallbackStream()479 void SwMSDffManager::EnableFallbackStream()
480 {
481     pStData2 = pFallbackStream;
482     pEscherBlipCache = pOldEscherBlipCache;
483     pOldEscherBlipCache = 0;
484     pFallbackStream = 0;
485 }
486 
GetToggleAttrFlags() const487 sal_uInt16 SwWW8ImplReader::GetToggleAttrFlags() const
488 {
489     return pCtrlStck ? pCtrlStck->GetToggleAttrFlags() : 0;
490 }
491 
GetToggleBiDiAttrFlags() const492 sal_uInt16 SwWW8ImplReader::GetToggleBiDiAttrFlags() const
493 {
494     return pCtrlStck ? pCtrlStck->GetToggleBiDiAttrFlags() : 0;
495 }
496 
SetToggleAttrFlags(sal_uInt16 nFlags)497 void SwWW8ImplReader::SetToggleAttrFlags(sal_uInt16 nFlags)
498 {
499     if (pCtrlStck)
500         pCtrlStck->SetToggleAttrFlags(nFlags);
501 }
502 
SetToggleBiDiAttrFlags(sal_uInt16 nFlags)503 void SwWW8ImplReader::SetToggleBiDiAttrFlags(sal_uInt16 nFlags)
504 {
505     if (pCtrlStck)
506         pCtrlStck->SetToggleBiDiAttrFlags(nFlags);
507 }
508 
509 
ProcessObj(SvStream & rSt,DffObjData & rObjData,void * pData,Rectangle & rTextRect,SdrObject * pObj)510 SdrObject* SwMSDffManager::ProcessObj(SvStream& rSt,
511                                        DffObjData& rObjData,
512                                        void* pData,
513                                        Rectangle& rTextRect,
514                                        SdrObject* pObj
515                                        )
516 {
517     if( !rTextRect.IsEmpty() )
518     {
519         SvxMSDffImportData& rImportData = *(SvxMSDffImportData*)pData;
520         SvxMSDffImportRec* pImpRec = new SvxMSDffImportRec;
521 
522         // fill Import Record with data
523         pImpRec->nShapeId   = rObjData.nShapeId;
524         pImpRec->eShapeType = rObjData.eShapeType;
525 
526         rObjData.bClientAnchor = maShapeRecords.SeekToContent( rSt,
527                                             DFF_msofbtClientAnchor,
528                                             SEEK_FROM_CURRENT_AND_RESTART );
529         if( rObjData.bClientAnchor )
530             ProcessClientAnchor( rSt,
531                     maShapeRecords.Current()->nRecLen,
532                     pImpRec->pClientAnchorBuffer, pImpRec->nClientAnchorLen );
533 
534         rObjData.bClientData = maShapeRecords.SeekToContent( rSt,
535                                             DFF_msofbtClientData,
536                                             SEEK_FROM_CURRENT_AND_RESTART );
537         if( rObjData.bClientData )
538             ProcessClientData( rSt,
539                     maShapeRecords.Current()->nRecLen,
540                     pImpRec->pClientDataBuffer, pImpRec->nClientDataLen );
541 
542 
543         // process user (== Winword) defined parameters in 0xF122 record
544         // #i84783# - set special value to determine, if property is provided or not.
545         pImpRec->nLayoutInTableCell = 0xFFFFFFFF;
546         if(    maShapeRecords.SeekToContent( rSt,
547                                              DFF_msofbtUDefProp,
548                                              SEEK_FROM_CURRENT_AND_RESTART )
549             && maShapeRecords.Current()->nRecLen )
550         {
551             sal_uInt32  nBytesLeft = maShapeRecords.Current()->nRecLen;
552             sal_uInt32  nUDData;
553             sal_uInt16  nPID;
554             while( 5 < nBytesLeft )
555             {
556                 rSt >> nPID;
557                 if ( rSt.GetError() != 0 )
558                     break;
559                 rSt >> nUDData;
560                 switch( nPID )
561                 {
562                     case 0x038F: pImpRec->nXAlign = nUDData; break;
563                     case 0x0390: pImpRec->nXRelTo = nUDData; break;
564                     case 0x0391: pImpRec->nYAlign = nUDData; break;
565                     case 0x0392: pImpRec->nYRelTo = nUDData; break;
566                     case 0x03BF: pImpRec->nLayoutInTableCell = nUDData; break;
567                 }
568                 if ( rSt.GetError() != 0 )
569                     break;
570                 pImpRec->bHasUDefProp = sal_True;
571                 nBytesLeft  -= 6;
572             }
573         }
574 
575         //  Textrahmen, auch Title oder Outline
576         sal_uInt32 nTextId = GetPropertyValue( DFF_Prop_lTxid, 0 );
577         if( nTextId )
578         {
579             SfxItemSet aSet( pSdrModel->GetItemPool() );
580 
581             //Originally anything that as a mso_sptTextBox was created as a
582             //textbox, this was changed to be created as a simple
583             //rect to keep impress happy. For the rest of us we'd like to turn
584             //it back into a textbox again.
585             sal_Bool bIsSimpleDrawingTextBox = (pImpRec->eShapeType == mso_sptTextBox);
586             if (!bIsSimpleDrawingTextBox)
587             {
588                 //Either
589                 //a) its a simple text object or
590                 //b) its a rectangle with text and square wrapping.
591                 bIsSimpleDrawingTextBox =
592                 (
593                     (pImpRec->eShapeType == mso_sptTextSimple) ||
594                     (
595                         (pImpRec->eShapeType == mso_sptRectangle)
596                         // && (eWrapMode == mso_wrapSquare)
597                         && ShapeHasText(pImpRec->nShapeId, rObjData.rSpHd.GetRecBegFilePos() )
598                     )
599                 );
600             }
601 
602             // Distance of Textbox to it's surrounding Autoshape
603             sal_Int32 nTextLeft = GetPropertyValue( DFF_Prop_dxTextLeft, 91440L);
604             sal_Int32 nTextRight = GetPropertyValue( DFF_Prop_dxTextRight, 91440L );
605             sal_Int32 nTextTop = GetPropertyValue( DFF_Prop_dyTextTop, 45720L  );
606             sal_Int32 nTextBottom = GetPropertyValue( DFF_Prop_dyTextBottom, 45720L );
607 
608             ScaleEmu( nTextLeft );
609             ScaleEmu( nTextRight );
610             ScaleEmu( nTextTop );
611             ScaleEmu( nTextBottom );
612 
613             sal_Int32 nTextRotationAngle=0;
614             bool bVerticalText = false;
615             if ( IsProperty( DFF_Prop_txflTextFlow ) )
616             {
617                 MSO_TextFlow eTextFlow = (MSO_TextFlow)(GetPropertyValue(
618                     DFF_Prop_txflTextFlow) & 0xFFFF);
619                 switch( eTextFlow )
620                 {
621                     case mso_txflBtoT:
622                         nTextRotationAngle = 9000;
623                     break;
624                     case mso_txflVertN:
625                     case mso_txflTtoBN:
626                         nTextRotationAngle = 27000;
627                         break;
628                     case mso_txflTtoBA:
629                         bVerticalText = true;
630                     break;
631                     case mso_txflHorzA:
632                         bVerticalText = true;
633                         nTextRotationAngle = 9000;
634                     case mso_txflHorzN:
635                     default :
636                         break;
637                 }
638             }
639 
640             if (nTextRotationAngle)
641             {
642                 while (nTextRotationAngle > 360000)
643                     nTextRotationAngle-=9000;
644                 switch (nTextRotationAngle)
645                 {
646                     case 9000:
647                         {
648                             long nWidth = rTextRect.GetWidth();
649                             rTextRect.Right() = rTextRect.Left() + rTextRect.GetHeight();
650                             rTextRect.Bottom() = rTextRect.Top() + nWidth;
651 
652                             sal_Int32 nOldTextLeft = nTextLeft;
653                             sal_Int32 nOldTextRight = nTextRight;
654                             sal_Int32 nOldTextTop = nTextTop;
655                             sal_Int32 nOldTextBottom = nTextBottom;
656 
657                             nTextLeft = nOldTextBottom;
658                             nTextRight = nOldTextTop;
659                             nTextTop = nOldTextLeft;
660                             nTextBottom = nOldTextRight;
661                         }
662                         break;
663                     case 27000:
664                         {
665                             long nWidth = rTextRect.GetWidth();
666                             rTextRect.Right() = rTextRect.Left() + rTextRect.GetHeight();
667                             rTextRect.Bottom() = rTextRect.Top() + nWidth;
668 
669                             sal_Int32 nOldTextLeft = nTextLeft;
670                             sal_Int32 nOldTextRight = nTextRight;
671                             sal_Int32 nOldTextTop = nTextTop;
672                             sal_Int32 nOldTextBottom = nTextBottom;
673 
674                             nTextLeft = nOldTextTop;
675                             nTextRight = nOldTextBottom;
676                             nTextTop = nOldTextRight;
677                             nTextBottom = nOldTextLeft;
678                         }
679                         break;
680                     default:
681                         break;
682                 }
683             }
684 
685             if (bIsSimpleDrawingTextBox)
686             {
687                 SdrObject::Free( pObj );
688                 pObj = new SdrRectObj(OBJ_TEXT, rTextRect);
689             }
690 
691             // Die vertikalen Absatzeinrueckungen sind im BoundRect mit drin,
692             // hier rausrechnen
693             Rectangle aNewRect(rTextRect);
694             aNewRect.Bottom() -= nTextTop + nTextBottom;
695             aNewRect.Right() -= nTextLeft + nTextRight;
696 
697             // Nur falls es eine einfache Textbox ist, darf der Writer
698             // das Objekt durch einen Rahmen ersetzen, ansonsten
699             if( bIsSimpleDrawingTextBox )
700             {
701                 SvxMSDffShapeInfo aTmpRec( 0, pImpRec->nShapeId );
702                 aTmpRec.bSortByShapeId = sal_True;
703 
704                 sal_uInt16 nFound;
705                 if( GetShapeInfos()->Seek_Entry( &aTmpRec, &nFound ) )
706                 {
707                     SvxMSDffShapeInfo& rInfo = *GetShapeInfos()->GetObject(nFound);
708                     pImpRec->bReplaceByFly   = rInfo.bReplaceByFly;
709                     pImpRec->bLastBoxInChain = rInfo.bLastBoxInChain;
710                 }
711             }
712 
713             if( bIsSimpleDrawingTextBox )
714                 ApplyAttributes( rSt, aSet, rObjData );
715 
716             bool bFitText = false;
717             if (GetPropertyValue(DFF_Prop_FitTextToShape) & 2)
718             {
719                 aSet.Put( SdrTextAutoGrowHeightItem( sal_True ) );
720                 aSet.Put( SdrTextMinFrameHeightItem(
721                     aNewRect.Bottom() - aNewRect.Top() ) );
722                 aSet.Put( SdrTextMinFrameWidthItem(
723                     aNewRect.Right() - aNewRect.Left() ) );
724                 bFitText = true;
725             }
726             else
727             {
728                 aSet.Put( SdrTextAutoGrowHeightItem( sal_False ) );
729                 aSet.Put( SdrTextAutoGrowWidthItem( sal_False ) );
730             }
731 
732             switch ( (MSO_WrapMode)
733                 GetPropertyValue( DFF_Prop_WrapText, mso_wrapSquare ) )
734             {
735                 case mso_wrapNone :
736                     aSet.Put( SdrTextAutoGrowWidthItem( sal_True ) );
737                     pImpRec->bAutoWidth = true;
738                 break;
739                 case mso_wrapByPoints :
740                     aSet.Put( SdrTextContourFrameItem( sal_True ) );
741                 break;
742                 default:
743                     ;
744             }
745 
746             // Abstaende an den Raendern der Textbox setzen
747             aSet.Put( SdrTextLeftDistItem( nTextLeft ) );
748             aSet.Put( SdrTextRightDistItem( nTextRight ) );
749             aSet.Put( SdrTextUpperDistItem( nTextTop ) );
750             aSet.Put( SdrTextLowerDistItem( nTextBottom ) );
751             pImpRec->nDxTextLeft    = nTextLeft;
752             pImpRec->nDyTextTop     = nTextTop;
753             pImpRec->nDxTextRight   = nTextRight;
754             pImpRec->nDyTextBottom  = nTextBottom;
755 
756             // --> SJ 2009-03-06 : taking the correct default (which is mso_anchorTop)
757             MSO_Anchor eTextAnchor =
758                 (MSO_Anchor)GetPropertyValue( DFF_Prop_anchorText, mso_anchorTop );
759 
760             SdrTextVertAdjust eTVA = bVerticalText
761                                      ? SDRTEXTVERTADJUST_BLOCK
762                                      : SDRTEXTVERTADJUST_CENTER;
763             SdrTextHorzAdjust eTHA = bVerticalText
764                                      ? SDRTEXTHORZADJUST_CENTER
765                                      : SDRTEXTHORZADJUST_BLOCK;
766 
767             switch( eTextAnchor )
768             {
769                 case mso_anchorTop:
770                 {
771                     if ( bVerticalText )
772                         eTHA = SDRTEXTHORZADJUST_RIGHT;
773                     else
774                         eTVA = SDRTEXTVERTADJUST_TOP;
775                 }
776                 break;
777                 case mso_anchorTopCentered:
778                 {
779                     if ( bVerticalText )
780                         eTHA = SDRTEXTHORZADJUST_RIGHT;
781                     else
782                         eTVA = SDRTEXTVERTADJUST_TOP;
783                 }
784                 break;
785                 case mso_anchorMiddle:
786                 break;
787                 case mso_anchorMiddleCentered:
788                 break;
789                 case mso_anchorBottom:
790                 {
791                     if ( bVerticalText )
792                         eTHA = SDRTEXTHORZADJUST_LEFT;
793                     else
794                         eTVA = SDRTEXTVERTADJUST_BOTTOM;
795                 }
796                 break;
797                 case mso_anchorBottomCentered:
798                 {
799                     if ( bVerticalText )
800                         eTHA = SDRTEXTHORZADJUST_LEFT;
801                     else
802                         eTVA = SDRTEXTVERTADJUST_BOTTOM;
803                 }
804                 break;
805 /*
806                 case mso_anchorTopBaseline:
807                 case mso_anchorBottomBaseline:
808                 case mso_anchorTopCenteredBaseline:
809                 case mso_anchorBottomCenteredBaseline:
810                 break;
811 */
812                 default:
813                     ;
814             }
815 
816             aSet.Put( SdrTextVertAdjustItem( eTVA ) );
817             aSet.Put( SdrTextHorzAdjustItem( eTHA ) );
818 
819             if (pObj != NULL)
820             {
821                 pObj->SetMergedItemSet(aSet);
822                 pObj->SetModel(pSdrModel);
823 
824                 if (bVerticalText && dynamic_cast< SdrTextObj* >( pObj ) )
825                     dynamic_cast< SdrTextObj* >( pObj )->SetVerticalWriting(sal_True);
826 
827                 if ( bIsSimpleDrawingTextBox )
828                 {
829                     if ( nTextRotationAngle )
830                     {
831                         long nMinWH = rTextRect.GetWidth() < rTextRect.GetHeight() ?
832                             rTextRect.GetWidth() : rTextRect.GetHeight();
833                         nMinWH /= 2;
834                         Point aPivot(rTextRect.TopLeft());
835                         aPivot.X() += nMinWH;
836                         aPivot.Y() += nMinWH;
837                         double a = nTextRotationAngle * nPi180;
838                         pObj->NbcRotate(aPivot, nTextRotationAngle, sin(a), cos(a));
839                     }
840                 }
841 
842                 if ( ( ( rObjData.nSpFlags & SP_FFLIPV ) || mnFix16Angle || nTextRotationAngle ) && dynamic_cast< SdrObjCustomShape* >( pObj ) )
843                 {
844                     SdrObjCustomShape* pCustomShape = dynamic_cast< SdrObjCustomShape* >( pObj );
845 
846                     double fExtraTextRotation = 0.0;
847                     if ( mnFix16Angle && !( GetPropertyValue( DFF_Prop_FitTextToShape ) & 4 ) )
848                     {   // text is already rotated, we have to take back the object rotation if DFF_Prop_RotateText is false
849                         fExtraTextRotation = -mnFix16Angle;
850                     }
851                     if ( rObjData.nSpFlags & SP_FFLIPV )    // sj: in ppt the text is flipped, whereas in word the text
852                     {                                       // remains unchanged, so we have to take back the flipping here
853                         fExtraTextRotation += 18000.0;      // because our core will flip text if the shape is flipped.
854                     }
855                     fExtraTextRotation += nTextRotationAngle;
856                     if ( !::basegfx::fTools::equalZero( fExtraTextRotation ) )
857                     {
858                         fExtraTextRotation /= 100.0;
859                         SdrCustomShapeGeometryItem aGeometryItem( (SdrCustomShapeGeometryItem&)pCustomShape->GetMergedItem( SDRATTR_CUSTOMSHAPE_GEOMETRY ) );
860                         const rtl::OUString sTextRotateAngle( RTL_CONSTASCII_USTRINGPARAM ( "TextRotateAngle" ) );
861                         com::sun::star::beans::PropertyValue aPropVal;
862                         aPropVal.Name = sTextRotateAngle;
863                         aPropVal.Value <<= fExtraTextRotation;
864                         aGeometryItem.SetPropertyValue( aPropVal );
865                         pCustomShape->SetMergedItem( aGeometryItem );
866                     }
867                 }
868                 else if ( mnFix16Angle )
869                 {
870                     // rotate text with shape ?
871                     double a = mnFix16Angle * nPi180;
872                     pObj->NbcRotate( rObjData.aBoundRect.Center(), mnFix16Angle,
873                                      sin( a ), cos( a ) );
874                 }
875             }
876         }
877         else if( !pObj )
878         {
879             // simple rectangular objects are ignored by ImportObj()  :-(
880             // this is OK for Draw but not for Calc and Writer
881             // cause here these objects have a default border
882             pObj = new SdrRectObj(rTextRect);
883             pObj->SetModel( pSdrModel );
884             SfxItemSet aSet( pSdrModel->GetItemPool() );
885             ApplyAttributes( rSt, aSet, rObjData );
886 
887             const SfxPoolItem* pPoolItem=NULL;
888             SfxItemState eState = aSet.GetItemState( XATTR_FILLCOLOR,
889                                                      sal_False, &pPoolItem );
890             if( SFX_ITEM_DEFAULT == eState )
891                 aSet.Put( XFillColorItem( String(),
892                           Color( mnDefaultColor ) ) );
893             pObj->SetMergedItemSet(aSet);
894         }
895 
896         //Means that fBehindDocument is set
897         if (GetPropertyValue(DFF_Prop_fPrint) & 0x20)
898             pImpRec->bDrawHell = sal_True;
899         else
900             pImpRec->bDrawHell = sal_False;
901         if (GetPropertyValue(DFF_Prop_fPrint) & 0x02)
902             pImpRec->bHidden = sal_True;
903         pImpRec->nNextShapeId   = GetPropertyValue( DFF_Prop_hspNext, 0 );
904 
905         if ( nTextId )
906         {
907             pImpRec->aTextId.nTxBxS = (sal_uInt16)( nTextId >> 16 );
908             pImpRec->aTextId.nSequence = (sal_uInt16)nTextId;
909         }
910 
911         pImpRec->nDxWrapDistLeft = GetPropertyValue(
912                                     DFF_Prop_dxWrapDistLeft, 114935L ) / 635L;
913         pImpRec->nDyWrapDistTop = GetPropertyValue(
914                                     DFF_Prop_dyWrapDistTop, 0 ) / 635L;
915         pImpRec->nDxWrapDistRight = GetPropertyValue(
916                                     DFF_Prop_dxWrapDistRight, 114935L ) / 635L;
917         pImpRec->nDyWrapDistBottom = GetPropertyValue(
918                                     DFF_Prop_dyWrapDistBottom, 0 ) / 635L;
919         // 16.16 fraction times total image width or height, as appropriate.
920 
921         if (SeekToContent(DFF_Prop_pWrapPolygonVertices, rSt))
922         {
923             delete pImpRec->pWrapPolygon;
924             pImpRec->pWrapPolygon = NULL;
925 
926             sal_uInt16 nNumElemVert, nNumElemMemVert, nElemSizeVert;
927             rSt >> nNumElemVert >> nNumElemMemVert >> nElemSizeVert;
928             if (nNumElemVert && ((nElemSizeVert == 8) || (nElemSizeVert == 4)))
929             {
930                 pImpRec->pWrapPolygon = new Polygon(nNumElemVert);
931                 for (sal_uInt16 i = 0; i < nNumElemVert; ++i)
932                 {
933                     sal_Int32 nX, nY;
934                     if (nElemSizeVert == 8)
935                         rSt >> nX >> nY;
936                     else
937                     {
938                         sal_Int16 nSmallX, nSmallY;
939                         rSt >> nSmallX >> nSmallY;
940                         nX = nSmallX;
941                         nY = nSmallY;
942                     }
943                     (*(pImpRec->pWrapPolygon))[i].X() = nX;
944                     (*(pImpRec->pWrapPolygon))[i].Y() = nY;
945                 }
946             }
947         }
948 
949         pImpRec->nCropFromTop = GetPropertyValue(
950                                     DFF_Prop_cropFromTop, 0 );
951         pImpRec->nCropFromBottom = GetPropertyValue(
952                                     DFF_Prop_cropFromBottom, 0 );
953         pImpRec->nCropFromLeft = GetPropertyValue(
954                                     DFF_Prop_cropFromLeft, 0 );
955         pImpRec->nCropFromRight = GetPropertyValue(
956                                     DFF_Prop_cropFromRight, 0 );
957 
958         sal_uInt32 nLineFlags = GetPropertyValue( DFF_Prop_fNoLineDrawDash );
959         if ( !IsHardAttribute( DFF_Prop_fLine ) &&
960              pImpRec->eShapeType == mso_sptPictureFrame )
961         {
962             nLineFlags &= ~0x08;
963         }
964         pImpRec->eLineStyle = (nLineFlags & 8)
965                               ? (MSO_LineStyle)GetPropertyValue(
966                                                     DFF_Prop_lineStyle,
967                                                     mso_lineSimple )
968                               : mso_lineNone;
969 
970         pImpRec->nFlags = rObjData.nSpFlags;
971 
972         if( pImpRec->nShapeId )
973         {
974             // Import-Record-Liste ergaenzen
975             pImpRec->pObj = pObj;
976             rImportData.aRecords.Insert( pImpRec );
977 
978             // Eintrag in Z-Order-Liste um Zeiger auf dieses Objekt ergaenzen
979             /*Only store objects which are not deep inside the tree*/
980             if( ( rObjData.nCalledByGroup == 0 )
981                 ||
982                 ( (rObjData.nSpFlags & SP_FGROUP)
983                  && (rObjData.nCalledByGroup < 2) )
984               )
985                 StoreShapeOrder( pImpRec->nShapeId,
986                                 ( ( (sal_uLong)pImpRec->aTextId.nTxBxS ) << 16 )
987                                     + pImpRec->aTextId.nSequence, pObj );
988         }
989         else
990             delete pImpRec;
991     }
992 
993     sal_uInt32 nBufferSize = GetPropertyValue( DFF_Prop_pihlShape );
994      if( (0 < nBufferSize) && (nBufferSize <= 0xFFFF) && SeekToContent( DFF_Prop_pihlShape, rSt ) )
995     {
996         SvMemoryStream aMemStream;
997         String aStrURL;
998         struct HyperLinksTable hlStr;
999         sal_uInt16 mnRawRecId,mnRawRecSize;
1000         aMemStream << sal_uInt16( 0 ) << static_cast< sal_uInt16 >( nBufferSize );
1001 
1002         // copy from DFF stream to memory stream
1003         ::std::vector< sal_uInt8 > aBuffer( nBufferSize );
1004         sal_uInt8* pnData = &aBuffer.front();
1005         sal_uInt8 mnStreamSize;
1006         if( pnData && rSt.Read( pnData, nBufferSize ) == nBufferSize )
1007         {
1008             aMemStream.Write( pnData, nBufferSize );
1009             aMemStream.Seek( STREAM_SEEK_TO_END );
1010             mnStreamSize = aMemStream.Tell();
1011             aMemStream.Seek( STREAM_SEEK_TO_BEGIN );
1012             bool bRet =  4 <= mnStreamSize;
1013             if( bRet )
1014                 aMemStream >> mnRawRecId >> mnRawRecSize;
1015             SwDocShell* pDocShell = rReader.mpDocShell;
1016             if(pDocShell)
1017             {
1018                 rReader.ReadEmbeddedData( aMemStream, pDocShell, hlStr);
1019             }
1020         }
1021 
1022         if(pObj && hlStr.hLinkAddr.Len() > 0)
1023         {
1024             SwMacroInfo* pInfo = GetMacroInfo( pObj, true );
1025             if( pInfo )
1026             {
1027                 pInfo->SetShapeId( rObjData.nShapeId );
1028                 pInfo->SetHlink( hlStr.hLinkAddr );
1029                 if(hlStr.tarFrm.Len() > 0)
1030                     pInfo->SetTarFrm( hlStr.tarFrm );
1031                 String aNameStr = GetPropertyString( DFF_Prop_wzName, rSt );
1032                 if(aNameStr.Len() > 0)
1033                     pInfo->SetName( aNameStr );
1034             }
1035         }
1036         }
1037 
1038     return pObj;
1039 }
1040 
1041 /***************************************************************************
1042 #  Spezial FastSave - Attribute
1043 #**************************************************************************/
1044 
Read_StyleCode(sal_uInt16,const sal_uInt8 * pData,short nLen)1045 void SwWW8ImplReader::Read_StyleCode( sal_uInt16, const sal_uInt8* pData, short nLen )
1046 {
1047     if (nLen < 0)
1048     {
1049         bCpxStyle = false;
1050         return;
1051     }
1052     sal_uInt16 nColl = 0;
1053     if (pWwFib->GetFIBVersion() <= ww::eWW2)
1054         nColl = *pData;
1055     else
1056         nColl = SVBT16ToShort(pData);
1057     if (nColl < nColls)
1058     {
1059         SetTxtFmtCollAndListLevel( *pPaM, pCollA[nColl] );
1060         bCpxStyle = true;
1061     }
1062 }
1063 
1064 // Read_Majority ist fuer Majority ( 103 ) und Majority50 ( 108 )
Read_Majority(sal_uInt16,const sal_uInt8 *,short)1065 void SwWW8ImplReader::Read_Majority( sal_uInt16, const sal_uInt8* , short )
1066 {
1067 }
1068 
1069 //-----------------------------------------
1070 //            Stack
1071 //-----------------------------------------
NewAttr(const SwPosition & rPos,const SfxPoolItem & rAttr)1072 void SwWW8FltControlStack::NewAttr(const SwPosition& rPos,
1073     const SfxPoolItem& rAttr)
1074 {
1075     ASSERT(RES_TXTATR_FIELD != rAttr.Which(), "probably don't want to put"
1076         "fields into the control stack");
1077     ASSERT(RES_TXTATR_ANNOTATION != rAttr.Which(), "probably don't want to put"
1078         "annotations into the control stack");
1079     ASSERT(RES_TXTATR_INPUTFIELD != rAttr.Which(), "probably don't want to put"
1080         "input fields into the control stack");
1081     ASSERT(RES_FLTR_REDLINE != rAttr.Which(), "probably don't want to put"
1082         "redlines into the control stack");
1083     SwFltControlStack::NewAttr(rPos, rAttr);
1084 }
1085 
SetAttr(const SwPosition & rPos,sal_uInt16 nAttrId,sal_Bool bTstEnde,long nHand,sal_Bool)1086 void SwWW8FltControlStack::SetAttr(const SwPosition& rPos, sal_uInt16 nAttrId,
1087     sal_Bool bTstEnde, long nHand, sal_Bool )
1088 {
1089     //Doing a textbox, and using the control stack only as a temporary
1090     //collection point for properties which will are not to be set into
1091     //the real document
1092     if (rReader.pPlcxMan && rReader.pPlcxMan->GetDoingDrawTextBox())
1093     {
1094         sal_uInt16 nCnt = static_cast< sal_uInt16 >(Count());
1095         for (sal_uInt16 i=0; i < nCnt; ++i)
1096         {
1097             SwFltStackEntry* pEntry = (*this)[i];
1098             if (nAttrId == pEntry->pAttr->Which())
1099             {
1100                 DeleteAndDestroy(i--);
1101                 --nCnt;
1102             }
1103         }
1104     }
1105     else //Normal case, set the attribute into the document
1106         SwFltControlStack::SetAttr(rPos, nAttrId, bTstEnde, nHand);
1107 }
1108 
GetListFirstLineIndent(const SwNumFmt & rFmt)1109 long GetListFirstLineIndent(const SwNumFmt &rFmt)
1110 {
1111     ASSERT( rFmt.GetPositionAndSpaceMode() == SvxNumberFormat::LABEL_WIDTH_AND_POSITION,
1112             "<GetListFirstLineIndent> - misusage: position-and-space-mode does not equal LABEL_WIDTH_AND_POSITION" );
1113 
1114     SvxAdjust eAdj = rFmt.GetNumAdjust();
1115     long nReverseListIndented;
1116     if (eAdj == SVX_ADJUST_RIGHT)
1117         nReverseListIndented = -rFmt.GetCharTextDistance();
1118     else if (eAdj == SVX_ADJUST_CENTER)
1119         nReverseListIndented = rFmt.GetFirstLineOffset()/2;
1120     else
1121         nReverseListIndented = rFmt.GetFirstLineOffset();
1122     return nReverseListIndented;
1123 }
1124 
lcl_GetTrueMargin(const SvxLRSpaceItem & rLR,const SwNumFmt & rFmt,long & rFirstLinePos)1125 long lcl_GetTrueMargin(const SvxLRSpaceItem &rLR, const SwNumFmt &rFmt,
1126     long &rFirstLinePos)
1127 {
1128     ASSERT( rFmt.GetPositionAndSpaceMode() == SvxNumberFormat::LABEL_WIDTH_AND_POSITION,
1129             "<lcl_GetTrueMargin> - misusage: position-and-space-mode does not equal LABEL_WIDTH_AND_POSITION" );
1130 
1131     const long nBodyIndent = rLR.GetTxtLeft();
1132     const long nFirstLineDiff = rLR.GetTxtFirstLineOfst();
1133     rFirstLinePos = nBodyIndent + nFirstLineDiff;
1134 
1135     const long nPseudoListBodyIndent = rFmt.GetAbsLSpace();
1136     const long nReverseListIndented = GetListFirstLineIndent(rFmt);
1137     long nExtraListIndent = nPseudoListBodyIndent + nReverseListIndented;
1138 
1139     return nExtraListIndent > 0 ? nExtraListIndent : 0;
1140 }
1141 
SyncIndentWithList(SvxLRSpaceItem & rLR,const SwNumFmt & rFmt,const bool bFirstLineOfstSet,const bool bLeftIndentSet)1142 void SyncIndentWithList( SvxLRSpaceItem &rLR,
1143                          const SwNumFmt &rFmt,
1144                          const bool bFirstLineOfstSet,
1145                          const bool bLeftIndentSet )
1146 {
1147     if ( rFmt.GetPositionAndSpaceMode() == SvxNumberFormat::LABEL_WIDTH_AND_POSITION )
1148     {
1149         long nWantedFirstLinePos;
1150         long nExtraListIndent = lcl_GetTrueMargin(rLR, rFmt, nWantedFirstLinePos);
1151         rLR.SetTxtLeft(nWantedFirstLinePos - nExtraListIndent);
1152         rLR.SetTxtFirstLineOfst(0);
1153     }
1154     else if ( rFmt.GetPositionAndSpaceMode() == SvxNumberFormat::LABEL_ALIGNMENT )
1155     {
1156         if ( !bFirstLineOfstSet && bLeftIndentSet &&
1157              rFmt.GetFirstLineIndent() != 0 )
1158         {
1159             rLR.SetTxtFirstLineOfst( rFmt.GetFirstLineIndent() );
1160         }
1161         else if ( bFirstLineOfstSet && !bLeftIndentSet &&
1162                   rFmt.GetIndentAt() != 0 )
1163         {
1164             rLR.SetTxtLeft( rFmt.GetIndentAt() );
1165         }
1166         else if (!bFirstLineOfstSet && !bLeftIndentSet )
1167         {
1168             if ( rFmt.GetFirstLineIndent() != 0 )
1169             {
1170                 rLR.SetTxtFirstLineOfst( rFmt.GetFirstLineIndent() );
1171             }
1172             if ( rFmt.GetIndentAt() != 0 )
1173             {
1174                 rLR.SetTxtLeft( rFmt.GetIndentAt() );
1175             }
1176         }
1177     }
1178 }
1179 
GetNumFmtFromStack(const SwPosition & rPos,const SwTxtNode & rTxtNode)1180 const SwNumFmt* SwWW8FltControlStack::GetNumFmtFromStack(const SwPosition &rPos,
1181     const SwTxtNode &rTxtNode)
1182 {
1183     const SwNumFmt *pRet = 0;
1184     const SfxPoolItem *pItem = GetStackAttr(rPos, RES_FLTR_NUMRULE);
1185     if (pItem && rTxtNode.GetNumRule())
1186     {
1187         String sName(((SfxStringItem*)pItem)->GetValue());
1188         if (rTxtNode.IsCountedInList())
1189         {
1190             const SwNumRule *pRule = pDoc->FindNumRulePtr(sName);
1191             sal_uInt8 nLvl = static_cast< sal_uInt8 >(rTxtNode.GetActualListLevel());
1192             pRet = &(pRule->Get(nLvl));
1193         }
1194     }
1195     return pRet;
1196 }
1197 
1198 //Modify here for #119405, by easyfan, 2012-05-24
GetCurrAttrCP() const1199 sal_Int32 SwWW8FltControlStack::GetCurrAttrCP() const
1200 {
1201     return rReader.GetCurrAttrCP();
1202 }
IsParaEndInCPs(sal_Int32 nStart,sal_Int32 nEnd,bool bSdOD) const1203 bool SwWW8FltControlStack::IsParaEndInCPs(sal_Int32 nStart,sal_Int32 nEnd,bool bSdOD) const
1204 {
1205     return rReader.IsParaEndInCPs(nStart,nEnd,bSdOD);
1206 }
1207 //End of modification, by easyfan
1208 //Modify for #119405 by chengjh, 2012-08-16
1209 //Clear the para end position recorded in reader intermittently for the least impact on loading performance
ClearParaEndPosition()1210 void SwWW8FltControlStack::ClearParaEndPosition()
1211 {
1212     if ( Count() != 0 )
1213         return;
1214 
1215     rReader.ClearParaEndPosition();
1216 }
CheckSdOD(sal_Int32 nStart,sal_Int32 nEnd)1217 bool SwWW8FltControlStack::CheckSdOD(sal_Int32 nStart,sal_Int32 nEnd)
1218 {
1219     return rReader.IsParaEndInCPs(nStart,nEnd);
1220 }
1221 //End
1222 
SetAttrInDoc(const SwPosition & rTmpPos,SwFltStackEntry * pEntry)1223 void SwWW8ReferencedFltEndStack::SetAttrInDoc( const SwPosition& rTmpPos,
1224                                                SwFltStackEntry* pEntry )
1225 {
1226     switch( pEntry->pAttr->Which() )
1227     {
1228     case RES_FLTR_BOOKMARK:
1229         {
1230             // suppress insertion of bookmark, which is recognized as an internal bookmark used for table-of-content
1231             // and which is not referenced.
1232             bool bInsertBookmarkIntoDoc = true;
1233 
1234             SwFltBookmark* pFltBookmark = dynamic_cast<SwFltBookmark*>(pEntry->pAttr);
1235             if ( pFltBookmark != 0 && pFltBookmark->IsTOCBookmark() )
1236             {
1237                 const String& rName = pFltBookmark->GetName();
1238                 ::std::set< String, SwWW8::ltstr >::const_iterator aResult = aReferencedTOCBookmarks.find(rName);
1239                 if ( aResult == aReferencedTOCBookmarks.end() )
1240                 {
1241                     bInsertBookmarkIntoDoc = false;
1242                 }
1243             }
1244             if ( bInsertBookmarkIntoDoc )
1245             {
1246                 SwFltEndStack::SetAttrInDoc( rTmpPos, pEntry );
1247             }
1248             break;
1249         }
1250     default:
1251         SwFltEndStack::SetAttrInDoc( rTmpPos, pEntry );
1252         break;
1253     }
1254 
1255 }
1256 
SetAttrInDoc(const SwPosition & rTmpPos,SwFltStackEntry * pEntry)1257 void SwWW8FltControlStack::SetAttrInDoc(const SwPosition& rTmpPos,
1258     SwFltStackEntry* pEntry)
1259 {
1260     switch( pEntry->pAttr->Which() )
1261     {
1262         case RES_LR_SPACE:
1263             {
1264                 /*
1265                  Loop over the affect nodes and
1266                  a) convert the word style absolute indent to indent relative
1267                   to any numbering indent active on the nodes
1268                  b) adjust the writer style tabstops relative to the old
1269                   paragraph indent to be relative to the new paragraph indent
1270                 */
1271                 using namespace sw::util;
1272                 SwPaM aRegion(rTmpPos);
1273                 if (pEntry->MakeRegion(pDoc, aRegion, false))
1274                 {
1275                     SvxLRSpaceItem aNewLR( *(SvxLRSpaceItem*)pEntry->pAttr );
1276                     sal_uLong nStart = aRegion.Start()->nNode.GetIndex();
1277                     sal_uLong nEnd   = aRegion.End()->nNode.GetIndex();
1278                     for(; nStart <= nEnd; ++nStart)
1279                     {
1280                         SwNode* pNode = pDoc->GetNodes()[ nStart ];
1281                         if (!pNode || !pNode->IsTxtNode())
1282                             continue;
1283 
1284                         SwCntntNode* pNd = (SwCntntNode*)pNode;
1285                         SvxLRSpaceItem aOldLR = (const SvxLRSpaceItem&)pNd->GetAttr(RES_LR_SPACE);
1286 
1287                         SwTxtNode *pTxtNode = (SwTxtNode*)pNode;
1288 
1289                         const SwNumFmt *pNum = 0;
1290                         pNum = GetNumFmtFromStack( *aRegion.GetPoint(), *pTxtNode );
1291                         if (!pNum)
1292                         {
1293                             pNum = GetNumFmtFromTxtNode(*pTxtNode);
1294                         }
1295 
1296                         if ( pNum )
1297                         {
1298                             const bool bFirstLineIndentSet =
1299                                 ( rReader.maTxtNodesHavingFirstLineOfstSet.end() !=
1300                                     rReader.maTxtNodesHavingFirstLineOfstSet.find( pNode ) );
1301                             const bool bLeftIndentSet =
1302                                 (  rReader.maTxtNodesHavingLeftIndentSet.end() !=
1303                                     rReader.maTxtNodesHavingLeftIndentSet.find( pNode ) );
1304                             SyncIndentWithList( aNewLR, *pNum,
1305                                                 bFirstLineIndentSet,
1306                                                 bLeftIndentSet );
1307                         }
1308 
1309                         if (aNewLR == aOldLR)
1310                             continue;
1311 
1312                         pNd->SetAttr(aNewLR);
1313 
1314                     }
1315                 }
1316             }
1317             break;
1318 
1319         case RES_TXTATR_FIELD:
1320             ASSERT(sal_False, "What is a field doing in the control stack,"
1321                 "probably should have been in the endstack");
1322             break;
1323 
1324         case RES_TXTATR_ANNOTATION:
1325             ASSERT(sal_False, "What is a annotation doing in the control stack,"
1326                 "probably should have been in the endstack");
1327             break;
1328 
1329         case RES_TXTATR_INPUTFIELD:
1330             ASSERT(sal_False, "What is a input field doing in the control stack,"
1331                 "probably should have been in the endstack");
1332             break;
1333 
1334         case RES_TXTATR_INETFMT:
1335             {
1336                 SwPaM aRegion(rTmpPos);
1337                 if (pEntry->MakeRegion(pDoc, aRegion, false))
1338                 {
1339                     SwFrmFmt *pFrm;
1340                     //If we have just one single inline graphic then
1341                     //don't insert a field for the single frame, set
1342                     //the frames hyperlink field attribute directly.
1343                     if (0 != (pFrm = rReader.ContainsSingleInlineGraphic(aRegion)))
1344                     {
1345                         const SwFmtINetFmt *pAttr = (const SwFmtINetFmt *)
1346                             pEntry->pAttr;
1347                         SwFmtURL aURL;
1348                         aURL.SetURL(pAttr->GetValue(), false);
1349                         aURL.SetTargetFrameName(pAttr->GetTargetFrame());
1350                         pFrm->SetFmtAttr(aURL);
1351                     }
1352                     else
1353                     {
1354                         pDoc->InsertPoolItem(aRegion, *pEntry->pAttr, 0);
1355                     }
1356                 }
1357             }
1358             break;
1359         default:
1360             SwFltControlStack::SetAttrInDoc(rTmpPos, pEntry);
1361             break;
1362     }
1363 }
1364 
GetFmtAttr(const SwPosition & rPos,sal_uInt16 nWhich)1365 const SfxPoolItem* SwWW8FltControlStack::GetFmtAttr(const SwPosition& rPos,
1366     sal_uInt16 nWhich)
1367 {
1368     const SfxPoolItem *pItem = GetStackAttr(rPos, nWhich);
1369     if (!pItem)
1370     {
1371         SwCntntNode const*const pNd = rPos.nNode.GetNode().GetCntntNode();
1372         if (!pNd)
1373             pItem = &pDoc->GetAttrPool().GetDefaultItem(nWhich);
1374         else
1375         {
1376             /*
1377             If we're hunting for the indent on a paragraph and need to use the
1378             parent style indent, then return the indent in msword format, and
1379             not writer format, because that's the style that the filter works
1380             in (naturally)
1381             */
1382             if (nWhich == RES_LR_SPACE)
1383             {
1384                 SfxItemState eState = SFX_ITEM_DEFAULT;
1385                 if (const SfxItemSet *pSet = pNd->GetpSwAttrSet())
1386                     eState = pSet->GetItemState(RES_LR_SPACE, false);
1387                 if (eState != SFX_ITEM_SET && rReader.pCollA != NULL)
1388                     pItem = &(rReader.pCollA[rReader.nAktColl].maWordLR);
1389             }
1390 
1391             if (!pItem)
1392                 pItem = &pNd->GetAttr(nWhich);
1393         }
1394     }
1395     return pItem;
1396 }
1397 
GetStackAttr(const SwPosition & rPos,sal_uInt16 nWhich)1398 const SfxPoolItem* SwWW8FltControlStack::GetStackAttr(const SwPosition& rPos,
1399     sal_uInt16 nWhich)
1400 {
1401     SwNodeIndex aNode( rPos.nNode, -1 );
1402     sal_uInt16 nIdx = rPos.nContent.GetIndex();
1403 
1404     sal_uInt16 nSize = static_cast< sal_uInt16 >(Count());
1405     while (nSize)
1406     {
1407         const SwFltStackEntry* pEntry = (*this)[ --nSize ];
1408         if (pEntry->pAttr->Which() == nWhich)
1409         {
1410             if ( (pEntry->bLocked) || (
1411                 (pEntry->nMkNode <= aNode) && (pEntry->nPtNode >= aNode) &&
1412                 (pEntry->nMkCntnt <= nIdx) && (pEntry->nPtCntnt >= nIdx) ) )
1413             {
1414                 return (const SfxPoolItem*)pEntry->pAttr;
1415             }
1416         }
1417     }
1418     return 0;
1419 }
1420 
IsFtnEdnBkmField(const SwFmtFld & rFmtFld,sal_uInt16 & rBkmNo)1421 bool SwWW8FltRefStack::IsFtnEdnBkmField(
1422     const SwFmtFld& rFmtFld,
1423     sal_uInt16& rBkmNo)
1424 {
1425     const SwField* pFld = rFmtFld.GetField();
1426     sal_uInt16 nSubType;
1427     if(pFld && (RES_GETREFFLD == pFld->Which())
1428         && ((REF_FOOTNOTE == (nSubType = pFld->GetSubType())) || (REF_ENDNOTE  == nSubType))
1429         && ((SwGetRefField*)pFld)->GetSetRefName().Len())
1430     {
1431         const IDocumentMarkAccess* const pMarkAccess = pDoc->getIDocumentMarkAccess();
1432         IDocumentMarkAccess::const_iterator_t ppBkmk =
1433             pMarkAccess->findMark( ((SwGetRefField*)pFld)->GetSetRefName() );
1434         if(ppBkmk != pMarkAccess->getAllMarksEnd())
1435         {
1436             // find Sequence No of corresponding Foot-/Endnote
1437             rBkmNo = ppBkmk - pMarkAccess->getAllMarksBegin();
1438             return true;
1439         }
1440     }
1441     return false;
1442 }
1443 
SetAttrInDoc(const SwPosition & rTmpPos,SwFltStackEntry * pEntry)1444 void SwWW8FltRefStack::SetAttrInDoc(const SwPosition& rTmpPos,
1445         SwFltStackEntry* pEntry)
1446 {
1447     switch( pEntry->pAttr->Which() )
1448     {
1449         /*
1450         Look up these in our lists of bookmarks that were changed to
1451         variables, and replace the ref field with a var field, otherwise
1452         do normal (?) strange stuff
1453         */
1454         case RES_TXTATR_FIELD:
1455         case RES_TXTATR_ANNOTATION:
1456         case RES_TXTATR_INPUTFIELD:
1457         {
1458             SwNodeIndex aIdx(pEntry->nMkNode, 1);
1459             SwPaM aPaM(aIdx, pEntry->nMkCntnt);
1460 
1461             SwFmtFld& rFmtFld   = *(SwFmtFld*)pEntry->pAttr;
1462             SwField* pFld = rFmtFld.GetField();
1463 
1464             if (!RefToVar(pFld,pEntry))
1465             {
1466                 sal_uInt16 nBkmNo;
1467                 if( IsFtnEdnBkmField(rFmtFld, nBkmNo) )
1468                 {
1469                     ::sw::mark::IMark const * const pMark = (pDoc->getIDocumentMarkAccess()->getAllMarksBegin() + nBkmNo)->get();
1470 
1471                     const SwPosition& rBkMrkPos = pMark->GetMarkPos();
1472 
1473                     SwTxtNode* pTxt = rBkMrkPos.nNode.GetNode().GetTxtNode();
1474                     if( pTxt && rBkMrkPos.nContent.GetIndex() )
1475                     {
1476                         SwTxtAttr* const pFtn = pTxt->GetTxtAttrForCharAt(
1477                             rBkMrkPos.nContent.GetIndex()-1, RES_TXTATR_FTN );
1478                         if( pFtn )
1479                         {
1480                             sal_uInt16 nRefNo = ((SwTxtFtn*)pFtn)->GetSeqRefNo();
1481 
1482                             ((SwGetRefField*)pFld)->SetSeqNo( nRefNo );
1483 
1484                             if( pFtn->GetFtn().IsEndNote() )
1485                                 ((SwGetRefField*)pFld)->SetSubType(REF_ENDNOTE);
1486                         }
1487                     }
1488                 }
1489             }
1490 
1491             pDoc->InsertPoolItem(aPaM, *pEntry->pAttr, 0);
1492             MoveAttrs(*aPaM.GetPoint());
1493         }
1494         break;
1495         case RES_FLTR_TOX:
1496             SwFltEndStack::SetAttrInDoc(rTmpPos, pEntry);
1497             break;
1498         default:
1499         case RES_FLTR_BOOKMARK:
1500             ASSERT(sal_False, "EndStck used with non field, not what we want");
1501             SwFltEndStack::SetAttrInDoc(rTmpPos, pEntry);
1502             break;
1503     }
1504 }
1505 
1506 /*
1507  For styles we will do our tabstop arithmetic in word style and adjust them to
1508  writer style after all the styles have been finished and the dust settles as
1509  to what affects what.
1510 
1511  For explicit attributes we turn the adjusted writer tabstops back into 0 based
1512  word indexes and we'll turn them back into writer indexes when setting them
1513  into the document. If explicit left indent exist which affects them, then this
1514  is handled when the explict left indent is set into the document
1515 */
Read_Tab(sal_uInt16,const sal_uInt8 * pData,short nLen)1516 void SwWW8ImplReader::Read_Tab(sal_uInt16 , const sal_uInt8* pData, short nLen)
1517 {
1518     if (nLen < 0)
1519     {
1520         pCtrlStck->SetAttr(*pPaM->GetPoint(), RES_PARATR_TABSTOP);
1521         return;
1522     }
1523 
1524     short i;
1525     const sal_uInt8* pDel = pData + 1;                       // Del - Array
1526     sal_uInt8 nDel = pData[0];
1527     const sal_uInt8* pIns = pData + 2*nDel + 2;          // Ins - Array
1528     sal_uInt8 nIns = pData[nDel*2+1];
1529     WW8_TBD* pTyp = (WW8_TBD*)(pData + 2*nDel + 2*nIns + 2);// Typ - Array
1530 
1531     SvxTabStopItem aAttr(0, 0, SVX_TAB_ADJUST_DEFAULT, RES_PARATR_TABSTOP);
1532 
1533     const SwTxtFmtColl* pSty = 0;
1534     sal_uInt16 nTabBase;
1535     if (pAktColl)               // StyleDef
1536     {
1537         nTabBase = pCollA[nAktColl].nBase;
1538         if (nTabBase < nColls)              // Based On
1539             pSty = (const SwTxtFmtColl*)pCollA[nTabBase].pFmt;
1540     }
1541     else
1542     {                                       // Text
1543         nTabBase = nAktColl;
1544         pSty = (const SwTxtFmtColl*)pCollA[nAktColl].pFmt;
1545     }
1546 
1547     bool bFound = false;
1548     ::std::unordered_set<size_t> aLoopWatch;
1549     while (pSty && !bFound)
1550     {
1551         const SfxPoolItem* pTabs;
1552         bFound = pSty->GetAttrSet().GetItemState(RES_PARATR_TABSTOP, false,
1553             &pTabs) == SFX_ITEM_SET;
1554         if( bFound )
1555             aAttr = *((const SvxTabStopItem*)pTabs);
1556         else
1557         {
1558 
1559             sal_uInt16 nOldTabBase = nTabBase;
1560             // If based on another
1561             if (nTabBase < nColls)
1562                 nTabBase = pCollA[nTabBase].nBase;
1563 
1564             if (
1565                     nTabBase < nColls &&
1566                     nOldTabBase != nTabBase &&
1567                     nTabBase != ww::stiNil
1568                )
1569             {
1570                 // #i61789: Stop searching when next style is the same as the
1571                 // current one (prevent loop)
1572                 aLoopWatch.insert(reinterpret_cast<size_t>(pSty));
1573                 pSty = (const SwTxtFmtColl*)pCollA[nTabBase].pFmt;
1574 
1575                 if (aLoopWatch.find(reinterpret_cast<size_t>(pSty)) !=
1576                     aLoopWatch.end())
1577                     pSty = 0;
1578             }
1579             else
1580                 pSty = 0;                           // gib die Suche auf
1581         }
1582     }
1583 
1584     SvxTabStop aTabStop;
1585     for (i=0; i < nDel; ++i)
1586     {
1587         sal_uInt16 nPos = aAttr.GetPos(SVBT16ToShort(pDel + i*2));
1588         if( nPos != SVX_TAB_NOTFOUND )
1589             aAttr.Remove( nPos, 1 );
1590     }
1591 
1592     for (i=0; i < nIns; ++i)
1593     {
1594         short nPos = SVBT16ToShort(pIns + i*2);
1595         aTabStop.GetTabPos() = nPos;
1596         switch( SVBT8ToByte( pTyp[i].aBits1 ) & 0x7 )       // pTyp[i].jc
1597         {
1598             case 0:
1599                 aTabStop.GetAdjustment() = SVX_TAB_ADJUST_LEFT;
1600                 break;
1601             case 1:
1602                 aTabStop.GetAdjustment() = SVX_TAB_ADJUST_CENTER;
1603                 break;
1604             case 2:
1605                 aTabStop.GetAdjustment() = SVX_TAB_ADJUST_RIGHT;
1606                 break;
1607             case 3:
1608                 aTabStop.GetAdjustment() = SVX_TAB_ADJUST_DECIMAL;
1609                 break;
1610             case 4:
1611                 continue;                   // ignoriere Bar
1612         }
1613 
1614         switch( SVBT8ToByte( pTyp[i].aBits1 ) >> 3 & 0x7 )
1615         {
1616             case 0:
1617                 aTabStop.GetFill() = ' ';
1618                 break;
1619             case 1:
1620                 aTabStop.GetFill() = '.';
1621                 break;
1622             case 2:
1623                 aTabStop.GetFill() = '-';
1624                 break;
1625             case 3:
1626             case 4:
1627                 aTabStop.GetFill() = '_';
1628                 break;
1629         }
1630 
1631         sal_uInt16 nPos2 = aAttr.GetPos( nPos );
1632         if (nPos2 != SVX_TAB_NOTFOUND)
1633             aAttr.Remove(nPos2, 1); // sonst weigert sich das Insert()
1634         aAttr.Insert(aTabStop);
1635     }
1636 
1637     if (nIns || nDel)
1638         NewAttr(aAttr);
1639     else
1640     {
1641         //Here we have a tab definition which inserts no extra tabs, or deletes
1642         //no existing tabs. An older version of writer is probably the creater
1643         //of the document  :-( . So if we are importing a style we can just
1644         //ignore it. But if we are importing into text we cannot as during
1645         //text SwWW8ImplReader::Read_Tab is called at the begin and end of
1646         //the range the attrib affects, and ignoring it would upset the
1647         //balance
1648         if (!pAktColl)  //not importing into a style
1649         {
1650             using namespace sw::util;
1651             SvxTabStopItem aOrig = pSty ?
1652             ItemGet<SvxTabStopItem>(*pSty, RES_PARATR_TABSTOP) :
1653             DefaultItemGet<SvxTabStopItem>(rDoc, RES_PARATR_TABSTOP);
1654             NewAttr(aOrig);
1655         }
1656     }
1657 }
1658 
1659 //-----------------------------------------
1660 //              DOP
1661 //-----------------------------------------
1662 
ImportDop()1663 void SwWW8ImplReader::ImportDop()
1664 {
1665     maTracer.EnterEnvironment(sw::log::eDocumentProperties);
1666     // correct the LastPrinted date in DocumentInfo
1667     uno::Reference<document::XDocumentPropertiesSupplier> xDPS(
1668         mpDocShell->GetModel(), uno::UNO_QUERY_THROW);
1669     uno::Reference<document::XDocumentProperties> xDocuProps(
1670         xDPS->getDocumentProperties());
1671     DBG_ASSERT(xDocuProps.is(), "DocumentProperties is null");
1672     if (xDocuProps.is())
1673     {
1674         DateTime aLastPrinted(
1675             sw::ms::DTTM2DateTime(pWDop->dttmLastPrint));
1676        ::util::DateTime uDT(aLastPrinted.Get100Sec(),
1677             aLastPrinted.GetSec(), aLastPrinted.GetMin(),
1678             aLastPrinted.GetHour(), aLastPrinted.GetDay(),
1679             aLastPrinted.GetMonth(), aLastPrinted.GetYear());
1680         xDocuProps->setPrintDate(uDT);
1681     }
1682 
1683     //
1684     // COMPATIBILITY FLAGS START
1685     //
1686 
1687     // #i78951# - remember the unknown compatibility options
1688     // so as to export them out
1689     rDoc.Setn32DummyCompatabilityOptions1( pWDop->GetCompatabilityOptions());
1690     rDoc.Setn32DummyCompatabilityOptions2( pWDop->GetCompatabilityOptions2());
1691 
1692     // Abstand zwischen zwei Absaetzen ist die SUMME von unterem
1693     // Abst. des ersten und oberem Abst. des zweiten
1694     rDoc.set(IDocumentSettingAccess::PARA_SPACE_MAX, pWDop->fDontUseHTMLAutoSpacing);
1695     rDoc.set(IDocumentSettingAccess::PARA_SPACE_MAX_AT_PAGES, true );
1696     maTracer.Log(sw::log::eDontUseHTMLAutoSpacing);
1697     // move tabs on alignment
1698     rDoc.set(IDocumentSettingAccess::TAB_COMPAT, true);
1699     // #i24363# tab stops relative to indent
1700     rDoc.set(IDocumentSettingAccess::TABS_RELATIVE_TO_INDENT, false);
1701     maTracer.Log(sw::log::eTabStopDistance);
1702     // #i18732# - adjust default of option 'FollowTextFlow'
1703     rDoc.SetDefault( SwFmtFollowTextFlow( sal_False ) );
1704 
1705     // Import Default-Tabs
1706     long nDefTabSiz = pWDop->dxaTab;
1707     if( nDefTabSiz < 56 )
1708         nDefTabSiz = 709;
1709 
1710     // wir wollen genau einen DefaultTab
1711     SvxTabStopItem aNewTab( 1, sal_uInt16(nDefTabSiz), SVX_TAB_ADJUST_DEFAULT, RES_PARATR_TABSTOP );
1712     ((SvxTabStop&)aNewTab[0]).GetAdjustment() = SVX_TAB_ADJUST_DEFAULT;
1713 
1714     rDoc.GetAttrPool().SetPoolDefaultItem( aNewTab );
1715 
1716     if (!pWDop->fUsePrinterMetrics)
1717         maTracer.Log(sw::log::ePrinterMetrics);
1718 
1719     if (!pWDop->fNoLeading)
1720         maTracer.Log(sw::log::eExtraLeading);
1721 
1722     rDoc.set(IDocumentSettingAccess::USE_VIRTUAL_DEVICE, !pWDop->fUsePrinterMetrics);
1723     rDoc.set(IDocumentSettingAccess::USE_HIRES_VIRTUAL_DEVICE, true);
1724     rDoc.set(IDocumentSettingAccess::ADD_FLY_OFFSETS, true );
1725     rDoc.set(IDocumentSettingAccess::ADD_EXT_LEADING, !pWDop->fNoLeading);
1726 
1727     rDoc.set(IDocumentSettingAccess::OLD_NUMBERING, false);
1728 
1729     // #i47448#
1730     rDoc.set(IDocumentSettingAccess::IGNORE_FIRST_LINE_INDENT_IN_NUMBERING, false);
1731 
1732     // #i49277#
1733     rDoc.set(IDocumentSettingAccess::DO_NOT_JUSTIFY_LINES_WITH_MANUAL_BREAK, !pWDop->fExpShRtn); // #i56856#
1734     // #i53199#
1735     rDoc.set(IDocumentSettingAccess::DO_NOT_RESET_PARA_ATTRS_FOR_NUM_FONT, false);
1736 
1737     rDoc.set(IDocumentSettingAccess::OLD_LINE_SPACING, false);
1738 
1739     // #i25901#- set new compatibility option 'Add paragraph and table spacing at bottom of table cells'
1740     rDoc.set(IDocumentSettingAccess::ADD_PARA_SPACING_TO_TABLE_CELLS, true);
1741 
1742     // #i11860# - set new compatibility option 'Use former object positioning' to <sal_False>
1743     rDoc.set(IDocumentSettingAccess::USE_FORMER_OBJECT_POS, false);
1744 
1745     // #i27767# - set new compatibility option 'Conder Wrapping mode when positioning object' to <sal_True>
1746     rDoc.set(IDocumentSettingAccess::CONSIDER_WRAP_ON_OBJECT_POSITION, true);
1747 
1748     // #i13832#, #i24135#
1749     rDoc.set(IDocumentSettingAccess::USE_FORMER_TEXT_WRAPPING, false);
1750 
1751     rDoc.set(IDocumentSettingAccess::TABLE_ROW_KEEP, true);
1752 
1753     // #i3952#
1754     rDoc.set(IDocumentSettingAccess::IGNORE_TABS_AND_BLANKS_FOR_LINE_CALCULATION, true);
1755 
1756     //
1757     // COMPATIBILITY FLAGS END
1758     //
1759 
1760     if (!pWDop->fNoLeading)
1761         maTracer.Log(sw::log::eExtraLeading);
1762 
1763     //import magic doptypography information, if its there
1764     if (pWwFib->nFib > 105)
1765         ImportDopTypography(pWDop->doptypography);
1766 
1767     // disable form design mode to be able to use imported controls directly
1768     // #i31239# always disable form design mode, not only in protected docs
1769     {
1770         using namespace com::sun::star;
1771 
1772         uno::Reference<lang::XComponent> xModelComp(mpDocShell->GetModel(),
1773            uno::UNO_QUERY);
1774         uno::Reference<beans::XPropertySet> xDocProps(xModelComp,
1775            uno::UNO_QUERY);
1776         if (xDocProps.is())
1777         {
1778             uno::Reference<beans::XPropertySetInfo> xInfo =
1779                 xDocProps->getPropertySetInfo();
1780             sal_Bool bValue = false;
1781             if (xInfo.is())
1782             {
1783                 if (xInfo->hasPropertyByName(C2U("ApplyFormDesignMode")))
1784                 {
1785                     xDocProps->setPropertyValue(C2U("ApplyFormDesignMode"),
1786                                                 cppu::bool2any(bValue));
1787                 }
1788             }
1789         }
1790     }
1791 
1792     mpDocShell->SetModifyPasswordHash(pWDop->lKeyProtDoc);
1793 
1794     {
1795         const SvtFilterOptions* pOpt = SvtFilterOptions::Get();
1796         const sal_Bool bUseEnhFields=(pOpt && pOpt->IsUseEnhancedFields());
1797         if (bUseEnhFields)
1798         {
1799             rDoc.set(IDocumentSettingAccess::PROTECT_FORM, pWDop->fProtEnabled );
1800         }
1801     }
1802 
1803     maTracer.LeaveEnvironment(sw::log::eDocumentProperties);
1804 }
1805 
ImportDopTypography(const WW8DopTypography & rTypo)1806 void SwWW8ImplReader::ImportDopTypography(const WW8DopTypography &rTypo)
1807 {
1808     using namespace com::sun::star;
1809     switch (rTypo.iLevelOfKinsoku)
1810     {
1811         case 2: //custom
1812             {
1813                 i18n::ForbiddenCharacters aForbidden(rTypo.rgxchFPunct,
1814                     rTypo.rgxchLPunct);
1815                 rDoc.setForbiddenCharacters(rTypo.GetConvertedLang(),
1816                         aForbidden);
1817                 //Obviously cannot set the standard level 1 for japanese, so
1818                 //bail out now while we can.
1819                 if (rTypo.GetConvertedLang() == LANGUAGE_JAPANESE)
1820                     return;
1821             }
1822             break;
1823         default:
1824             break;
1825     }
1826 
1827     /*
1828     This MS hack means that level 2 of japanese is not in operation, so we put
1829     in what we know are the MS defaults, there is a complementary reverse
1830     hack in the writer. Its our default as well, but we can set it anyway
1831     as a flag for later.
1832     */
1833     if (!rTypo.reserved2)
1834     {
1835         i18n::ForbiddenCharacters aForbidden(rTypo.GetJapanNotBeginLevel1(),
1836             rTypo.GetJapanNotEndLevel1());
1837         rDoc.setForbiddenCharacters(LANGUAGE_JAPANESE,aForbidden);
1838     }
1839 
1840     rDoc.set(IDocumentSettingAccess::KERN_ASIAN_PUNCTUATION, rTypo.fKerningPunct);
1841     rDoc.setCharacterCompressionType(static_cast<SwCharCompressType>(rTypo.iJustification));
1842 }
1843 
1844 //-----------------------------------------
1845 //      Fuss- und Endnoten
1846 
1847 //-----------------------------------------
1848 
WW8ReaderSave(SwWW8ImplReader * pRdr,WW8_CP nStartCp)1849 WW8ReaderSave::WW8ReaderSave(SwWW8ImplReader* pRdr ,WW8_CP nStartCp) :
1850     maTmpPos(*pRdr->pPaM->GetPoint()),
1851     mpOldStck(pRdr->pCtrlStck),
1852     mpOldAnchorStck(pRdr->pAnchorStck),
1853     mpOldRedlines(pRdr->mpRedlineStack),
1854     mpOldPlcxMan(pRdr->pPlcxMan),
1855     mpWFlyPara(pRdr->pWFlyPara),
1856     mpSFlyPara(pRdr->pSFlyPara),
1857     mpPreviousNumPaM(pRdr->pPreviousNumPaM),
1858     mpPrevNumRule(pRdr->pPrevNumRule),
1859     mpTableDesc(pRdr->pTableDesc),
1860     mnInTable(pRdr->nInTable),
1861     mnAktColl(pRdr->nAktColl),
1862     mcSymbol(pRdr->cSymbol),
1863     mbIgnoreText(pRdr->bIgnoreText),
1864     mbSymbol(pRdr->bSymbol),
1865     mbHdFtFtnEdn(pRdr->bHdFtFtnEdn),
1866     mbTxbxFlySection(pRdr->bTxbxFlySection),
1867     mbAnl(pRdr->bAnl),
1868     mbInHyperlink(pRdr->bInHyperlink),
1869     mbPgSecBreak(pRdr->bPgSecBreak),
1870     mbWasParaEnd(pRdr->bWasParaEnd),
1871     mbHasBorder(pRdr->bHasBorder),
1872     mbFirstPara(pRdr->bFirstPara)
1873 {
1874     pRdr->bSymbol = false;
1875     pRdr->bHdFtFtnEdn = true;
1876     pRdr->bTxbxFlySection = pRdr->bAnl = pRdr->bPgSecBreak = pRdr->bWasParaEnd
1877         = pRdr->bHasBorder = false;
1878     pRdr->bFirstPara = true;
1879     pRdr->nInTable = 0;
1880     pRdr->pWFlyPara = 0;
1881     pRdr->pSFlyPara = 0;
1882     pRdr->pPreviousNumPaM = 0;
1883     pRdr->pPrevNumRule = 0;
1884     pRdr->pTableDesc = 0;
1885     pRdr->nAktColl = 0;
1886 
1887 
1888     pRdr->pCtrlStck = new SwWW8FltControlStack(&pRdr->rDoc, pRdr->nFieldFlags,
1889         *pRdr);
1890 
1891     pRdr->mpRedlineStack = new sw::util::RedlineStack(pRdr->rDoc);
1892 
1893     pRdr->pAnchorStck = new SwWW8FltAnchorStack(&pRdr->rDoc, pRdr->nFieldFlags);
1894 
1895     // rette die Attributverwaltung: dies ist noetig, da der neu anzulegende
1896     // PLCFx Manager natuerlich auf die gleichen FKPs zugreift, wie der alte
1897     // und deren Start-End-Positionen veraendert...
1898     if (pRdr->pPlcxMan)
1899         pRdr->pPlcxMan->SaveAllPLCFx(maPLCFxSave);
1900 
1901     if (nStartCp != -1)
1902     {
1903         pRdr->pPlcxMan = new WW8PLCFMan(pRdr->pSBase,
1904             mpOldPlcxMan->GetManType(), nStartCp);
1905     }
1906 
1907     maOldApos.push_back(false);
1908     maOldApos.swap(pRdr->maApos);
1909     maOldFieldStack.swap(pRdr->maFieldStack);
1910 }
1911 
Restore(SwWW8ImplReader * pRdr)1912 void WW8ReaderSave::Restore( SwWW8ImplReader* pRdr )
1913 {
1914     pRdr->pWFlyPara = mpWFlyPara;
1915     pRdr->pSFlyPara = mpSFlyPara;
1916     pRdr->pPreviousNumPaM = mpPreviousNumPaM;
1917     pRdr->pPrevNumRule = mpPrevNumRule;
1918     pRdr->pTableDesc = mpTableDesc;
1919     pRdr->cSymbol = mcSymbol;
1920     pRdr->bSymbol = mbSymbol;
1921     pRdr->bIgnoreText = mbIgnoreText;
1922     pRdr->bHdFtFtnEdn = mbHdFtFtnEdn;
1923     pRdr->bTxbxFlySection = mbTxbxFlySection;
1924     pRdr->nInTable = mnInTable;
1925     pRdr->bAnl = mbAnl;
1926     pRdr->bInHyperlink = mbInHyperlink;
1927     pRdr->bWasParaEnd = mbWasParaEnd;
1928     pRdr->bPgSecBreak = mbPgSecBreak;
1929     pRdr->nAktColl = mnAktColl;
1930     pRdr->bHasBorder = mbHasBorder;
1931     pRdr->bFirstPara = mbFirstPara;
1932 
1933     // schliesse alle Attribute, da sonst Attribute
1934     // entstehen koennen, die aus dem Fly rausragen
1935     pRdr->DeleteCtrlStk();
1936     pRdr->pCtrlStck = mpOldStck;
1937 
1938     pRdr->mpRedlineStack->closeall(*pRdr->pPaM->GetPoint());
1939     delete pRdr->mpRedlineStack;
1940     pRdr->mpRedlineStack = mpOldRedlines;
1941 
1942     pRdr->DeleteAnchorStk();
1943     pRdr->pAnchorStck = mpOldAnchorStck;
1944 
1945     *pRdr->pPaM->GetPoint() = maTmpPos;
1946 
1947     if (mpOldPlcxMan != pRdr->pPlcxMan)
1948     {
1949         delete pRdr->pPlcxMan;
1950         pRdr->pPlcxMan = mpOldPlcxMan;
1951     }
1952     if (pRdr->pPlcxMan)
1953         pRdr->pPlcxMan->RestoreAllPLCFx(maPLCFxSave);
1954     pRdr->maApos.swap(maOldApos);
1955     pRdr->maFieldStack.swap(maOldFieldStack);
1956 }
1957 
Read_HdFtFtnText(const SwNodeIndex * pSttIdx,long nStartCp,long nLen,ManTypes nType)1958 void SwWW8ImplReader::Read_HdFtFtnText( const SwNodeIndex* pSttIdx,
1959     long nStartCp, long nLen, ManTypes nType )
1960 {
1961     // rettet Flags u.ae. u. setzt sie zurueck
1962     WW8ReaderSave aSave( this );
1963 
1964     pPaM->GetPoint()->nNode = pSttIdx->GetIndex() + 1;      //
1965     pPaM->GetPoint()->nContent.Assign( pPaM->GetCntntNode(), 0 );
1966 
1967     // dann Text fuer Header, Footer o. Footnote einlesen
1968 
1969     ReadText( nStartCp, nLen, nType );              // Sepx dabei ignorieren
1970     aSave.Restore( this );
1971 }
1972 
1973 //Use authornames, if not available fall back to initials.
Read_And(WW8PLCFManResult * pRes)1974 long SwWW8ImplReader::Read_And(WW8PLCFManResult* pRes)
1975 {
1976     WW8PLCFx_SubDoc* pSD = pPlcxMan->GetAtn();
1977     if( !pSD )
1978         return 0;
1979 
1980     String sAuthor;
1981     if( bVer67 )
1982     {
1983         const WW67_ATRD* pDescri = (const WW67_ATRD*)pSD->GetData();
1984         const String* pA = GetAnnotationAuthor(SVBT16ToShort(pDescri->ibst));
1985         if (pA)
1986             sAuthor = *pA;
1987         else
1988             sAuthor = String(pDescri->xstUsrInitl + 1, pDescri->xstUsrInitl[0],
1989                 RTL_TEXTENCODING_MS_1252);
1990     }
1991     else
1992     {
1993         const WW8_ATRD* pDescri = (const WW8_ATRD*)pSD->GetData();
1994 
1995         if (const String* pA = GetAnnotationAuthor(SVBT16ToShort(pDescri->ibst)))
1996             sAuthor = *pA;
1997         else
1998         {
1999             sal_uInt16 nLen = SVBT16ToShort(pDescri->xstUsrInitl[0]);
2000             for(sal_uInt16 nIdx = 1; nIdx <= nLen; ++nIdx)
2001                 sAuthor += SVBT16ToShort(pDescri->xstUsrInitl[nIdx]);
2002         }
2003     }
2004 
2005     sal_uInt32 nDateTime = 0;
2006 
2007     if (sal_uInt8 * pExtended = pPlcxMan->GetExtendedAtrds()) // Word < 2002 has no date data for comments
2008     {
2009         sal_uLong nIndex = pSD->GetIdx() & 0xFFFF; //Index is (stupidly) multiplexed for WW8PLCFx_SubDocs
2010         if (pWwFib->lcbAtrdExtra/18 > nIndex)
2011             nDateTime = SVBT32ToUInt32(*(SVBT32*)(pExtended+(nIndex*18)));
2012     }
2013 
2014     DateTime aDate = sw::ms::DTTM2DateTime(nDateTime);
2015 
2016     String sTxt;
2017     OutlinerParaObject *pOutliner = ImportAsOutliner( sTxt, pRes->nCp2OrIdx,
2018         pRes->nCp2OrIdx + pRes->nMemLen, MAN_AND );
2019 
2020     this->pFmtOfJustInsertedApo = 0;
2021     SwPostItField aPostIt(
2022         (SwPostItFieldType*)rDoc.GetSysFldType(RES_POSTITFLD),
2023         sTxt,
2024         sAuthor,
2025         aEmptyStr,
2026         aEmptyStr,
2027         aDate );
2028     aPostIt.SetTextObject(pOutliner);
2029 
2030     pCtrlStck->NewAttr(*pPaM->GetPoint(), SvxCharHiddenItem(false, RES_CHRATR_HIDDEN));
2031     rDoc.InsertPoolItem(*pPaM, SwFmtFld(aPostIt), 0);
2032     pCtrlStck->SetAttr(*pPaM->GetPoint(), RES_CHRATR_HIDDEN);
2033 
2034     return 0;
2035 }
2036 
Read_HdFtTextAsHackedFrame(long nStart,long nLen,SwFrmFmt & rHdFtFmt,sal_uInt16 nPageWidth)2037 void SwWW8ImplReader::Read_HdFtTextAsHackedFrame(long nStart, long nLen,
2038     SwFrmFmt &rHdFtFmt, sal_uInt16 nPageWidth)
2039 {
2040     const SwNodeIndex* pSttIdx = rHdFtFmt.GetCntnt().GetCntntIdx();
2041     ASSERT(pSttIdx, "impossible");
2042     if (!pSttIdx)
2043         return;
2044 
2045     SwPosition aTmpPos(*pPaM->GetPoint());
2046 
2047     pPaM->GetPoint()->nNode = pSttIdx->GetIndex() + 1;
2048     pPaM->GetPoint()->nContent.Assign(pPaM->GetCntntNode(), 0);
2049 
2050     SwFlyFrmFmt *pFrame = rDoc.MakeFlySection(FLY_AT_PARA, pPaM->GetPoint());
2051 
2052     SwFmtAnchor aAnch( pFrame->GetAnchor() );
2053     aAnch.SetType( FLY_AT_PARA );
2054     pFrame->SetFmtAttr( aAnch );
2055     SwFmtFrmSize aSz(ATT_MIN_SIZE, nPageWidth, MINLAY);
2056     SwFrmSize eFrmSize = ATT_MIN_SIZE;
2057     if( eFrmSize != aSz.GetWidthSizeType() )
2058         aSz.SetWidthSizeType( eFrmSize );
2059     pFrame->SetFmtAttr(aSz);
2060     pFrame->SetFmtAttr(SwFmtSurround(SURROUND_THROUGHT));
2061     pFrame->SetFmtAttr(SwFmtHoriOrient(0, text::HoriOrientation::LEFT)); //iFOO
2062 
2063     // #i43427# - send frame for header/footer into background.
2064     pFrame->SetFmtAttr( SvxOpaqueItem( RES_OPAQUE, false ) );
2065     SdrObject* pFrmObj = CreateContactObject( pFrame );
2066     ASSERT( pFrmObj,
2067             "<SwWW8ImplReader::Read_HdFtTextAsHackedFrame(..)> - missing SdrObject instance" );
2068     if ( pFrmObj )
2069     {
2070         pFrmObj->SetOrdNum( 0L );
2071     }
2072     MoveInsideFly(pFrame);
2073 
2074     const SwNodeIndex* pHackIdx = pFrame->GetCntnt().GetCntntIdx();
2075 
2076     Read_HdFtFtnText(pHackIdx, nStart, nLen - 1, MAN_HDFT);
2077 
2078     MoveOutsideFly(pFrame, aTmpPos);
2079 }
2080 
Read_HdFtText(long nStart,long nLen,SwFrmFmt * pHdFtFmt)2081 void SwWW8ImplReader::Read_HdFtText(long nStart, long nLen, SwFrmFmt* pHdFtFmt)
2082 {
2083     const SwNodeIndex* pSttIdx = pHdFtFmt->GetCntnt().GetCntntIdx();
2084     if (!pSttIdx)
2085         return;
2086 
2087     SwPosition aTmpPos( *pPaM->GetPoint() );    // merke alte Cursorposition
2088 
2089     Read_HdFtFtnText(pSttIdx, nStart, nLen - 1, MAN_HDFT);
2090 
2091     *pPaM->GetPoint() = aTmpPos;
2092 }
2093 
2094 
isValid_HdFt_CP(WW8_CP nHeaderCP) const2095 bool SwWW8ImplReader::isValid_HdFt_CP(WW8_CP nHeaderCP) const
2096 {
2097     //each CP of Plcfhdd MUST be less than FibRgLw97.ccpHdd
2098     return (nHeaderCP < pWwFib->ccpHdr) ? true : false;
2099 }
2100 
HasOwnHeaderFooter(sal_uInt8 nWhichItems,sal_uInt8 grpfIhdt,int nSect)2101 bool SwWW8ImplReader::HasOwnHeaderFooter(sal_uInt8 nWhichItems, sal_uInt8 grpfIhdt,
2102     int nSect)
2103 {
2104     if (pHdFt)
2105     {
2106         WW8_CP start;
2107         long nLen;
2108         sal_uInt8 nNumber = 5;
2109 
2110         for( sal_uInt8 nI = 0x20; nI; nI >>= 1, nNumber-- )
2111         {
2112             if (nI & nWhichItems)
2113             {
2114                 bool bOk = true;
2115                 if( bVer67 )
2116                     bOk = ( pHdFt->GetTextPos(grpfIhdt, nI, start, nLen ) && nLen >= 2 );
2117                 else
2118                 {
2119                     pHdFt->GetTextPosExact( static_cast< short >(nNumber + (nSect+1)*6), start, nLen);
2120                     bOk = ( 2 <= nLen ) && isValid_HdFt_CP(start);
2121                 }
2122 
2123                 if (bOk)
2124                     return true;
2125             }
2126         }
2127     }
2128     return false;
2129 }
2130 
Read_HdFt(bool bIsTitle,int nSect,const SwPageDesc * pPrev,const wwSection & rSection)2131 void SwWW8ImplReader::Read_HdFt(bool bIsTitle, int nSect,
2132     const SwPageDesc *pPrev, const wwSection &rSection)
2133 {
2134     sal_uInt8 nWhichItems = 0;
2135     SwPageDesc *pPD = 0;
2136     if (!bIsTitle)
2137     {
2138         nWhichItems =
2139             rSection.maSep.grpfIhdt & ~(WW8_HEADER_FIRST | WW8_FOOTER_FIRST);
2140         pPD = rSection.mpPage;
2141     }
2142     else
2143     {
2144         // Always read title page header/footer data - it could be used by following sections
2145         nWhichItems = ( WW8_HEADER_FIRST | WW8_FOOTER_FIRST );
2146         pPD = rSection.mpTitlePage;
2147     }
2148 
2149     sal_uInt8 grpfIhdt = rSection.maSep.grpfIhdt;
2150 
2151 
2152     if( pHdFt )
2153     {
2154         WW8_CP start;
2155         long nLen;
2156         sal_uInt8 nNumber = 5;
2157 
2158         for( sal_uInt8 nI = 0x20; nI; nI >>= 1, nNumber-- )
2159         {
2160             if (nI & nWhichItems)
2161             {
2162                 bool bOk = true;
2163                 if( bVer67 )
2164                     bOk = ( pHdFt->GetTextPos(grpfIhdt, nI, start, nLen ) && nLen >= 2 );
2165                 else
2166                 {
2167                     pHdFt->GetTextPosExact( static_cast< short >(nNumber + (nSect+1)*6), start, nLen);
2168                     bOk = ( 2 <= nLen ) && isValid_HdFt_CP(start);
2169                 }
2170 
2171                 bool bUseLeft
2172                     = (nI & ( WW8_HEADER_EVEN | WW8_FOOTER_EVEN )) ? true: false;
2173                 bool bFooter
2174                     = (nI & ( WW8_FOOTER_EVEN | WW8_FOOTER_ODD | WW8_FOOTER_FIRST )) ? true: false;
2175 
2176                 SwFrmFmt* pFmt = bUseLeft ? &pPD->GetLeft() : &pPD->GetMaster();
2177 
2178                 SwFrmFmt* pHdFtFmt;
2179                 if (bFooter)
2180                 {
2181                     bIsFooter = true;
2182                     //#i17196# Cannot have left without right
2183                     if (!pPD->GetMaster().GetFooter().GetFooterFmt())
2184                         pPD->GetMaster().SetFmtAttr(SwFmtFooter(true));
2185                     if (bUseLeft)
2186                         pPD->GetLeft().SetFmtAttr(SwFmtFooter(true));
2187                     pHdFtFmt = (SwFrmFmt*)pFmt->GetFooter().GetFooterFmt();
2188                 }
2189                 else
2190                 {
2191                     bIsHeader = true;
2192                     //#i17196# Cannot have left without right
2193                     if (!pPD->GetMaster().GetHeader().GetHeaderFmt())
2194                         pPD->GetMaster().SetFmtAttr(SwFmtHeader(true));
2195                     if (bUseLeft)
2196                         pPD->GetLeft().SetFmtAttr(SwFmtHeader(true));
2197                     pHdFtFmt = (SwFrmFmt*)pFmt->GetHeader().GetHeaderFmt();
2198                 }
2199 
2200                 if (bOk)
2201                 {
2202                     bool bHackRequired = false;
2203                     if (bIsHeader && rSection.IsFixedHeightHeader())
2204                         bHackRequired = true;
2205                     else if (bIsFooter && rSection.IsFixedHeightFooter())
2206                         bHackRequired = true;
2207 
2208                     if (bHackRequired)
2209                     {
2210                         Read_HdFtTextAsHackedFrame(start, nLen, *pHdFtFmt,
2211                             static_cast< sal_uInt16 >(rSection.GetTextAreaWidth()) );
2212                     }
2213                     else
2214                         Read_HdFtText(start, nLen, pHdFtFmt);
2215                 }
2216                 else if (!bOk && pPrev)
2217                     CopyPageDescHdFt(pPrev, pPD, nI);
2218 
2219                 bIsHeader = bIsFooter = false;
2220             }
2221         }
2222     }
2223     maTracer.LeaveEnvironment(sw::log::eDocumentProperties);
2224 }
2225 
SectionIsProtected(const wwSection & rSection) const2226 bool wwSectionManager::SectionIsProtected(const wwSection &rSection) const
2227 {
2228     return (mrReader.pWwFib->fReadOnlyRecommended && !rSection.IsNotProtected());
2229 }
2230 
SetHdFt(wwSection & rSection,int nSect,const wwSection * pPrevious)2231 void wwSectionManager::SetHdFt(wwSection &rSection, int nSect,
2232     const wwSection *pPrevious)
2233 {
2234     // Header / Footer nicht da
2235     if (!rSection.maSep.grpfIhdt)
2236         return;
2237 
2238     ASSERT(rSection.mpPage, "makes no sense to call with a main page");
2239     if (rSection.mpPage)
2240     {
2241         mrReader.Read_HdFt(false, nSect, pPrevious ? pPrevious->mpPage : 0,
2242                 rSection);
2243     }
2244 
2245     if (rSection.mpTitlePage)
2246     {
2247         // 2 Pagedescs noetig: 1.Seite und folgende
2248         // 1. Seite einlesen
2249         mrReader.Read_HdFt(true, nSect, pPrevious ? pPrevious->mpTitlePage : 0,
2250             rSection);
2251     }
2252 
2253     // Kopf / Fuss - Index Updaten
2254     // Damit der Index auch spaeter noch stimmt
2255     if (mrReader.pHdFt)
2256         mrReader.pHdFt->UpdateIndex(rSection.maSep.grpfIhdt);
2257 
2258 }
2259 
2260 class AttribHere
2261 {
2262 public:
2263     typedef const xub_StrLen* argument_type;
2264     typedef bool result_type;
2265 private:
2266 private:
2267     xub_StrLen nPosition;
2268 public:
AttribHere(xub_StrLen nPos)2269     AttribHere(xub_StrLen nPos) : nPosition(nPos) {}
operator ()(const xub_StrLen * pPosition) const2270     bool operator()(const xub_StrLen *pPosition) const
2271     {
2272         return (*pPosition >= nPosition);
2273     }
2274 };
2275 
AppendTxtNode(SwPosition & rPos)2276 void SwWW8ImplReader::AppendTxtNode(SwPosition& rPos)
2277 {
2278     SwTxtNode* pTxt = pPaM->GetNode()->GetTxtNode();
2279 
2280     const SwNumRule* pRule = NULL;
2281 
2282     if (pTxt != NULL)
2283         pRule = sw::util::GetNumRuleFromTxtNode(*pTxt);
2284 
2285     if (
2286          pRule && !pWDop->fDontUseHTMLAutoSpacing &&
2287          (bParaAutoBefore || bParaAutoAfter)
2288        )
2289     {
2290         // If after spacing is set to auto, set the after space to 0
2291         if (bParaAutoAfter)
2292             SetLowerSpacing(*pPaM, 0);
2293 
2294         // If the previous textnode had numbering and
2295         // and before spacing is set to auto, set before space to 0
2296         if(pPrevNumRule && bParaAutoBefore)
2297             SetUpperSpacing(*pPaM, 0);
2298 
2299         // If the previous numbering rule was different we need
2300         // to insert a space after the previous paragraph
2301         if((pRule != pPrevNumRule) && pPreviousNumPaM)
2302             SetLowerSpacing(*pPreviousNumPaM, GetParagraphAutoSpace(pWDop->fDontUseHTMLAutoSpacing));
2303 
2304         // cache current paragraph
2305         if(pPreviousNumPaM)
2306             delete pPreviousNumPaM, pPreviousNumPaM = 0;
2307 
2308         pPreviousNumPaM = new SwPaM(*pPaM);
2309         pPrevNumRule = pRule;
2310     }
2311     else if(!pRule && pPreviousNumPaM)
2312     {
2313         // If the previous paragraph has numbering but the current one does not
2314         // we need to add a space after the previous paragraph
2315         SetLowerSpacing(*pPreviousNumPaM, GetParagraphAutoSpace(pWDop->fDontUseHTMLAutoSpacing));
2316         delete pPreviousNumPaM, pPreviousNumPaM = 0;
2317         pPrevNumRule = 0;
2318     }
2319     else
2320     {
2321         // clear paragraph cache
2322         if(pPreviousNumPaM)
2323             delete pPreviousNumPaM, pPreviousNumPaM = 0;
2324         pPrevNumRule = pRule;
2325     }
2326 
2327     // If this is the first paragraph in the document and
2328     // Auto-spacing before paragraph is set,
2329     // set the upper spacing value to 0
2330     if(bParaAutoBefore && bFirstPara && !pWDop->fDontUseHTMLAutoSpacing)
2331         SetUpperSpacing(*pPaM, 0);
2332 
2333     bFirstPara = false;
2334 
2335     rDoc.AppendTxtNode(rPos);
2336 
2337     //We can flush all anchored graphics at the end of a paragraph.
2338     pAnchorStck->Flush();
2339 }
2340 
SetSpacing(SwPaM & rMyPam,int nSpace,bool bIsUpper)2341 bool SwWW8ImplReader::SetSpacing(SwPaM &rMyPam, int nSpace, bool bIsUpper )
2342 {
2343         bool bRet = false;
2344         const SwPosition* pSpacingPos = rMyPam.GetPoint();
2345 
2346         const SvxULSpaceItem* pULSpaceItem = (const SvxULSpaceItem*)pCtrlStck->GetFmtAttr(*pSpacingPos, RES_UL_SPACE);
2347 
2348         if(pULSpaceItem != 0)
2349         {
2350             SvxULSpaceItem aUL(*pULSpaceItem);
2351 
2352             if(bIsUpper)
2353                 aUL.SetUpper( static_cast< sal_uInt16 >(nSpace) );
2354             else
2355                 aUL.SetLower( static_cast< sal_uInt16 >(nSpace) );
2356 
2357             xub_StrLen nEnd = pSpacingPos->nContent.GetIndex();
2358             rMyPam.GetPoint()->nContent.Assign(rMyPam.GetCntntNode(), 0);
2359             pCtrlStck->NewAttr(*pSpacingPos, aUL);
2360             rMyPam.GetPoint()->nContent.Assign(rMyPam.GetCntntNode(), nEnd);
2361             pCtrlStck->SetAttr(*pSpacingPos, RES_UL_SPACE);
2362             bRet = true;
2363         }
2364         return bRet;
2365 }
2366 
SetLowerSpacing(SwPaM & rMyPam,int nSpace)2367 bool SwWW8ImplReader::SetLowerSpacing(SwPaM &rMyPam, int nSpace)
2368 {
2369     return SetSpacing(rMyPam, nSpace, false);
2370 }
2371 
SetUpperSpacing(SwPaM & rMyPam,int nSpace)2372 bool SwWW8ImplReader::SetUpperSpacing(SwPaM &rMyPam, int nSpace)
2373 {
2374     return SetSpacing(rMyPam, nSpace, true);
2375 }
2376 
TabRowSprm(int nLevel) const2377 sal_uInt16 SwWW8ImplReader::TabRowSprm(int nLevel) const
2378 {
2379     if (bVer67)
2380         return 25;
2381     return nLevel ? 0x244C : 0x2417;
2382 }
2383 
EndSpecial()2384 void SwWW8ImplReader::EndSpecial()
2385 {
2386     // Frame / Table / Anl
2387     if (bAnl)
2388         StopAllAnl();                  // -> bAnl = false
2389 
2390     while(maApos.size() > 1)
2391     {
2392         StopTable();
2393         maApos.pop_back();
2394         --nInTable;
2395         if (maApos[nInTable] == true)
2396             StopApo();
2397     }
2398 
2399     if (maApos[0] == true)
2400         StopApo();
2401 
2402     ASSERT(!nInTable, "unclosed table!");
2403 }
2404 
ProcessSpecial(bool & rbReSync,WW8_CP nStartCp)2405 bool SwWW8ImplReader::ProcessSpecial(bool &rbReSync, WW8_CP nStartCp)
2406 {
2407     // Frame / Table / Anl
2408     if (bInHyperlink)
2409         return false;
2410 
2411     rbReSync = false;
2412 
2413     ASSERT(nInTable >= 0,"nInTable < 0!");
2414 
2415     // TabRowEnd
2416     bool bTableRowEnd = (pPlcxMan->HasParaSprm(bVer67 ? 25 : 0x2417) != 0 );
2417 
2418 // es muss leider fuer jeden Absatz zuerst nachgesehen werden,
2419 // ob sich unter den sprms
2420 // das sprm 29 (bzw. 0x261B) befindet, das ein APO einleitet.
2421 // Alle weiteren sprms  beziehen sich dann naemlich auf das APO und nicht
2422 // auf den normalen Text drumrum.
2423 // Dasselbe gilt fuer eine Tabelle ( sprm 24 (bzw. 0x2416) )
2424 // und Anls ( sprm 13 ).
2425 // WW: Tabelle in APO geht ( Beide Anfaende treten gleichzeitig auf )
2426 // WW: APO in Tabelle geht nicht
2427 // d.h. Wenn eine Tabelle Inhalt eines Apo ist, dann muss der
2428 // Apo-Anfang zuerst bearbeitet werden, damit die Tabelle im Apo steht
2429 // und nicht umgekehrt. Am Ende muss dagegen zuerst das Tabellenende
2430 // bearbeitet werden, da die Apo erst nach der Tabelle abgeschlossen
2431 // werden darf ( sonst wird das Apo-Ende nie gefunden ).
2432 // Dasselbe gilt fuer Fly / Anl, Tab / Anl, Fly / Tab / Anl.
2433 //
2434 // Wenn die Tabelle in einem Apo steht, fehlen im TabRowEnd-Bereich
2435 // die Apo-Angaben. Damit hier die Apo nicht beendet wird, wird
2436 // ProcessApo dann nicht aufgerufen.
2437 
2438 // KHZ: When there is a table inside the Apo the Apo-flags are also
2439 //      missing for the 2nd, 3rd... paragraphs of each cell.
2440 
2441 
2442 //  1st look for in-table flag, for 2000+ there is a subtable flag to
2443 //  be considered, the sprm 6649 gives the level of the table
2444     sal_uInt8 nCellLevel = 0;
2445 
2446     if (bVer67)
2447         nCellLevel = 0 != pPlcxMan->HasParaSprm(24);
2448     else
2449     {
2450         nCellLevel = 0 != pPlcxMan->HasParaSprm(0x2416);
2451         if (!nCellLevel)
2452             nCellLevel = 0 != pPlcxMan->HasParaSprm(0x244B);
2453     }
2454 
2455     WW8_TablePos *pTabPos=0;
2456     WW8_TablePos aTabPos;
2457     WW8PLCFx_Cp_FKP* pPap = 0;
2458     bool bTableHasPositionInfo = false;
2459 
2460     if (nCellLevel && !bVer67)
2461     {
2462         WW8PLCFxSave1 aSave;
2463         pPlcxMan->GetPap()->Save( aSave );
2464         rbReSync = true;
2465         pPap = pPlcxMan->GetPapPLCF();
2466         WW8_CP nMyStartCp=nStartCp;
2467 
2468         if (const sal_uInt8 *pLevel = pPlcxMan->HasParaSprm(0x6649))
2469             nCellLevel = *pLevel;
2470 
2471         bool bHasRowEnd = SearchRowEnd(pPap, nMyStartCp, nCellLevel-1);
2472 
2473         //Bad Table, remain unchanged in level, e.g. #i19667#
2474         if (!bHasRowEnd)
2475             nCellLevel = static_cast< sal_uInt8 >(nInTable);
2476 
2477         sal_uLong idstart = rDoc.GetNodes().GetEndOfContent().StartOfSectionIndex(); // get the node index
2478         sal_uLong idcur = 0;
2479         if ( pPaM && pPaM->GetPoint() )
2480             idcur = pPaM->GetPoint()->nNode.GetIndex();
2481 
2482         // Memory first table position info
2483         if ( !pFirstTablePap && idstart + 1 == idcur )
2484             pFirstTablePap = pPap;
2485 
2486         if ( bHasRowEnd  && ParseTabPos(&aTabPos,pPap) )
2487         {
2488             // If table front don't have some content and it is doc first table, ignore table text wrapping property
2489             bTableHasPositionInfo = true;
2490             if ( pFirstTablePap != pPap )
2491                 pTabPos = &aTabPos;
2492         }
2493 
2494         pPlcxMan->GetPap()->Restore( aSave );
2495     }
2496 
2497 //  then look if we are in an Apo
2498 
2499     ApoTestResults aApo = TestApo(nCellLevel, bTableRowEnd, pTabPos, !(pFirstTablePap == pPap && bTableHasPositionInfo));
2500 
2501     //look to see if we are in a Table, but Table in foot/end note not allowed
2502     bool bStartTab = (nInTable < nCellLevel) && !bFtnEdn;
2503 
2504     bool bStopTab = bWasTabRowEnd && (nInTable > nCellLevel) && !bFtnEdn;
2505 
2506     bWasTabRowEnd = false;  // must be deactivated right here to prevent next
2507                             // WW8TabDesc::TableCellEnd() from making nonsense
2508 
2509     if (nInTable && !bTableRowEnd && !bStopTab && (nInTable == nCellLevel && aApo.HasStartStop()))
2510         bStopTab = bStartTab = true;    // Required to stop and start table
2511 
2512 //  Dann auf Anl (Nummerierung) testen
2513 //  und dann alle Ereignisse in der richtigen Reihenfolge bearbeiten
2514 
2515     if( bAnl && !bTableRowEnd )
2516     {
2517         const sal_uInt8* pSprm13 = pPlcxMan->HasParaSprm( 13 );
2518         if( pSprm13 )
2519         {                                   // Noch Anl ?
2520             sal_uInt8 nT = static_cast< sal_uInt8 >(GetNumType( *pSprm13 ));
2521             if( ( nT != WW8_Pause && nT != nWwNumType ) // Anl-Wechsel
2522                 || aApo.HasStartStop()                  // erzwungenes Anl-Ende
2523                 || bStopTab || bStartTab )
2524             {
2525                 StopAnlToRestart(nT);  // Anl-Restart ( = Wechsel ) ueber sprms
2526             }
2527             else
2528             {
2529                 NextAnlLine( pSprm13 );                 // naechste Anl-Zeile
2530             }
2531         }
2532         else
2533         {                                           // Anl normal zuende
2534             StopAllAnl();                                  // Wirkliches Ende
2535         }
2536     }
2537     if (bStopTab)
2538     {
2539         StopTable();
2540         maApos.pop_back();
2541         --nInTable;
2542     }
2543     if (aApo.mbStopApo)
2544     {
2545         StopApo();
2546         maApos[nInTable] = false;
2547     }
2548 
2549     if (aApo.mbStartApo)
2550     {
2551         maApos[nInTable] = StartApo(aApo, pTabPos);
2552         // nach StartApo ist ein ReSync noetig ( eigentlich nur, falls die Apo
2553         // ueber eine FKP-Grenze geht
2554         rbReSync = true;
2555     }
2556     if (bStartTab)
2557     {
2558         WW8PLCFxSave1 aSave;
2559         pPlcxMan->GetPap()->Save( aSave );
2560 
2561         if (bAnl)                           // Nummerierung ueber Zellengrenzen
2562             StopAllAnl();                   // fuehrt zu Absturz -> keine Anls
2563                                             // in Tabellen
2564         while (nInTable < nCellLevel)
2565         {
2566             if (StartTable(nStartCp))
2567                 ++nInTable;
2568             else
2569                 break;
2570 
2571             maApos.push_back(false);
2572         }
2573         // nach StartTable ist ein ReSync noetig ( eigentlich nur, falls die
2574         // Tabelle ueber eine FKP-Grenze geht
2575         rbReSync = true;
2576         pPlcxMan->GetPap()->Restore( aSave );
2577     }
2578     return bTableRowEnd;
2579 }
2580 
GetCurrentCharSet()2581 CharSet SwWW8ImplReader::GetCurrentCharSet()
2582 {
2583     /*
2584     #i2015
2585     If the hard charset is set use it, if not see if there is an open
2586     character run that has set the charset, if not then fallback to the
2587     current underlying paragraph style.
2588     */
2589     CharSet eSrcCharSet = eHardCharSet;
2590     if (eSrcCharSet == RTL_TEXTENCODING_DONTKNOW)
2591     {
2592         if (!maFontSrcCharSets.empty())
2593             eSrcCharSet = maFontSrcCharSets.top();
2594         if ((eSrcCharSet == RTL_TEXTENCODING_DONTKNOW) && (nCharFmt != -1))
2595             eSrcCharSet = pCollA[nCharFmt].GetCharSet();
2596         if ((eSrcCharSet == RTL_TEXTENCODING_DONTKNOW) && StyleExists(nAktColl))
2597             eSrcCharSet = pCollA[nAktColl].GetCharSet();
2598         if (eSrcCharSet == RTL_TEXTENCODING_DONTKNOW)
2599         { // patch from cmc for #i52786#
2600             /*
2601              #i22206#/#i52786#
2602              The (default) character set used for a run of text is the default
2603              character set for the version of Word that last saved the document.
2604 
2605              This is a bit tentative, more might be required if the concept is correct.
2606              When later version of word write older 6/95 documents the charset is
2607              correctly set in the character runs involved, so its hard to reproduce
2608              documents that require this to be sure of the process involved.
2609             */
2610             const SvxLanguageItem *pLang =
2611                 (const SvxLanguageItem*)GetFmtAttr(RES_CHRATR_LANGUAGE);
2612             if (pLang)
2613             {
2614                 switch (pLang->GetLanguage())
2615                 {
2616                     case LANGUAGE_CZECH:
2617                     case LANGUAGE_HUNGARIAN:
2618                     case LANGUAGE_POLISH:
2619                         eSrcCharSet = RTL_TEXTENCODING_MS_1250;
2620                         break;
2621                     case LANGUAGE_RUSSIAN:
2622                         eSrcCharSet = RTL_TEXTENCODING_MS_1251;
2623                         break;
2624                     case LANGUAGE_GREEK:
2625                         eSrcCharSet = RTL_TEXTENCODING_MS_1253;
2626                         break;
2627                     case LANGUAGE_TURKISH:
2628                         eSrcCharSet = RTL_TEXTENCODING_MS_1254;
2629                         break;
2630                     default:
2631                         eSrcCharSet = RTL_TEXTENCODING_MS_1252;
2632                         break;
2633                 }
2634             }
2635         }
2636     }
2637     return eSrcCharSet;
2638 }
2639 
2640 //Takashi Ono for CJK
GetCurrentCJKCharSet()2641 CharSet SwWW8ImplReader::GetCurrentCJKCharSet()
2642 {
2643     /*
2644     #i2015
2645     If the hard charset is set use it, if not see if there is an open
2646     character run that has set the charset, if not then fallback to the
2647     current underlying paragraph style.
2648     */
2649     CharSet eSrcCharSet = eHardCharSet;
2650     if (eSrcCharSet == RTL_TEXTENCODING_DONTKNOW)
2651     {
2652         if (!maFontSrcCJKCharSets.empty())
2653             eSrcCharSet = maFontSrcCJKCharSets.top();
2654         if (pCollA != NULL)
2655         {
2656             if ((eSrcCharSet == RTL_TEXTENCODING_DONTKNOW) && (nCharFmt != -1))
2657                 eSrcCharSet = pCollA[nCharFmt].GetCJKCharSet();
2658             if (eSrcCharSet == RTL_TEXTENCODING_DONTKNOW)
2659                 eSrcCharSet = pCollA[nAktColl].GetCJKCharSet();
2660         }
2661         if (eSrcCharSet == RTL_TEXTENCODING_DONTKNOW)
2662         { // patch from cmc for #i52786#
2663             /*
2664              #i22206#/#i52786#
2665              The (default) character set used for a run of text is the default
2666              character set for the version of Word that last saved the document.
2667 
2668              This is a bit tentative, more might be required if the concept is correct.
2669              When later version of word write older 6/95 documents the charset is
2670              correctly set in the character runs involved, so its hard to reproduce
2671              documents that require this to be sure of the process involved.
2672             */
2673             const SvxLanguageItem *pLang =
2674                 (const SvxLanguageItem*)GetFmtAttr(RES_CHRATR_LANGUAGE);
2675             if (pLang)
2676             {
2677                 switch (pLang->GetLanguage())
2678                 {
2679                     case LANGUAGE_CZECH:
2680                         eSrcCharSet = RTL_TEXTENCODING_MS_1250;
2681                         break;
2682                     default:
2683                         eSrcCharSet = RTL_TEXTENCODING_MS_1252;
2684                         break;
2685                 }
2686             }
2687         }
2688     }
2689     return eSrcCharSet;
2690 }
2691 
PostProcessAttrs()2692 void SwWW8ImplReader::PostProcessAttrs()
2693 {
2694     if (mpPostProcessAttrsInfo != NULL)
2695     {
2696         SfxItemIter aIter(mpPostProcessAttrsInfo->mItemSet);
2697 
2698         const SfxPoolItem * pItem = aIter.GetCurItem();
2699         if (pItem != NULL)
2700         {
2701             do
2702             {
2703                 pCtrlStck->NewAttr(*mpPostProcessAttrsInfo->mPaM.GetPoint(),
2704                                    *pItem);
2705                 pCtrlStck->SetAttr(*mpPostProcessAttrsInfo->mPaM.GetMark(),
2706                                    pItem->Which(), true);
2707             }
2708             while (!aIter.IsAtEnd() && 0 != (pItem = aIter.NextItem()));
2709         }
2710 
2711         delete mpPostProcessAttrsInfo;
2712         mpPostProcessAttrsInfo = NULL;
2713     }
2714 }
2715 
2716 /*
2717  #i9241#
2718  It appears that some documents that are in a baltic 8 bit encoding which has
2719  some undefined characters can have use made of those characters, in which
2720  case they default to CP1252. If not then its perhaps that the font encoding
2721  is only in use for 6/7 and for 8+ if we are in 8bit mode then the encoding
2722  is always 1252.
2723 
2724  So a encoding converter that on an undefined character attempts to
2725  convert from 1252 on the undefined character
2726 */
Custom8BitToUnicode(rtl_TextToUnicodeConverter hConverter,sal_Char * pIn,sal_Size nInLen,sal_Unicode * pOut,sal_Size nOutLen)2727 sal_Size Custom8BitToUnicode(rtl_TextToUnicodeConverter hConverter,
2728     sal_Char *pIn, sal_Size nInLen, sal_Unicode *pOut, sal_Size nOutLen)
2729 {
2730     const sal_uInt32 nFlags =
2731         RTL_TEXTTOUNICODE_FLAGS_UNDEFINED_ERROR |
2732         RTL_TEXTTOUNICODE_FLAGS_MBUNDEFINED_ERROR |
2733         RTL_TEXTTOUNICODE_FLAGS_INVALID_IGNORE |
2734         RTL_TEXTTOUNICODE_FLAGS_FLUSH;
2735 
2736     const sal_uInt32 nFlags2 =
2737         RTL_TEXTTOUNICODE_FLAGS_UNDEFINED_IGNORE |
2738         RTL_TEXTTOUNICODE_FLAGS_MBUNDEFINED_IGNORE |
2739         RTL_TEXTTOUNICODE_FLAGS_INVALID_IGNORE |
2740         RTL_TEXTTOUNICODE_FLAGS_FLUSH;
2741 
2742     sal_Size nDestChars=0;
2743     sal_Size nConverted=0;
2744 
2745     do
2746     {
2747         sal_uInt32 nInfo = 0;
2748         sal_Size nThisConverted=0;
2749 
2750         nDestChars += rtl_convertTextToUnicode(hConverter, 0,
2751             pIn+nConverted, nInLen-nConverted,
2752             pOut+nDestChars, nOutLen-nDestChars,
2753             nFlags, &nInfo, &nThisConverted);
2754 
2755         ASSERT(nInfo == 0, "A character conversion failed!");
2756 
2757         nConverted += nThisConverted;
2758 
2759         if (
2760             nInfo & RTL_TEXTTOUNICODE_FLAGS_UNDEFINED_ERROR ||
2761             nInfo & RTL_TEXTTOUNICODE_FLAGS_MBUNDEFINED_ERROR
2762            )
2763         {
2764             sal_Size nOtherConverted;
2765             rtl_TextToUnicodeConverter hCP1252Converter =
2766                 rtl_createTextToUnicodeConverter(RTL_TEXTENCODING_MS_1252);
2767             nDestChars += rtl_convertTextToUnicode(hCP1252Converter, 0,
2768                 pIn+nConverted, 1,
2769                 pOut+nDestChars, nOutLen-nDestChars,
2770                 nFlags2, &nInfo, &nOtherConverted);
2771             rtl_destroyTextToUnicodeConverter(hCP1252Converter);
2772             nConverted+=1;
2773         }
2774     } while (nConverted < nInLen);
2775 
2776     return nDestChars;
2777 }
2778 
LangUsesHindiNumbers(sal_uInt16 nLang)2779 bool SwWW8ImplReader::LangUsesHindiNumbers(sal_uInt16 nLang)
2780 {
2781     bool bResult = false;
2782 
2783     switch (nLang)
2784     {
2785         case 0x1401: // Arabic(Algeria)
2786         case 0x3c01: // Arabic(Bahrain)
2787         case 0xc01: // Arabic(Egypt)
2788         case 0x801: // Arabic(Iraq)
2789         case 0x2c01: // Arabic (Jordan)
2790         case 0x3401: // Arabic(Kuwait)
2791         case 0x3001: // Arabic(Lebanon)
2792         case 0x1001: // Arabic(Libya)
2793         case 0x1801: // Arabic(Morocco)
2794         case 0x2001: // Arabic(Oman)
2795         case 0x4001: // Arabic(Qatar)
2796         case 0x401: // Arabic(Saudi Arabia)
2797         case 0x2801: // Arabic(Syria)
2798         case 0x1c01: // Arabic(Tunisia)
2799         case 0x3801: // Arabic(U.A.E)
2800         case 0x2401: // Arabic(Yemen)
2801             bResult = true;
2802             break;
2803         default:
2804             break;
2805     }
2806 
2807     return bResult;
2808 }
2809 
TranslateToHindiNumbers(sal_Unicode nChar)2810 sal_Unicode SwWW8ImplReader::TranslateToHindiNumbers(sal_Unicode nChar)
2811 {
2812     if (nChar >= 0x0030 && nChar <= 0x0039)
2813         return nChar + 0x0630;
2814 
2815     return nChar;
2816 }
2817 
2818 // Returnwert: true for no Sonderzeichen
ReadPlainChars(WW8_CP & rPos,long nEnd,long nCpOfs)2819 bool SwWW8ImplReader::ReadPlainChars(WW8_CP& rPos, long nEnd, long nCpOfs)
2820 {
2821     // Unicode-Flag neu setzen und notfalls File-Pos korrigieren
2822     // merke: Seek kostet nicht viel, da inline geprueft wird,
2823     //        ob die korrekte FilePos nicht schon erreicht ist.
2824     WW8_FC nStreamPos = pSBase->WW8Cp2Fc(nCpOfs+rPos, &bIsUnicode);
2825     pStrm->Seek( nStreamPos );
2826 
2827     xub_StrLen nLen;
2828     if (nEnd - rPos <= (STRING_MAXLEN-1))
2829         nLen = writer_cast<xub_StrLen>(nEnd - rPos);
2830     else
2831         nLen = STRING_MAXLEN-1;
2832     ASSERT(nLen, "String is 0");
2833     if (!nLen)
2834         return true;
2835 
2836     const CharSet eSrcCharSet = bVer67 ? GetCurrentCharSet() :
2837         RTL_TEXTENCODING_MS_1252;
2838     const CharSet eSrcCJKCharSet = bVer67 ? GetCurrentCJKCharSet() :
2839         RTL_TEXTENCODING_MS_1252;
2840 
2841     // (re)alloc UniString data
2842     String sPlainCharsBuf;
2843 
2844     sal_Unicode* pBuffer = sPlainCharsBuf.AllocBuffer( nLen );
2845     sal_Unicode* pWork = pBuffer;
2846 
2847     sal_Char* p8Bits = NULL;
2848 
2849     rtl_TextToUnicodeConverter hConverter = 0;
2850     if (!bIsUnicode || bVer67)
2851         hConverter = rtl_createTextToUnicodeConverter(eSrcCharSet);
2852 
2853     if (!bIsUnicode)
2854         p8Bits = new sal_Char[nLen];
2855 
2856     // read the stream data
2857     sal_uInt8   nBCode = 0;
2858     sal_uInt16 nUCode;
2859     xub_StrLen nL2;
2860 
2861     sal_uInt16 nCTLLang = 0;
2862     const SfxPoolItem * pItem = GetFmtAttr(RES_CHRATR_CTL_LANGUAGE);
2863     if (pItem != NULL)
2864         nCTLLang = dynamic_cast<const SvxLanguageItem *>(pItem)->GetLanguage();
2865 
2866     for( nL2 = 0; nL2 < nLen; ++nL2, ++pWork )
2867     {
2868         if (bIsUnicode)
2869             *pStrm >> nUCode;   // unicode  --> read 2 bytes
2870         else
2871         {
2872             *pStrm >> nBCode;   // old code --> read 1 byte
2873             nUCode = nBCode;
2874         }
2875 
2876         if (pStrm->GetError())
2877         {
2878             rPos = WW8_CP_MAX-10;     // -> eof or other error
2879             sPlainCharsBuf.ReleaseBufferAccess( 0 );
2880             delete [] p8Bits;
2881             return true;
2882         }
2883 
2884         if ((32 > nUCode) || (0xa0 == nUCode))
2885         {
2886             pStrm->SeekRel( bIsUnicode ? -2 : -1 );
2887             break;              // Sonderzeichen < 32, == 0xa0 gefunden
2888         }
2889 
2890         if (bIsUnicode)
2891         {
2892             if (!bVer67)
2893                 *pWork = nUCode;
2894             else
2895             {
2896                 if (nUCode >= 0x3000)       //0x8000 ?
2897                 {
2898                     sal_Char aTest[2];
2899                     aTest[0] = static_cast< sal_Char >((nUCode & 0xFF00) >> 8);
2900                     aTest[1] = static_cast< sal_Char >(nUCode & 0x00FF);
2901                     String aTemp(aTest, 2, eSrcCJKCharSet);
2902                     ASSERT(aTemp.Len() == 1, "so much for that theory");
2903                     *pWork = aTemp.GetChar(0);
2904                 }
2905                 else
2906                 {
2907                     sal_Char cTest = static_cast< sal_Char >(nUCode & 0x00FF);
2908                     Custom8BitToUnicode(hConverter, &cTest, 1, pWork, 1);
2909                 }
2910             }
2911         }
2912         else
2913             p8Bits[nL2] = nBCode;
2914     }
2915 
2916     if (nL2)
2917     {
2918         xub_StrLen nEndUsed = nL2;
2919 
2920         if (!bIsUnicode)
2921             nEndUsed = Custom8BitToUnicode(hConverter, p8Bits, nL2, pBuffer, nLen);
2922 
2923         for( xub_StrLen nI = 0; nI < nLen; ++nI, ++pBuffer )
2924             if (m_bRegardHindiDigits && bBidi && LangUsesHindiNumbers(nCTLLang))
2925                 *pBuffer = TranslateToHindiNumbers(*pBuffer);
2926 
2927         sPlainCharsBuf.ReleaseBufferAccess( nEndUsed );
2928 
2929         AddTextToParagraph(sPlainCharsBuf);
2930         rPos += nL2;
2931         if (!maApos.back()) //a para end in apo doesn't count
2932             bWasParaEnd = false;            //kein CR
2933     }
2934 
2935     if (hConverter)
2936         rtl_destroyTextToUnicodeConverter(hConverter);
2937     delete [] p8Bits;
2938     return nL2 >= nLen;
2939 }
2940 
AddTextToParagraph(const String & rAddString)2941 bool SwWW8ImplReader::AddTextToParagraph(const String& rAddString)
2942 {
2943     const SwTxtNode* pNd = pPaM->GetCntntNode()->GetTxtNode();
2944     if (rAddString.Len())
2945     {
2946 /*
2947 #ifdef DEBUG
2948 //!! does not compile with debug=t -> unresolved external (dbg_out),
2949 //!! someone who knows what he wants to get should fix this
2950 //        ::std::clog << "<addTextToParagraph>" << dbg_out(rAddString)
2951 //        << "</addTextToParagraph>" << ::std::endl;
2952 #endif
2953 */
2954         if ((pNd->GetTxt().Len() + rAddString.Len()) < STRING_MAXLEN -1)
2955         {
2956             rDoc.InsertString(*pPaM, rAddString);
2957         }
2958         else
2959         {
2960 
2961             if (pNd->GetTxt().Len()< STRING_MAXLEN -1)
2962             {
2963                 String sTempStr (rAddString,0,
2964                     STRING_MAXLEN - pNd->GetTxt().Len() -1);
2965                 rDoc.InsertString(*pPaM, sTempStr);
2966                 sTempStr = rAddString.Copy(sTempStr.Len(),
2967                     rAddString.Len() - sTempStr.Len());
2968                 AppendTxtNode(*pPaM->GetPoint());
2969                 rDoc.InsertString(*pPaM, sTempStr);
2970             }
2971             else
2972             {
2973                 AppendTxtNode(*pPaM->GetPoint());
2974                 rDoc.InsertString(*pPaM, rAddString);
2975             }
2976         }
2977 
2978         bReadTable = false;
2979     }
2980 
2981     return true;
2982 }
2983 
2984 // Returnwert: true for para end
ReadChars(WW8_CP & rPos,WW8_CP nNextAttr,long nTextEnd,long nCpOfs)2985 bool SwWW8ImplReader::ReadChars(WW8_CP& rPos, WW8_CP nNextAttr, long nTextEnd,
2986     long nCpOfs)
2987 {
2988     long nEnd = ( nNextAttr < nTextEnd ) ? nNextAttr : nTextEnd;
2989 
2990     if (bSymbol || bIgnoreText)
2991     {
2992         if( bSymbol )   // Spezialzeichen einfuegen
2993         {
2994             for(sal_uInt16 nCh = 0; nCh < nEnd - rPos; ++nCh)
2995             {
2996                 rDoc.InsertString( *pPaM, cSymbol );
2997             }
2998             pCtrlStck->SetAttr( *pPaM->GetPoint(), RES_CHRATR_FONT );
2999         }
3000         pStrm->SeekRel( nEnd- rPos );
3001         rPos = nEnd;    // ignoriere bis Attributende
3002         return false;
3003     }
3004 
3005     while (true)
3006     {
3007         if (ReadPlainChars(rPos, nEnd, nCpOfs))
3008             return false;                   // Fertig
3009 
3010         bool bStartLine = ReadChar(rPos, nCpOfs);
3011         rPos++;
3012         if (bPgSecBreak || bStartLine || rPos == nEnd)  // CR oder Fertig
3013         {
3014             return bStartLine;
3015         }
3016     }
3017 }
3018 
HandlePageBreakChar()3019 bool SwWW8ImplReader::HandlePageBreakChar()
3020 {
3021     bool bParaEndAdded = false;
3022     //#i1909# section/page breaks should not occur in tables, word
3023     //itself ignores them in this case.
3024     if (!nInTable)
3025     {
3026         //xushanchuan add for issue106569
3027         sal_Bool IsTemp=sal_True;
3028         SwTxtNode* pTemp = pPaM->GetNode()->GetTxtNode();
3029         if ( pTemp && !( pTemp->GetTxt().Len() ) && ( bFirstPara || bFirstParaOfPage ) )
3030         {
3031             IsTemp = sal_False;
3032             AppendTxtNode(*pPaM->GetPoint());
3033             pTemp->SetAttr(*GetDfltAttr(RES_PARATR_NUMRULE));
3034         }
3035         //xushanchuan end
3036         bPgSecBreak = true;
3037         pCtrlStck->KillUnlockedAttrs(*pPaM->GetPoint());
3038         /*
3039         If its a 0x0c without a paragraph end before it, act like a
3040         paragraph end, but nevertheless, numbering (and perhaps other
3041         similar constructs) do not exist on the para.
3042         */
3043         //xushanchuan add for issue106569
3044         if (!bWasParaEnd && IsTemp)
3045             //xushanchuan end
3046         {
3047             bParaEndAdded = true;
3048             if (0 >= pPaM->GetPoint()->nContent.GetIndex())
3049             {
3050                 if (SwTxtNode* pTxtNode = pPaM->GetNode()->GetTxtNode())
3051                 {
3052                     pTxtNode->SetAttr(
3053                         *GetDfltAttr(RES_PARATR_NUMRULE));
3054                 }
3055             }
3056         }
3057     }
3058     return bParaEndAdded;
3059 }
3060 
ReadChar(long nPosCp,long nCpOfs)3061 bool SwWW8ImplReader::ReadChar(long nPosCp, long nCpOfs)
3062 {
3063     bool bNewParaEnd = false;
3064     // Unicode-Flag neu setzen und notfalls File-Pos korrigieren
3065     // merke: Seek kostet nicht viel, da inline geprueft wird,
3066     //        ob die korrekte FilePos nicht schon erreicht ist.
3067     pStrm->Seek( pSBase->WW8Cp2Fc(nCpOfs+nPosCp, &bIsUnicode) );
3068 
3069     sal_uInt8   nBCode;
3070     sal_uInt16 nWCharVal;
3071     if( bIsUnicode )
3072         *pStrm >> nWCharVal;    // unicode  --> read 2 bytes
3073     else
3074     {
3075         *pStrm  >>  nBCode;     // old code --> read 1 byte
3076         nWCharVal = nBCode;
3077     }
3078 
3079     sal_Char cInsert = '\x0';
3080     bool bRet = false;
3081     //xushanchuan add for issue106569
3082     if ( 0xc != nWCharVal )
3083         bFirstParaOfPage = false;
3084     //xushanchuan end
3085     switch (nWCharVal)
3086     {
3087         case 0:
3088             {
3089                 // Seitennummer
3090                 SwPageNumberField aFld(
3091                     (SwPageNumberFieldType*)rDoc.GetSysFldType(
3092                     RES_PAGENUMBERFLD ), PG_RANDOM, SVX_NUM_ARABIC);
3093                 rDoc.InsertPoolItem(*pPaM, SwFmtFld(aFld), 0);
3094             }
3095             break;
3096         case 0xe:
3097             // if there is only one column word treats a column break like a pagebreak.
3098             if (maSectionManager.CurrentSectionColCount() < 2)
3099                 bRet = HandlePageBreakChar();
3100             else if (!nInTable)
3101             {
3102                 // Always insert a txtnode for a column break, e.g. ##
3103                 AppendTxtNode(*pPaM->GetPoint());
3104                 rDoc.InsertPoolItem(*pPaM,
3105                     SvxFmtBreakItem(SVX_BREAK_COLUMN_BEFORE, RES_BREAK), 0);
3106             }
3107             break;
3108         case 0x7:
3109             bNewParaEnd = true;
3110             TabCellEnd();       // table cell end (Flags abfragen!)
3111             break;
3112         case 0xf:
3113             if( !bSpec )        // "Satellit"
3114                 cInsert = '\xa4';
3115             break;
3116         case 0x14:
3117             if( !bSpec )        // "Para-Ende"-Zeichen
3118                 cInsert = '\xb5';
3119             break;
3120         case 0x15:
3121             if( !bSpec )        // Juristenparagraph
3122             {
3123                 cp_set::iterator aItr = maTOXEndCps.find((WW8_CP)nPosCp);
3124              if (aItr == maTOXEndCps.end())
3125                     cInsert = '\xa7';
3126              else
3127               maTOXEndCps.erase(aItr);
3128             }
3129             break;
3130         case 0x9:
3131             cInsert = '\x9';    // Tab
3132             break;
3133         case 0xb:
3134             cInsert = '\xa';    // Hard NewLine
3135             break;
3136         case 0xc:
3137             bRet = HandlePageBreakChar();
3138             break;
3139         case 0x1e:   // Non-breaking hyphen
3140             rDoc.InsertString( *pPaM, CHAR_HARDHYPHEN );
3141             break;
3142         case 0x1f:   // Non-required hyphens
3143             rDoc.InsertString( *pPaM, CHAR_SOFTHYPHEN );
3144             break;
3145         case 0xa0:   // Non-breaking spaces
3146             rDoc.InsertString( *pPaM, CHAR_HARDBLANK  );
3147             break;
3148         case 0x1:
3149             /*
3150             Current thinking is that if bObj is set then we have a
3151             straightforward "traditional" ole object, otherwise we have a
3152             graphic preview of an associated ole2 object (or a simple
3153             graphic of course)
3154             */
3155             //normally in the canvas field, the code is 0x8 0x1.
3156             //in a special case, the code is 0x1 0x1, which yields a simple picture
3157             {
3158                 bool bReadObj = IsInlineEscherHack();
3159                 if( bReadObj )
3160                 {
3161                     long nCurPos = pStrm->Tell();
3162                     sal_uInt8   nByteCode;
3163                     sal_uInt16 nWordCode;
3164 
3165                     if( bIsUnicode )
3166                         *pStrm >> nWordCode;
3167                     else
3168                     {
3169                         *pStrm >> nByteCode;
3170                         nWordCode = nByteCode;
3171                     }
3172                     if( nWordCode == 0x1 )
3173                         bReadObj = false;
3174                     pStrm->Seek( nCurPos );
3175                 }
3176                 if( !bReadObj )
3177                 {
3178                     SwFrmFmt *pResult = 0;
3179                     if (bObj)
3180                         pResult = ImportOle();
3181                     else if (bSpec)
3182                         pResult = ImportGraf();
3183 
3184                     // If we have a bad 0x1 insert a space instead.
3185                     if (!pResult)
3186                     {
3187                         cInsert = ' ';
3188                         ASSERT(!bObj && !bEmbeddObj && !nObjLocFc,
3189                             "WW8: Please report this document, it may have a "
3190                             "missing graphic");
3191                     }
3192                     else
3193                     {
3194                         // reset the flags.
3195                         bObj = bEmbeddObj = false;
3196                         nObjLocFc = 0;
3197                     }
3198                 }
3199             }
3200             break;
3201         case 0x8:
3202             if( !bObj )
3203                 Read_GrafLayer( nPosCp );
3204             break;
3205         case 0xd:
3206             bNewParaEnd = bRet = true;
3207             if (nInTable > 1)
3208             {
3209                 /*
3210                 #i9666#/#i23161#
3211                 Yes complex, if there is an entry in the undocumented PLCF
3212                 which I believe to be a record of cell and row boundaries
3213                 see if the magic bit which I believe to mean cell end is
3214                 set. I also think btw that the third byte of the 4 byte
3215                 value is the level of the cell
3216                 */
3217                 WW8PLCFspecial* pTest = pPlcxMan->GetMagicTables();
3218                 if (pTest && pTest->SeekPosExact(nPosCp+1+nCpOfs) &&
3219                     pTest->Where() == nPosCp+1+nCpOfs)
3220                 {
3221                     WW8_FC nPos;
3222                     void *pData;
3223                     pTest->Get(nPos, pData);
3224                     sal_uInt32 nData = SVBT32ToUInt32(*(SVBT32*)pData);
3225                     if (nData & 0x2)    //Might be how it works
3226                     {
3227                         TabCellEnd();
3228                         bRet = false;
3229                     }
3230                 }
3231                 else if (bWasTabCellEnd)
3232                 {
3233                     TabCellEnd();
3234                     bRet = false;
3235                 }
3236             }
3237 
3238             bWasTabCellEnd = false;
3239 
3240             break;              // line end
3241         case 0x5:               // Annotation reference
3242         case 0x13:
3243             break;
3244         case 0x2:
3245             if (!maFtnStack.empty())
3246                 cInsert = 0x2;
3247             break;                  // Auto-Fussnoten-Nummer
3248 #if OSL_DEBUG_LEVEL > 1
3249         default:
3250             ::std::clog << "<unknownValue val=\"" << nWCharVal << "\">" << ::std::endl;
3251             break;
3252 #endif
3253     }
3254 
3255     if( '\x0' != cInsert )
3256     {
3257         String sInsert = ByteString::ConvertToUnicode(cInsert,
3258             RTL_TEXTENCODING_MS_1252 );
3259         AddTextToParagraph(sInsert);
3260     }
3261     if (!maApos.back()) //a para end in apo doesn't count
3262         bWasParaEnd = bNewParaEnd;
3263     return bRet;
3264 }
3265 
ProcessAktCollChange(WW8PLCFManResult & rRes,bool * pStartAttr,bool bCallProcessSpecial)3266 void SwWW8ImplReader::ProcessAktCollChange(WW8PLCFManResult& rRes,
3267     bool* pStartAttr, bool bCallProcessSpecial)
3268 {
3269     sal_uInt16 nOldColl = nAktColl;
3270     nAktColl = pPlcxMan->GetColl();
3271 
3272     // Invalid Style-Id
3273     if (nAktColl >= nColls || !pCollA[nAktColl].pFmt || !pCollA[nAktColl].bColl)
3274     {
3275         nAktColl = 0;
3276         bParaAutoBefore = false;
3277         bParaAutoAfter = false;
3278     }
3279     else
3280     {
3281         bParaAutoBefore = pCollA[nAktColl].bParaAutoBefore;
3282         bParaAutoAfter = pCollA[nAktColl].bParaAutoAfter;
3283     }
3284 
3285     bool bTabRowEnd = false;
3286     if( pStartAttr && bCallProcessSpecial && !bInHyperlink )
3287     {
3288         bool bReSync;
3289         // Frame / Table / Autonumbering List Level
3290         bTabRowEnd = ProcessSpecial(bReSync, rRes.nAktCp+pPlcxMan->GetCpOfs());
3291         if( bReSync )
3292             *pStartAttr = pPlcxMan->Get( &rRes ); // hole Attribut-Pos neu
3293     }
3294 
3295     if (!bTabRowEnd && StyleExists(nAktColl))
3296     {
3297         SetTxtFmtCollAndListLevel( *pPaM, pCollA[ nAktColl ]);
3298         ChkToggleAttr(pCollA[ nOldColl ].n81Flags, pCollA[ nAktColl ].n81Flags);
3299         ChkToggleBiDiAttr(pCollA[nOldColl].n81BiDiFlags,
3300             pCollA[nAktColl].n81BiDiFlags);
3301     }
3302 }
3303 
ReadTextAttr(WW8_CP & rTxtPos,bool & rbStartLine)3304 long SwWW8ImplReader::ReadTextAttr(WW8_CP& rTxtPos, bool& rbStartLine)
3305 {
3306     long nSkipChars = 0;
3307     WW8PLCFManResult aRes;
3308 
3309     ASSERT(pPaM->GetNode()->GetTxtNode(), "Missing txtnode");
3310     bool bStartAttr = pPlcxMan->Get(&aRes); // hole Attribut-Pos
3311     aRes.nAktCp = rTxtPos;              // Akt. Cp-Pos
3312 
3313     bool bNewSection = (aRes.nFlags & MAN_MASK_NEW_SEP) && !bIgnoreText;
3314     if ( bNewSection )  // neue Section
3315     {
3316         ASSERT(pPaM->GetNode()->GetTxtNode(), "Missing txtnode");
3317         // PageDesc erzeugen und fuellen
3318         maSectionManager.CreateSep(rTxtPos, bPgSecBreak);
3319                                             // -> 0xc war ein Sectionbreak, aber
3320                                             // kein Pagebreak;
3321         bPgSecBreak = false;                // PageDesc erzeugen und fuellen
3322         ASSERT(pPaM->GetNode()->GetTxtNode(), "Missing txtnode");
3323     }
3324 
3325     // neuer Absatz ueber Plcx.Fkp.papx
3326     if ( (aRes.nFlags & MAN_MASK_NEW_PAP)|| rbStartLine )
3327     {
3328         ProcessAktCollChange( aRes, &bStartAttr,
3329             MAN_MASK_NEW_PAP == (aRes.nFlags & MAN_MASK_NEW_PAP) &&
3330             !bIgnoreText );
3331         rbStartLine = false;
3332     }
3333 
3334     // position of last CP that's to be ignored
3335     long nSkipPos = -1;
3336 
3337     if( 0 < aRes.nSprmId )                      // leere Attrs ignorieren
3338     {
3339         if( ( eFTN > aRes.nSprmId ) || ( 0x0800 <= aRes.nSprmId ) )
3340         {
3341             if( bStartAttr )                            // WW-Attribute
3342             {
3343                 if( aRes.nMemLen >= 0 )
3344                     ImportSprm(aRes.pMemPos, aRes.nSprmId);
3345             }
3346             else
3347                 EndSprm( aRes.nSprmId );        // Attr ausschalten
3348         }
3349         else if( aRes.nSprmId < 0x800 ) // eigene Hilfs-Attribute
3350         {
3351             if (bStartAttr)
3352             {
3353                 nSkipChars = ImportExtSprm(&aRes);
3354                 if (
3355                     (aRes.nSprmId == eFTN) || (aRes.nSprmId == eEDN) ||
3356                     (aRes.nSprmId == eFLD) || (aRes.nSprmId == eAND)
3357                    )
3358                 {
3359                     // Felder/Ftn-/End-Note hier ueberlesen
3360                     rTxtPos += nSkipChars;
3361                     nSkipPos = rTxtPos-1;
3362                 }
3363             }
3364             else
3365                 EndExtSprm( aRes.nSprmId );
3366         }
3367     }
3368 
3369     pStrm->Seek(pSBase->WW8Cp2Fc( pPlcxMan->GetCpOfs() + rTxtPos, &bIsUnicode));
3370 
3371     // Find next Attr position (and Skip attributes of field contents if needed)
3372     if (nSkipChars && !bIgnoreText)
3373         pCtrlStck->MarkAllAttrsOld();
3374     bool bOldIgnoreText = bIgnoreText;
3375     bIgnoreText = true;
3376     sal_uInt16 nOldColl = nAktColl;
3377     bool bDoPlcxManPlusPLus = true;
3378     long nNext;
3379     do
3380     {
3381         if( bDoPlcxManPlusPLus )
3382             (*pPlcxMan)++;
3383         nNext = pPlcxMan->Where();
3384 
3385         if (mpPostProcessAttrsInfo &&
3386             mpPostProcessAttrsInfo->mnCpStart == nNext)
3387         {
3388             mpPostProcessAttrsInfo->mbCopy = true;
3389         }
3390 
3391         if( (0 <= nNext) && (nSkipPos >= nNext) )
3392         {
3393             nNext = ReadTextAttr( rTxtPos, rbStartLine );
3394             bDoPlcxManPlusPLus = false;
3395             bIgnoreText = true;
3396         }
3397 
3398         if (mpPostProcessAttrsInfo &&
3399             nNext > mpPostProcessAttrsInfo->mnCpEnd)
3400         {
3401             mpPostProcessAttrsInfo->mbCopy = false;
3402         }
3403     }
3404     while( nSkipPos >= nNext );
3405     bIgnoreText    = bOldIgnoreText;
3406     if( nSkipChars )
3407     {
3408         pCtrlStck->KillUnlockedAttrs( *pPaM->GetPoint() );
3409         if( nOldColl != pPlcxMan->GetColl() )
3410             ProcessAktCollChange(aRes, 0, false);
3411     }
3412 
3413     return nNext;
3414 }
3415 //Modify here for #119405, by easyfan, 2012-05-24
3416 //Revised 2012.8.16 for the complex attribute presentation of 0x0D in MS
IsParaEndInCPs(sal_Int32 nStart,sal_Int32 nEnd,bool bSdOD) const3417 bool SwWW8ImplReader::IsParaEndInCPs(sal_Int32 nStart, sal_Int32 nEnd,bool bSdOD) const
3418 {
3419     //Modify for #119405 by chengjh, 2012-08-16
3420     //Revised for performance consideration
3421     if (nStart == -1 || nEnd == -1 || nEnd < nStart )
3422         return false;
3423 
3424     for (cp_vector::const_reverse_iterator aItr = maEndParaPos.rbegin(); aItr!= maEndParaPos.rend(); aItr++)
3425     //End
3426     {
3427         //Revised 2012.8.16,to the 0x0D,the attribute will have two situations
3428         //*********within***********exact******//
3429         //*********but also sample with only left and the position of 0x0d is the edge of the right side***********//
3430         if ( bSdOD && ( (nStart < *aItr && nEnd > *aItr) || ( nStart == nEnd && *aItr == nStart)) )
3431             return true;
3432         else if ( !bSdOD &&  (nStart < *aItr && nEnd >= *aItr) )
3433             return true;
3434     }
3435 
3436     return false;
3437 }
3438 //End of modification, by easyfan
3439 //Modify for #119405 by chengjh, 2012-08-16
3440 //Clear the para end position recorded in reader intermittently for the least impact on loading performance
ClearParaEndPosition()3441 void SwWW8ImplReader::ClearParaEndPosition()
3442 {
3443     if ( maEndParaPos.size() > 0 )
3444         maEndParaPos.clear();
3445 }
3446 //End
ReadAttrs(WW8_CP & rNext,WW8_CP & rTxtPos,bool & rbStartLine)3447 void SwWW8ImplReader::ReadAttrs(WW8_CP& rNext, WW8_CP& rTxtPos, bool& rbStartLine)
3448 {
3449     if( rTxtPos >= rNext )
3450     {           // Stehen Attribute an ?
3451 
3452         do
3453         {
3454         //Modify here for #119405, by easyfan, 2012-05-24
3455             maCurrAttrCP = rTxtPos;
3456         //End of modification, by easyfan
3457             rNext = ReadTextAttr( rTxtPos, rbStartLine );
3458         }
3459         while( rTxtPos >= rNext );
3460 
3461     }
3462     else if ( rbStartLine )
3463     {
3464 // keine Attribute, aber trotzdem neue Zeile
3465 // wenn eine Zeile mit einem Seitenumbruch aufhoert und sich keine
3466 // Absatzattribute / Absatzvorlagen aendern, ist das Zeilenende
3467 // nicht im Plcx.Fkp.papx eingetragen, d.h. ( nFlags & MAN_MASK_NEW_PAP )
3468 // ist false. Deshalb muss als Sonderbehandlung hier die Vorlage gesetzt
3469 // werden.
3470         if (!bCpxStyle && nAktColl < nColls)
3471             SetTxtFmtCollAndListLevel(*pPaM, pCollA[nAktColl]);
3472         rbStartLine = false;
3473     }
3474 }
3475 
3476 // CloseAttrEnds zum Lesen nur der Attributenden am Ende eines Textes oder
3477 // Textbereiches ( Kopfzeile, Fussnote, ...). Attributanfaenge, Felder
3478 // werden ignoriert.
CloseAttrEnds()3479 void SwWW8ImplReader::CloseAttrEnds()
3480 {
3481     //If there are any unclosed sprms then copy them to
3482     //another stack and close the ones that must be closed
3483     std::stack<sal_uInt16> aStack;
3484     pPlcxMan->TransferOpenSprms(aStack);
3485 
3486     while (!aStack.empty())
3487     {
3488         sal_uInt16 nSprmId = aStack.top();
3489         if ((0 < nSprmId) && (( eFTN > nSprmId) || (0x0800 <= nSprmId)))
3490             EndSprm(nSprmId);
3491         aStack.pop();
3492     }
3493 
3494     EndSpecial();
3495 }
3496 
ReadText(long nStartCp,long nTextLen,ManTypes nType)3497 bool SwWW8ImplReader::ReadText(long nStartCp, long nTextLen, ManTypes nType)
3498 {
3499     sw::log::Environment eContext = sw::log::eMainText;
3500     if (nType == MAN_MAINTEXT)
3501         eContext = sw::log::eMainText;
3502     else
3503         eContext = sw::log::eSubDoc;
3504     maTracer.EnterEnvironment(eContext);
3505 
3506     bool bJoined=false;
3507 
3508     bool bStartLine = true;
3509     short nCrCount = 0;
3510     short nDistance = 0;
3511 
3512     bWasParaEnd = false;
3513     nAktColl    =  0;
3514     pAktItemSet =  0;
3515     nCharFmt    = -1;
3516     bSpec = false;
3517     bPgSecBreak = false;
3518 
3519     pPlcxMan = new WW8PLCFMan( pSBase, nType, nStartCp );
3520     long nCpOfs = pPlcxMan->GetCpOfs(); // Offset fuer Header/Footer, Footnote
3521 
3522     WW8_CP nNext = pPlcxMan->Where();
3523     SwTxtNode* pPreviousNode = 0;
3524     sal_uInt8 nDropLines = 0;
3525     SwCharFmt* pNewSwCharFmt = 0;
3526     const SwCharFmt* pFmt = 0;
3527     pStrm->Seek( pSBase->WW8Cp2Fc( nStartCp + nCpOfs, &bIsUnicode ) );
3528 
3529     WW8_CP l = nStartCp;
3530     while ( l<nStartCp+nTextLen )
3531     {
3532         ReadAttrs( nNext, l, bStartLine );// behandelt auch Section-Breaks
3533         ASSERT(pPaM->GetNode()->GetTxtNode(), "Missing txtnode");
3534 
3535         if (mpPostProcessAttrsInfo != NULL)
3536             PostProcessAttrs();
3537 
3538         if( l>= nStartCp + nTextLen )
3539             break;
3540 
3541         bStartLine = ReadChars(l, nNext, nStartCp+nTextLen, nCpOfs);
3542 
3543         // If the previous paragraph was a dropcap then do not
3544         // create a new txtnode and join the two paragraphs together
3545 
3546         if (bStartLine && !pPreviousNode) // Zeilenende
3547         {
3548             bool bSplit = true;
3549             if (mbCareFirstParaEndInToc)
3550             {
3551                 mbCareFirstParaEndInToc = false;
3552                 if (pPaM->End() && pPaM->End()->nNode.GetNode().GetTxtNode() &&  pPaM->End()->nNode.GetNode().GetTxtNode()->Len() == 0)
3553                     bSplit = false;
3554             }
3555             if (mbCareLastParaEndInToc)
3556             {
3557                 mbCareLastParaEndInToc = false;
3558                 if (pPaM->End() && pPaM->End()->nNode.GetNode().GetTxtNode() &&  pPaM->End()->nNode.GetNode().GetTxtNode()->Len() == 0)
3559                     bSplit = false;
3560             }
3561             if (bSplit)
3562             {
3563                 // #119405# - We will record the CP of a paragraph end ('0x0D'), if current loading contents is from main stream;
3564                 if (mbOnLoadingMain)
3565                     maEndParaPos.push_back(l-1);
3566                 AppendTxtNode(*pPaM->GetPoint());
3567             }
3568         }
3569 
3570         if (pPreviousNode && bStartLine)
3571         {
3572             SwTxtNode* pEndNd = pPaM->GetNode()->GetTxtNode();
3573             const xub_StrLen nDropCapLen = pPreviousNode->GetTxt().Len();
3574 
3575             // Need to reset the font size and text position for the dropcap
3576             {
3577                 SwPaM aTmp(*pEndNd, 0, *pEndNd, nDropCapLen+1);
3578                 pCtrlStck->Delete(aTmp);
3579             }
3580 
3581             // Get the default document dropcap which we can use as our template
3582             const SwFmtDrop* defaultDrop =
3583                 (const SwFmtDrop*) GetFmtAttr(RES_PARATR_DROP);
3584             SwFmtDrop aDrop(*defaultDrop);
3585 
3586             aDrop.GetLines() = nDropLines;
3587             aDrop.GetDistance() = nDistance;
3588             aDrop.GetChars() = writer_cast<sal_uInt8>(nDropCapLen);
3589             // Word has no concept of a "whole word dropcap"
3590             aDrop.GetWholeWord() = false;
3591 
3592             if (pFmt)
3593                 aDrop.SetCharFmt(const_cast<SwCharFmt*>(pFmt));
3594             else if(pNewSwCharFmt)
3595                 aDrop.SetCharFmt(const_cast<SwCharFmt*>(pNewSwCharFmt));
3596 
3597             SwPosition aStart(*pEndNd);
3598             pCtrlStck->NewAttr(aStart, aDrop);
3599             pCtrlStck->SetAttr(*pPaM->GetPoint(), RES_PARATR_DROP);
3600             pPreviousNode = 0;
3601         }
3602         else if (bDropCap)
3603         {
3604             // If we have found a dropcap store the textnode
3605             pPreviousNode = pPaM->GetNode()->GetTxtNode();
3606 
3607             const sal_uInt8 *pDCS;
3608 
3609             if (bVer67)
3610                 pDCS = pPlcxMan->GetPapPLCF()->HasSprm(46);
3611             else
3612                 pDCS = pPlcxMan->GetPapPLCF()->HasSprm(0x442C);
3613 
3614             if (pDCS)
3615                 nDropLines = (*pDCS) >> 3;
3616             else    // There is no Drop Cap Specifier hence no dropcap
3617                 pPreviousNode = 0;
3618 
3619             if (const sal_uInt8 *pDistance = pPlcxMan->GetPapPLCF()->HasSprm(0x842F))
3620                 nDistance = SVBT16ToShort( pDistance );
3621             else
3622                 nDistance = 0;
3623 
3624             const SwFmtCharFmt *pSwFmtCharFmt = 0;
3625 
3626             if(pAktItemSet)
3627                 pSwFmtCharFmt = &(ItemGet<SwFmtCharFmt>(*pAktItemSet, RES_TXTATR_CHARFMT));
3628 
3629             if(pSwFmtCharFmt)
3630                 pFmt = pSwFmtCharFmt->GetCharFmt();
3631 
3632             if(pAktItemSet && !pFmt)
3633             {
3634                 String sPrefix(CREATE_CONST_ASC( "WW8Dropcap"));
3635                 sPrefix += String::CreateFromInt32( nDropCap++ );
3636                 pNewSwCharFmt = rDoc.MakeCharFmt(sPrefix, (SwCharFmt*)rDoc.GetDfltCharFmt());
3637                  pAktItemSet->ClearItem(RES_CHRATR_ESCAPEMENT);
3638                 pNewSwCharFmt->SetFmtAttr( *pAktItemSet );
3639             }
3640 
3641             delete pAktItemSet;
3642             pAktItemSet = 0;
3643             bDropCap=false;
3644         }
3645 
3646         if (bStartLine || bWasTabRowEnd)
3647         {
3648             // alle 64 CRs aufrufen not for Header u. ae.
3649             if ((nCrCount++ & 0x40) == 0 && nType == MAN_MAINTEXT)
3650             {
3651                 nProgress = (sal_uInt16)( l * 100 / nTextLen );
3652                 ::SetProgressState(nProgress, mpDocShell); // Update
3653             }
3654         }
3655 
3656         // If we have encountered a 0x0c which indicates either section of
3657         // pagebreak then look it up to see if it is a section break, and
3658         // if it is not then insert a page break. If it is a section break
3659         // it will be handled as such in the ReadAttrs of the next loop
3660         if (bPgSecBreak)
3661         {
3662             // We need only to see if a section is ending at this cp,
3663             // the plcf will already be sitting on the correct location
3664             // if it is there.
3665             WW8PLCFxDesc aTemp;
3666             aTemp.nStartPos = aTemp.nEndPos = WW8_CP_MAX;
3667             if (pPlcxMan->GetSepPLCF())
3668                 pPlcxMan->GetSepPLCF()->GetSprms(&aTemp);
3669             if ((aTemp.nStartPos != l) && (aTemp.nEndPos != l))
3670             {
3671                 // #i39251# - insert text node for page break, if no one inserted.
3672                 // #i43118# - refine condition: the anchor control stack has to have entries,
3673                 // otherwise it's not needed to insert a text node.
3674                 if ( !bStartLine && pAnchorStck->Count() > 0 )
3675                 {
3676                     AppendTxtNode(*pPaM->GetPoint());
3677                 }
3678                 rDoc.InsertPoolItem(*pPaM,
3679                     SvxFmtBreakItem(SVX_BREAK_PAGE_BEFORE, RES_BREAK), 0);
3680                 bFirstParaOfPage = true;//xushanchuan add for issue106569
3681                 bPgSecBreak = false;
3682             }
3683         }
3684     }
3685 
3686     if (pPaM->GetPoint()->nContent.GetIndex())
3687         AppendTxtNode(*pPaM->GetPoint());
3688 
3689     if (!bInHyperlink)
3690         bJoined = JoinNode(*pPaM);
3691 
3692     CloseAttrEnds();
3693 
3694     delete pPlcxMan, pPlcxMan = 0;
3695     maTracer.LeaveEnvironment(eContext);
3696     return bJoined;
3697 }
3698 
3699 /***************************************************************************
3700 #           class SwWW8ImplReader
3701 #**************************************************************************/
3702 
SwWW8ImplReader(sal_uInt8 nVersionPara,SvStorage * pStorage,SvStream * pSt,SwDoc & rD,const String & rBaseURL,bool bNewDoc)3703 SwWW8ImplReader::SwWW8ImplReader(sal_uInt8 nVersionPara, SvStorage* pStorage,
3704     SvStream* pSt, SwDoc& rD, const String& rBaseURL, bool bNewDoc)
3705     : mpDocShell(rD.GetDocShell())
3706     , maTracer(*(mpDocShell->GetMedium()))
3707     , pStg(pStorage)
3708     , pStrm(pSt)
3709     , pTableStream(0)
3710     , pDataStream(0)
3711     , rDoc(rD)
3712     , maSectionManager(*this)
3713     , maInsertedTables(rD)
3714     , maSectionNameGenerator(rD,CREATE_CONST_ASC("WW"))
3715     , maGrfNameGenerator(bNewDoc,String('G'))
3716     , maParaStyleMapper(rD)
3717     , maCharStyleMapper(rD)
3718     , maTxtNodesHavingFirstLineOfstSet()
3719     , maTxtNodesHavingLeftIndentSet()
3720     , pMSDffManager(0)
3721     , mpAtnNames(0)
3722     , pAuthorInfos(0)
3723     , sBaseURL(rBaseURL)
3724     , m_bRegardHindiDigits( false )
3725     , mbNewDoc(bNewDoc)
3726     , nDropCap(0)
3727     , nIdctHint(0)
3728     , bBidi(false)
3729     , bReadTable(false)
3730     , mbLoadingTOXCache(false)
3731     , mnEmbeddedTOXLevel(0)
3732     , mbLoadingTOXHyperlink(false)
3733     , mpPosAfterTOC(0)
3734     , mbCareFirstParaEndInToc(false)
3735     , mbCareLastParaEndInToc(false)
3736     , maTOXEndCps()
3737     //Modify here for #119405, by easyfan, 2012-05-24
3738     ,maCurrAttrCP(-1),
3739     mbOnLoadingMain(false)
3740     //End of modification, by easyfan
3741 {
3742     pStrm->SetNumberFormatInt( NUMBERFORMAT_INT_LITTLEENDIAN );
3743     nWantedVersion = nVersionPara;
3744     pCtrlStck   = 0;
3745     mpRedlineStack = 0;
3746     pReffedStck = 0;
3747     pReffingStck = 0;
3748     pAnchorStck = 0;
3749     pFonts = 0;
3750     pSBase = 0;
3751     pPlcxMan = 0;
3752     pStyles = 0;
3753     pAktColl = 0;
3754     pLstManager = 0;
3755     pAktItemSet = 0;
3756     pCollA = 0;
3757     pDfltTxtFmtColl = 0;
3758     pStandardFmtColl = 0;
3759     pHdFt = 0;
3760     pWFlyPara = 0;
3761     pSFlyPara = 0;
3762     pFlyFmtOfJustInsertedGraphic   = 0;
3763     pFmtOfJustInsertedApo = 0;
3764     pPreviousNumPaM = 0;
3765     pPrevNumRule = 0;
3766     nColls = nAktColl = 0;
3767     nObjLocFc = nPicLocFc = 0;
3768     nInTable=0;
3769     bReadNoTbl = bPgSecBreak = bSpec = bObj = bTxbxFlySection
3770                = bHasBorder = bSymbol = bIgnoreText
3771                = bWasTabRowEnd = bWasTabCellEnd = false;
3772     bShdTxtCol = bCharShdTxtCol = bAnl = bHdFtFtnEdn = bFtnEdn
3773                = bIsHeader = bIsFooter = bIsUnicode = bCpxStyle = bStyNormal =
3774                  bWWBugNormal  = false;
3775 
3776     mpPostProcessAttrsInfo = 0;
3777 
3778     bNoAttrImport = bPgChpLevel = bEmbeddObj = false;
3779     bAktAND_fNumberAcross = false;
3780     bNoLnNumYet = true;
3781     bInHyperlink = false;
3782     bWasParaEnd = false;
3783     bDropCap = false;
3784     bFirstPara = true;
3785       bFirstParaOfPage = false;//xushanchuan add for issue106569
3786     bParaAutoBefore = false;
3787     bParaAutoAfter = false;
3788     nProgress = 0;
3789     nSwNumLevel = nWwNumType = 0xff;
3790     pTableDesc = 0;
3791     pNumOlst = 0;
3792     pNode_FLY_AT_PARA = 0;
3793     pDrawModel = 0;
3794     pDrawPg = 0;
3795     mpDrawEditEngine = 0;
3796     pWWZOrder = 0;
3797     pFormImpl = 0;
3798     pNumFldType = 0;
3799     nFldNum = 0;
3800 
3801     nLFOPosition = USHRT_MAX;
3802     nListLevel = WW8ListManager::nMaxLevel;
3803     eHardCharSet = RTL_TEXTENCODING_DONTKNOW;
3804 
3805     nPgChpDelim = nPgChpLevel = 0;
3806 
3807     maApos.push_back(false);
3808 }
3809 
DeleteStk(SwFltControlStack * pStck)3810 void SwWW8ImplReader::DeleteStk(SwFltControlStack* pStck)
3811 {
3812     if( pStck )
3813     {
3814         pStck->SetAttr( *pPaM->GetPoint(), 0, false);
3815         pStck->SetAttr( *pPaM->GetPoint(), 0, false);
3816         delete pStck;
3817     }
3818     else
3819     {
3820         ASSERT( sal_False, "WW stack already deleted" );
3821     }
3822 }
3823 
SetSegmentToPageDesc(const wwSection & rSection,bool bTitlePage,bool bIgnoreCols)3824 void wwSectionManager::SetSegmentToPageDesc(const wwSection &rSection,
3825     bool bTitlePage, bool bIgnoreCols)
3826 {
3827     SwPageDesc &rPage = bTitlePage ? *rSection.mpTitlePage : *rSection.mpPage;
3828 
3829     SetNumberingType(rSection, rPage);
3830 
3831     SwFrmFmt &rFmt = rPage.GetMaster();
3832 
3833     if(mrReader.pWDop->fUseBackGroundInAllmodes)  // #i56806# Make sure mrReader is initialized
3834         mrReader.GrafikCtor();
3835 
3836 
3837     if (mrReader.pWDop->fUseBackGroundInAllmodes && mrReader.pMSDffManager)
3838     {
3839         Rectangle aRect(0, 0, 100, 100); //A dummy, we don't care about the size
3840         SvxMSDffImportData aData(aRect);
3841         SdrObject* pObject = 0;
3842         if (mrReader.pMSDffManager->GetShape(0x401, pObject, aData))
3843         {
3844             SvxMSDffImportRec * pRec = aData.GetRecord(0);
3845 
3846             // Only handle shape if it is a background shape
3847             if ((pRec->nFlags & 0x400) != 0)
3848             {
3849                 SfxItemSet aSet(rFmt.GetAttrSet());
3850                 mrReader.MatchSdrItemsIntoFlySet(pObject, aSet, mso_lineSimple,
3851                                                  mso_sptRectangle, aRect);
3852                 rFmt.SetFmtAttr(aSet.Get(RES_BACKGROUND));
3853             }
3854         }
3855     }
3856     wwULSpaceData aULData;
3857     GetPageULData(rSection, bTitlePage, aULData);
3858     SetPageULSpaceItems(rFmt, aULData, rSection);
3859 
3860     SetPage(rPage, rFmt, rSection, bIgnoreCols);
3861 
3862     bool bSetBorder = false;
3863     switch (rSection.maSep.pgbApplyTo)
3864     {
3865         case 0:
3866         case 3:
3867             bSetBorder = true;
3868             break;
3869         case 1:
3870             bSetBorder = bTitlePage;
3871             break;
3872         case 2:
3873             bSetBorder = !bTitlePage;
3874             break;
3875     }
3876     if (bSetBorder)
3877         mrReader.SetPageBorder(rFmt, rSection);
3878 
3879     mrReader.SetDocumentGrid(rFmt, rSection);
3880 }
3881 
SetUseOn(wwSection & rSection)3882 void wwSectionManager::SetUseOn(wwSection &rSection)
3883 {
3884     bool bEven = (rSection.maSep.grpfIhdt & (WW8_HEADER_EVEN|WW8_FOOTER_EVEN)) ?
3885         true : false;
3886 
3887     bool bMirror = mrReader.pWDop->fMirrorMargins ||
3888         mrReader.pWDop->doptypography.f2on1;
3889 
3890     UseOnPage eUseBase = bMirror ? nsUseOnPage::PD_MIRROR : nsUseOnPage::PD_ALL;
3891     UseOnPage eUse = eUseBase;
3892     if (!bEven)
3893         eUse = (UseOnPage)(eUse | nsUseOnPage::PD_HEADERSHARE | nsUseOnPage::PD_FOOTERSHARE);
3894 
3895     ASSERT(rSection.mpPage, "Makes no sense to call me with no pages to set");
3896     if (rSection.mpPage)
3897         rSection.mpPage->WriteUseOn(eUse);
3898     if (rSection.mpTitlePage)
3899     {
3900         rSection.mpTitlePage->WriteUseOn(
3901             (UseOnPage) (eUseBase | nsUseOnPage::PD_HEADERSHARE | nsUseOnPage::PD_FOOTERSHARE));
3902     }
3903 }
3904 
3905 //Set the page descriptor on this node, handle the different cases for a text
3906 //node or a table
GiveNodePageDesc(SwNodeIndex & rIdx,const SwFmtPageDesc & rPgDesc,SwDoc & rDoc)3907 void GiveNodePageDesc(SwNodeIndex &rIdx, const SwFmtPageDesc &rPgDesc,
3908     SwDoc &rDoc)
3909 {
3910     /*
3911     If its a table here, apply the pagebreak to the table
3912     properties, otherwise we add it to the para at this
3913     position
3914     */
3915     if (rIdx.GetNode().IsTableNode())
3916     {
3917         SwTable& rTable =
3918             rIdx.GetNode().GetTableNode()->GetTable();
3919         SwFrmFmt* pApply = rTable.GetFrmFmt();
3920         ASSERT(pApply, "impossible");
3921         if (pApply)
3922             pApply->SetFmtAttr(rPgDesc);
3923     }
3924     else
3925     {
3926         SwPosition aPamStart(rIdx);
3927         aPamStart.nContent.Assign(
3928             rIdx.GetNode().GetCntntNode(), 0);
3929         SwPaM aPage(aPamStart);
3930 
3931         rDoc.InsertPoolItem(aPage, rPgDesc, 0);
3932     }
3933 }
3934 
3935 //Map a word section with to either one or two writer page descriptors
3936 //depending on if the word section has a title page
SetSwFmtPageDesc(mySegIter & rIter,mySegIter & rStart,bool bIgnoreCols)3937 SwFmtPageDesc wwSectionManager::SetSwFmtPageDesc(mySegIter &rIter,
3938     mySegIter &rStart, bool bIgnoreCols)
3939 {
3940     SwFmtPageDesc aEmpty;
3941     // Always read title page header/footer data - it could be used by following sections
3942     {
3943         if (IsNewDoc() && rIter == rStart)
3944         {
3945             rIter->mpTitlePage =
3946                 mrReader.rDoc.GetPageDescFromPool(RES_POOLPAGE_FIRST);
3947         }
3948         else
3949         {
3950             sal_uInt16 nPos = mrReader.rDoc.MakePageDesc(
3951                 ViewShell::GetShellRes()->GetPageDescName(mnDesc)
3952                 , 0, false);
3953             rIter->mpTitlePage = &mrReader.rDoc._GetPageDesc(nPos);
3954         }
3955         ASSERT(rIter->mpTitlePage, "no page!");
3956         if (!rIter->mpTitlePage)
3957             return aEmpty;
3958 
3959         SetSegmentToPageDesc(*rIter, true, bIgnoreCols);
3960     }
3961 
3962     if (IsNewDoc() && rIter == rStart)
3963     {
3964         rIter->mpPage =
3965             mrReader.rDoc.GetPageDescFromPool(RES_POOLPAGE_STANDARD);
3966     }
3967     else
3968     {
3969         sal_uInt16 nPos = mrReader.rDoc.MakePageDesc(
3970             ViewShell::GetShellRes()->GetPageDescName(mnDesc,
3971                 false, rIter->HasTitlePage()),
3972                 rIter->mpTitlePage, false);
3973         rIter->mpPage = &mrReader.rDoc._GetPageDesc(nPos);
3974     }
3975     ASSERT(rIter->mpPage, "no page!");
3976     if (!rIter->mpPage)
3977         return aEmpty;
3978 
3979     //Set page before hd/ft
3980     const wwSection *pPrevious = 0;
3981 
3982     mySegIter aPrev = rIter;
3983     while( aPrev!= rStart )
3984     {
3985         aPrev--;
3986         pPrevious = &(*(aPrev));
3987         if( aPrev->IsContinous())
3988             continue;
3989         else{
3990             break;
3991         }
3992     }
3993 
3994     SetHdFt(*rIter, std::distance(rStart, rIter), pPrevious);
3995     SetUseOn(*rIter);
3996 
3997     //Set hd/ft after set page
3998     if (rIter->mpTitlePage)
3999         SetSegmentToPageDesc(*rIter, true, bIgnoreCols);
4000     SetSegmentToPageDesc(*rIter, false, bIgnoreCols);
4001 
4002     SwFmtPageDesc aRet(rIter->HasTitlePage() ?
4003         rIter->mpTitlePage : rIter->mpPage);
4004 
4005     rIter->mpPage->SetFollow(rIter->mpPage);
4006 
4007     if (rIter->mpTitlePage)
4008         rIter->mpTitlePage->SetFollow(rIter->mpPage);
4009 
4010     if (rIter->PageRestartNo())
4011         aRet.SetNumOffset(rIter->PageStartAt());
4012 
4013     ++mnDesc;
4014     return aRet;
4015 }
4016 
IsNewDoc() const4017 bool wwSectionManager::IsNewDoc() const
4018 {
4019     return mrReader.mbNewDoc;
4020 }
4021 
InsertSegments()4022 void wwSectionManager::InsertSegments()
4023 {
4024     const SvtFilterOptions* pOpt = SvtFilterOptions::Get();
4025     sal_Bool bUseEnhFields=(pOpt && pOpt->IsUseEnhancedFields());
4026     mySegIter aEnd = maSegments.end();
4027     mySegIter aStart = maSegments.begin();
4028     for (mySegIter aIter = aStart; aIter != aEnd; ++aIter)
4029     {
4030         mySegIter aNext = aIter+1;
4031         mySegIter aPrev = (aIter == aStart) ? aIter : aIter-1;
4032 
4033         // If two following sections are different in following properties, Word will interprete a continuous
4034         // section break between them as if it was a section break next page.
4035         bool bThisAndPreviousAreCompatible = ((aIter->GetPageWidth() == aPrev->GetPageWidth()) &&
4036             (aIter->GetPageHeight() == aPrev->GetPageHeight()) && (aIter->IsLandScape() == aPrev->IsLandScape()));
4037 
4038         bool bInsertSection = (aIter != aStart) ? (aIter->IsContinous() &&  bThisAndPreviousAreCompatible): false;
4039         bool bInsertPageDesc = !bInsertSection;
4040         bool bProtected = SectionIsProtected(*aIter); // do we really  need this ?? I guess I have a different logic in editshell which disales this...
4041         if (bUseEnhFields && mrReader.pWDop->fProtEnabled && aIter->IsNotProtected())
4042         {
4043             // here we have the special case that the whole document is protected, with the exception of this section.
4044             // I want to address this when I do the section rework, so for the moment we disable the overall protection then...
4045             mrReader.rDoc.set(IDocumentSettingAccess::PROTECT_FORM, false );
4046         }
4047 
4048 
4049         if (bInsertPageDesc)
4050         {
4051             /*
4052              If a cont section follows this section then we won't be
4053              creating a page desc with 2+ cols as we cannot host a one
4054              col section in a 2+ col pagedesc and make it look like
4055              word. But if the current section actually has columns then
4056              we are forced to insert a section here as well as a page
4057              descriptor.
4058             */
4059 
4060             bool bIgnoreCols = false;
4061             bool bThisAndNextAreCompatible = (aNext != aEnd) ? ((aIter->GetPageWidth() == aNext->GetPageWidth()) &&
4062                 (aIter->GetPageHeight() == aNext->GetPageHeight()) && (aIter->IsLandScape() == aNext->IsLandScape())) : true;
4063 
4064             if (((aNext != aEnd && aNext->IsContinous() && bThisAndNextAreCompatible) || bProtected))
4065             {
4066                 bIgnoreCols = true;
4067                 if ((aIter->NoCols() > 1) || bProtected)
4068                     bInsertSection = true;
4069             }
4070 
4071             SwFmtPageDesc aDesc(SetSwFmtPageDesc(aIter, aStart, bIgnoreCols));
4072             if (!aDesc.GetPageDesc())
4073                 continue;
4074             GiveNodePageDesc(aIter->maStart, aDesc, mrReader.rDoc);
4075         }
4076 
4077         SwTxtNode* pTxtNd = 0;
4078         if (bInsertSection)
4079         {
4080             //Start getting the bounds of this section
4081             SwPaM aSectPaM(*mrReader.pPaM);
4082             SwNodeIndex aAnchor(aSectPaM.GetPoint()->nNode);
4083             if (aNext != aEnd)
4084             {
4085                 aAnchor = aNext->maStart;
4086                 aSectPaM.GetPoint()->nNode = aAnchor;
4087                 aSectPaM.GetPoint()->nContent.Assign(
4088                     aNext->maStart.GetNode().GetCntntNode(), 0);
4089                 aSectPaM.Move(fnMoveBackward);
4090             }
4091 
4092             const SwPosition* pPos  = aSectPaM.GetPoint();
4093             SwTxtNode const*const pSttNd = pPos->nNode.GetNode().GetTxtNode();
4094             const SwTableNode* pTableNd = pSttNd ? pSttNd->FindTableNode() : 0;
4095             if (pTableNd)
4096             {
4097                 pTxtNd =
4098                     mrReader.rDoc.GetNodes().MakeTxtNode(aAnchor,
4099                     mrReader.rDoc.GetTxtCollFromPool( RES_POOLCOLL_TEXT ));
4100 
4101                 aSectPaM.GetPoint()->nNode = SwNodeIndex(*pTxtNd);
4102                 aSectPaM.GetPoint()->nContent.Assign(
4103                     aSectPaM.GetCntntNode(), 0);
4104             }
4105 
4106             aSectPaM.SetMark();
4107 
4108             aSectPaM.GetPoint()->nNode = aIter->maStart;
4109             aSectPaM.GetPoint()->nContent.Assign(
4110                 aSectPaM.GetCntntNode(), 0);
4111             //End getting the bounds of this section, quite a job eh ?
4112 
4113             SwSectionFmt *pRet = InsertSection(aSectPaM, *aIter);
4114             //The last section if continuous is always unbalanced
4115             if (pRet)
4116             {
4117                 //Set the columns to be UnBalanced if that compatibility option
4118                 //is set
4119                 if (mrReader.pWDop->fNoColumnBalance)
4120                     pRet->SetFmtAttr(SwFmtNoBalancedColumns(true));
4121                 else
4122                 {
4123                     //Otherwise set to unbalanced if the following section is
4124                     //not continuous, (which also means that the last section
4125                     //is unbalanced)
4126                     if (aNext == aEnd || !aNext->IsContinous())
4127                         pRet->SetFmtAttr(SwFmtNoBalancedColumns(true));
4128                 }
4129             }
4130 
4131             bool bHasOwnHdFt = false;
4132             /*
4133              In this nightmare scenario the continuous section has its own
4134              headers and footers so we will try and find a hard page break
4135              between here and the end of the section and put the headers and
4136              footers there.
4137             */
4138             if (!bInsertPageDesc)
4139             {
4140                bHasOwnHdFt =
4141                 mrReader.HasOwnHeaderFooter(
4142                  aIter->maSep.grpfIhdt & ~(WW8_HEADER_FIRST | WW8_FOOTER_FIRST),
4143                  aIter->maSep.grpfIhdt, std::distance(aStart, aIter)
4144                 );
4145             }
4146             if (bHasOwnHdFt)
4147             {
4148                 // #i40766# Need to cache the page descriptor in case there is
4149                 // no page break in the section
4150                 SwPageDesc *pOrig = aIter->mpPage;
4151                 SwPageDesc *pOrigTitle = aIter->mpTitlePage;
4152                 bool bFailed = true;
4153                 SwFmtPageDesc aDesc(SetSwFmtPageDesc(aIter, aStart, true));
4154                 if (aDesc.GetPageDesc())
4155                 {
4156                     sal_uLong nStart = aSectPaM.Start()->nNode.GetIndex();
4157                     sal_uLong nEnd   = aSectPaM.End()->nNode.GetIndex();
4158                     for(; nStart <= nEnd; ++nStart)
4159                     {
4160                         SwNode* pNode = mrReader.rDoc.GetNodes()[nStart];
4161                         if (!pNode)
4162                             continue;
4163                         if (sw::util::HasPageBreak(*pNode))
4164                         {
4165                             SwNodeIndex aIdx(*pNode);
4166                             GiveNodePageDesc(aIdx, aDesc, mrReader.rDoc);
4167                             bFailed = false;
4168                             break;
4169                         }
4170                     }
4171                 }
4172                 if(bFailed)
4173                 {
4174                     aIter->mpPage = pOrig;
4175                     aIter->mpTitlePage = pOrigTitle;
4176                 }
4177             }
4178         }
4179 
4180         if (pTxtNd)
4181         {
4182             SwNodeIndex aIdx(*pTxtNd);
4183             SwPosition aPos(aIdx);
4184             SwPaM aTest(aPos);
4185             mrReader.rDoc.DelFullPara(aTest);
4186             pTxtNd = 0;
4187         }
4188     }
4189 }
4190 
StoreMacroCmds()4191 void SwWW8ImplReader::StoreMacroCmds()
4192 {
4193     if (pWwFib->lcbCmds)
4194     {
4195         maTracer.Log(sw::log::eContainsWordBasic);
4196 
4197         pTableStream->Seek(pWwFib->fcCmds);
4198 
4199         uno::Reference < embed::XStorage > xRoot(mpDocShell->GetStorage());
4200         try
4201         {
4202             uno::Reference < io::XStream > xStream =
4203                     xRoot->openStreamElement( CREATE_CONST_ASC(SL::aMSMacroCmds), embed::ElementModes::READWRITE );
4204             SvStream* pStream = ::utl::UcbStreamHelper::CreateStream( xStream );
4205 
4206             sal_uInt8 *pBuffer = new sal_uInt8[pWwFib->lcbCmds];
4207             pTableStream->Read(pBuffer, pWwFib->lcbCmds);
4208             pStream->Write(pBuffer, pWwFib->lcbCmds);
4209             delete[] pBuffer;
4210             delete pStream;
4211         }
4212         catch ( uno::Exception& )
4213         {
4214         }
4215     }
4216 }
4217 
ReadDocVars()4218 void SwWW8ImplReader::ReadDocVars()
4219 {
4220     std::vector<String> aDocVarStrings;
4221     std::vector<ww::bytes> aDocVarStringIds;
4222     std::vector<String> aDocValueStrings;
4223     WW8ReadSTTBF(!bVer67, *pTableStream, pWwFib->fcStwUser,
4224         pWwFib->lcbStwUser, bVer67 ? 2 : 0, eStructCharSet,
4225         aDocVarStrings, &aDocVarStringIds, &aDocValueStrings);
4226     if (!bVer67) {
4227         using namespace ::com::sun::star;
4228 
4229         uno::Reference<document::XDocumentPropertiesSupplier> xDPS(
4230             mpDocShell->GetModel(), uno::UNO_QUERY_THROW);
4231         uno::Reference<document::XDocumentProperties> xDocProps(
4232             xDPS->getDocumentProperties());
4233         DBG_ASSERT(xDocProps.is(), "DocumentProperties is null");
4234         uno::Reference<beans::XPropertyContainer> xUserDefinedProps =
4235             xDocProps->getUserDefinedProperties();
4236         DBG_ASSERT(xUserDefinedProps.is(), "UserDefinedProperties is null");
4237 
4238         for(size_t i=0; i<aDocVarStrings.size(); i++)
4239         {
4240             uno::Any aDefaultValue;
4241             ::rtl::OUString name(aDocVarStrings[i]);
4242             uno::Any aValue;
4243             aValue <<= ::rtl::OUString(aDocValueStrings[i]);
4244             try {
4245                 xUserDefinedProps->addProperty( name,
4246                     beans::PropertyAttribute::REMOVEABLE,
4247                     aValue );
4248             } catch (uno::Exception &) {
4249                 // ignore
4250             }
4251         }
4252     }
4253 }
4254 
4255 //-----------------------------------------
4256 //      Document Info
4257 //-----------------------------------------
4258 
ReadDocInfo()4259 void SwWW8ImplReader::ReadDocInfo()
4260 {
4261     if( pStg )
4262     {
4263         uno::Reference<document::XDocumentPropertiesSupplier> xDPS(
4264             mpDocShell->GetModel(), uno::UNO_QUERY_THROW);
4265         uno::Reference<document::XDocumentProperties> xDocProps(
4266             xDPS->getDocumentProperties());
4267         DBG_ASSERT(xDocProps.is(), "DocumentProperties is null");
4268 
4269         if (xDocProps.is()) {
4270             sfx2::LoadOlePropertySet(xDocProps, pStg);
4271         }
4272     }
4273 }
4274 
CoreLoad(WW8Glossary * pGloss,const SwPosition & rPos)4275 sal_uLong SwWW8ImplReader::CoreLoad(WW8Glossary *pGloss, const SwPosition &rPos)
4276 {
4277     sal_uLong nErrRet = 0;
4278 
4279     rDoc.SetDocumentType( SwDoc::DOCTYPE_MSWORD );
4280     if (mbNewDoc && pStg && !pGloss)
4281         ReadDocInfo();
4282 
4283     ::ww8::WW8FibData * pFibData = new ::ww8::WW8FibData();
4284 
4285     if (pWwFib->fReadOnlyRecommended)
4286         pFibData->setReadOnlyRecommended(true);
4287     else
4288         pFibData->setReadOnlyRecommended(false);
4289 
4290     if (pWwFib->fWriteReservation)
4291         pFibData->setWriteReservation(true);
4292     else
4293         pFibData->setWriteReservation(false);
4294 
4295     ::sw::tExternalDataPointer pExternalFibData(pFibData);
4296 
4297     rDoc.setExternalData(::sw::FIB, pExternalFibData);
4298 
4299     ::sw::tExternalDataPointer pSttbfAsoc
4300           (new ::ww8::WW8Sttb<ww8::WW8Struct>(*pTableStream, pWwFib->fcSttbfAssoc, pWwFib->lcbSttbfAssoc));
4301 
4302     rDoc.setExternalData(::sw::STTBF_ASSOC, pSttbfAsoc);
4303 
4304     if (pWwFib->fWriteReservation || pWwFib->fReadOnlyRecommended)
4305     {
4306         SwDocShell * pDocShell = rDoc.GetDocShell();
4307         if (pDocShell)
4308             pDocShell->SetReadOnlyUI(sal_True);
4309     }
4310 
4311     pPaM = new SwPaM(rPos);
4312 
4313     pCtrlStck = new SwWW8FltControlStack( &rDoc, nFieldFlags, *this );
4314 
4315     mpRedlineStack = new sw::util::RedlineStack(rDoc);
4316 
4317     /*
4318         RefFldStck: Keeps track of bookmarks which may be inserted as
4319         variables intstead.
4320     */
4321     pReffedStck = new SwWW8ReferencedFltEndStack(&rDoc, nFieldFlags);
4322     pReffingStck = new SwWW8FltRefStack(&rDoc, nFieldFlags);
4323 
4324     pAnchorStck = new SwWW8FltAnchorStack(&rDoc, nFieldFlags);
4325 
4326     sal_uInt16 nPageDescOffset = rDoc.GetPageDescCnt();
4327 
4328     SwNodeIndex aSttNdIdx( rDoc.GetNodes() );
4329     SwRelNumRuleSpaces aRelNumRule(rDoc, mbNewDoc);
4330 
4331     sal_uInt16 eMode = nsRedlineMode_t::REDLINE_SHOW_INSERT;
4332 
4333     mpSprmParser = new wwSprmParser(pWwFib->GetFIBVersion());
4334 
4335     // praktische Hilfsvariablen besetzen:
4336     bVer6  = (6 == pWwFib->nVersion);
4337     bVer7  = (7 == pWwFib->nVersion);
4338     bVer67 = bVer6 || bVer7;
4339     bVer8  = (8 == pWwFib->nVersion);
4340 
4341     eTextCharSet = WW8Fib::GetFIBCharset(pWwFib->chse);
4342     eStructCharSet = WW8Fib::GetFIBCharset(pWwFib->chseTables);
4343 
4344     bWWBugNormal = pWwFib->nProduct == 0xc03d;
4345 
4346     if (!mbNewDoc)
4347         aSttNdIdx = pPaM->GetPoint()->nNode;
4348 
4349     ::StartProgress(STR_STATSTR_W4WREAD, 0, 100, mpDocShell);
4350 
4351 #ifdef DEBUGDUMP
4352     //experimental embedded ttf dumper
4353     if (pWwFib->lcbSttbttmbd && (7 < pWwFib->nVersion))
4354     {
4355         pTableStream->Seek(pWwFib->fcSttbttmbd);
4356         sal_uInt16 nZeros;
4357         *pTableStream >> nZeros;
4358         sal_uInt16 nNoEntries;
4359         *pTableStream >> nNoEntries;
4360         sal_uInt32 nUnknown1;
4361         *pTableStream >> nUnknown1;
4362         sal_uInt16 nUnknown2;
4363         *pTableStream >> nUnknown2;
4364         std::vector<sal_uInt32> aOffsets;
4365         for (sal_uInt16 nI = 0; nI < nNoEntries; ++nI)
4366         {
4367             sal_uInt32 nOffset;
4368             *pTableStream >> nOffset;
4369             aOffsets.push_back(nOffset);
4370             sal_uInt32 nUnknown3;
4371             *pTableStream >> nUnknown3;
4372             sal_uInt32 nUnknown4;
4373             *pTableStream >> nUnknown4;
4374         }
4375         typedef std::vector<sal_uInt32>::iterator myIter;
4376         myIter aEnd = aOffsets.end();
4377         myIter aIter = aOffsets.begin();
4378         while (aIter != aEnd)
4379         {
4380             sal_uInt32 nOffset = *aIter;
4381             sal_uInt32 nLen = STREAM_SEEK_TO_END;
4382             ++aIter;
4383             pStrm->Seek(nOffset);
4384             if (aIter != aEnd)
4385                 nLen = *aIter - nOffset;
4386             SvStream *pDbg = sw::hack::CreateDebuggingStream(CREATE_CONST_ASC(".ttf.dump"));
4387             sw::hack::DumpStream(*pStrm, *pDbg, nLen);
4388             delete pDbg;
4389         }
4390     }
4391 #endif
4392 
4393     // read Font Table
4394     pFonts = new WW8Fonts( *pTableStream, *pWwFib );
4395 
4396     // Document Properties
4397     pWDop = new WW8Dop( *pTableStream, pWwFib->nFib, pWwFib->fcDop,
4398         pWwFib->lcbDop );
4399 
4400     if (mbNewDoc)
4401         ImportDop();
4402 
4403     /*
4404         Import revisioning data: author names
4405     */
4406     if( pWwFib->lcbSttbfRMark )
4407     {
4408         ReadRevMarkAuthorStrTabl( *pTableStream,
4409                                     pWwFib->fcSttbfRMark,
4410                                     pWwFib->lcbSttbfRMark, rDoc );
4411     }
4412 
4413     // M.M. Initialize our String/ID map for Linked Sections
4414     std::vector<String> aLinkStrings;
4415     std::vector<ww::bytes> aStringIds;
4416 
4417     WW8ReadSTTBF(!bVer67, *pTableStream, pWwFib->fcSttbFnm,
4418         pWwFib->lcbSttbFnm, bVer67 ? 2 : 0, eStructCharSet,
4419         aLinkStrings, &aStringIds);
4420 
4421     for (size_t i=0; i < aLinkStrings.size(); ++i)
4422     {
4423         ww::bytes stringId = aStringIds[i];
4424         WW8_STRINGID *stringIdStruct = (WW8_STRINGID*)(&stringId[0]);
4425         aLinkStringMap[SVBT16ToShort(stringIdStruct->nStringId)] =
4426             aLinkStrings[i];
4427     }
4428 
4429     ReadDocVars(); // import document variables as meta information.
4430 
4431     ::SetProgressState(nProgress, mpDocShell);    // Update
4432 
4433     pLstManager = new WW8ListManager( *pTableStream, *this );
4434 
4435     /*
4436         zuerst(!) alle Styles importieren   (siehe WW8PAR2.CXX)
4437             VOR dem Import der Listen !!
4438     */
4439     ::SetProgressState(nProgress, mpDocShell);    // Update
4440     pStyles = new WW8RStyle( *pWwFib, this );   // Styles
4441     pStyles->Import();
4442 
4443     /*
4444         zu guter Letzt: (siehe ebenfalls WW8PAR3.CXX)
4445         ===============
4446         alle Styles durchgehen und ggfs. zugehoeriges Listen-Format
4447         anhaengen NACH dem Import der Styles und NACH dem Import der
4448         Listen !!
4449     */
4450     ::SetProgressState(nProgress, mpDocShell);    // Update
4451     pStyles->PostProcessStyles();
4452 
4453     if (pCollA)
4454         SetOutlineStyles();
4455 
4456     pSBase = new WW8ScannerBase(pStrm,pTableStream,pDataStream,pWwFib);
4457 
4458     if ( !pSBase->IsValid() )
4459     {
4460         return ERR_SWG_READ_ERROR;
4461     }
4462 
4463     static const SvxExtNumType eNumTA[16] =
4464     {
4465         SVX_NUM_ARABIC, SVX_NUM_ROMAN_UPPER, SVX_NUM_ROMAN_LOWER,
4466         SVX_NUM_CHARS_UPPER_LETTER_N, SVX_NUM_CHARS_LOWER_LETTER_N,
4467         SVX_NUM_ARABIC, SVX_NUM_ARABIC, SVX_NUM_ARABIC,
4468         SVX_NUM_ARABIC, SVX_NUM_ARABIC, SVX_NUM_ARABIC,
4469         SVX_NUM_ARABIC, SVX_NUM_ARABIC, SVX_NUM_ARABIC,
4470         SVX_NUM_ARABIC, SVX_NUM_ARABIC
4471     };
4472 
4473     if (pSBase->AreThereFootnotes())
4474     {
4475         static const SwFtnNum eNumA[4] =
4476         {
4477             FTNNUM_DOC, FTNNUM_CHAPTER, FTNNUM_PAGE, FTNNUM_DOC
4478         };
4479 
4480         SwFtnInfo aInfo;
4481         aInfo = rDoc.GetFtnInfo();      // Copy-Ctor privat
4482 
4483         aInfo.ePos = FTNPOS_PAGE;
4484         aInfo.eNum = eNumA[pWDop->rncFtn];
4485         aInfo.aFmt.SetNumberingType( static_cast< sal_uInt16 >(eNumTA[pWDop->nfcFtnRef]) );
4486         if( pWDop->nFtn )
4487             aInfo.nFtnOffset = pWDop->nFtn - 1;
4488         rDoc.SetFtnInfo( aInfo );
4489     }
4490     if( pSBase->AreThereEndnotes() )
4491     {
4492         SwEndNoteInfo aInfo;
4493         aInfo = rDoc.GetEndNoteInfo();  // parallel zu Ftn
4494 
4495         // Ich kann nicht setzen, wann neu nummerieren...
4496         //  aInfo.eNum = eNumA[pWDop->pDop->rncEdn];
4497         aInfo.aFmt.SetNumberingType( static_cast< sal_uInt16 >(eNumTA[pWDop->nfcEdnRef]) );
4498         if( pWDop->nEdn )
4499             aInfo.nFtnOffset = pWDop->nEdn - 1;
4500         rDoc.SetEndNoteInfo( aInfo );
4501     }
4502 
4503     if( pWwFib->lcbPlcfhdd )
4504         pHdFt = new WW8PLCF_HdFt( pTableStream, *pWwFib, *pWDop );
4505 
4506     if (!mbNewDoc)
4507     {
4508         // inserting into an existing document:
4509         // As only complete paragraphs are inserted, the current one
4510         // needs to be splitted - once or even twice.
4511         const SwPosition* pPos = pPaM->GetPoint();
4512 
4513         // split current paragraph to get new paragraph for the insertion
4514         rDoc.SplitNode( *pPos, false );
4515 
4516         // another split, if insertion position was not at the end of the current paragraph.
4517         SwTxtNode const*const pTxtNd = pPos->nNode.GetNode().GetTxtNode();
4518         if ( pTxtNd->GetTxt().Len() )
4519         {
4520             rDoc.SplitNode( *pPos, false );
4521             // move PaM back to the newly empty paragraph
4522             pPaM->Move( fnMoveBackward );
4523         }
4524 
4525         // suppress insertion of tables inside footnotes.
4526         const sal_uLong nNd = pPos->nNode.GetIndex();
4527         bReadNoTbl = ( nNd < rDoc.GetNodes().GetEndOfInserts().GetIndex() &&
4528                        rDoc.GetNodes().GetEndOfInserts().StartOfSectionIndex() < nNd );
4529 
4530     }
4531 
4532     ::SetProgressState(nProgress, mpDocShell);    // Update
4533 
4534     // loop for each glossary entry and add dummy section node
4535     if (pGloss)
4536     {
4537         WW8PLCF aPlc(pTableStream, pWwFib->fcPlcfglsy, pWwFib->lcbPlcfglsy, 0);
4538         if ( aPlc.IsValid() )
4539         {
4540             WW8_CP nStart, nEnd;
4541             void* pDummy;
4542 
4543             for (int i=0; i<pGloss->GetNoStrings(); i++,aPlc++)
4544             {
4545                 SwNodeIndex aIdx( rDoc.GetNodes().GetEndOfContent());
4546                 SwTxtFmtColl* pColl =
4547                     rDoc.GetTxtCollFromPool(RES_POOLCOLL_STANDARD,
4548                     false);
4549                 SwStartNode *pNode =
4550                     rDoc.GetNodes().MakeTextSection(aIdx,
4551                     SwNormalStartNode,pColl);
4552                 pPaM->GetPoint()->nNode = pNode->GetIndex()+1;
4553                 pPaM->GetPoint()->nContent.Assign(pPaM->GetCntntNode(),0);
4554                 aPlc.Get( nStart, nEnd, pDummy );
4555                 ReadText(nStart,nEnd-nStart-1,MAN_MAINTEXT);
4556             }
4557         }
4558     }
4559     else //ordinary case
4560     {
4561         //Modify here for #119405, by easyfan, 2012-05-24
4562         mbOnLoadingMain = true;
4563         //End of modification, by easyfan
4564         ReadText( 0, pWwFib->ccpText, MAN_MAINTEXT );
4565         //Modify here for #119405, by easyfan, 2012-05-24
4566         mbOnLoadingMain = false;
4567         //End of modification, by easyfan
4568     }
4569 
4570     ::SetProgressState(nProgress, mpDocShell);    // Update
4571 
4572     if (pDrawPg && pMSDffManager && pMSDffManager->GetShapeOrders())
4573     {
4574         // Hilfsarray zum Verketten der (statt SdrTxtObj) eingefuegten
4575         // Rahmen
4576         SvxMSDffShapeTxBxSort aTxBxSort;
4577 
4578         // korrekte Z-Order der eingelesen Escher-Objekte sicherstellen
4579         sal_uInt16 nShapeCount = pMSDffManager->GetShapeOrders()->Count();
4580 
4581         for (sal_uInt16 nShapeNum=0; nShapeNum < nShapeCount; nShapeNum++)
4582         {
4583             SvxMSDffShapeOrder *pOrder =
4584                 pMSDffManager->GetShapeOrders()->GetObject(nShapeNum);
4585             // Pointer in neues Sort-Array einfuegen
4586             if (pOrder->nTxBxComp && pOrder->pFly)
4587                 aTxBxSort.Insert(pOrder);
4588         }
4589         // zu verkettende Rahmen jetzt verketten
4590         sal_uInt16 nTxBxCount = aTxBxSort.Count();
4591         if( nTxBxCount )
4592         {
4593             SwFmtChain aChain;
4594             for (sal_uInt16 nTxBxNum=0; nTxBxNum < nTxBxCount; nTxBxNum++)
4595             {
4596                 SvxMSDffShapeOrder *pOrder =
4597                     aTxBxSort.GetObject(nTxBxNum);
4598 
4599                 // Fly-Frame-Formate initialisieren
4600                 SwFlyFrmFmt* pFlyFmt     = pOrder->pFly;
4601                 SwFlyFrmFmt* pNextFlyFmt = 0;
4602                 SwFlyFrmFmt* pPrevFlyFmt = 0;
4603                 // ggfs. Nachfolger ermitteln
4604                 if( 1+nTxBxNum < nTxBxCount )
4605                 {
4606                     SvxMSDffShapeOrder *pNextOrder =
4607                         aTxBxSort.GetObject(nTxBxNum+1);
4608                     if ((0xFFFF0000 & pOrder->nTxBxComp)
4609                            == (0xFFFF0000 & pNextOrder->nTxBxComp))
4610                         pNextFlyFmt = pNextOrder->pFly;
4611                 }
4612                 // ggfs. Vorgaenger ermitteln
4613                 if( nTxBxNum )
4614                 {
4615                     SvxMSDffShapeOrder *pPrevOrder =
4616                         aTxBxSort.GetObject(nTxBxNum-1);
4617                     if ((0xFFFF0000 & pOrder->nTxBxComp)
4618                            == (0xFFFF0000 & pPrevOrder->nTxBxComp))
4619                         pPrevFlyFmt = pPrevOrder->pFly;
4620                 }
4621                 // Falls Nachfolger oder Vorgaenger vorhanden,
4622                 // die Verkettung am Fly-Frame-Format eintragen
4623                 if (pNextFlyFmt || pPrevFlyFmt)
4624                 {
4625                     aChain.SetNext( pNextFlyFmt );
4626                     aChain.SetPrev( pPrevFlyFmt );
4627                     pFlyFmt->SetFmtAttr( aChain );
4628                 }
4629             }
4630 
4631         }
4632 
4633     }
4634 
4635     if (mbNewDoc)
4636     {
4637         if( pWDop->fRevMarking )
4638             eMode |= nsRedlineMode_t::REDLINE_ON;
4639         if( pWDop->fRMView )
4640             eMode |= nsRedlineMode_t::REDLINE_SHOW_DELETE;
4641         if (pStg && !pGloss) /*meaningless for a glossary, cmc*/
4642         {
4643             const SvtFilterOptions* pVBAFlags = SvtFilterOptions::Get();
4644             maTracer.EnterEnvironment(sw::log::eMacros);
4645             SvxImportMSVBasic aVBasic(*mpDocShell, *pStg,
4646                             pVBAFlags->IsLoadWordBasicCode(),
4647                             pVBAFlags->IsLoadWordBasicStorage() );
4648             String s1(CREATE_CONST_ASC("Macros"));
4649             String s2(CREATE_CONST_ASC("VBA"));
4650             int nRet = aVBasic.Import( s1, s2 );
4651             if( 2 & nRet )
4652             {
4653                 maTracer.Log(sw::log::eContainsVisualBasic);
4654                 rDoc.SetContainsMSVBasic(true);
4655             }
4656 
4657             StoreMacroCmds();
4658 
4659             maTracer.LeaveEnvironment(sw::log::eMacros);
4660         }
4661     }
4662 
4663     maInsertedTables.DelAndMakeTblFrms();
4664     maSectionManager.InsertSegments();
4665 
4666     if (pCollA)
4667         delete[] pCollA;
4668 
4669     DELETEZ( pStyles );
4670 
4671     if( pFormImpl )
4672         DeleteFormImpl();
4673     GrafikDtor();
4674     DELETEZ( pMSDffManager );
4675     DELETEZ( pHdFt );
4676     //For i120928,delay the destruct action
4677     //DELETEZ( pLstManager );
4678     DELETEZ( pSBase );
4679     delete pWDop;
4680     DELETEZ( pFonts );
4681     delete mpAtnNames;
4682     DELETEZ( pAuthorInfos );
4683     delete mpSprmParser;
4684     ::EndProgress(mpDocShell);
4685 
4686     pDataStream = 0;
4687     pTableStream = 0;
4688 
4689     DeleteCtrlStk();
4690     mpRedlineStack->closeall(*pPaM->GetPoint());
4691     delete mpRedlineStack;
4692     DeleteAnchorStk();
4693     DeleteRefStks();
4694 
4695     //For i120928,achieve the graphics from the special bookmark with is for graphic bullet
4696     {
4697         std::vector<const SwGrfNode*> vecBulletGrf;
4698         std::vector<SwFrmFmt*> vecFrmFmt;
4699 
4700         IDocumentMarkAccess* const pMarkAccess =
4701             rDoc.getIDocumentMarkAccess();
4702         if ( pMarkAccess )
4703         {
4704             IDocumentMarkAccess::const_iterator_t ppBkmk =
4705                 pMarkAccess->findBookmark( C2U("_PictureBullets") );
4706             if ( ppBkmk != pMarkAccess->getBookmarksEnd()
4707                  && IDocumentMarkAccess::GetType( *(ppBkmk->get()) ) == IDocumentMarkAccess::BOOKMARK )
4708             {
4709                 SwTxtNode* pTxtNode = ppBkmk->get()->GetMarkStart().nNode.GetNode().GetTxtNode();
4710                 if ( pTxtNode )
4711                 {
4712                     const SwpHints* pHints = pTxtNode->GetpSwpHints();
4713                     for( sal_uInt16 nHintPos = 0; pHints && nHintPos < pHints->Count(); ++nHintPos)
4714                     {
4715                         const SwTxtAttr *pHt = (*pHints)[nHintPos];
4716                         const xub_StrLen st = *(pHt->GetStart());
4717                         if( pHt
4718                             && pHt->Which() == RES_TXTATR_FLYCNT
4719                             && (st >= ppBkmk->get()->GetMarkStart().nContent.GetIndex()) )
4720                         {
4721                             SwFrmFmt* pFrmFmt = pHt->GetFlyCnt().GetFrmFmt();
4722                             vecFrmFmt.push_back(pFrmFmt);
4723                             const SwNodeIndex* pNdIdx = pFrmFmt->GetCntnt().GetCntntIdx();
4724                             const SwNodes* pNodesArray = (pNdIdx != NULL)
4725                                                          ? &(pNdIdx->GetNodes())
4726                                                          : NULL;
4727                             const SwGrfNode *pGrf = (pNodesArray != NULL)
4728                                                     ? dynamic_cast<const SwGrfNode*>((*pNodesArray)[pNdIdx->GetIndex() + 1])
4729                                                     : NULL;
4730                             vecBulletGrf.push_back(pGrf);
4731                         }
4732                     }
4733                     // update graphic bullet information
4734                     sal_uInt16 nCount = pLstManager->GetWW8LSTInfoNum();
4735                     for (sal_uInt16 i = 0; i < nCount; ++i)
4736                     {
4737                         SwNumRule* pRule = pLstManager->GetNumRule(i);
4738                         for (sal_uInt16 j = 0; j < MAXLEVEL; ++j)
4739                         {
4740                             SwNumFmt aNumFmt(pRule->Get(j));
4741                             const sal_Int16 nType = aNumFmt.GetNumberingType();
4742                             const sal_uInt16 nGrfBulletCP = aNumFmt.GetGrfBulletCP();
4743                             if ( nType == SVX_NUM_BITMAP
4744                                  && vecBulletGrf.size() > nGrfBulletCP
4745                                  && vecBulletGrf[nGrfBulletCP] != NULL )
4746                             {
4747                                 Graphic aGraphic = vecBulletGrf[nGrfBulletCP]->GetGrf();
4748                                 SvxBrushItem aBrush(aGraphic, GPOS_AREA, SID_ATTR_BRUSH);
4749                                 Font aFont = numfunc::GetDefBulletFont();
4750                                 int nHeight = aFont.GetHeight() * 12;
4751                                 Size aPrefSize( aGraphic.GetPrefSize());
4752                                 if (aPrefSize.Height() * aPrefSize.Width() != 0 )
4753                                 {
4754                                     int nWidth = (nHeight * aPrefSize.Width()) / aPrefSize.Height();
4755                                     Size aSize(nWidth, nHeight);
4756                                     aNumFmt.SetGraphicBrush(&aBrush, &aSize);
4757                                 }
4758                                 else
4759                                 {
4760                                     aNumFmt.SetNumberingType(SVX_NUM_CHAR_SPECIAL);
4761                                     aNumFmt.SetBulletChar(0x2190);
4762                                 }
4763                                 pRule->Set( j, aNumFmt );
4764                             }
4765                         }
4766                     }
4767                     // Remove additional pictures
4768                     for (sal_uInt16 i = 0; i < vecFrmFmt.size(); ++i)
4769                     {
4770                         rDoc.DelLayoutFmt(vecFrmFmt[i]);
4771                     }
4772                 }
4773             }
4774             DELETEZ( pLstManager );
4775         }
4776     }
4777 
4778     UpdateFields();
4779 
4780     // delete the pam before the call for hide all redlines (Bug 73683)
4781     if (mbNewDoc)
4782       rDoc.SetRedlineMode((RedlineMode_t)( eMode ));
4783 
4784     UpdatePageDescs(rDoc, nPageDescOffset);
4785 
4786     delete pPaM, pPaM = 0;
4787     return nErrRet;
4788 }
4789 
SetSubStreams(SvStorageStreamRef & rTableStream,SvStorageStreamRef & rDataStream)4790 sal_uLong SwWW8ImplReader::SetSubStreams(SvStorageStreamRef &rTableStream,
4791     SvStorageStreamRef &rDataStream)
4792 {
4793     sal_uLong nErrRet = 0;
4794     // 6 stands for "6 OR 7",  7 stand for "ONLY 7"
4795     switch (pWwFib->nVersion)
4796     {
4797         case 6:
4798         case 7:
4799             pTableStream = pStrm;
4800             pDataStream = pStrm;
4801             break;
4802         case 8:
4803             if(!pStg)
4804             {
4805                 ASSERT( pStg, "Version 8 muss immer einen Storage haben!" );
4806                 nErrRet = ERR_SWG_READ_ERROR;
4807                 break;
4808             }
4809 
4810             rTableStream = pStg->OpenSotStream( String::CreateFromAscii(
4811                 pWwFib->fWhichTblStm ? SL::a1Table : SL::a0Table),
4812                 STREAM_STD_READ);
4813 
4814             pTableStream = &rTableStream;
4815             pTableStream->SetNumberFormatInt( NUMBERFORMAT_INT_LITTLEENDIAN );
4816 
4817             rDataStream = pStg->OpenSotStream(CREATE_CONST_ASC(SL::aData),
4818                 STREAM_STD_READ | STREAM_NOCREATE );
4819 
4820             if (rDataStream.Is() && SVSTREAM_OK == rDataStream->GetError())
4821             {
4822                 pDataStream = &rDataStream;
4823                 pDataStream->SetNumberFormatInt(NUMBERFORMAT_INT_LITTLEENDIAN);
4824             }
4825             else
4826                 pDataStream = pStrm;
4827             break;
4828         default:
4829             // Programm-Fehler!
4830             ASSERT( sal_False, "It was forgotten to encode nVersion!" );
4831             nErrRet = ERR_SWG_READ_ERROR;
4832             break;
4833     }
4834     return nErrRet;
4835 }
4836 
4837 namespace
4838 {
MakeTemp(SvFileStream & rSt)4839     utl::TempFile *MakeTemp(SvFileStream &rSt)
4840     {
4841         utl::TempFile *pT = new utl::TempFile;
4842         pT->EnableKillingFile();
4843         rSt.Open(pT->GetFileName(), STREAM_READWRITE | STREAM_SHARE_DENYWRITE);
4844         return pT;
4845     }
4846 
4847 #define WW_BLOCKSIZE 0x200
4848 
DecryptRC4(msfilter::MSCodec_Std97 & rCtx,SvStream & rIn,SvStream & rOut)4849     void DecryptRC4(msfilter::MSCodec_Std97& rCtx, SvStream &rIn, SvStream &rOut)
4850     {
4851         rIn.Seek(STREAM_SEEK_TO_END);
4852         sal_uLong nLen = rIn.Tell();
4853         rIn.Seek(0);
4854 
4855         sal_uInt8 in[WW_BLOCKSIZE];
4856         for (sal_uLong nI = 0, nBlock = 0; nI < nLen; nI += WW_BLOCKSIZE, ++nBlock)
4857         {
4858             sal_uLong nBS = (nLen - nI > WW_BLOCKSIZE) ? WW_BLOCKSIZE : nLen - nI;
4859             rIn.Read(in, nBS);
4860             rCtx.InitCipher(nBlock);
4861             rCtx.Decode(in, nBS, in, nBS);
4862             rOut.Write(in, nBS);
4863         }
4864     }
4865 
DecryptXOR(msfilter::MSCodec_XorWord95 & rCtx,SvStream & rIn,SvStream & rOut)4866     void DecryptXOR(msfilter::MSCodec_XorWord95 &rCtx, SvStream &rIn, SvStream &rOut)
4867     {
4868         sal_uLong nSt = rIn.Tell();
4869         rIn.Seek(STREAM_SEEK_TO_END);
4870         sal_uLong nLen = rIn.Tell();
4871         rIn.Seek(nSt);
4872 
4873         rCtx.InitCipher();
4874         rCtx.Skip(nSt);
4875 
4876         sal_uInt8 in[0x4096];
4877         for (sal_uLong nI = nSt; nI < nLen; nI += 0x4096)
4878         {
4879             sal_uLong nBS = (nLen - nI > 0x4096 ) ? 0x4096 : nLen - nI;
4880             rIn.Read(in, nBS);
4881             rCtx.Decode(in, nBS);
4882             rOut.Write(in, nBS);
4883         }
4884     }
4885 
4886     //moan, copy and paste :-(
QueryPasswordForMedium(SfxMedium & rMedium)4887     String QueryPasswordForMedium(SfxMedium& rMedium)
4888     {
4889         String aPassw;
4890 
4891         using namespace com::sun::star;
4892 
4893         const SfxItemSet* pSet = rMedium.GetItemSet();
4894         const SfxPoolItem *pPasswordItem;
4895 
4896         if(pSet && SFX_ITEM_SET == pSet->GetItemState(SID_PASSWORD, sal_True, &pPasswordItem))
4897             aPassw = ((const SfxStringItem *)pPasswordItem)->GetValue();
4898         else
4899         {
4900             try
4901             {
4902                 uno::Reference< task::XInteractionHandler > xHandler( rMedium.GetInteractionHandler() );
4903                 if( xHandler.is() )
4904                 {
4905                     ::comphelper::DocPasswordRequest* pRequest = new ::comphelper::DocPasswordRequest(
4906                         ::comphelper::DocPasswordRequestType_MS, task::PasswordRequestMode_PASSWORD_ENTER,
4907                         INetURLObject( rMedium.GetOrigURL() ).GetName( INetURLObject::DECODE_WITH_CHARSET ) );
4908                     uno::Reference< task::XInteractionRequest > xRequest( pRequest );
4909 
4910                     xHandler->handle( xRequest );
4911 
4912                     if( pRequest->isPassword() )
4913                         aPassw = pRequest->getPassword();
4914                 }
4915             }
4916             catch( uno::Exception& )
4917             {
4918             }
4919         }
4920 
4921         return aPassw;
4922     }
4923 
InitXorWord95Codec(::msfilter::MSCodec_XorWord95 & rCodec,SfxMedium & rMedium,WW8Fib * pWwFib)4924     uno::Sequence< beans::NamedValue > InitXorWord95Codec( ::msfilter::MSCodec_XorWord95& rCodec, SfxMedium& rMedium, WW8Fib* pWwFib )
4925     {
4926         uno::Sequence< beans::NamedValue > aEncryptionData;
4927         SFX_ITEMSET_ARG( rMedium.GetItemSet(), pEncryptionData, SfxUnoAnyItem, SID_ENCRYPTIONDATA, sal_False );
4928         if ( pEncryptionData && ( pEncryptionData->GetValue() >>= aEncryptionData ) && !rCodec.InitCodec( aEncryptionData ) )
4929             aEncryptionData.realloc( 0 );
4930 
4931         if ( !aEncryptionData.getLength() )
4932         {
4933             String sUniPassword = QueryPasswordForMedium( rMedium );
4934 
4935             ByteString sPassword(sUniPassword, WW8Fib::GetFIBCharset( pWwFib->chseTables ) );
4936 
4937             xub_StrLen nLen = sPassword.Len();
4938             if( nLen <= 15 )
4939             {
4940                 sal_uInt8 pPassword[16];
4941                 memset( pPassword, 0, sizeof( pPassword ) );
4942 
4943                 for (xub_StrLen nChar = 0; nChar < sPassword.Len(); ++nChar )
4944                     pPassword[nChar] = sPassword.GetChar(nChar);
4945 
4946                 rCodec.InitKey( pPassword );
4947                 aEncryptionData = rCodec.GetEncryptionData();
4948 
4949                 // the export supports RC4 algorithm only, so we have to generate the related EncryptionData as well,
4950                 // so that Save can export the document without asking for a password;
4951                 // as result there will be EncryptionData for both algorithms in the MediaDescriptor
4952                 ::msfilter::MSCodec_Std97 aCodec97;
4953 
4954                 // Generate random number with a seed of time as salt.
4955                 TimeValue aTime;
4956                 osl_getSystemTime( &aTime );
4957                 rtlRandomPool aRandomPool = rtl_random_createPool();
4958                 rtl_random_addBytes ( aRandomPool, &aTime, 8 );
4959 
4960                 sal_uInt8 pDocId[ 16 ];
4961                 rtl_random_getBytes( aRandomPool, pDocId, 16 );
4962 
4963                 rtl_random_destroyPool( aRandomPool );
4964 
4965                 sal_uInt16 pStd97Pass[16];
4966                 memset( pStd97Pass, 0, sizeof( pStd97Pass ) );
4967                 for (xub_StrLen nChar = 0; nChar < nLen; ++nChar )
4968                     pStd97Pass[nChar] = sUniPassword.GetChar(nChar);
4969 
4970                 aCodec97.InitKey( pStd97Pass, pDocId );
4971 
4972                 // merge the EncryptionData, there should be no conflicts
4973                 ::comphelper::SequenceAsHashMap aEncryptionHash( aEncryptionData );
4974                 aEncryptionHash.update( ::comphelper::SequenceAsHashMap( aCodec97.GetEncryptionData() ) );
4975                 aEncryptionHash >> aEncryptionData;
4976             }
4977         }
4978 
4979         return aEncryptionData;
4980     }
4981 
InitStd97Codec(::msfilter::MSCodec_Std97 & rCodec,sal_uInt8 pDocId[16],SfxMedium & rMedium)4982     uno::Sequence< beans::NamedValue > InitStd97Codec( ::msfilter::MSCodec_Std97& rCodec, sal_uInt8 pDocId[16], SfxMedium& rMedium )
4983     {
4984         uno::Sequence< beans::NamedValue > aEncryptionData;
4985         SFX_ITEMSET_ARG( rMedium.GetItemSet(), pEncryptionData, SfxUnoAnyItem, SID_ENCRYPTIONDATA, sal_False );
4986         if ( pEncryptionData && ( pEncryptionData->GetValue() >>= aEncryptionData ) && !rCodec.InitCodec( aEncryptionData ) )
4987             aEncryptionData.realloc( 0 );
4988 
4989         if ( !aEncryptionData.getLength() )
4990         {
4991             String sUniPassword = QueryPasswordForMedium( rMedium );
4992 
4993             xub_StrLen nLen = sUniPassword.Len();
4994             if ( nLen <= 15 )
4995             {
4996                 sal_Unicode pPassword[16];
4997                 memset( pPassword, 0, sizeof( pPassword ) );
4998                 for (xub_StrLen nChar = 0; nChar < nLen; ++nChar )
4999                     pPassword[nChar] = sUniPassword.GetChar(nChar);
5000 
5001                 rCodec.InitKey( pPassword, pDocId );
5002                 aEncryptionData = rCodec.GetEncryptionData();
5003             }
5004         }
5005 
5006         return aEncryptionData;
5007     }
5008 }
5009 
LoadThroughDecryption(SwPaM & rPaM,WW8Glossary * pGloss)5010 sal_uLong SwWW8ImplReader::LoadThroughDecryption(SwPaM& rPaM ,WW8Glossary *pGloss)
5011 {
5012     sal_uLong nErrRet = 0;
5013     if (pGloss)
5014         pWwFib = pGloss->GetFib();
5015     else
5016         pWwFib = new WW8Fib(*pStrm, nWantedVersion);
5017 
5018     if (pWwFib->nFibError)
5019         nErrRet = ERR_SWG_READ_ERROR;
5020 
5021     SvStorageStreamRef xTableStream, xDataStream;
5022 
5023     if (!nErrRet)
5024         nErrRet = SetSubStreams(xTableStream, xDataStream);
5025 
5026     utl::TempFile *pTempMain = 0;
5027     utl::TempFile *pTempTable = 0;
5028     utl::TempFile *pTempData = 0;
5029     SvFileStream aDecryptMain;
5030     SvFileStream aDecryptTable;
5031     SvFileStream aDecryptData;
5032 
5033     bool bDecrypt = false;
5034     enum {RC4, XOR, Other} eAlgo = Other;
5035     if (pWwFib->fEncrypted && !nErrRet)
5036     {
5037         if (!pGloss)
5038         {
5039             bDecrypt = true;
5040             if (8 != pWwFib->nVersion)
5041                 eAlgo = XOR;
5042             else
5043             {
5044                 if (pWwFib->nKey != 0)
5045                     eAlgo = XOR;
5046                 else
5047                 {
5048                     pTableStream->Seek(0);
5049                     sal_uInt32 nEncType;
5050                     *pTableStream >> nEncType;
5051                     if (nEncType == 0x10001)
5052                         eAlgo = RC4;
5053                 }
5054             }
5055         }
5056     }
5057 
5058     if (bDecrypt)
5059     {
5060         nErrRet = ERRCODE_SVX_WRONGPASS;
5061         SfxMedium* pMedium = mpDocShell->GetMedium();
5062 
5063         if ( pMedium )
5064         {
5065             switch (eAlgo)
5066             {
5067                 default:
5068                     nErrRet = ERRCODE_SVX_READ_FILTER_CRYPT;
5069                     break;
5070                 case XOR:
5071                 {
5072                     msfilter::MSCodec_XorWord95 aCtx;
5073                     uno::Sequence< beans::NamedValue > aEncryptionData = InitXorWord95Codec( aCtx, *pMedium, pWwFib );
5074 
5075                     // if initialization has failed the EncryptionData should be empty
5076                     if ( aEncryptionData.getLength() && aCtx.VerifyKey( pWwFib->nKey, pWwFib->nHash ) )
5077                     {
5078                         nErrRet = 0;
5079                         pTempMain = MakeTemp(aDecryptMain);
5080 
5081                         pStrm->Seek(0);
5082                         size_t nUnencryptedHdr =
5083                             (8 == pWwFib->nVersion) ? 0x44 : 0x34;
5084                         sal_uInt8 *pIn = new sal_uInt8[nUnencryptedHdr];
5085                         pStrm->Read(pIn, nUnencryptedHdr);
5086                         aDecryptMain.Write(pIn, nUnencryptedHdr);
5087                         delete [] pIn;
5088 
5089                         DecryptXOR(aCtx, *pStrm, aDecryptMain);
5090 
5091                         if (!pTableStream || pTableStream == pStrm)
5092                             pTableStream = &aDecryptMain;
5093                         else
5094                         {
5095                             pTempTable = MakeTemp(aDecryptTable);
5096                             DecryptXOR(aCtx, *pTableStream, aDecryptTable);
5097                             pTableStream = &aDecryptTable;
5098                         }
5099 
5100                         if (!pDataStream || pDataStream == pStrm)
5101                             pDataStream = &aDecryptMain;
5102                         else
5103                         {
5104                             pTempData = MakeTemp(aDecryptData);
5105                             DecryptXOR(aCtx, *pDataStream, aDecryptData);
5106                             pDataStream = &aDecryptData;
5107                         }
5108 
5109                         pMedium->GetItemSet()->ClearItem( SID_PASSWORD );
5110                         pMedium->GetItemSet()->Put( SfxUnoAnyItem( SID_ENCRYPTIONDATA, uno::makeAny( aEncryptionData ) ) );
5111                     }
5112                 }
5113                 break;
5114                 case RC4:
5115                 {
5116                     msfilter::MSCodec_Std97 aCtx;
5117 
5118                     sal_uInt8 aDocId[ 16 ];
5119                     pTableStream->Read(aDocId, 16);
5120                     sal_uInt8 aSaltData[ 16 ];
5121                     pTableStream->Read(aSaltData, 16);
5122                     sal_uInt8 aSaltHash[ 16 ];
5123                     pTableStream->Read(aSaltHash, 16);
5124 
5125                     // if initialization has failed the EncryptionData should be empty
5126                     uno::Sequence< beans::NamedValue > aEncryptionData = InitStd97Codec( aCtx, aDocId, *pMedium );
5127                     if ( aEncryptionData.getLength() && aCtx.VerifyKey( aSaltData, aSaltHash ) )
5128                     {
5129                         nErrRet = 0;
5130 
5131                         pTempTable = MakeTemp(aDecryptTable);
5132                         DecryptRC4(aCtx, *pTableStream, aDecryptTable);
5133                         pTableStream = &aDecryptTable;
5134 
5135                         pTempMain = MakeTemp(aDecryptMain);
5136                         DecryptRC4(aCtx, *pStrm, aDecryptMain);
5137 
5138                         if (!pDataStream || pDataStream == pStrm)
5139                             pDataStream = &aDecryptMain;
5140                         else
5141                         {
5142                             pTempData = MakeTemp(aDecryptData);
5143                             DecryptRC4(aCtx, *pDataStream, aDecryptData);
5144                             pDataStream = &aDecryptData;
5145                         }
5146 
5147                         pMedium->GetItemSet()->ClearItem( SID_PASSWORD );
5148                         pMedium->GetItemSet()->Put( SfxUnoAnyItem( SID_ENCRYPTIONDATA, uno::makeAny( aEncryptionData ) ) );
5149                     }
5150                 }
5151                 break;
5152             }
5153         }
5154 
5155         if (nErrRet == 0)
5156         {
5157             pStrm = &aDecryptMain;
5158 
5159             delete pWwFib;
5160             pWwFib = new WW8Fib(*pStrm, nWantedVersion);
5161             if (pWwFib->nFibError)
5162                 nErrRet = ERR_SWG_READ_ERROR;
5163         }
5164     }
5165 
5166     if (!nErrRet)
5167         nErrRet = CoreLoad(pGloss, *rPaM.GetPoint());
5168 
5169     delete pTempMain;
5170     delete pTempTable;
5171     delete pTempData;
5172 
5173     if (!pGloss)
5174         delete pWwFib;
5175     return nErrRet;
5176 }
5177 
5178 class outlineeq
5179 {
5180 public:
5181     typedef const SwTxtFmtColl* argument_type;
5182     typedef bool result_type;
5183 private:
5184 private:
5185     sal_uInt8 mnNum;
5186 public:
outlineeq(sal_uInt8 nNum)5187     outlineeq(sal_uInt8 nNum) : mnNum(nNum) {}
operator ()(const SwTxtFmtColl * pTest) const5188     bool operator()(const SwTxtFmtColl *pTest) const
5189     {
5190         //return pTest->GetOutlineLevel() == mnNum; //#outline level,zhaojianwei
5191         return pTest->IsAssignedToListLevelOfOutlineStyle() && pTest->GetAssignedOutlineStyleLevel() == mnNum;  //<-end,zhaojianwei
5192     }
5193 };
5194 
5195 
SetOutlineStyles()5196 void SwWW8ImplReader::SetOutlineStyles()
5197 {
5198 
5199     // If we are inserted into a document then don't clobber existing outline levels.
5200     sal_uInt16 nOutlineStyleListLevelWithAssignment = 0;
5201     if ( !mbNewDoc )
5202     {
5203         sw::ParaStyles aOutLined( sw::util::GetParaStyles( rDoc ) );
5204         sw::util::SortByAssignedOutlineStyleListLevel( aOutLined );
5205         sw::ParaStyles::reverse_iterator aEnd = aOutLined.rend();
5206         for ( sw::ParaStyles::reverse_iterator aIter = aOutLined.rbegin(); aIter < aEnd; ++aIter )
5207         {
5208             if ( ( *aIter )->IsAssignedToListLevelOfOutlineStyle() )
5209                 nOutlineStyleListLevelWithAssignment |= 1 << ( *aIter )->GetAssignedOutlineStyleLevel();
5210             else
5211                 break;
5212         }
5213     }
5214 
5215     // Check applied WW8 list styles at WW8 Built-In Heading Styles
5216     // - Choose the list style which occurs most often as the one which provides
5217     //   the list level properties for the Outline Style.
5218     // - Populate temporary list of WW8 Built-In Heading Styles for further iteration
5219     std::vector< SwWW8StyInf* > aWW8BuiltInHeadingStyles;
5220     const SwNumRule* pChosenWW8ListStyle = NULL;
5221     {
5222         std::map< const SwNumRule*, int > aWW8ListStyleCounts;
5223         for ( sal_uInt16 nI = 0; nI < nColls; ++nI )
5224         {
5225             SwWW8StyInf& rSI = pCollA[nI];
5226 
5227             if ( !rSI.IsWW8BuiltInHeadingStyle()
5228                  || !rSI.HasWW8OutlineLevel() )
5229             {
5230                 continue;
5231             }
5232 
5233             aWW8BuiltInHeadingStyles.push_back( &rSI );
5234 
5235             const SwNumRule* pWW8ListStyle = rSI.GetOutlineNumrule();
5236             if ( pWW8ListStyle != NULL )
5237             {
5238                 std::map< const SwNumRule*, int >::iterator aCountIter =
5239                         aWW8ListStyleCounts.find( pWW8ListStyle );
5240                 if ( aCountIter == aWW8ListStyleCounts.end() )
5241                 {
5242                     aWW8ListStyleCounts[pWW8ListStyle] = 1;
5243                 }
5244                 else
5245                 {
5246                     ++(aCountIter->second);
5247                 }
5248             }
5249         }
5250 
5251         int nCurrentMaxCount = 0;
5252         std::map< const SwNumRule*, int >::iterator aCountIterEnd =
5253             aWW8ListStyleCounts.end();
5254         for ( std::map< const SwNumRule*, int >::iterator aIter = aWW8ListStyleCounts.begin();
5255               aIter != aCountIterEnd;
5256               ++aIter )
5257         {
5258             if ( aIter->second > nCurrentMaxCount )
5259             {
5260                 nCurrentMaxCount = aIter->second;
5261                 pChosenWW8ListStyle = aIter->first;
5262             }
5263         }
5264     }
5265 
5266     // - set list level properties of Outline Style - ODF's list style applied by default to headings
5267     // - assign corresponding Heading Paragraph Styles to the Outline Style
5268     // - If a heading Paragraph Styles is not applying the WW8 list style which had been chosen as
5269     //   the one which provides the list level properties for the Outline Style, its assignment to
5270     //   the Outline Style is removed. A potential applied WW8 list style is assigned directly and
5271     //   its default outline level is applied.
5272     SwNumRule aOutlineRule( *rDoc.GetOutlineNumRule() );
5273     bool bAppliedChangedOutlineStyle = false;
5274     std::vector< SwWW8StyInf* >::iterator aStylesIterEnd =
5275         aWW8BuiltInHeadingStyles.end();
5276     for ( std::vector< SwWW8StyInf* >::iterator aStyleIter = aWW8BuiltInHeadingStyles.begin();
5277           aStyleIter != aStylesIterEnd;
5278           ++aStyleIter )
5279     {
5280         SwWW8StyInf* pStyleInf = (*aStyleIter);
5281 
5282         const sal_uInt16 nOutlineStyleListLevelOfWW8BuiltInHeadingStyle = 1 << pStyleInf->mnWW8OutlineLevel;
5283         if ( nOutlineStyleListLevelOfWW8BuiltInHeadingStyle & nOutlineStyleListLevelWithAssignment )
5284         {
5285             continue;
5286         }
5287 
5288         if ( pChosenWW8ListStyle != NULL
5289              && pStyleInf->mnWW8OutlineLevel == pStyleInf->nListLevel )
5290         {
5291             const SwNumFmt& rRule = pChosenWW8ListStyle->Get( pStyleInf->mnWW8OutlineLevel );
5292             aOutlineRule.Set( pStyleInf->mnWW8OutlineLevel, rRule );
5293             bAppliedChangedOutlineStyle = true;
5294         }
5295 
5296         // in case that there are more styles on this level ignore them
5297         nOutlineStyleListLevelWithAssignment |= nOutlineStyleListLevelOfWW8BuiltInHeadingStyle;
5298 
5299         SwTxtFmtColl* pTxtFmtColl = static_cast<SwTxtFmtColl*>(pStyleInf->pFmt);
5300         if ( pStyleInf->GetOutlineNumrule() != pChosenWW8ListStyle
5301              || ( pStyleInf->nListLevel < WW8ListManager::nMaxLevel
5302                   && pStyleInf->mnWW8OutlineLevel != pStyleInf->nListLevel ) )
5303         {
5304             // WW8 Built-In Heading Style does not apply the chosen one.
5305             // --> delete assignment to OutlineStyle, but keep its current outline level
5306             pTxtFmtColl->DeleteAssignmentToListLevelOfOutlineStyle( false );
5307             // Apply existing WW8 list style a normal list style at the Paragraph Style
5308             if ( pStyleInf->GetOutlineNumrule() != NULL )
5309             {
5310                 pTxtFmtColl->SetFmtAttr( SwNumRuleItem( pStyleInf->GetOutlineNumrule()->GetName() ) );
5311             }
5312             // apply default outline level of WW8 Built-in Heading Style
5313             const sal_uInt8 nOutlineLevel =
5314                     SwWW8StyInf::WW8OutlineLevelToOutlinelevel( pStyleInf->mnWW8OutlineLevel );
5315             pTxtFmtColl->SetFmtAttr( SfxUInt16Item( RES_PARATR_OUTLINELEVEL, nOutlineLevel ) );
5316         }
5317         else
5318         {
5319             pTxtFmtColl->AssignToListLevelOfOutlineStyle( pStyleInf->mnWW8OutlineLevel );
5320         }
5321     }
5322 
5323     if ( bAppliedChangedOutlineStyle )
5324     {
5325         rDoc.SetOutlineNumRule(aOutlineRule);
5326     }
5327 }
5328 
GetAnnotationAuthor(sal_uInt16 nIdx)5329 const String* SwWW8ImplReader::GetAnnotationAuthor(sal_uInt16 nIdx)
5330 {
5331     if (!mpAtnNames && pWwFib->lcbGrpStAtnOwners)
5332     {
5333         // Authoren bestimmen: steht im TableStream
5334         mpAtnNames = new ::std::vector<String>;
5335         SvStream& rStrm = *pTableStream;
5336 
5337         long nOldPos = rStrm.Tell();
5338         rStrm.Seek( pWwFib->fcGrpStAtnOwners );
5339 
5340         long nRead = 0, nCount = pWwFib->lcbGrpStAtnOwners;
5341         while (nRead < nCount)
5342         {
5343             if( bVer67 )
5344             {
5345                 mpAtnNames->push_back(WW8ReadPString(rStrm, false));
5346                 nRead += mpAtnNames->rbegin()->Len() + 1;   // Laenge + sal_uInt8 Count
5347             }
5348             else
5349             {
5350                 mpAtnNames->push_back(WW8Read_xstz(rStrm, 0, false));
5351                 // UNICode: doppelte Laenge + sal_uInt16 Count
5352                 nRead += mpAtnNames->rbegin()->Len() * 2 + 2;
5353             }
5354         }
5355         rStrm.Seek( nOldPos );
5356     }
5357 
5358     const String *pRet = 0;
5359     if (mpAtnNames && nIdx < mpAtnNames->size())
5360         pRet = &((*mpAtnNames)[nIdx]);
5361     return pRet;
5362 }
5363 
LoadDoc(SwPaM & rPaM,WW8Glossary * pGloss)5364 sal_uLong SwWW8ImplReader::LoadDoc( SwPaM& rPaM,WW8Glossary *pGloss)
5365 {
5366     sal_uLong nErrRet = 0;
5367 
5368     {
5369         static const sal_Char* aNames[ 13 ] = {
5370             "WinWord/WW", "WinWord/WW8", "WinWord/WWFT",
5371             "WinWord/WWFLX", "WinWord/WWFLY",
5372             "WinWord/WWF",
5373             "WinWord/WWFA0", "WinWord/WWFA1", "WinWord/WWFA2",
5374             "WinWord/WWFB0", "WinWord/WWFB1", "WinWord/WWFB2",
5375             "WinWord/RegardHindiDigits"
5376         };
5377         sal_uInt32 aVal[ 13 ];
5378 
5379         SwFilterOptions aOpt( 13, aNames, aVal );
5380 
5381         nIniFlags = aVal[ 0 ];
5382         nIniFlags1= aVal[ 1 ];
5383         // schiebt Flys um x twips nach rechts o. links
5384         nIniFlyDx = aVal[ 3 ];
5385         nIniFlyDy = aVal[ 4 ];
5386 
5387         nFieldFlags = aVal[ 5 ];
5388         nFieldTagAlways[0] = aVal[ 6 ];
5389         nFieldTagAlways[1] = aVal[ 7 ];
5390         nFieldTagAlways[2] = aVal[ 8 ];
5391         nFieldTagBad[0] = aVal[ 9 ];
5392         nFieldTagBad[1] = aVal[ 10 ];
5393         nFieldTagBad[2] = aVal[ 11 ];
5394         m_bRegardHindiDigits = aVal[ 12 ] > 0;
5395     }
5396 
5397     sal_uInt16 nMagic;
5398     *pStrm >> nMagic;
5399 
5400     // beachte: 6 steht fuer "6 ODER 7",  7 steht fuer "NUR 7"
5401     switch (nWantedVersion)
5402     {
5403         case 6:
5404         case 7:
5405             if (
5406                 (0xa5dc != nMagic && 0xa5db != nMagic) &&
5407                 (nMagic < 0xa697 || nMagic > 0xa699)
5408                )
5409             {
5410                 //JP 06.05.99: teste auf eigenen 97-Fake!
5411                 if (pStg && 0xa5ec == nMagic)
5412                 {
5413                     sal_uLong nCurPos = pStrm->Tell();
5414                     if (pStrm->Seek(nCurPos + 22))
5415                     {
5416                         sal_uInt32 nfcMin;
5417                         *pStrm >> nfcMin;
5418                         if (0x300 != nfcMin)
5419                             nErrRet = ERR_WW6_NO_WW6_FILE_ERR;
5420                     }
5421                     pStrm->Seek( nCurPos );
5422                 }
5423                 else
5424                     nErrRet = ERR_WW6_NO_WW6_FILE_ERR;
5425             }
5426             break;
5427         case 8:
5428             if (0xa5ec != nMagic)
5429                 nErrRet = ERR_WW8_NO_WW8_FILE_ERR;
5430             break;
5431         default:
5432             nErrRet = ERR_WW8_NO_WW8_FILE_ERR;
5433             ASSERT( sal_False, "It was forgotten to encode nVersion!" );
5434             break;
5435     }
5436 
5437     if (!nErrRet)
5438         nErrRet = LoadThroughDecryption(rPaM ,pGloss);
5439 
5440     rDoc.PropagateOutlineRule();
5441 
5442     return nErrRet;
5443 }
5444 
ImportDOC()5445 extern "C" SAL_DLLPUBLIC_EXPORT Reader* SAL_CALL ImportDOC()
5446 {
5447     return new WW8Reader();
5448 }
5449 
Read(SwDoc & rDoc,const String & rBaseURL,SwPaM & rPam,const String &)5450 sal_uLong WW8Reader::Read(SwDoc &rDoc, const String& rBaseURL, SwPaM &rPam, const String & /* FileName */)
5451 {
5452     sal_uInt16 nOldBuffSize = 32768;
5453     bool bNew = !bInsertMode;               // Neues Doc ( kein Einfuegen )
5454 
5455 
5456     SvStorageStreamRef refStrm;         // damit uns keiner den Stream klaut
5457     SvStream* pIn = pStrm;
5458 
5459     sal_uLong nRet = 0;
5460     sal_uInt8 nVersion = 8;
5461 
5462     String sFltName = GetFltName();
5463     if( sFltName.EqualsAscii( "WW6" ) )
5464     {
5465         if (pStrm)
5466             nVersion = 6;
5467         else
5468         {
5469             ASSERT(sal_False, "WinWord 95 Reader-Read without stream");
5470             nRet = ERR_SWG_READ_ERROR;
5471         }
5472     }
5473     else
5474     {
5475         if( sFltName.EqualsAscii( "CWW6" ) )
5476             nVersion = 6;
5477         else if( sFltName.EqualsAscii( "CWW7" ) )
5478             nVersion = 7;
5479 
5480         if( pStg )
5481         {
5482             nRet = OpenMainStream( refStrm, nOldBuffSize );
5483             pIn = &refStrm;
5484         }
5485         else
5486         {
5487             ASSERT(sal_False, "WinWord 95/97 Reader-Read without storage");
5488             nRet = ERR_SWG_READ_ERROR;
5489         }
5490     }
5491 
5492     if( !nRet )
5493     {
5494         //JP 18.01.96: Alle Ueberschriften sind normalerweise ohne
5495         //              Kapitelnummer. Darum hier explizit abschalten
5496         //              weil das Default jetzt wieder auf AN ist.
5497         if (bNew)
5498         {
5499             Reader::SetNoOutlineNum( rDoc );
5500             // MIB 27.09.96: Umrandung uns Abstaende aus Frm-Vorlagen entf.
5501             Reader::ResetFrmFmts( rDoc );
5502         }
5503         SwWW8ImplReader* pRdr = new SwWW8ImplReader(nVersion, pStg, pIn, rDoc,
5504             rBaseURL, bNew);
5505         try
5506         {
5507             nRet = pRdr->LoadDoc( rPam );
5508         }
5509         catch( const std::exception& )
5510         {
5511             nRet = ERR_WW8_NO_WW8_FILE_ERR;
5512         }
5513         delete pRdr;
5514 
5515         if( refStrm.Is() )
5516         {
5517             refStrm->SetBufferSize( nOldBuffSize );
5518             refStrm.Clear();
5519         }
5520         else if (pIn)
5521             pIn->ResetError();
5522 
5523     }
5524     return nRet;
5525 }
5526 
GetReaderType()5527 int WW8Reader::GetReaderType()
5528 {
5529     return SW_STORAGE_READER | SW_STREAM_READER;
5530 }
5531 
HasGlossaries() const5532 sal_Bool WW8Reader::HasGlossaries() const
5533 {
5534     return true;
5535 }
5536 
ReadGlossaries(SwTextBlocks & rBlocks,sal_Bool bSaveRelFiles) const5537 sal_Bool WW8Reader::ReadGlossaries(SwTextBlocks& rBlocks, sal_Bool bSaveRelFiles) const
5538 {
5539     bool bRet=false;
5540 
5541     WW8Reader *pThis = const_cast<WW8Reader *>(this);
5542 
5543     sal_uInt16 nOldBuffSize = 32768;
5544     SvStorageStreamRef refStrm;
5545     if (!pThis->OpenMainStream(refStrm, nOldBuffSize))
5546     {
5547         WW8Glossary aGloss( refStrm, 8, pStg );
5548         bRet = aGloss.Load( rBlocks, bSaveRelFiles ? true : false);
5549     }
5550     return bRet ? true : false;
5551 }
5552 
GetOLEStorageName(long nOLEId,String & rStorageName,SvStorageRef & rSrcStorage,uno::Reference<embed::XStorage> & rDestStorage) const5553 sal_Bool SwMSDffManager::GetOLEStorageName(long nOLEId, String& rStorageName,
5554     SvStorageRef& rSrcStorage, uno::Reference < embed::XStorage >& rDestStorage) const
5555 {
5556     bool bRet = false;
5557 
5558     long nPictureId = 0;
5559     if (rReader.pStg)
5560     {
5561         // dann holen wir uns mal ueber den TextBox-PLCF die richtigen
5562         // Char Start-/End-Positionen. In dem Bereich sollte dann
5563         // das EinbettenFeld und die entsprechenden Sprms zu finden
5564         // sein. Wir brauchen hier aber nur das Sprm fuer die Picture Id
5565         long nOldPos = rReader.pStrm->Tell();
5566         {
5567             // #i32596# - consider return value of method
5568             // <rReader.GetTxbxTextSttEndCp(..)>. If it returns false, method
5569             // wasn't successful. Thus, continue in this case.
5570             // Note: Ask MM for initialization of <nStartCp> and <nEndCp>.
5571             // Note: Ask MM about assertions in method <rReader.GetTxbxTextSttEndCp(..)>.
5572             WW8_CP nStartCp, nEndCp;
5573             if ( rReader.GetTxbxTextSttEndCp(nStartCp, nEndCp,
5574                             static_cast<sal_uInt16>((nOLEId >> 16) & 0xFFFF),
5575                             static_cast<sal_uInt16>(nOLEId & 0xFFFF)) )
5576             {
5577                 WW8PLCFxSaveAll aSave;
5578                 memset( &aSave, 0, sizeof( aSave ) );
5579                 rReader.pPlcxMan->SaveAllPLCFx( aSave );
5580 
5581                 nStartCp += rReader.nDrawCpO;
5582                 nEndCp   += rReader.nDrawCpO;
5583                 WW8PLCFx_Cp_FKP* pChp = rReader.pPlcxMan->GetChpPLCF();
5584                 wwSprmParser aSprmParser(rReader.pWwFib->GetFIBVersion());
5585                 while (nStartCp <= nEndCp && !nPictureId)
5586                 {
5587                     WW8PLCFxDesc aDesc;
5588                     pChp->SeekPos( nStartCp );
5589                     pChp->GetSprms( &aDesc );
5590 
5591                     if (aDesc.nSprmsLen && aDesc.pMemPos)   // Attribut(e) vorhanden
5592                     {
5593                         long nLen = aDesc.nSprmsLen;
5594                         const sal_uInt8* pSprm = aDesc.pMemPos;
5595 
5596                         while (nLen >= 2 && !nPictureId)
5597                         {
5598                             sal_uInt16 nId = aSprmParser.GetSprmId(pSprm);
5599                             sal_uInt16 nSL = aSprmParser.GetSprmSize(nId, pSprm);
5600 
5601                             if( nLen < nSL )
5602                                 break;              // nicht mehr genug Bytes uebrig
5603 
5604                             if( 0x6A03 == nId && 0 < nLen )
5605                             {
5606                                 nPictureId = SVBT32ToUInt32(pSprm +
5607                                     aSprmParser.DistanceToData(nId));
5608                                 bRet = true;
5609                             }
5610                             pSprm += nSL;
5611                             nLen -= nSL;
5612                         }
5613                     }
5614                     nStartCp = aDesc.nEndPos;
5615                 }
5616 
5617                 rReader.pPlcxMan->RestoreAllPLCFx( aSave );
5618             }
5619         }
5620         rReader.pStrm->Seek( nOldPos );
5621     }
5622 
5623     if( bRet )
5624     {
5625         rStorageName = '_';
5626         rStorageName += String::CreateFromInt32(nPictureId);
5627         rSrcStorage = rReader.pStg->OpenSotStorage(CREATE_CONST_ASC(
5628             SL::aObjectPool));
5629         if (!rReader.mpDocShell)
5630             bRet=false;
5631         else
5632             rDestStorage = rReader.mpDocShell->GetStorage();
5633     }
5634     return bRet;
5635 }
5636 
ShapeHasText(sal_uLong,sal_uLong) const5637 sal_Bool SwMSDffManager::ShapeHasText(sal_uLong, sal_uLong) const
5638 {
5639     // Zur Zeit des Einlesens einer einzelnen Box, die womoeglich Teil einer
5640     // Gruppe ist, liegen noch nicht genuegend Informationen vor, um
5641     // entscheiden zu koennen, ob wir sie nicht doch als Textfeld benoetigen.
5642     // Also vorsichtshalber mal alle umwandeln:
5643     return true;
5644 }
5645 
InEqualOrHigherApo(int nLvl) const5646 bool SwWW8ImplReader::InEqualOrHigherApo(int nLvl) const
5647 {
5648     if (nLvl)
5649         --nLvl;
5650     // #i60827# - check size of <maApos> to assure that <maApos.begin() + nLvl> can be performed.
5651     if ( sal::static_int_cast< sal_Int32>(nLvl) >= sal::static_int_cast< sal_Int32>(maApos.size()) )
5652     {
5653         return false;
5654     }
5655     mycApoIter aIter = std::find(maApos.begin() + nLvl, maApos.end(), true);
5656     if (aIter != maApos.end())
5657         return true;
5658     else
5659         return false;
5660 }
5661 
InEqualApo(int nLvl) const5662 bool SwWW8ImplReader::InEqualApo(int nLvl) const
5663 {
5664     //If we are in a table, see if an apo was inserted at the level below
5665     //the table.
5666     if (nLvl)
5667         --nLvl;
5668     return maApos[nLvl];
5669 }
5670 
5671 namespace sw
5672 {
5673     namespace hack
5674     {
Position(const SwPosition & rPos)5675         Position::Position(const SwPosition &rPos)
5676             : maPtNode(rPos.nNode), mnPtCntnt(rPos.nContent.GetIndex())
5677         {
5678         }
5679 
Position(const Position & rPos)5680         Position::Position(const Position &rPos)
5681             : maPtNode(rPos.maPtNode), mnPtCntnt(rPos.mnPtCntnt)
5682         {
5683         }
5684 
operator SwPosition() const5685         Position::operator SwPosition() const
5686         {
5687             SwPosition aRet(maPtNode);
5688             aRet.nContent.Assign(maPtNode.GetNode().GetCntntNode(), mnPtCntnt);
5689             return aRet;
5690         }
5691     }
5692 }
5693 
5694 /* vi:set tabstop=4 shiftwidth=4 expandtab: */
5695 
SwMacroInfo()5696 SwMacroInfo::SwMacroInfo() :
5697     SdrObjUserData( SW_DRAWLAYER, SW_UD_IMAPDATA, 0 )
5698 {
5699 }
5700 
~SwMacroInfo()5701 SwMacroInfo::~SwMacroInfo()
5702 {
5703 }
5704 
Clone(SdrObject *) const5705 SdrObjUserData* SwMacroInfo::Clone( SdrObject* /*pObj*/ ) const
5706 {
5707    return new SwMacroInfo( *this );
5708 }
5709