summaryrefslogtreecommitdiff
path: root/sc/source/ui/docshell/docsh3.cxx
blob: 8424ef56617211b8fc5c4b37dc66ce7613cd04c5 (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
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <com/sun/star/document/XDocumentPropertiesSupplier.hpp>
#include <com/sun/star/document/XDocumentProperties.hpp>

#include "scitems.hxx"
#include "rangelst.hxx"
#include <editeng/flstitem.hxx>
#include <editeng/paperinf.hxx>
#include <editeng/sizeitem.hxx>
#include <rtl/strbuf.hxx>
#include <sfx2/viewfrm.hxx>
#include <sfx2/app.hxx>
#include <sfx2/docfile.hxx>
#include <sfx2/printer.hxx>
#include <svx/postattr.hxx>
#include <unotools/misccfg.hxx>
#include <vcl/virdev.hxx>
#include <vcl/msgbox.hxx>

#include "docsh.hxx"
#include "docshimp.hxx"
#include "scmod.hxx"
#include "tabvwsh.hxx"
#include "viewdata.hxx"
#include "docpool.hxx"
#include "stlpool.hxx"
#include "patattr.hxx"
#include "uiitems.hxx"
#include "hints.hxx"
#include "docoptio.hxx"
#include "viewopti.hxx"
#include "pntlock.hxx"
#include "chgtrack.hxx"
#include "docfunc.hxx"
#include "formulacell.hxx"
#include "chgviset.hxx"
#include "progress.hxx"
#include "redcom.hxx"
#include "sc.hrc"
#include "inputopt.hxx"
#include "drwlayer.hxx"
#include "inputhdl.hxx"
#include "conflictsdlg.hxx"
#include "globstr.hrc"
#include "markdata.hxx"
#include <boost/scoped_ptr.hpp>

//          Redraw - Benachrichtigungen

void ScDocShell::PostEditView( ScEditEngineDefaulter* pEditEngine, const ScAddress& rCursorPos )
{
//  Broadcast( ScEditViewHint( pEditEngine, rCursorPos ) );

        //  Test: nur aktive ViewShell

    ScTabViewShell* pViewSh = ScTabViewShell::GetActiveViewShell();
    if (pViewSh && pViewSh->GetViewData().GetDocShell() == this)
    {
        ScEditViewHint aHint( pEditEngine, rCursorPos );
        pViewSh->Notify( *this, aHint );
    }
}

void ScDocShell::PostDataChanged()
{
    Broadcast( SfxSimpleHint( FID_DATACHANGED ) );
    SfxGetpApp()->Broadcast(SfxSimpleHint( FID_ANYDATACHANGED ));      // Navigator
    aDocument.ClearFormulaContext();
    //! Navigator direkt benachrichtigen!
}

void ScDocShell::PostPaint( SCCOL nStartCol, SCROW nStartRow, SCTAB nStartTab,
                            SCCOL nEndCol, SCROW nEndRow, SCTAB nEndTab, sal_uInt16 nPart,
                            sal_uInt16 nExtFlags )
{
    ScRange aRange(nStartCol, nStartRow, nStartTab, nEndCol, nEndRow, nEndTab);
    PostPaint(aRange, nPart, nExtFlags);
}

void ScDocShell::PostPaint( const ScRangeList& rRanges, sal_uInt16 nPart, sal_uInt16 nExtFlags )
{
    ScRangeList aPaintRanges;
    for (size_t i = 0, n = rRanges.size(); i < n; ++i)
    {
        const ScRange& rRange = *rRanges[i];
        SCCOL nCol1 = rRange.aStart.Col(), nCol2 = rRange.aEnd.Col();
        SCROW nRow1 = rRange.aStart.Row(), nRow2 = rRange.aEnd.Row();
        SCTAB nTab1 = rRange.aStart.Tab(), nTab2 = rRange.aEnd.Tab();

        if (!ValidCol(nCol1)) nCol1 = MAXCOL;
        if (!ValidRow(nRow1)) nRow1 = MAXROW;
        if (!ValidCol(nCol2)) nCol2 = MAXCOL;
        if (!ValidRow(nRow2)) nRow2 = MAXROW;

        if ( pPaintLockData )
        {
            // #i54081# PAINT_EXTRAS still has to be broadcast because it changes the
            // current sheet if it's invalid. All other flags added to pPaintLockData.
            sal_uInt16 nLockPart = nPart & ~PAINT_EXTRAS;
            if ( nLockPart )
            {
                //! nExtFlags ???
                pPaintLockData->AddRange( ScRange( nCol1, nRow1, nTab1,
                                                   nCol2, nRow2, nTab2 ), nLockPart );
            }

            nPart &= PAINT_EXTRAS;  // for broadcasting
            if (!nPart)
                continue;
        }

        if (nExtFlags & SC_PF_LINES)            // Platz fuer Linien beruecksichtigen
        {
                                                //! Abfrage auf versteckte Spalten/Zeilen!
            if (nCol1>0) --nCol1;
            if (nCol2<MAXCOL) ++nCol2;
            if (nRow1>0) --nRow1;
            if (nRow2<MAXROW) ++nRow2;
        }

                                                // um zusammengefasste erweitern
        if (nExtFlags & SC_PF_TESTMERGE)
            aDocument.ExtendMerge( nCol1, nRow1, nCol2, nRow2, nTab1 );

        if ( nCol1 != 0 || nCol2 != MAXCOL )
        {
            //  Extend to whole rows if SC_PF_WHOLEROWS is set, or rotated or non-left
            //  aligned cells are contained (see UpdatePaintExt).
            //  Special handling for RTL text (#i9731#) is unnecessary now with full
            //  support of right-aligned text.

            if ( ( nExtFlags & SC_PF_WHOLEROWS ) ||
                 aDocument.HasAttrib( nCol1,nRow1,nTab1,
                                      MAXCOL,nRow2,nTab2, HASATTR_ROTATE | HASATTR_RIGHTORCENTER ) )
            {
                nCol1 = 0;
                nCol2 = MAXCOL;
            }
        }
        aPaintRanges.Append(ScRange(nCol1, nRow1, nTab1, nCol2, nRow2, nTab2));
    }

    Broadcast(ScPaintHint(aPaintRanges.Combine(), nPart));
}

void ScDocShell::PostPaintGridAll()
{
    PostPaint( 0,0,0, MAXCOL,MAXROW,MAXTAB, PAINT_GRID );
}

void ScDocShell::PostPaintCell( SCCOL nCol, SCROW nRow, SCTAB nTab )
{
    PostPaint( nCol,nRow,nTab, nCol,nRow,nTab, PAINT_GRID, SC_PF_TESTMERGE );
}

void ScDocShell::PostPaintCell( const ScAddress& rPos )
{
    PostPaintCell( rPos.Col(), rPos.Row(), rPos.Tab() );
}

void ScDocShell::PostPaintExtras()
{
    PostPaint( 0,0,0, MAXCOL,MAXROW,MAXTAB, PAINT_EXTRAS );
}

void ScDocShell::UpdatePaintExt( sal_uInt16& rExtFlags, const ScRange& rRange )
{
    if ( ( rExtFlags & SC_PF_LINES ) == 0 && aDocument.HasAttrib( rRange, HASATTR_PAINTEXT ) )
    {
        //  If the range contains lines, shadow or conditional formats,
        //  set SC_PF_LINES to include one extra cell in all directions.

        rExtFlags |= SC_PF_LINES;
    }

    if ( ( rExtFlags & SC_PF_WHOLEROWS ) == 0 &&
         ( rRange.aStart.Col() != 0 || rRange.aEnd.Col() != MAXCOL ) &&
         aDocument.HasAttrib( rRange, HASATTR_ROTATE | HASATTR_RIGHTORCENTER ) )
    {
        //  If the range contains (logically) right- or center-aligned cells,
        //  or rotated cells, set SC_PF_WHOLEROWS to paint the whole rows.
        //  This test isn't needed after the cell changes, because it's also
        //  tested in PostPaint. UpdatePaintExt may later be changed to do this
        //  only if called before the changes.

        rExtFlags |= SC_PF_WHOLEROWS;
    }
}

void ScDocShell::UpdatePaintExt( sal_uInt16& rExtFlags, SCCOL nStartCol, SCROW nStartRow, SCTAB nStartTab,
                                                   SCCOL nEndCol, SCROW nEndRow, SCTAB nEndTab )
{
    UpdatePaintExt( rExtFlags, ScRange( nStartCol, nStartRow, nStartTab, nEndCol, nEndRow, nEndTab ) );
}

void ScDocShell::LockPaint_Impl(bool bDoc)
{
    if ( !pPaintLockData )
        pPaintLockData = new ScPaintLockData;
    pPaintLockData->IncLevel(bDoc);
}

void ScDocShell::UnlockPaint_Impl(bool bDoc)
{
    if ( pPaintLockData )
    {
        if ( pPaintLockData->GetLevel(bDoc) )
            pPaintLockData->DecLevel(bDoc);
        if (!pPaintLockData->GetLevel(!bDoc) && !pPaintLockData->GetLevel(bDoc))
        {
            //      Paint jetzt ausfuehren

            ScPaintLockData* pPaint = pPaintLockData;
            pPaintLockData = NULL;                      // nicht weitersammeln

            ScRangeListRef xRangeList = pPaint->GetRangeList();
            if (xRangeList)
            {
                sal_uInt16 nParts = pPaint->GetParts();
                for ( size_t i = 0, nCount = xRangeList->size(); i < nCount; i++ )
                {
                    //! nExtFlags ???
                    ScRange aRange = *(*xRangeList)[i];
                    PostPaint( aRange.aStart.Col(), aRange.aStart.Row(), aRange.aStart.Tab(),
                                aRange.aEnd.Col(), aRange.aEnd.Row(), aRange.aEnd.Tab(),
                                nParts );
                }
            }

            if ( pPaint->GetModified() )
                SetDocumentModified();

            delete pPaint;
        }
    }
    else
    {
        OSL_FAIL("UnlockPaint ohne LockPaint");
    }
}

void ScDocShell::LockDocument_Impl(sal_uInt16 nNew)
{
    if (!nDocumentLock)
    {
        ScDrawLayer* pDrawLayer = aDocument.GetDrawLayer();
        if (pDrawLayer)
            pDrawLayer->setLock(true);
    }
    nDocumentLock = nNew;
}

void ScDocShell::UnlockDocument_Impl(sal_uInt16 nNew)
{
    nDocumentLock = nNew;
    if (!nDocumentLock)
    {
        ScDrawLayer* pDrawLayer = aDocument.GetDrawLayer();
        if (pDrawLayer)
            pDrawLayer->setLock(false);
    }
}

void ScDocShell::SetLockCount(sal_uInt16 nNew)
{
    if (nNew)                   // setzen
    {
        if ( !pPaintLockData )
            pPaintLockData = new ScPaintLockData;
        pPaintLockData->SetLevel(nNew-1, true);
        LockDocument_Impl(nNew);
    }
    else if (pPaintLockData)    // loeschen
    {
        pPaintLockData->SetLevel(0, true);  // bei Unlock sofort ausfuehren
        UnlockPaint_Impl(true);                 // jetzt
        UnlockDocument_Impl(0);
    }
}

void ScDocShell::LockPaint()
{
    LockPaint_Impl(false);
}

void ScDocShell::UnlockPaint()
{
    UnlockPaint_Impl(false);
}

void ScDocShell::LockDocument()
{
    LockPaint_Impl(true);
    LockDocument_Impl(nDocumentLock + 1);
}

void ScDocShell::UnlockDocument()
{
    if (nDocumentLock)
    {
        UnlockPaint_Impl(true);
        UnlockDocument_Impl(nDocumentLock - 1);
    }
    else
    {
        OSL_FAIL("UnlockDocument without LockDocument");
    }
}

void ScDocShell::SetInplace( bool bInplace )
{
    if (bIsInplace != bInplace)
    {
        bIsInplace = bInplace;
        CalcOutputFactor();
    }
}

void ScDocShell::CalcOutputFactor()
{
    if (bIsInplace)
    {
        nPrtToScreenFactor = 1.0;           // passt sonst nicht zur inaktiven Darstellung
        return;
    }

    bool bTextWysiwyg = SC_MOD()->GetInputOptions().GetTextWysiwyg();
    if (bTextWysiwyg)
    {
        nPrtToScreenFactor = 1.0;
        return;
    }

    OUString aTestString(
            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890123456789");
    long nPrinterWidth = 0;
    long nWindowWidth = 0;
    const ScPatternAttr* pPattern = (const ScPatternAttr*)&aDocument.GetPool()->
                                            GetDefaultItem(ATTR_PATTERN);

    Font aDefFont;
    OutputDevice* pRefDev = GetRefDevice();
    MapMode aOldMode = pRefDev->GetMapMode();
    Font    aOldFont = pRefDev->GetFont();

    pRefDev->SetMapMode(MAP_PIXEL);
    pPattern->GetFont(aDefFont, SC_AUTOCOL_BLACK, pRefDev); // font color doesn't matter here
    pRefDev->SetFont(aDefFont);
    nPrinterWidth = pRefDev->PixelToLogic( Size( pRefDev->GetTextWidth(aTestString), 0 ), MAP_100TH_MM ).Width();
    pRefDev->SetFont(aOldFont);
    pRefDev->SetMapMode(aOldMode);

    VirtualDevice aVirtWindow( *Application::GetDefaultDevice() );
    aVirtWindow.SetMapMode(MAP_PIXEL);
    pPattern->GetFont(aDefFont, SC_AUTOCOL_BLACK, &aVirtWindow);    // font color doesn't matter here
    aVirtWindow.SetFont(aDefFont);
    nWindowWidth = aVirtWindow.GetTextWidth(aTestString);
    nWindowWidth = (long) ( nWindowWidth / ScGlobal::nScreenPPTX * HMM_PER_TWIPS );

    if (nPrinterWidth && nWindowWidth)
        nPrtToScreenFactor = nPrinterWidth / (double) nWindowWidth;
    else
    {
        OSL_FAIL("GetTextSize gibt 0 ??");
        nPrtToScreenFactor = 1.0;
    }
}

void ScDocShell::InitOptions(bool bForLoading)      // called from InitNew and Load
{
    //  Einstellungen aus dem SpellCheckCfg kommen in Doc- und ViewOptions

    sal_uInt16 nDefLang, nCjkLang, nCtlLang;
    bool bAutoSpell;
    ScModule::GetSpellSettings( nDefLang, nCjkLang, nCtlLang, bAutoSpell );
    ScModule* pScMod = SC_MOD();

    ScDocOptions  aDocOpt  = pScMod->GetDocOptions();
    ScFormulaOptions aFormulaOpt = pScMod->GetFormulaOptions();
    ScViewOptions aViewOpt = pScMod->GetViewOptions();
    aDocOpt.SetAutoSpell( bAutoSpell );

    // zweistellige Jahreszahleneingabe aus Extras->Optionen->Allgemein->Sonstiges
    aDocOpt.SetYear2000( sal::static_int_cast<sal_uInt16>( ::utl::MiscCfg().GetYear2000() ) );

    if (bForLoading)
    {
        // #i112123# No style:decimal-places attribute means automatic decimals, not the configured default,
        // so it must not be taken from the global options.
        // Calculation settings are handled separately in ScXMLBodyContext::EndElement.
        aDocOpt.SetStdPrecision( SvNumberFormatter::UNLIMITED_PRECISION );

        // fdo#78294 The default null-date if
        // <table:null-date table:date-value='...' />
        // is absent is 1899-12-30 regardless what the configuration is set to.
        // Import filters may override this value.
        aDocOpt.SetDate( 30, 12, 1899);
    }

    aDocument.SetDocOptions( aDocOpt );
    aDocument.SetViewOptions( aViewOpt );
    SetFormulaOptions( aFormulaOpt, bForLoading );

    //  Druck-Optionen werden jetzt direkt vor dem Drucken gesetzt

    aDocument.SetLanguage( (LanguageType) nDefLang, (LanguageType) nCjkLang, (LanguageType) nCtlLang );
}

Printer* ScDocShell::GetDocumentPrinter()       // fuer OLE
{
    return aDocument.GetPrinter();
}

SfxPrinter* ScDocShell::GetPrinter(bool bCreateIfNotExist)
{
    return aDocument.GetPrinter(bCreateIfNotExist);
}

void ScDocShell::UpdateFontList()
{
    delete pImpl->pFontList;
    // pImpl->pFontList = new FontList( GetPrinter(), Application::GetDefaultDevice() );
    pImpl->pFontList = new FontList( GetRefDevice(), NULL, false ); // sal_False or sal_True???
    SvxFontListItem aFontListItem( pImpl->pFontList, SID_ATTR_CHAR_FONTLIST );
    PutItem( aFontListItem );

    CalcOutputFactor();
}

OutputDevice* ScDocShell::GetRefDevice()
{
    return aDocument.GetRefDevice();
}

sal_uInt16 ScDocShell::SetPrinter( SfxPrinter* pNewPrinter, sal_uInt16 nDiffFlags )
{
    SfxPrinter *pOld = aDocument.GetPrinter( false );
    if ( pOld && pOld->IsPrinting() )
        return SFX_PRINTERROR_BUSY;

    if (nDiffFlags & SFX_PRINTER_PRINTER)
    {
        if ( aDocument.GetPrinter() != pNewPrinter )
        {
            aDocument.SetPrinter( pNewPrinter );
            aDocument.SetPrintOptions();

            // MT: Use UpdateFontList: Will use Printer fonts only if needed!
            /*
            delete pImpl->pFontList;
            pImpl->pFontList = new FontList( pNewPrinter, Application::GetDefaultDevice() );
            SvxFontListItem aFontListItem( pImpl->pFontList, SID_ATTR_CHAR_FONTLIST );
            PutItem( aFontListItem );

            CalcOutputFactor();
            */
            if ( SC_MOD()->GetInputOptions().GetTextWysiwyg() )
                UpdateFontList();

            ScModule* pScMod = SC_MOD();
            SfxViewFrame *pFrame = SfxViewFrame::GetFirst( this );
            while (pFrame)
            {
                SfxViewShell* pSh = pFrame->GetViewShell();
                if (pSh && pSh->ISA(ScTabViewShell))
                {
                    ScTabViewShell* pViewSh = (ScTabViewShell*)pSh;
                    ScInputHandler* pInputHdl = pScMod->GetInputHdl(pViewSh);
                    if (pInputHdl)
                        pInputHdl->UpdateRefDevice();
                }
                pFrame = SfxViewFrame::GetNext( *pFrame, this );
            }
        }
    }
    else if (nDiffFlags & SFX_PRINTER_JOBSETUP)
    {
        SfxPrinter* pOldPrinter = aDocument.GetPrinter();
        if (pOldPrinter)
        {
            pOldPrinter->SetJobSetup( pNewPrinter->GetJobSetup() );

            //  #i6706# Call SetPrinter with the old printer again, so the drawing layer
            //  RefDevice is set (calling ReformatAllTextObjects and rebuilding charts),
            //  because the JobSetup (printer device settings) may affect text layout.
            aDocument.SetPrinter( pOldPrinter );
            CalcOutputFactor();                         // also with the new settings
        }
    }

    if (nDiffFlags & SFX_PRINTER_OPTIONS)
    {
        aDocument.SetPrintOptions();        //! aus neuem Printer ???
    }

    if (nDiffFlags & (SFX_PRINTER_CHG_ORIENTATION | SFX_PRINTER_CHG_SIZE))
    {
        OUString aStyle = aDocument.GetPageStyle( GetCurTab() );
        ScStyleSheetPool* pStPl = aDocument.GetStyleSheetPool();
        SfxStyleSheet* pStyleSheet = (SfxStyleSheet*)pStPl->Find(aStyle, SFX_STYLE_FAMILY_PAGE);
        if (pStyleSheet)
        {
            SfxItemSet& rSet = pStyleSheet->GetItemSet();

            if (nDiffFlags & SFX_PRINTER_CHG_ORIENTATION)
            {
                const SvxPageItem& rOldItem = (const SvxPageItem&)rSet.Get(ATTR_PAGE);
                bool bWasLand = rOldItem.IsLandscape();
                bool bNewLand = ( pNewPrinter->GetOrientation() == ORIENTATION_LANDSCAPE );
                if (bNewLand != bWasLand)
                {
                    SvxPageItem aNewItem( rOldItem );
                    aNewItem.SetLandscape( bNewLand );
                    rSet.Put( aNewItem );

                    //  Groesse umdrehen
                    Size aOldSize = ((const SvxSizeItem&)rSet.Get(ATTR_PAGE_SIZE)).GetSize();
                    Size aNewSize(aOldSize.Height(),aOldSize.Width());
                    SvxSizeItem aNewSItem(ATTR_PAGE_SIZE,aNewSize);
                    rSet.Put( aNewSItem );
                }
            }
            if (nDiffFlags & SFX_PRINTER_CHG_SIZE)
            {
                SvxSizeItem aPaperSizeItem( ATTR_PAGE_SIZE, SvxPaperInfo::GetPaperSize(pNewPrinter) );
                rSet.Put( aPaperSizeItem );
            }
        }
    }

    PostPaint(0,0,0,MAXCOL,MAXROW,MAXTAB,PAINT_ALL);

    return 0;
}

ScChangeAction* ScDocShell::GetChangeAction( const ScAddress& rPos )
{
    ScChangeTrack* pTrack = GetDocument().GetChangeTrack();
    if (!pTrack)
        return NULL;

    SCTAB nTab = rPos.Tab();

    const ScChangeAction* pFound = NULL;
    long nModified = 0;
    const ScChangeAction* pAction = pTrack->GetFirst();
    while (pAction)
    {
        ScChangeActionType eType = pAction->GetType();
        //! ScViewUtil::IsActionShown( *pAction, *pSettings, *pDoc )...
        if ( pAction->IsVisible() && eType != SC_CAT_DELETE_TABS )
        {
            const ScBigRange& rBig = pAction->GetBigRange();
            if ( rBig.aStart.Tab() == nTab )
            {
                ScRange aRange = rBig.MakeRange();

                if ( eType == SC_CAT_DELETE_ROWS )
                    aRange.aEnd.SetRow( aRange.aStart.Row() );
                else if ( eType == SC_CAT_DELETE_COLS )
                    aRange.aEnd.SetCol( aRange.aStart.Col() );

                if ( aRange.In( rPos ) )
                {
                    pFound = pAction;       // der letzte gewinnt
                    ++nModified;
                }
            }
            if ( pAction->GetType() == SC_CAT_MOVE )
            {
                ScRange aRange =
                    ((const ScChangeActionMove*)pAction)->
                    GetFromRange().MakeRange();
                if ( aRange.In( rPos ) )
                {
                    pFound = pAction;
                    ++nModified;
                }
            }
        }
        pAction = pAction->GetNext();
    }

    return (ScChangeAction*)pFound;
}

void ScDocShell::SetChangeComment( ScChangeAction* pAction, const OUString& rComment )
{
    if (pAction)
    {
        pAction->SetComment( rComment );
        //! Undo ???
        SetDocumentModified();

        //  Dialog-Notify
        ScChangeTrack* pTrack = GetDocument().GetChangeTrack();
        if (pTrack)
        {
            sal_uLong nNumber = pAction->GetActionNumber();
            pTrack->NotifyModified( SC_CTM_CHANGE, nNumber, nNumber );
        }
    }
}

void ScDocShell::ExecuteChangeCommentDialog( ScChangeAction* pAction, Window* pParent, bool bPrevNext)
{
    if (!pAction) return;           // ohne Aktion ist nichts..

    OUString aComment = pAction->GetComment();
    OUString aAuthor = pAction->GetUser();

    DateTime aDT = pAction->GetDateTime();
    OUString aDate = ScGlobal::pLocaleData->getDate( aDT );
    aDate += " ";
    aDate += ScGlobal::pLocaleData->getTime( aDT, false, false );

    SfxItemSet aSet( GetPool(),
                      SID_ATTR_POSTIT_AUTHOR, SID_ATTR_POSTIT_AUTHOR,
                      SID_ATTR_POSTIT_DATE,   SID_ATTR_POSTIT_DATE,
                      SID_ATTR_POSTIT_TEXT,   SID_ATTR_POSTIT_TEXT,
                      0 );

    aSet.Put( SvxPostItTextItem  ( aComment, SID_ATTR_POSTIT_TEXT ) );
    aSet.Put( SvxPostItAuthorItem( aAuthor,  SID_ATTR_POSTIT_AUTHOR ) );
    aSet.Put( SvxPostItDateItem  ( aDate,    SID_ATTR_POSTIT_DATE ) );

    boost::scoped_ptr<ScRedComDialog> pDlg(new ScRedComDialog( pParent, aSet,this,pAction,bPrevNext));

    pDlg->Execute();
}

void ScDocShell::CompareDocument( ScDocument& rOtherDoc )
{
    ScChangeTrack* pTrack = aDocument.GetChangeTrack();
    if ( pTrack && pTrack->GetFirst() )
    {
        //! Changes vorhanden -> Nachfrage ob geloescht werden soll
    }

    aDocument.EndChangeTracking();
    aDocument.StartChangeTracking();

    OUString aOldUser;
    pTrack = aDocument.GetChangeTrack();
    if ( pTrack )
    {
        aOldUser = pTrack->GetUser();

        //  check if comparing to same document

        OUString aThisFile;
        const SfxMedium* pThisMed = GetMedium();
        if (pThisMed)
            aThisFile = pThisMed->GetName();
        OUString aOtherFile;
        SfxObjectShell* pOtherSh = rOtherDoc.GetDocumentShell();
        if (pOtherSh)
        {
            const SfxMedium* pOtherMed = pOtherSh->GetMedium();
            if (pOtherMed)
                aOtherFile = pOtherMed->GetName();
        }
        bool bSameDoc = ( aThisFile == aOtherFile && !aThisFile.isEmpty() );
        if ( !bSameDoc )
        {
            //  create change actions from comparing with the name of the user
            //  who last saved the document
            //  (only if comparing different documents)

            using namespace ::com::sun::star;
            uno::Reference<document::XDocumentPropertiesSupplier> xDPS(
                GetModel(), uno::UNO_QUERY_THROW);
            uno::Reference<document::XDocumentProperties> xDocProps(
                xDPS->getDocumentProperties());
            OSL_ENSURE(xDocProps.is(), "no DocumentProperties");
            OUString aDocUser = xDocProps->getModifiedBy();

            if ( !aDocUser.isEmpty() )
                pTrack->SetUser( aDocUser );
        }
    }

    aDocument.CompareDocument( rOtherDoc );

    pTrack = aDocument.GetChangeTrack();
    if ( pTrack )
        pTrack->SetUser( aOldUser );

    PostPaintGridAll();
    SetDocumentModified();
}

//              Merge (Aenderungen zusammenfuehren)

static inline bool lcl_Equal( const ScChangeAction* pA, const ScChangeAction* pB, bool bIgnore100Sec )
{
    return pA && pB &&
        pA->GetActionNumber() == pB->GetActionNumber() &&
        pA->GetType()         == pB->GetType() &&
        pA->GetUser()         == pB->GetUser() &&
        (bIgnore100Sec ?
         pA->GetDateTimeUTC().IsEqualIgnoreNanoSec( pB->GetDateTimeUTC() ) :
         pA->GetDateTimeUTC() == pB->GetDateTimeUTC());
    //  State nicht vergleichen, falls eine alte Aenderung akzeptiert wurde
}

static bool lcl_FindAction( ScDocument* pDoc, const ScChangeAction* pAction, ScDocument* pSearchDoc, const ScChangeAction* pFirstSearchAction, const ScChangeAction* pLastSearchAction, bool bIgnore100Sec )
{
    if ( !pDoc || !pAction || !pSearchDoc || !pFirstSearchAction || !pLastSearchAction )
    {
        return false;
    }

    sal_uLong nLastSearchAction = pLastSearchAction->GetActionNumber();
    const ScChangeAction* pA = pFirstSearchAction;
    while ( pA && pA->GetActionNumber() <= nLastSearchAction )
    {
        if ( pAction->GetType() == pA->GetType() &&
             pAction->GetUser() == pA->GetUser() &&
             (bIgnore100Sec ?
                pAction->GetDateTimeUTC().IsEqualIgnoreNanoSec( pA->GetDateTimeUTC() ) :
                pAction->GetDateTimeUTC() == pA->GetDateTimeUTC() ) &&
             pAction->GetBigRange() == pA->GetBigRange() )
        {
            OUString aActionDesc;
            pAction->GetDescription(aActionDesc, pDoc, true);
            OUString aADesc;
            pA->GetDescription(aADesc, pSearchDoc, true);
            if (aActionDesc.equals(aADesc))
            {
                OSL_FAIL( "lcl_FindAction(): found equal action!" );
                return true;
            }
        }
        pA = pA->GetNext();
    }

    return false;
}

void ScDocShell::MergeDocument( ScDocument& rOtherDoc, bool bShared, bool bCheckDuplicates, sal_uLong nOffset, ScChangeActionMergeMap* pMergeMap, bool bInverseMap )
{
    ScTabViewShell* pViewSh = GetBestViewShell( false );    //! Funktionen an die DocShell
    if (!pViewSh)
        return;

    ScChangeTrack* pSourceTrack = rOtherDoc.GetChangeTrack();
    if (!pSourceTrack)
        return;             //! nichts zu tun - Fehlermeldung?

    ScChangeTrack* pThisTrack = aDocument.GetChangeTrack();
    if ( !pThisTrack )
    {   // anschalten
        aDocument.StartChangeTracking();
        pThisTrack = aDocument.GetChangeTrack();
        OSL_ENSURE(pThisTrack,"ChangeTracking nicht angeschaltet?");
        if ( !bShared )
        {
            // visuelles RedLining einschalten
            ScChangeViewSettings aChangeViewSet;
            aChangeViewSet.SetShowChanges(true);
            aDocument.SetChangeViewSettings(aChangeViewSet);
        }
    }

    // include Nano seconds in compare?
    bool bIgnore100Sec = !pSourceTrack->IsTimeNanoSeconds() ||
            !pThisTrack->IsTimeNanoSeconds();

    //  gemeinsame Ausgangsposition suchen
    sal_uLong nFirstNewNumber = 0;
    const ScChangeAction* pSourceAction = pSourceTrack->GetFirst();
    const ScChangeAction* pThisAction = pThisTrack->GetFirst();
    // skip identical actions
    while ( lcl_Equal( pSourceAction, pThisAction, bIgnore100Sec ) )
    {
        nFirstNewNumber = pSourceAction->GetActionNumber() + 1;
        pSourceAction = pSourceAction->GetNext();
        pThisAction = pThisAction->GetNext();
    }
    //  pSourceAction und pThisAction zeigen jetzt auf die ersten "eigenen" Aktionen
    //  Die gemeinsamen Aktionen davor interessieren ueberhaupt nicht

    //! Abfrage, ob die Dokumente vor dem Change-Tracking gleich waren !!!

    const ScChangeAction* pFirstMergeAction = pSourceAction;
    const ScChangeAction* pFirstSearchAction = pThisAction;

    // #i94841# [Collaboration] When deleting rows is rejected, the content is sometimes wrong
    const ScChangeAction* pLastSearchAction = pThisTrack->GetLast();

    //  MergeChangeData aus den folgenden Aktionen erzeugen
    sal_uLong nNewActionCount = 0;
    const ScChangeAction* pCount = pSourceAction;
    while ( pCount )
    {
        if ( bShared || !ScChangeTrack::MergeIgnore( *pCount, nFirstNewNumber ) )
            ++nNewActionCount;
        pCount = pCount->GetNext();
    }
    if (!nNewActionCount)
        return;             //! nichts zu tun - Fehlermeldung?
                            //  ab hier kein return mehr

    ScProgress aProgress( this, OUString("..."),
                    nNewActionCount );

    sal_uLong nLastMergeAction = pSourceTrack->GetLast()->GetActionNumber();
    // UpdateReference-Undo, gueltige Referenzen fuer den letzten gemeinsamen Zustand
    pSourceTrack->MergePrepare( (ScChangeAction*) pFirstMergeAction, bShared );

    //  MergeChangeData an alle noch folgenden Aktionen in diesem Dokument anpassen
    //  -> Referenzen gueltig fuer dieses Dokument
    while ( pThisAction )
    {
        // #i87049# [Collaboration] Conflict between delete row and insert content is not merged correctly
        if ( !bShared || !ScChangeTrack::MergeIgnore( *pThisAction, nFirstNewNumber ) )
        {
            ScChangeActionType eType = pThisAction->GetType();
            switch ( eType )
            {
                case SC_CAT_INSERT_COLS :
                case SC_CAT_INSERT_ROWS :
                case SC_CAT_INSERT_TABS :
                    pSourceTrack->AppendInsert( pThisAction->GetBigRange().MakeRange() );
                break;
                case SC_CAT_DELETE_COLS :
                case SC_CAT_DELETE_ROWS :
                case SC_CAT_DELETE_TABS :
                {
                    const ScChangeActionDel* pDel = (const ScChangeActionDel*) pThisAction;
                    if ( pDel->IsTopDelete() && !pDel->IsTabDeleteCol() )
                    {   // deleted Table enthaelt deleted Cols, die nicht
                        sal_uLong nStart, nEnd;
                        pSourceTrack->AppendDeleteRange(
                            pDel->GetOverAllRange().MakeRange(), NULL, nStart, nEnd );
                    }
                }
                break;
                case SC_CAT_MOVE :
                {
                    const ScChangeActionMove* pMove = (const ScChangeActionMove*) pThisAction;
                    pSourceTrack->AppendMove( pMove->GetFromRange().MakeRange(),
                        pMove->GetBigRange().MakeRange(), NULL );
                }
                break;
                default:
                {
                    // added to avoid warnings
                }
            }
        }
        pThisAction = pThisAction->GetNext();
    }

    LockPaint();    // #i73877# no repainting after each action

    //  MergeChangeData in das aktuelle Dokument uebernehmen
    bool bHasRejected = false;
    OUString aOldUser = pThisTrack->GetUser();
    pThisTrack->SetUseFixDateTime( true );
    ScMarkData& rMarkData = pViewSh->GetViewData().GetMarkData();
    ScMarkData aOldMarkData( rMarkData );
    pSourceAction = pFirstMergeAction;
    while ( pSourceAction && pSourceAction->GetActionNumber() <= nLastMergeAction )
    {
        bool bMergeAction = false;
        if ( bShared )
        {
            if ( !bCheckDuplicates || !lcl_FindAction( &rOtherDoc, pSourceAction, &aDocument, pFirstSearchAction, pLastSearchAction, bIgnore100Sec ) )
            {
                bMergeAction = true;
            }
        }
        else
        {
            if ( !ScChangeTrack::MergeIgnore( *pSourceAction, nFirstNewNumber ) )
            {
                bMergeAction = true;
            }
        }

        if ( bMergeAction )
        {
            ScChangeActionType eSourceType = pSourceAction->GetType();
            if ( !bShared && pSourceAction->IsDeletedIn() )
            {
                //! muss hier noch festgestellt werden, ob wirklich in
                //! _diesem_ Dokument geloescht?

                //  liegt in einem Bereich, der in diesem Dokument geloescht wurde
                //  -> wird weggelassen
                //! ??? Loesch-Aktion rueckgaengig machen ???
                //! ??? Aktion irgendwo anders speichern  ???
#if OSL_DEBUG_LEVEL > 0
                OUString aValue;
                if ( eSourceType == SC_CAT_CONTENT )
                    ((const ScChangeActionContent*)pSourceAction)->GetNewString( aValue, &aDocument );
                OStringBuffer aError(OUStringToOString(aValue,
                    osl_getThreadTextEncoding()));
                aError.append(" weggelassen");
                OSL_FAIL( aError.getStr() );
#endif
            }
            else
            {
                //! Datum/Autor/Kommentar der Source-Aktion uebernehmen!

                pThisTrack->SetUser( pSourceAction->GetUser() );
                pThisTrack->SetFixDateTimeUTC( pSourceAction->GetDateTimeUTC() );
                sal_uLong nOldActionMax = pThisTrack->GetActionMax();

                bool bExecute = true;
                sal_uLong nReject = pSourceAction->GetRejectAction();
                if ( nReject )
                {
                    if ( bShared )
                    {
                        if ( nReject >= nFirstNewNumber )
                        {
                            nReject += nOffset;
                        }
                        ScChangeAction* pOldAction = pThisTrack->GetAction( nReject );
                        if ( pOldAction && pOldAction->IsVirgin() )
                        {
                            pThisTrack->Reject( pOldAction );
                            bHasRejected = true;
                            bExecute = false;
                        }
                    }
                    else
                    {
                        //  alte Aktion (aus den gemeinsamen) ablehnen
                        ScChangeAction* pOldAction = pThisTrack->GetAction( nReject );
                        if (pOldAction && pOldAction->GetState() == SC_CAS_VIRGIN)
                        {
                            //! was passiert bei Aktionen, die in diesem Dokument accepted worden sind???
                            //! Fehlermeldung oder was???
                            //! oder Reject-Aenderung normal ausfuehren

                            pThisTrack->Reject(pOldAction);
                            bHasRejected = true;                // fuer Paint
                        }
                        bExecute = false;
                    }
                }

                if ( bExecute )
                {
                    //  normal ausfuehren
                    ScRange aSourceRange = pSourceAction->GetBigRange().MakeRange();
                    rMarkData.SelectOneTable( aSourceRange.aStart.Tab() );
                    switch ( eSourceType )
                    {
                        case SC_CAT_CONTENT:
                        {
                            //! Test, ob es ganz unten im Dokument war, dann automatisches
                            //! Zeilen-Einfuegen ???

                            OSL_ENSURE( aSourceRange.aStart == aSourceRange.aEnd, "huch?" );
                            ScAddress aPos = aSourceRange.aStart;
                            OUString aValue;
                            ((const ScChangeActionContent*)pSourceAction)->GetNewString( aValue, &aDocument );
                            sal_uInt8 eMatrix = MM_NONE;
                            const ScCellValue& rCell = ((const ScChangeActionContent*)pSourceAction)->GetNewCell();
                            if (rCell.meType == CELLTYPE_FORMULA)
                                eMatrix = rCell.mpFormula->GetMatrixFlag();
                            switch ( eMatrix )
                            {
                                case MM_NONE :
                                    pViewSh->EnterData( aPos.Col(), aPos.Row(), aPos.Tab(), aValue );
                                break;
                                case MM_FORMULA :
                                {
                                    SCCOL nCols;
                                    SCROW nRows;
                                    rCell.mpFormula->GetMatColsRows(nCols, nRows);
                                    aSourceRange.aEnd.SetCol( aPos.Col() + nCols - 1 );
                                    aSourceRange.aEnd.SetRow( aPos.Row() + nRows - 1 );
                                    aValue = aValue.copy(1, aValue.getLength()-2); // remove the 1st and last characters.
                                    GetDocFunc().EnterMatrix( aSourceRange,
                                        NULL, NULL, aValue, false, false,
                                        EMPTY_OUSTRING, formula::FormulaGrammar::GRAM_DEFAULT );
                                }
                                break;
                                case MM_REFERENCE :     // do nothing
                                break;
                                case MM_FAKE :
                                    OSL_FAIL( "MergeDocument: MatrixFlag MM_FAKE" );
                                    pViewSh->EnterData( aPos.Col(), aPos.Row(), aPos.Tab(), aValue );
                                break;
                                default:
                                    OSL_FAIL( "MergeDocument: unknown MatrixFlag" );
                            }
                        }
                        break;
                        case SC_CAT_INSERT_TABS :
                        {
                            OUString aName;
                            aDocument.CreateValidTabName( aName );
                            GetDocFunc().InsertTable( aSourceRange.aStart.Tab(), aName, true, false );
                        }
                        break;
                        case SC_CAT_INSERT_ROWS:
                            GetDocFunc().InsertCells( aSourceRange, NULL, INS_INSROWS, true, false );
                        break;
                        case SC_CAT_INSERT_COLS:
                            GetDocFunc().InsertCells( aSourceRange, NULL, INS_INSCOLS, true, false );
                        break;
                        case SC_CAT_DELETE_TABS :
                            GetDocFunc().DeleteTable( aSourceRange.aStart.Tab(), true, false );
                        break;
                        case SC_CAT_DELETE_ROWS:
                        {
                            const ScChangeActionDel* pDel = (const ScChangeActionDel*) pSourceAction;
                            if ( pDel->IsTopDelete() )
                            {
                                aSourceRange = pDel->GetOverAllRange().MakeRange();
                                GetDocFunc().DeleteCells( aSourceRange, NULL, DEL_DELROWS, true, false );

                                // #i101099# [Collaboration] Changes are not correctly shown
                                if ( bShared )
                                {
                                    ScChangeAction* pAct = pThisTrack->GetLast();
                                    if ( pAct && pAct->GetType() == eSourceType && pAct->IsDeletedIn() && !pSourceAction->IsDeletedIn() )
                                    {
                                        pAct->RemoveAllDeletedIn();
                                    }
                                }
                            }
                        }
                        break;
                        case SC_CAT_DELETE_COLS:
                        {
                            const ScChangeActionDel* pDel = (const ScChangeActionDel*) pSourceAction;
                            if ( pDel->IsTopDelete() && !pDel->IsTabDeleteCol() )
                            {   // deleted Table enthaelt deleted Cols, die nicht
                                aSourceRange = pDel->GetOverAllRange().MakeRange();
                                GetDocFunc().DeleteCells( aSourceRange, NULL, DEL_DELCOLS, true, false );
                            }
                        }
                        break;
                        case SC_CAT_MOVE :
                        {
                            const ScChangeActionMove* pMove = (const ScChangeActionMove*) pSourceAction;
                            ScRange aFromRange( pMove->GetFromRange().MakeRange() );
                            GetDocFunc().MoveBlock( aFromRange,
                                aSourceRange.aStart, true, true, false, false );
                        }
                        break;
                        default:
                        {
                            // added to avoid warnings
                        }
                    }
                }
                const OUString& rComment = pSourceAction->GetComment();
                if ( !rComment.isEmpty() )
                {
                    ScChangeAction* pAct = pThisTrack->GetLast();
                    if ( pAct && pAct->GetActionNumber() > nOldActionMax )
                        pAct->SetComment( rComment );
                    else
                        OSL_FAIL( "MergeDocument: wohin mit dem Kommentar?!?" );
                }

                // Referenzen anpassen
                pSourceTrack->MergeOwn( (ScChangeAction*) pSourceAction, nFirstNewNumber, bShared );

                // merge action state
                if ( bShared && !pSourceAction->IsRejected() )
                {
                    ScChangeAction* pAct = pThisTrack->GetLast();
                    if ( pAct && pAct->GetActionNumber() > nOldActionMax )
                    {
                        pThisTrack->MergeActionState( pAct, pSourceAction );
                    }
                }

                // fill merge map
                if ( bShared && pMergeMap )
                {
                    ScChangeAction* pAct = pThisTrack->GetLast();
                    if ( pAct && pAct->GetActionNumber() > nOldActionMax )
                    {
                        sal_uLong nActionMax = pAct->GetActionNumber();
                        sal_uLong nActionCount = nActionMax - nOldActionMax;
                        sal_uLong nAction = nActionMax - nActionCount + 1;
                        sal_uLong nSourceAction = pSourceAction->GetActionNumber() - nActionCount + 1;
                        while ( nAction <= nActionMax )
                        {
                            if ( bInverseMap )
                            {
                                (*pMergeMap)[ nAction++ ] = nSourceAction++;
                            }
                            else
                            {
                                (*pMergeMap)[ nSourceAction++ ] = nAction++;
                            }
                        }
                    }
                }
            }
            aProgress.SetStateCountDown( --nNewActionCount );
        }
        pSourceAction = pSourceAction->GetNext();
    }

    rMarkData = aOldMarkData;
    pThisTrack->SetUser(aOldUser);
    pThisTrack->SetUseFixDateTime( false );

    pSourceTrack->Clear();      //! der ist jetzt verhunzt

    if (bHasRejected)
        PostPaintGridAll();         // Reject() paintet nicht selber

    UnlockPaint();
}

bool ScDocShell::MergeSharedDocument( ScDocShell* pSharedDocShell )
{
    if ( !pSharedDocShell )
    {
        return false;
    }

    ScChangeTrack* pThisTrack = aDocument.GetChangeTrack();
    if ( !pThisTrack )
    {
        return false;
    }

    ScDocument& rSharedDoc = pSharedDocShell->GetDocument();
    ScChangeTrack* pSharedTrack = rSharedDoc.GetChangeTrack();
    if ( !pSharedTrack )
    {
        return false;
    }

    // reset show changes
    ScChangeViewSettings aChangeViewSet;
    aChangeViewSet.SetShowChanges( false );
    aDocument.SetChangeViewSettings( aChangeViewSet );

    // find first merge action in this document
    bool bIgnore100Sec = !pThisTrack->IsTimeNanoSeconds() || !pSharedTrack->IsTimeNanoSeconds();
    ScChangeAction* pThisAction = pThisTrack->GetFirst();
    ScChangeAction* pSharedAction = pSharedTrack->GetFirst();
    while ( lcl_Equal( pThisAction, pSharedAction, bIgnore100Sec ) )
    {
        pThisAction = pThisAction->GetNext();
        pSharedAction = pSharedAction->GetNext();
    }

    if ( pSharedAction )
    {
        if ( pThisAction )
        {
            // merge own changes into shared document
            sal_uLong nActStartShared = pSharedAction->GetActionNumber();
            sal_uLong nActEndShared = pSharedTrack->GetActionMax();
            ScDocument* pTmpDoc = new ScDocument;
            for ( sal_Int32 nIndex = 0; nIndex < aDocument.GetTableCount(); ++nIndex )
            {
                OUString sTabName;
                pTmpDoc->CreateValidTabName( sTabName );
                pTmpDoc->InsertTab( SC_TAB_APPEND, sTabName );
            }
            aDocument.GetChangeTrack()->Clone( pTmpDoc );
            ScChangeActionMergeMap aOwnInverseMergeMap;
            pSharedDocShell->MergeDocument( *pTmpDoc, true, true, 0, &aOwnInverseMergeMap, true );
            delete pTmpDoc;
            sal_uLong nActStartOwn = nActEndShared + 1;
            sal_uLong nActEndOwn = pSharedTrack->GetActionMax();

            // find conflicts
            ScConflictsList aConflictsList;
            ScConflictsFinder aFinder( pSharedTrack, nActStartShared, nActEndShared, nActStartOwn, nActEndOwn, aConflictsList );
            if ( aFinder.Find() )
            {
                ScConflictsListHelper::TransformConflictsList( aConflictsList, NULL, &aOwnInverseMergeMap );
                bool bLoop = true;
                while ( bLoop )
                {
                    bLoop = false;
                    ScConflictsDlg aDlg( GetActiveDialogParent(), GetViewData(), &rSharedDoc, aConflictsList );
                    if ( aDlg.Execute() == RET_CANCEL )
                    {
                        QueryBox aBox( GetActiveDialogParent(), WinBits( WB_YES_NO | WB_DEF_YES ),
                            ScGlobal::GetRscString( STR_DOC_WILLNOTBESAVED ) );
                        if ( aBox.Execute() == RET_YES )
                        {
                            return false;
                        }
                        else
                        {
                            bLoop = true;
                        }
                    }
                }
            }

            // undo own changes in shared document
            pSharedTrack->Undo( nActStartOwn, nActEndOwn );

            // clone change track for merging into own document
            pTmpDoc = new ScDocument;
            for ( sal_Int32 nIndex = 0; nIndex < aDocument.GetTableCount(); ++nIndex )
            {
                OUString sTabName;
                pTmpDoc->CreateValidTabName( sTabName );
                pTmpDoc->InsertTab( SC_TAB_APPEND, sTabName );
            }
            pThisTrack->Clone( pTmpDoc );

            // undo own changes since last save in own document
            sal_uLong nStartShared = pThisAction->GetActionNumber();
            ScChangeAction* pAction = pThisTrack->GetLast();
            while ( pAction && pAction->GetActionNumber() >= nStartShared )
            {
                pThisTrack->Reject( pAction, true );
                pAction = pAction->GetPrev();
            }

            // #i94841# [Collaboration] When deleting rows is rejected, the content is sometimes wrong
            pThisTrack->Undo( nStartShared, pThisTrack->GetActionMax(), true );

            // merge shared changes into own document
            ScChangeActionMergeMap aSharedMergeMap;
            MergeDocument( rSharedDoc, true, true, 0, &aSharedMergeMap );
            sal_uLong nEndShared = pThisTrack->GetActionMax();

            // resolve conflicts for shared non-content actions
            if ( !aConflictsList.empty() )
            {
                ScConflictsListHelper::TransformConflictsList( aConflictsList, &aSharedMergeMap, NULL );
                ScConflictsResolver aResolver( pThisTrack, aConflictsList );
                pAction = pThisTrack->GetAction( nEndShared );
                while ( pAction && pAction->GetActionNumber() >= nStartShared )
                {
                    aResolver.HandleAction( pAction, true /*bIsSharedAction*/,
                        false /*bHandleContentAction*/, true /*bHandleNonContentAction*/ );
                    pAction = pAction->GetPrev();
                }
            }
            nEndShared = pThisTrack->GetActionMax();

            // only show changes from shared document
            aChangeViewSet.SetShowChanges( true );
            aChangeViewSet.SetShowAccepted( true );
            aChangeViewSet.SetHasActionRange( true );
            aChangeViewSet.SetTheActionRange( nStartShared, nEndShared );
            aDocument.SetChangeViewSettings( aChangeViewSet );

            // merge own changes back into own document
            sal_uLong nStartOwn = nEndShared + 1;
            ScChangeActionMergeMap aOwnMergeMap;
            MergeDocument( *pTmpDoc, true, true, nEndShared - nStartShared + 1, &aOwnMergeMap );
            delete pTmpDoc;
            sal_uLong nEndOwn = pThisTrack->GetActionMax();

            // resolve conflicts for shared content actions and own actions
            if ( !aConflictsList.empty() )
            {
                ScConflictsListHelper::TransformConflictsList( aConflictsList, NULL, &aOwnMergeMap );
                ScConflictsResolver aResolver( pThisTrack, aConflictsList );
                pAction = pThisTrack->GetAction( nEndShared );
                while ( pAction && pAction->GetActionNumber() >= nStartShared )
                {
                    aResolver.HandleAction( pAction, true /*bIsSharedAction*/,
                        true /*bHandleContentAction*/, false /*bHandleNonContentAction*/ );
                    pAction = pAction->GetPrev();
                }

                pAction = pThisTrack->GetAction( nEndOwn );
                while ( pAction && pAction->GetActionNumber() >= nStartOwn )
                {
                    aResolver.HandleAction( pAction, false /*bIsSharedAction*/,
                        true /*bHandleContentAction*/, true /*bHandleNonContentAction*/ );
                    pAction = pAction->GetPrev();
                }
            }
            nEndOwn = pThisTrack->GetActionMax();
        }
        else
        {
            // merge shared changes into own document
            sal_uLong nStartShared = pThisTrack->GetActionMax() + 1;
            MergeDocument( rSharedDoc, true, true );
            sal_uLong nEndShared = pThisTrack->GetActionMax();

            // only show changes from shared document
            aChangeViewSet.SetShowChanges( true );
            aChangeViewSet.SetShowAccepted( true );
            aChangeViewSet.SetHasActionRange( true );
            aChangeViewSet.SetTheActionRange( nStartShared, nEndShared );
            aDocument.SetChangeViewSettings( aChangeViewSet );
        }

        // update view
        PostPaintExtras();
        PostPaintGridAll();

        InfoBox aInfoBox( GetActiveDialogParent(), ScGlobal::GetRscString( STR_DOC_UPDATED ) );
        aInfoBox.Execute();
    }

    return ( pThisAction != NULL );
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */