summaryrefslogtreecommitdiff
path: root/sc/source/filter/excel/xicontent.cxx
blob: e095ef98761504602a080ee6c762f99799dc1b92 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#include "xicontent.hxx"
#include <sfx2/objsh.hxx>
#include <sfx2/docfile.hxx>
#include <tools/urlobj.hxx>
#include <editeng/editeng.hxx>
#include <editeng/editobj.hxx>
#include <sfx2/linkmgr.hxx>
#include <svl/itemset.hxx>
#include "scitems.hxx"
#include <editeng/eeitem.hxx>
#include <svl/intitem.hxx>
#include <svl/stritem.hxx>
#include <editeng/flditem.hxx>
#include <editeng/fhgtitem.hxx>
#include <editeng/wghtitem.hxx>
#include <editeng/udlnitem.hxx>
#include <editeng/postitem.hxx>
#include <editeng/colritem.hxx>
#include <editeng/crsditem.hxx>
#include "document.hxx"
#include "editutil.hxx"
#include "cell.hxx"
#include "validat.hxx"
#include "patattr.hxx"
#include "docpool.hxx"
#include "rangenam.hxx"
#include "arealink.hxx"
#include "stlsheet.hxx"
#include "scextopt.hxx"
#include "xlformula.hxx"
#include "xltracer.hxx"
#include "xistream.hxx"
#include "xihelper.hxx"
#include "xistyle.hxx"
#include "xiescher.hxx"
#include "xiname.hxx"

#include "excform.hxx"
#include "tabprotection.hxx"

#include <memory>

using ::com::sun::star::uno::Sequence;
using ::std::auto_ptr;

// Shared string table ========================================================

XclImpSst::XclImpSst( const XclImpRoot& rRoot ) :
    XclImpRoot( rRoot )
{
}

void XclImpSst::ReadSst( XclImpStream& rStrm )
{
    sal_uInt32 nStrCount;
    rStrm.Ignore( 4 );
    rStrm >> nStrCount;
    maStrings.clear();
    maStrings.reserve( static_cast< size_t >( nStrCount ) );
    while( (nStrCount > 0) && rStrm.IsValid() )
    {
        XclImpString aString;
        aString.Read( rStrm );
        maStrings.push_back( aString );
        --nStrCount;
    }
}

const XclImpString* XclImpSst::GetString( sal_uInt32 nSstIndex ) const
{
    return (nSstIndex < maStrings.size()) ? &maStrings[ nSstIndex ] : 0;
}

ScBaseCell* XclImpSst::CreateCell( sal_uInt32 nSstIndex, sal_uInt16 nXFIndex ) const
{
    ScBaseCell* pCell = 0;
    if( const XclImpString* pString = GetString( nSstIndex ) )
        pCell = XclImpStringHelper::CreateCell( *this, *pString, nXFIndex );
    return pCell;
}

// Hyperlinks =================================================================

namespace {

/** Reads character array and stores it into rString.
    @param nChars  Number of following characters (not byte count!).
    @param b16Bit  true = 16-bit characters, false = 8-bit characters. */
void lclAppendString32( String& rString, XclImpStream& rStrm, sal_uInt32 nChars, bool b16Bit )
{
    sal_uInt16 nReadChars = ulimit_cast< sal_uInt16 >( nChars );
    rString.Append( rStrm.ReadRawUniString( nReadChars, b16Bit ) );
    // ignore remaining chars
    sal_Size nIgnore = nChars - nReadChars;
    if( b16Bit )
        nIgnore *= 2;
    rStrm.Ignore( nIgnore );
}

/** Reads 32-bit string length and the character array and stores it into rString.
    @param b16Bit  true = 16-bit characters, false = 8-bit characters. */
void lclAppendString32( String& rString, XclImpStream& rStrm, bool b16Bit )
{
    lclAppendString32( rString, rStrm, rStrm.ReaduInt32(), b16Bit );
}

/** Reads 32-bit string length and ignores following character array.
    @param b16Bit  true = 16-bit characters, false = 8-bit characters. */
void lclIgnoreString32( XclImpStream& rStrm, bool b16Bit )
{
    sal_uInt32 nChars;
    rStrm >> nChars;
    if( b16Bit )
        nChars *= 2;
    rStrm.Ignore( nChars );
}

/** Converts a path to an absolute path.
    @param rPath  The source path. The resulting path is returned here.
    @param nLevel  Number of parent directories to add in front of the path. */
void lclGetAbsPath( String& rPath, sal_uInt16 nLevel, SfxObjectShell* pDocShell )
{
    String aTmpStr;
    while( nLevel )
    {
        aTmpStr.AppendAscii( "../" );
        --nLevel;
    }
    aTmpStr += rPath;

    if( pDocShell )
    {
        bool bWasAbs = false;
        rPath = pDocShell->GetMedium()->GetURLObject().smartRel2Abs( aTmpStr, bWasAbs ).GetMainURL( INetURLObject::NO_DECODE );
        // full path as stored in SvxURLField must be encoded
    }
    else
        rPath = aTmpStr;
}

/** Inserts the URL into a text cell. Does not modify value or formula cells. */
void lclInsertUrl( const XclImpRoot& rRoot, const String& rUrl, SCCOL nScCol, SCROW nScRow, SCTAB nScTab )
{
    ScDocument& rDoc = rRoot.GetDoc();
    ScAddress aScPos( nScCol, nScRow, nScTab );
    CellType eCellType = rDoc.GetCellType( aScPos );
    switch( eCellType )
    {
        // #i54261# hyperlinks in string cells
        case CELLTYPE_STRING:
        case CELLTYPE_EDIT:
        {
            String aDisplText;
            rDoc.GetString( nScCol, nScRow, nScTab, aDisplText );
            if( !aDisplText.Len() )
                aDisplText = rUrl;

            ScEditEngineDefaulter& rEE = rRoot.GetEditEngine();
            SvxURLField aUrlField( rUrl, aDisplText, SVXURLFORMAT_APPDEFAULT );

            const ScEditCell* pEditCell = (eCellType == CELLTYPE_EDIT) ? static_cast< const ScEditCell* >( rDoc.GetCell( aScPos ) ) : 0;
            const EditTextObject* pEditObj = pEditCell ? pEditCell->GetData() : 0;
            if( pEditObj )
            {
                rEE.SetText( *pEditObj );
                rEE.QuickInsertField( SvxFieldItem( aUrlField, EE_FEATURE_FIELD ), ESelection( 0, 0, 0xFFFF, 0 ) );
            }
            else
            {
                rEE.SetText( EMPTY_STRING );
                rEE.QuickInsertField( SvxFieldItem( aUrlField, EE_FEATURE_FIELD ), ESelection() );
                if( const ScPatternAttr* pPattern = rDoc.GetPattern( aScPos.Col(), aScPos.Row(), nScTab ) )
                {
                    SfxItemSet aItemSet( rEE.GetEmptyItemSet() );
                    pPattern->FillEditItemSet( &aItemSet );
                    rEE.QuickSetAttribs( aItemSet, ESelection( 0, 0, 0xFFFF, 0 ) );
                }
            }
            ::std::auto_ptr< EditTextObject > xTextObj( rEE.CreateTextObject() );

            ScEditCell* pCell = new ScEditCell( xTextObj.get(), &rDoc, rEE.GetEditTextObjectPool() );
            rDoc.PutCell( aScPos, pCell );
        }
        break;

        // fix for #i31050# disabled, HYPERLINK is not able to return numeric value (#i91351#)
#if 0
        case CELLTYPE_VALUE:
        {
            // #i31050# replace number with HYPERLINK function
            ScTokenArray aTokenArray;
            aTokenArray.AddOpCode( ocHyperLink );
            aTokenArray.AddOpCode( ocOpen );
            aTokenArray.AddString( rUrl );
            aTokenArray.AddOpCode( ocSep );
            aTokenArray.AddDouble( rDoc.GetValue( aScPos ) );
            aTokenArray.AddOpCode( ocClose );
            rDoc.PutCell( aScPos, new ScFormulaCell( &rDoc, aScPos, &aTokenArray ) );
        }
        break;
#endif

        default:;
    }
}

} // namespace

// ----------------------------------------------------------------------------

void XclImpHyperlink::ReadHlink( XclImpStream& rStrm )
{
    XclRange aXclRange( ScAddress::UNINITIALIZED );
    rStrm >> aXclRange;
    // #i80006# Excel silently ignores invalid hi-byte of column index (TODO: everywhere?)
    aXclRange.maFirst.mnCol &= 0xFF;
    aXclRange.maLast.mnCol &= 0xFF;
    String aString = ReadEmbeddedData( rStrm );
    if ( aString.Len() > 0 )
        rStrm.GetRoot().GetXFRangeBuffer().SetHyperlink( aXclRange, aString );
}

String XclImpHyperlink::ReadEmbeddedData( XclImpStream& rStrm )
{
    const XclImpRoot& rRoot = rStrm.GetRoot();
    SfxObjectShell* pDocShell = rRoot.GetDocShell();

    DBG_ASSERT_BIFF( rRoot.GetBiff() == EXC_BIFF8 );

    sal_uInt32 nFlags;
    XclGuid aGuid;
    rStrm >> aGuid;
    rStrm.Ignore( 4 );
    rStrm >> nFlags;

    DBG_ASSERT( aGuid == XclTools::maGuidStdLink, "XclImpHyperlink::ReadEmbeddedData - unknown header GUID" );

    sal_uInt16 nLevel = 0;                  // counter for level to climb down in path
    ::std::auto_ptr< String > xLongName;    // link / file name
    ::std::auto_ptr< String > xShortName;   // 8.3-representation of file name
    ::std::auto_ptr< String > xTextMark;    // text mark

    // description (ignore)
    if( ::get_flag( nFlags, EXC_HLINK_DESCR ) )
        lclIgnoreString32( rStrm, true );
    // target frame (ignore) !! DESCR/FRAME - is this the right order? (never seen them together)
    if( ::get_flag( nFlags, EXC_HLINK_FRAME ) )
        lclIgnoreString32( rStrm, true );

    // URL fields are zero-terminated - do not let the stream replace them
    // in the lclAppendString32() with the '?' character.
    rStrm.SetNulSubstChar( '\0' );

    // UNC path
    if( ::get_flag( nFlags, EXC_HLINK_UNC ) )
    {
        xLongName.reset( new String );
        lclAppendString32( *xLongName, rStrm, true );
        lclGetAbsPath( *xLongName, 0, pDocShell );
    }
    // file link or URL
    else if( ::get_flag( nFlags, EXC_HLINK_BODY ) )
    {
        rStrm >> aGuid;

        if( aGuid == XclTools::maGuidFileMoniker )
        {
            rStrm >> nLevel;
            xShortName.reset( new String );
            lclAppendString32( *xShortName, rStrm, false );
            rStrm.Ignore( 24 );

            sal_uInt32 nStrLen;
            rStrm >> nStrLen;
            if( nStrLen )
            {
                rStrm >> nStrLen;
                nStrLen /= 2;       // it's byte count here...
                rStrm.Ignore( 2 );
                xLongName.reset( new String );
                lclAppendString32( *xLongName, rStrm, nStrLen, true );
                lclGetAbsPath( *xLongName, nLevel, pDocShell );
            }
            else
                lclGetAbsPath( *xShortName, nLevel, pDocShell );
        }
        else if( aGuid == XclTools::maGuidUrlMoniker )
        {
            sal_uInt32 nStrLen;
            rStrm >> nStrLen;
            nStrLen /= 2;       // it's byte count here...
            xLongName.reset( new String );
            lclAppendString32( *xLongName, rStrm, nStrLen, true );
            if( !::get_flag( nFlags, EXC_HLINK_ABS ) )
                lclGetAbsPath( *xLongName, 0, pDocShell );
        }
        else
        {
            DBG_ERRORFILE( "XclImpHyperlink::ReadEmbeddedData - unknown content GUID" );
        }
    }

    // text mark
    if( ::get_flag( nFlags, EXC_HLINK_MARK ) )
    {
        xTextMark.reset( new String );
        lclAppendString32( *xTextMark, rStrm, true );
    }

    rStrm.SetNulSubstChar();    // back to default

    DBG_ASSERT( rStrm.GetRecLeft() == 0, "XclImpHyperlink::ReadEmbeddedData - record size mismatch" );

    if( !xLongName.get() && xShortName.get() )
        xLongName = xShortName;
    else if( !xLongName.get() && xTextMark.get() )
        xLongName.reset( new String );

    if( xLongName.get() )
    {
        if( xTextMark.get() )
        {
            if( xLongName->Len() == 0 )
                xTextMark->SearchAndReplaceAll( '!', '.' );
            xLongName->Append( '#' );
            xLongName->Append( *xTextMark );
        }
        return *xLongName;
    }
    return String::EmptyString();
}

void XclImpHyperlink::ConvertToValidTabName(String& rUrl)
{
    xub_StrLen n = rUrl.Len();
    if (n < 4)
        // Needs at least 4 characters.
        return;

    sal_Unicode c = rUrl.GetChar(0);
    if (c != sal_Unicode('#'))
        // the 1st character must be '#'.
        return;

    String aNewUrl(sal_Unicode('#')), aTabName;

    bool bInQuote = false;
    bool bQuoteTabName = false;
    for (xub_StrLen i = 1; i < n; ++i)
    {
        c = rUrl.GetChar(i);
        if (c == sal_Unicode('\''))
        {
            if (bInQuote && i+1 < n && rUrl.GetChar(i+1) == sal_Unicode('\''))
            {
                // Two consecutive single quotes ('') signify a single literal
                // quite.  When this occurs, the whole table name needs to be
                // quoted.
                bQuoteTabName = true;
                aTabName.Append(c);
                aTabName.Append(c);
                ++i;
                continue;
            }

            bInQuote = !bInQuote;
            if (!bInQuote && aTabName.Len() > 0)
            {
                if (bQuoteTabName)
                    aNewUrl.Append(sal_Unicode('\''));
                aNewUrl.Append(aTabName);
                if (bQuoteTabName)
                    aNewUrl.Append(sal_Unicode('\''));
            }
        }
        else if (bInQuote)
            aTabName.Append(c);
        else
            aNewUrl.Append(c);
    }

    if (bInQuote)
        // It should be outside the quotes!
        return;

    // All is good.  Pass the new URL.
    rUrl = aNewUrl;
}

void XclImpHyperlink::InsertUrl( const XclImpRoot& rRoot, const XclRange& rXclRange, const String& rUrl )
{
    String aUrl(rUrl);
    ConvertToValidTabName(aUrl);

    SCTAB nScTab = rRoot.GetCurrScTab();
    ScRange aScRange( ScAddress::UNINITIALIZED );
    if( rRoot.GetAddressConverter().ConvertRange( aScRange, rXclRange, nScTab, nScTab, true ) )
    {
        SCCOL nScCol1, nScCol2;
        SCROW nScRow1, nScRow2;
        aScRange.GetVars( nScCol1, nScRow1, nScTab, nScCol2, nScRow2, nScTab );
        for( SCCOL nScCol = nScCol1; nScCol <= nScCol2; ++nScCol )
            for( SCROW nScRow = nScRow1; nScRow <= nScRow2; ++nScRow )
                lclInsertUrl( rRoot, aUrl, nScCol, nScRow, nScTab );
    }
}

// Label ranges ===============================================================

void XclImpLabelranges::ReadLabelranges( XclImpStream& rStrm )
{
    const XclImpRoot& rRoot = rStrm.GetRoot();
    DBG_ASSERT_BIFF( rRoot.GetBiff() == EXC_BIFF8 );

    ScDocument& rDoc = rRoot.GetDoc();
    SCTAB nScTab = rRoot.GetCurrScTab();
    XclImpAddressConverter& rAddrConv = rRoot.GetAddressConverter();
    ScRangePairListRef xLabelRangesRef;
    const ScRange* pScRange = 0;

    XclRangeList aRowXclRanges, aColXclRanges;
    rStrm >> aRowXclRanges >> aColXclRanges;

    // row label ranges
    ScRangeList aRowScRanges;
    rAddrConv.ConvertRangeList( aRowScRanges, aRowXclRanges, nScTab, false );
    xLabelRangesRef = rDoc.GetRowNameRangesRef();
    for( pScRange = aRowScRanges.First(); pScRange; pScRange = aRowScRanges.Next() )
    {
        ScRange aDataRange( *pScRange );
        if( aDataRange.aEnd.Col() < MAXCOL )
        {
            aDataRange.aStart.SetCol( aDataRange.aEnd.Col() + 1 );
            aDataRange.aEnd.SetCol( MAXCOL );
        }
        else if( aDataRange.aStart.Col() > 0 )
        {
            aDataRange.aEnd.SetCol( aDataRange.aStart.Col() - 1 );
            aDataRange.aStart.SetCol( 0 );
        }
        xLabelRangesRef->Append( ScRangePair( *pScRange, aDataRange ) );
    }

    // column label ranges
    ScRangeList aColScRanges;
    rAddrConv.ConvertRangeList( aColScRanges, aColXclRanges, nScTab, false );
    xLabelRangesRef = rDoc.GetColNameRangesRef();
    for( pScRange = aColScRanges.First(); pScRange; pScRange = aColScRanges.Next() )
    {
        ScRange aDataRange( *pScRange );
        if( aDataRange.aEnd.Row() < MAXROW )
        {
            aDataRange.aStart.SetRow( aDataRange.aEnd.Row() + 1 );
            aDataRange.aEnd.SetRow( MAXROW );
        }
        else if( aDataRange.aStart.Row() > 0 )
        {
            aDataRange.aEnd.SetRow( aDataRange.aStart.Row() - 1 );
            aDataRange.aStart.SetRow( 0 );
        }
        xLabelRangesRef->Append( ScRangePair( *pScRange, aDataRange ) );
    }
}

// Conditional formatting =====================================================

XclImpCondFormat::XclImpCondFormat( const XclImpRoot& rRoot, sal_uInt32 nFormatIndex ) :
    XclImpRoot( rRoot ),
    mnFormatIndex( nFormatIndex ),
    mnCondCount( 0 ),
    mnCondIndex( 0 )
{
}

XclImpCondFormat::~XclImpCondFormat()
{
}

void XclImpCondFormat::ReadCondfmt( XclImpStream& rStrm )
{
    DBG_ASSERT( !mnCondCount, "XclImpCondFormat::ReadCondfmt - already initialized" );
    XclRangeList aXclRanges;
    rStrm >> mnCondCount;
    rStrm.Ignore( 10 );
    rStrm >> aXclRanges;
    GetAddressConverter().ConvertRangeList( maRanges, aXclRanges, GetCurrScTab(), true );
}

void XclImpCondFormat::ReadCF( XclImpStream& rStrm )
{
    if( mnCondIndex >= mnCondCount )
    {
        DBG_ERRORFILE( "XclImpCondFormat::ReadCF - CF without leading CONDFMT" );
        return;
    }

    // entire conditional format outside of valid range?
    if( !maRanges.Count() )
        return;

    sal_uInt8 nType, nOperator;
    sal_uInt16 nFmlaSize1, nFmlaSize2;
    sal_uInt32 nFlags;

    rStrm >> nType >> nOperator >> nFmlaSize1 >> nFmlaSize2 >> nFlags;
    rStrm.Ignore( 2 );

    // *** mode and comparison operator ***

    ScConditionMode eMode = SC_COND_NONE;
    switch( nType )
    {
        case EXC_CF_TYPE_CELL:
        {
            switch( nOperator )
            {
                case EXC_CF_CMP_BETWEEN:        eMode = SC_COND_BETWEEN;    break;
                case EXC_CF_CMP_NOT_BETWEEN:    eMode = SC_COND_NOTBETWEEN; break;
                case EXC_CF_CMP_EQUAL:          eMode = SC_COND_EQUAL;      break;
                case EXC_CF_CMP_NOT_EQUAL:      eMode = SC_COND_NOTEQUAL;   break;
                case EXC_CF_CMP_GREATER:        eMode = SC_COND_GREATER;    break;
                case EXC_CF_CMP_LESS:           eMode = SC_COND_LESS;       break;
                case EXC_CF_CMP_GREATER_EQUAL:  eMode = SC_COND_EQGREATER;  break;
                case EXC_CF_CMP_LESS_EQUAL:     eMode = SC_COND_EQLESS;     break;
                default:
                    DBG_ERROR1( "XclImpCondFormat::ReadCF - unknown CF comparison 0x%02hX", nOperator );
            }
        }
        break;

        case EXC_CF_TYPE_FMLA:
            eMode = SC_COND_DIRECT;
        break;

        default:
            DBG_ERROR1( "XclImpCondFormat::ReadCF - unknown CF mode 0x%02hX", nType );
            return;
    }

    // *** create style sheet ***

    String aStyleName( XclTools::GetCondFormatStyleName( GetCurrScTab(), mnFormatIndex, mnCondIndex ) );
    SfxItemSet& rStyleItemSet = ScfTools::MakeCellStyleSheet( GetStyleSheetPool(), aStyleName, true ).GetItemSet();

    const XclImpPalette& rPalette = GetPalette();

    // *** font block ***

    if( ::get_flag( nFlags, EXC_CF_BLOCK_FONT ) )
    {
        XclImpFont aFont( GetRoot() );
        aFont.ReadCFFontBlock( rStrm );
        aFont.FillToItemSet( rStyleItemSet, EXC_FONTITEM_CELL );
    }

    // *** border block ***

    if( ::get_flag( nFlags, EXC_CF_BLOCK_BORDER ) )
    {
        sal_uInt16 nLineStyle;
        sal_uInt32 nLineColor;
        rStrm >> nLineStyle >> nLineColor;
        rStrm.Ignore( 2 );

        XclImpCellBorder aBorder;
        aBorder.FillFromCF8( nLineStyle, nLineColor, nFlags );
        aBorder.FillToItemSet( rStyleItemSet, rPalette );
    }

    // *** pattern block ***

    if( ::get_flag( nFlags, EXC_CF_BLOCK_AREA ) )
    {
        sal_uInt16 nPattern, nColor;
        rStrm >> nPattern >> nColor;

        XclImpCellArea aArea;
        aArea.FillFromCF8( nPattern, nColor, nFlags );
        aArea.FillToItemSet( rStyleItemSet, rPalette );
    }

    // *** formulas ***

    const ScAddress& rPos = maRanges.GetObject( 0 )->aStart;    // assured above that maRanges is not empty
    ExcelToSc& rFmlaConv = GetOldFmlaConverter();

    ::std::auto_ptr< ScTokenArray > xTokArr1;
    if( nFmlaSize1 > 0 )
    {
        const ScTokenArray* pTokArr = 0;
        rFmlaConv.Reset( rPos );
        rFmlaConv.Convert( pTokArr, rStrm, nFmlaSize1, false, FT_RangeName );
        // formula converter owns pTokArr -> create a copy of the token array
        if( pTokArr )
            xTokArr1.reset( pTokArr->Clone() );
    }

    ::std::auto_ptr< ScTokenArray > pTokArr2;
    if( nFmlaSize2 > 0 )
    {
        const ScTokenArray* pTokArr = 0;
        rFmlaConv.Reset( rPos );
        rFmlaConv.Convert( pTokArr, rStrm, nFmlaSize2, false, FT_RangeName );
        // formula converter owns pTokArr -> create a copy of the token array
        if( pTokArr )
            pTokArr2.reset( pTokArr->Clone() );
    }

    // *** create the Calc conditional formatting ***

    if( !mxScCondFmt.get() )
    {
        ULONG nKey = 0;
        mxScCondFmt.reset( new ScConditionalFormat( nKey, GetDocPtr() ) );
    }

    ScCondFormatEntry aEntry( eMode, xTokArr1.get(), pTokArr2.get(), GetDocPtr(), rPos, aStyleName );
    mxScCondFmt->AddEntry( aEntry );
    ++mnCondIndex;
}

void XclImpCondFormat::Apply()
{
    if( mxScCondFmt.get() )
    {
        ScDocument& rDoc = GetDoc();

        ULONG nKey = rDoc.AddCondFormat( *mxScCondFmt );
        ScPatternAttr aPattern( rDoc.GetPool() );
        aPattern.GetItemSet().Put( SfxUInt32Item( ATTR_CONDITIONAL, nKey ) );

        // maRanges contains only valid cell ranges
        for( const ScRange* pScRange = maRanges.First(); pScRange; pScRange = maRanges.Next() )
        {
            rDoc.ApplyPatternAreaTab(
                pScRange->aStart.Col(), pScRange->aStart.Row(),
                pScRange->aEnd.Col(), pScRange->aEnd.Row(),
                pScRange->aStart.Tab(), aPattern );
        }
    }
}

// ----------------------------------------------------------------------------

XclImpCondFormatManager::XclImpCondFormatManager( const XclImpRoot& rRoot ) :
    XclImpRoot( rRoot )
{
}

void XclImpCondFormatManager::ReadCondfmt( XclImpStream& rStrm )
{
    XclImpCondFormat* pFmt = new XclImpCondFormat( GetRoot(), maCondFmtList.Count() );
    pFmt->ReadCondfmt( rStrm );
    maCondFmtList.Append( pFmt );
}

void XclImpCondFormatManager::ReadCF( XclImpStream& rStrm )
{
    DBG_ASSERT( !maCondFmtList.Empty(), "XclImpCondFormatManager::ReadCF - CF without leading CONDFMT" );
    if( !maCondFmtList.Empty() )
        maCondFmtList.GetObject( maCondFmtList.Count() - 1 )->ReadCF( rStrm );
}

void XclImpCondFormatManager::Apply()
{
    for( XclImpCondFormat* pFmt = maCondFmtList.First(); pFmt; pFmt = maCondFmtList.Next() )
        pFmt->Apply();
    maCondFmtList.Clear();
}

// Data Validation ============================================================

void XclImpValidation::ReadDval( XclImpStream& rStrm )
{
    const XclImpRoot& rRoot = rStrm.GetRoot();
    DBG_ASSERT_BIFF( rRoot.GetBiff() == EXC_BIFF8 );

    sal_uInt32 nObjId;
    rStrm.Ignore( 10 );
    rStrm >> nObjId;
    if( nObjId != EXC_DVAL_NOOBJ )
    {
        DBG_ASSERT( nObjId <= 0xFFFF, "XclImpValidation::ReadDval - invalid object ID" );
        rRoot.GetCurrSheetDrawing().SetSkipObj( static_cast< sal_uInt16 >( nObjId ) );
    }
}

void XclImpValidation::ReadDV( XclImpStream& rStrm )
{
    const XclImpRoot& rRoot = rStrm.GetRoot();
    DBG_ASSERT_BIFF( rRoot.GetBiff() == EXC_BIFF8 );

    ScDocument& rDoc = rRoot.GetDoc();
    SCTAB nScTab = rRoot.GetCurrScTab();
    ExcelToSc& rFmlaConv = rRoot.GetOldFmlaConverter();

    // flags
    sal_uInt32 nFlags;
    rStrm >> nFlags;

    // message strings
    /*  Empty strings are single NUL characters in Excel (string length is 1).
        -> Do not let the stream replace them with '?' characters. */
    rStrm.SetNulSubstChar( '\0' );
    String aPromptTitle(   rStrm.ReadUniString() );
    String aErrorTitle(    rStrm.ReadUniString() );
    String aPromptMessage( rStrm.ReadUniString() );
    String aErrorMessage(  rStrm.ReadUniString() );
    rStrm.SetNulSubstChar();    // back to default

    // formula(s)
    if( rStrm.GetRecLeft() > 8 )
    {
        sal_uInt16 nLen;

        // first formula
        // string list is single tStr token with NUL separators -> replace them with LF
        rStrm.SetNulSubstChar( '\n' );
        ::std::auto_ptr< ScTokenArray > xTokArr1;
        rStrm >> nLen;
        rStrm.Ignore( 2 );
        if( nLen > 0 )
        {
            const ScTokenArray* pTokArr = 0;
            rFmlaConv.Reset();
            rFmlaConv.Convert( pTokArr, rStrm, nLen, false, FT_RangeName );
            // formula converter owns pTokArr -> create a copy of the token array
            if( pTokArr )
                xTokArr1.reset( pTokArr->Clone() );
        }
        rStrm.SetNulSubstChar();    // back to default

        // second formula
        ::std::auto_ptr< ScTokenArray > xTokArr2;
        rStrm >> nLen;
        rStrm.Ignore( 2 );
        if( nLen > 0 )
        {
            const ScTokenArray* pTokArr = 0;
            rFmlaConv.Reset();
            rFmlaConv.Convert( pTokArr, rStrm, nLen, false, FT_RangeName );
            // formula converter owns pTokArr -> create a copy of the token array
            if( pTokArr )
                xTokArr2.reset( pTokArr->Clone() );
        }

        // read all cell ranges
        XclRangeList aXclRanges;
        rStrm >> aXclRanges;

        // convert to Calc range list
        ScRangeList aScRanges;
        rRoot.GetAddressConverter().ConvertRangeList( aScRanges, aXclRanges, nScTab, true );

        // only continue if there are valid ranges
        if( aScRanges.Count() )
        {
            bool bIsValid = true;   // valid settings in flags field

            ScValidationMode eValMode = SC_VALID_ANY;
            switch( nFlags & EXC_DV_MODE_MASK )
            {
                case EXC_DV_MODE_ANY:       eValMode = SC_VALID_ANY;        break;
                case EXC_DV_MODE_WHOLE:     eValMode = SC_VALID_WHOLE;      break;
                case EXC_DV_MODE_DECIMAL:   eValMode = SC_VALID_DECIMAL;    break;
                case EXC_DV_MODE_LIST:      eValMode = SC_VALID_LIST;       break;
                case EXC_DV_MODE_DATE:      eValMode = SC_VALID_DATE;       break;
                case EXC_DV_MODE_TIME:      eValMode = SC_VALID_TIME;       break;
                case EXC_DV_MODE_TEXTLEN:   eValMode = SC_VALID_TEXTLEN;    break;
                case EXC_DV_MODE_CUSTOM:    eValMode = SC_VALID_CUSTOM;     break;
                default:                    bIsValid = false;
            }
            rRoot.GetTracer().TraceDVType(eValMode == SC_VALID_CUSTOM);

            ScConditionMode eCondMode = SC_COND_BETWEEN;
            switch( nFlags & EXC_DV_COND_MASK )
            {
                case EXC_DV_COND_BETWEEN:   eCondMode = SC_COND_BETWEEN;    break;
                case EXC_DV_COND_NOTBETWEEN:eCondMode = SC_COND_NOTBETWEEN; break;
                case EXC_DV_COND_EQUAL:     eCondMode = SC_COND_EQUAL;      break;
                case EXC_DV_COND_NOTEQUAL:  eCondMode = SC_COND_NOTEQUAL;   break;
                case EXC_DV_COND_GREATER:   eCondMode = SC_COND_GREATER;    break;
                case EXC_DV_COND_LESS:      eCondMode = SC_COND_LESS;       break;
                case EXC_DV_COND_EQGREATER: eCondMode = SC_COND_EQGREATER;  break;
                case EXC_DV_COND_EQLESS:    eCondMode = SC_COND_EQLESS;     break;
                default:                    bIsValid = false;
            }

            if( bIsValid )
            {
                // first range for base address for relative references
                const ScRange& rScRange = *aScRanges.GetObject( 0 );    // aScRanges is not empty

                // process string list of a list validity (convert to list of string tokens)
                if( xTokArr1.get() && (eValMode == SC_VALID_LIST) && ::get_flag( nFlags, EXC_DV_STRINGLIST ) )
                    XclTokenArrayHelper::ConvertStringToList( *xTokArr1, '\n', true );

                ScValidationData aValidData( eValMode, eCondMode, xTokArr1.get(), xTokArr2.get(), &rDoc, rScRange.aStart );

                aValidData.SetIgnoreBlank( ::get_flag( nFlags, EXC_DV_IGNOREBLANK ) );
                aValidData.SetListType( ::get_flagvalue( nFlags, EXC_DV_SUPPRESSDROPDOWN, ValidListType::INVISIBLE, ValidListType::UNSORTED ) );

                // *** prompt box ***
                if( aPromptTitle.Len() || aPromptMessage.Len() )
                {
                    // set any text stored in the record
                    aValidData.SetInput( aPromptTitle, aPromptMessage );
                    if( !::get_flag( nFlags, EXC_DV_SHOWPROMPT ) )
                        aValidData.ResetInput();
                }

                // *** error box ***
                ScValidErrorStyle eErrStyle = SC_VALERR_STOP;
                switch( nFlags & EXC_DV_ERROR_MASK )
                {
                    case EXC_DV_ERROR_WARNING:  eErrStyle = SC_VALERR_WARNING;  break;
                    case EXC_DV_ERROR_INFO:     eErrStyle = SC_VALERR_INFO;     break;
                }
                // set texts and error style
                aValidData.SetError( aErrorTitle, aErrorMessage, eErrStyle );
                if( !::get_flag( nFlags, EXC_DV_SHOWERROR ) )
                    aValidData.ResetError();

                // set the handle ID
                ULONG nHandle = rDoc.AddValidationEntry( aValidData );
                ScPatternAttr aPattern( rDoc.GetPool() );
                aPattern.GetItemSet().Put( SfxUInt32Item( ATTR_VALIDDATA, nHandle ) );

                // apply all ranges
                for( const ScRange* pScRange = aScRanges.First(); pScRange; pScRange = aScRanges.Next() )
                    rDoc.ApplyPatternAreaTab( pScRange->aStart.Col(), pScRange->aStart.Row(),
                        pScRange->aEnd.Col(), pScRange->aEnd.Row(), nScTab, aPattern );
            }
        }
    }
}

// Web queries ================================================================

XclImpWebQuery::XclImpWebQuery( const ScRange& rDestRange ) :
    maDestRange( rDestRange ),
    meMode( xlWQUnknown ),
    mnRefresh( 0 )
{
}

void XclImpWebQuery::ReadParamqry( XclImpStream& rStrm )
{
    sal_uInt16 nFlags = rStrm.ReaduInt16();
    sal_uInt16 nType = ::extract_value< sal_uInt16 >( nFlags, 0, 3 );
    if( (nType == EXC_PQRYTYPE_WEBQUERY) && ::get_flag( nFlags, EXC_PQRY_WEBQUERY ) )
    {
        if( ::get_flag( nFlags, EXC_PQRY_TABLES ) )
        {
            meMode = xlWQAllTables;
            maTables = ScfTools::GetHTMLTablesName();
        }
        else
        {
            meMode = xlWQDocument;
            maTables = ScfTools::GetHTMLDocName();
        }
    }
}

void XclImpWebQuery::ReadWqstring( XclImpStream& rStrm )
{
    maURL = rStrm.ReadUniString();
}

void XclImpWebQuery::ReadWqsettings( XclImpStream& rStrm )
{
    sal_uInt16 nFlags;
    rStrm.Ignore( 10 );
    rStrm >> nFlags;
    rStrm.Ignore( 10 );
    rStrm >> mnRefresh;

    if( ::get_flag( nFlags, EXC_WQSETT_SPECTABLES ) && (meMode == xlWQAllTables) )
        meMode = xlWQSpecTables;
}

void XclImpWebQuery::ReadWqtables( XclImpStream& rStrm )
{
    if( meMode == xlWQSpecTables )
    {
        rStrm.Ignore( 4 );
        String aTables( rStrm.ReadUniString() );

        const sal_Unicode cSep = ';';
        aTables.SearchAndReplaceAll( ',', cSep );
        String aQuotedPairs( RTL_CONSTASCII_USTRINGPARAM( "\"\"" ) );
        xub_StrLen nTokenCnt = aTables.GetQuotedTokenCount( aQuotedPairs, cSep );
        maTables.Erase();
        xub_StrLen nStringIx = 0;
        for( xub_StrLen nToken = 0; nToken < nTokenCnt; ++nToken )
        {
            String aToken( aTables.GetQuotedToken( 0, aQuotedPairs, cSep, nStringIx ) );
            sal_Int32 nTabNum = CharClass::isAsciiNumeric( aToken ) ? aToken.ToInt32() : 0;
            if( nTabNum > 0 )
                ScGlobal::AddToken( maTables, ScfTools::GetNameFromHTMLIndex( static_cast< sal_uInt32 >( nTabNum ) ), cSep );
            else
            {
                ScGlobal::EraseQuotes( aToken, '"', false );
                if( aToken.Len() )
                    ScGlobal::AddToken( maTables, ScfTools::GetNameFromHTMLName( aToken ), cSep );
            }
        }
    }
}

void XclImpWebQuery::Apply( ScDocument& rDoc, const String& rFilterName )
{
    if( maURL.Len() && (meMode != xlWQUnknown) && rDoc.GetDocumentShell() )
    {
        ScAreaLink* pLink = new ScAreaLink( rDoc.GetDocumentShell(),
            maURL, rFilterName, EMPTY_STRING, maTables, maDestRange, mnRefresh * 60UL );
        rDoc.GetLinkManager()->InsertFileLink( *pLink, OBJECT_CLIENT_FILE,
            maURL, &rFilterName, &maTables );
    }
}

// ----------------------------------------------------------------------------

XclImpWebQueryBuffer::XclImpWebQueryBuffer( const XclImpRoot& rRoot ) :
    XclImpRoot( rRoot )
{
}

void XclImpWebQueryBuffer::ReadQsi( XclImpStream& rStrm )
{
    if( GetBiff() == EXC_BIFF8 )
    {
        rStrm.Ignore( 10 );
        String aXclName( rStrm.ReadUniString() );

        // #i64794# Excel replaces spaces with underscores
        aXclName.SearchAndReplaceAll( ' ', '_' );

        // #101529# find the defined name used in Calc
        if( const XclImpName* pName = GetNameManager().FindName( aXclName, GetCurrScTab() ) )
        {
            if( const ScRangeData* pRangeData = pName->GetScRangeData() )
            {
                ScRange aRange;
                if( pRangeData->IsReference( aRange ) )
                    maWQList.Append( new XclImpWebQuery( aRange ) );
            }
        }
    }
    else
    {
        DBG_ERROR_BIFF();
    }
}

void XclImpWebQueryBuffer::ReadParamqry( XclImpStream& rStrm )
{
    if( XclImpWebQuery* pQuery = maWQList.Last() )
        pQuery->ReadParamqry( rStrm );
}

void XclImpWebQueryBuffer::ReadWqstring( XclImpStream& rStrm )
{
    if( XclImpWebQuery* pQuery = maWQList.Last() )
        pQuery->ReadWqstring( rStrm );
}

void XclImpWebQueryBuffer::ReadWqsettings( XclImpStream& rStrm )
{
    if( XclImpWebQuery* pQuery = maWQList.Last() )
        pQuery->ReadWqsettings( rStrm );
}

void XclImpWebQueryBuffer::ReadWqtables( XclImpStream& rStrm )
{
    if( XclImpWebQuery* pQuery = maWQList.Last() )
        pQuery->ReadWqtables( rStrm );
}

void XclImpWebQueryBuffer::Apply()
{
    ScDocument& rDoc = GetDoc();
    String aFilterName( RTL_CONSTASCII_USTRINGPARAM( EXC_WEBQRY_FILTER ) );
    for( XclImpWebQuery* pQuery = maWQList.First(); pQuery; pQuery = maWQList.Next() )
        pQuery->Apply( rDoc, aFilterName );
}

// Decryption =================================================================

namespace {

XclImpDecrypterRef lclReadFilepass5( XclImpStream& rStrm )
{
    XclImpDecrypterRef xDecr;
    DBG_ASSERT( rStrm.GetRecLeft() == 4, "lclReadFilepass5 - wrong record size" );
    if( rStrm.GetRecLeft() == 4 )
    {
        sal_uInt16 nKey, nHash;
        rStrm >> nKey >> nHash;
        xDecr.reset( new XclImpBiff5Decrypter( nKey, nHash ) );
    }
    return xDecr;
}

XclImpDecrypterRef lclReadFilepass8_Standard( XclImpStream& rStrm )
{
    XclImpDecrypterRef xDecr;
    DBG_ASSERT( rStrm.GetRecLeft() == 48, "lclReadFilepass8 - wrong record size" );
    if( rStrm.GetRecLeft() == 48 )
    {
        sal_uInt8 pnSalt[ 16 ];
        sal_uInt8 pnVerifier[ 16 ];
        sal_uInt8 pnVerifierHash[ 16 ];
        rStrm.Read( pnSalt, 16 );
        rStrm.Read( pnVerifier, 16 );
        rStrm.Read( pnVerifierHash, 16 );
        xDecr.reset( new XclImpBiff8Decrypter( pnSalt, pnVerifier, pnVerifierHash ) );
    }
    return xDecr;
}

XclImpDecrypterRef lclReadFilepass8_Strong( XclImpStream& /*rStrm*/ )
{
    // not supported
    return XclImpDecrypterRef();
}

XclImpDecrypterRef lclReadFilepass8( XclImpStream& rStrm )
{
    XclImpDecrypterRef xDecr;

    sal_uInt16 nMode;
    rStrm >> nMode;
    switch( nMode )
    {
        case EXC_FILEPASS_BIFF5:
            xDecr = lclReadFilepass5( rStrm );
        break;

        case EXC_FILEPASS_BIFF8:
        {
            rStrm.Ignore( 2 );
            sal_uInt16 nSubMode;
            rStrm >> nSubMode;
            switch( nSubMode )
            {
                case EXC_FILEPASS_BIFF8_STD:
                    xDecr = lclReadFilepass8_Standard( rStrm );
                break;
                case EXC_FILEPASS_BIFF8_STRONG:
                    xDecr = lclReadFilepass8_Strong( rStrm );
                break;
                default:
                    DBG_ERRORFILE( "lclReadFilepass8 - unknown BIFF8 encryption sub mode" );
            }
        }
        break;

        default:
            DBG_ERRORFILE( "lclReadFilepass8 - unknown encryption mode" );
    }

    return xDecr;
}

} // namespace

// ----------------------------------------------------------------------------

ErrCode XclImpDecryptHelper::ReadFilepass( XclImpStream& rStrm )
{
    XclImpDecrypterRef xDecr;
    rStrm.DisableDecryption();

    // read the FILEPASS record and create a new decrypter object
    switch( rStrm.GetRoot().GetBiff() )
    {
        case EXC_BIFF2:
        case EXC_BIFF3:
        case EXC_BIFF4:
        case EXC_BIFF5: xDecr = lclReadFilepass5( rStrm );  break;
        case EXC_BIFF8: xDecr = lclReadFilepass8( rStrm );  break;
        default:        DBG_ERROR_BIFF();
    };

    // set decrypter at import stream
    rStrm.SetDecrypter( xDecr );

    // request and verify a password (decrypter implements IDocPasswordVerifier)
    if( xDecr.is() )
        rStrm.GetRoot().RequestPassword( *xDecr );

    // return error code (success, wrong password, etc.)
    return xDecr.is() ? xDecr->GetError() : EXC_ENCR_ERROR_UNSUPP_CRYPT;
}

// Document protection ========================================================

XclImpDocProtectBuffer::XclImpDocProtectBuffer( const XclImpRoot& rRoot ) :
    XclImpRoot( rRoot ),
    mnPassHash(0x0000),
    mbDocProtect(false),
    mbWinProtect(false)
{
}

void XclImpDocProtectBuffer::ReadDocProtect( XclImpStream& rStrm )
{
    mbDocProtect = rStrm.ReaduInt16() ? true : false;
}

void XclImpDocProtectBuffer::ReadWinProtect( XclImpStream& rStrm )
{
    mbWinProtect = rStrm.ReaduInt16() ? true : false;
}

void XclImpDocProtectBuffer::ReadPasswordHash( XclImpStream& rStrm )
{
    rStrm.EnableDecryption();
    mnPassHash = rStrm.ReaduInt16();
}

void XclImpDocProtectBuffer::Apply() const
{
    if (!mbDocProtect && !mbWinProtect)
        // Excel requires either the structure or windows protection is set.
        // If neither is set then the document is not protected at all.
        return;

    auto_ptr<ScDocProtection> pProtect(new ScDocProtection);
    pProtect->setProtected(true);

#if ENABLE_SHEET_PROTECTION
    if (mnPassHash)
    {
        // 16-bit password pash.
        Sequence<sal_Int8> aPass(2);
        aPass[0] = (mnPassHash >> 8) & 0xFF;
        aPass[1] = mnPassHash & 0xFF;
        pProtect->setPasswordHash(aPass, PASSHASH_XL);
    }
#endif

    // document protection options
    pProtect->setOption(ScDocProtection::STRUCTURE, mbDocProtect);
    pProtect->setOption(ScDocProtection::WINDOWS,   mbWinProtect);

    GetDoc().SetDocProtection(pProtect.get());
}

// Sheet Protection ===========================================================

XclImpSheetProtectBuffer::Sheet::Sheet() :
    mbProtected(false),
    mnPasswordHash(0x0000),
    mnOptions(0x4400)
{
}

// ----------------------------------------------------------------------------

XclImpSheetProtectBuffer::Sheet::Sheet(const Sheet& r) :
    mbProtected(r.mbProtected),
    mnPasswordHash(r.mnPasswordHash),
    mnOptions(r.mnOptions)
{
}

XclImpSheetProtectBuffer::XclImpSheetProtectBuffer( const XclImpRoot& rRoot ) :
    XclImpRoot( rRoot )
{
}

void XclImpSheetProtectBuffer::ReadProtect( XclImpStream& rStrm, SCTAB nTab )
{
    if ( rStrm.ReaduInt16() )
    {
        Sheet* pSheet = GetSheetItem(nTab);
        if (pSheet)
            pSheet->mbProtected = true;
    }
}

void XclImpSheetProtectBuffer::ReadOptions( XclImpStream& rStrm, SCTAB nTab )
{
    rStrm.Ignore(19);
    sal_uInt16 nOptions;
    rStrm >> nOptions;

    Sheet* pSheet = GetSheetItem(nTab);
    if (pSheet)
        pSheet->mnOptions = nOptions;
}

void XclImpSheetProtectBuffer::ReadPasswordHash( XclImpStream& rStrm, SCTAB nTab )
{
    sal_uInt16 nHash;
    rStrm >> nHash;
    Sheet* pSheet = GetSheetItem(nTab);
    if (pSheet)
        pSheet->mnPasswordHash = nHash;
}

void XclImpSheetProtectBuffer::Apply() const
{
    for (ProtectedSheetMap::const_iterator itr = maProtectedSheets.begin(), itrEnd = maProtectedSheets.end();
         itr != itrEnd; ++itr)
    {
        if (!itr->second.mbProtected)
            // This sheet is (for whatever reason) not protected.
            continue;

        auto_ptr<ScTableProtection> pProtect(new ScTableProtection);
        pProtect->setProtected(true);

#if ENABLE_SHEET_PROTECTION
        // 16-bit hash password
        const sal_uInt16 nHash = itr->second.mnPasswordHash;
        if (nHash)
        {
            Sequence<sal_Int8> aPass(2);
            aPass[0] = (nHash >> 8) & 0xFF;
            aPass[1] = nHash & 0xFF;
            pProtect->setPasswordHash(aPass, PASSHASH_XL);
        }
#endif

        // sheet protection options
        const sal_uInt16 nOptions = itr->second.mnOptions;
        pProtect->setOption( ScTableProtection::OBJECTS,               (nOptions & 0x0001) );
        pProtect->setOption( ScTableProtection::SCENARIOS,             (nOptions & 0x0002) );
        pProtect->setOption( ScTableProtection::FORMAT_CELLS,          (nOptions & 0x0004) );
        pProtect->setOption( ScTableProtection::FORMAT_COLUMNS,        (nOptions & 0x0008) );
        pProtect->setOption( ScTableProtection::FORMAT_ROWS,           (nOptions & 0x0010) );
        pProtect->setOption( ScTableProtection::INSERT_COLUMNS,        (nOptions & 0x0020) );
        pProtect->setOption( ScTableProtection::INSERT_ROWS,           (nOptions & 0x0040) );
        pProtect->setOption( ScTableProtection::INSERT_HYPERLINKS,     (nOptions & 0x0080) );
        pProtect->setOption( ScTableProtection::DELETE_COLUMNS,        (nOptions & 0x0100) );
        pProtect->setOption( ScTableProtection::DELETE_ROWS,           (nOptions & 0x0200) );
        pProtect->setOption( ScTableProtection::SELECT_LOCKED_CELLS,   (nOptions & 0x0400) );
        pProtect->setOption( ScTableProtection::SORT,                  (nOptions & 0x0800) );
        pProtect->setOption( ScTableProtection::AUTOFILTER,            (nOptions & 0x1000) );
        pProtect->setOption( ScTableProtection::PIVOT_TABLES,          (nOptions & 0x2000) );
        pProtect->setOption( ScTableProtection::SELECT_UNLOCKED_CELLS, (nOptions & 0x4000) );

        // all done.  now commit.
        GetDoc().SetTabProtection(itr->first, pProtect.get());
    }
}

XclImpSheetProtectBuffer::Sheet* XclImpSheetProtectBuffer::GetSheetItem( SCTAB nTab )
{
    ProtectedSheetMap::iterator itr = maProtectedSheets.find(nTab);
    if (itr == maProtectedSheets.end())
    {
        // new sheet
        if ( !maProtectedSheets.insert( ProtectedSheetMap::value_type(nTab, Sheet()) ).second )
            return NULL;

        itr = maProtectedSheets.find(nTab);
    }

    return &itr->second;
}

// ============================================================================