summaryrefslogtreecommitdiff
path: root/sc/source/filter/xml/xmlimprt.cxx
blob: f692d7d045688ab39adefa3b6edf49df9515caa2 (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
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
/* -*- 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 <sal/config.h>
#include <sal/log.hxx>
#include <osl/diagnose.h>

#include <svl/zforlist.hxx>

#include <xmloff/namespacemap.hxx>
#include <xmloff/xmlnamespace.hxx>
#include <xmloff/xmltkmap.hxx>
#include <xmloff/xmlictxt.hxx>
#include <xmloff/xmlmetai.hxx>
#include <sfx2/objsh.hxx>
#include <unotools/streamwrap.hxx>
#include <xmloff/xmlscripti.hxx>
#include <xmloff/XMLFontStylesContext.hxx>
#include <xmloff/DocumentSettingsContext.hxx>
#include <xmloff/xmluconv.hxx>
#include <xmloff/numehelp.hxx>
#include <xmloff/xmltoken.hxx>
#include <xmloff/xmlerror.hxx>
#include <xmloff/ProgressBarHelper.hxx>

#include <svl/languageoptions.hxx>
#include <editeng/editstat.hxx>
#include <formula/errorcodes.hxx>
#include <vcl/svapp.hxx>

#include <appluno.hxx>
#include "xmlimprt.hxx"
#include "importcontext.hxx"
#include <document.hxx>
#include <docsh.hxx>
#include <docuno.hxx>
#include "xmlbodyi.hxx"
#include "xmlstyli.hxx"
#include <ViewSettingsSequenceDefines.hxx>

#include <compiler.hxx>

#include "XMLConverter.hxx"
#include "XMLDetectiveContext.hxx"
#include "XMLTableShapeImportHelper.hxx"
#include "XMLChangeTrackingImportHelper.hxx"
#include <chgviset.hxx>
#include "XMLStylesImportHelper.hxx"
#include <sheetdata.hxx>
#include <rangeutl.hxx>
#include <formulaparserpool.hxx>
#include <externalrefmgr.hxx>
#include <editutil.hxx>
#include "editattributemap.hxx"
#include <documentimport.hxx>
#include "pivotsource.hxx"
#include <unonames.hxx>
#include <numformat.hxx>
#include <sizedev.hxx>
#include <scdll.hxx>
#include "xmlstyle.hxx"

#include <comphelper/base64.hxx>
#include <comphelper/extract.hxx>
#include <comphelper/propertysequence.hxx>
#include <comphelper/processfactory.hxx>

#include <com/sun/star/document/XDocumentPropertiesSupplier.hpp>
#include <com/sun/star/frame/XModel.hpp>
#include <com/sun/star/io/IOException.hpp>
#include <com/sun/star/lang/WrappedTargetRuntimeException.hpp>
#include <com/sun/star/document/XActionLockable.hpp>
#include <com/sun/star/util/MalformedNumberFormatException.hpp>
#include <com/sun/star/util/NumberFormat.hpp>
#include <com/sun/star/util/XNumberFormatTypes.hpp>
#include <com/sun/star/util/XNumberFormatsSupplier.hpp>
#include <com/sun/star/sheet/NamedRangeFlag.hpp>
#include <com/sun/star/sheet/XLabelRanges.hpp>
#include <com/sun/star/io/XSeekable.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/sheet/XSheetCellRangeContainer.hpp>
#include <cellsuno.hxx>

#include <memory>
#include <utility>

#define SC_LOCALE           "Locale"
#define SC_CURRENCYSYMBOL   "CurrencySymbol"
#define SC_REPEAT_ROW "repeat-row"
#define SC_FILTER "filter"
#define SC_PRINT_RANGE "print-range"

using namespace com::sun::star;
using namespace ::xmloff::token;
using namespace ::formula;

extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface*
Calc_XMLOasisImporter_get_implementation(
    css::uno::XComponentContext* context, css::uno::Sequence<css::uno::Any> const& )
{
    return cppu::acquire(static_cast<cppu::OWeakObject*>(
        new ScXMLImport(
            context,
            "com.sun.star.comp.Calc.XMLOasisImporter",
            SvXMLImportFlags::ALL,
            { "com.sun.star.comp.Calc.XMLOasisImporter" } )));
}

extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface*
Calc_XMLOasisMetaImporter_get_implementation(
    css::uno::XComponentContext* context, css::uno::Sequence<css::uno::Any> const& )
{
    return cppu::acquire(static_cast<cppu::OWeakObject*>(
        new ScXMLImport(
            context,
            "com.sun.star.comp.Calc.XMLOasisMetaImporter",
            SvXMLImportFlags::META,
            { "com.sun.star.comp.Calc.XMLOasisMetaImporter" }  )));
}

extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface*
Calc_XMLOasisStylesImporter_get_implementation(
    css::uno::XComponentContext* context, css::uno::Sequence<css::uno::Any> const& )
{
    return cppu::acquire(static_cast<cppu::OWeakObject*>(
        new ScXMLImport(
            context,
            "com.sun.star.comp.Calc.XMLOasisStylesImporter",
            SvXMLImportFlags::STYLES|SvXMLImportFlags::AUTOSTYLES|SvXMLImportFlags::MASTERSTYLES|SvXMLImportFlags::FONTDECLS,
            { "com.sun.star.comp.Calc.XMLOasisStylesImporter" } )));
}

extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface*
Calc_XMLOasisContentImporter_get_implementation(
    css::uno::XComponentContext* context, css::uno::Sequence<css::uno::Any> const& )
{
    return cppu::acquire(static_cast<cppu::OWeakObject*>(new ScXMLImport(
        context,
        "com.sun.star.comp.Calc.XMLOasisContentImporter",
        SvXMLImportFlags::AUTOSTYLES|SvXMLImportFlags::CONTENT|SvXMLImportFlags::SCRIPTS|SvXMLImportFlags::FONTDECLS,
        uno::Sequence< OUString > { "com.sun.star.comp.Calc.XMLOasisContentImporter" })));
}


extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface*
Calc_XMLOasisSettingsImporter_get_implementation(
    css::uno::XComponentContext* context, css::uno::Sequence<css::uno::Any> const& )
{
    return cppu::acquire(static_cast<cppu::OWeakObject*>(
        new ScXMLImport(
            context,
            "com.sun.star.comp.Calc.XMLOasisSettingsImporter",
            SvXMLImportFlags::SETTINGS,
            { "com.sun.star.comp.Calc.XMLOasisSettingsImporter" } )));
}

const SvXMLTokenMap& ScXMLImport::GetTableRowCellAttrTokenMap()
{
    static const SvXMLTokenMapEntry aTableRowCellAttrTokenMap[] =
    {
        { XML_NAMESPACE_TABLE,  XML_STYLE_NAME,                     XML_TOK_TABLE_ROW_CELL_ATTR_STYLE_NAME              },
        { XML_NAMESPACE_TABLE,  XML_CONTENT_VALIDATION_NAME,        XML_TOK_TABLE_ROW_CELL_ATTR_CONTENT_VALIDATION_NAME },
        { XML_NAMESPACE_TABLE,  XML_NUMBER_ROWS_SPANNED,            XML_TOK_TABLE_ROW_CELL_ATTR_SPANNED_ROWS            },
        { XML_NAMESPACE_TABLE,  XML_NUMBER_COLUMNS_SPANNED,         XML_TOK_TABLE_ROW_CELL_ATTR_SPANNED_COLS            },
        { XML_NAMESPACE_TABLE,  XML_NUMBER_MATRIX_COLUMNS_SPANNED,  XML_TOK_TABLE_ROW_CELL_ATTR_SPANNED_MATRIX_COLS     },
        { XML_NAMESPACE_TABLE,  XML_NUMBER_MATRIX_ROWS_SPANNED,     XML_TOK_TABLE_ROW_CELL_ATTR_SPANNED_MATRIX_ROWS     },
        { XML_NAMESPACE_TABLE,  XML_NUMBER_COLUMNS_REPEATED,        XML_TOK_TABLE_ROW_CELL_ATTR_REPEATED                },
        { XML_NAMESPACE_OFFICE, XML_VALUE_TYPE,                     XML_TOK_TABLE_ROW_CELL_ATTR_VALUE_TYPE              },
        { XML_NAMESPACE_CALC_EXT, XML_VALUE_TYPE,                   XML_TOK_TABLE_ROW_CELL_ATTR_NEW_VALUE_TYPE          },
        { XML_NAMESPACE_OFFICE, XML_VALUE,                          XML_TOK_TABLE_ROW_CELL_ATTR_VALUE                   },
        { XML_NAMESPACE_OFFICE, XML_DATE_VALUE,                     XML_TOK_TABLE_ROW_CELL_ATTR_DATE_VALUE              },
        { XML_NAMESPACE_OFFICE, XML_TIME_VALUE,                     XML_TOK_TABLE_ROW_CELL_ATTR_TIME_VALUE              },
        { XML_NAMESPACE_OFFICE, XML_STRING_VALUE,                   XML_TOK_TABLE_ROW_CELL_ATTR_STRING_VALUE            },
        { XML_NAMESPACE_OFFICE, XML_BOOLEAN_VALUE,                  XML_TOK_TABLE_ROW_CELL_ATTR_BOOLEAN_VALUE           },
        { XML_NAMESPACE_TABLE,  XML_FORMULA,                        XML_TOK_TABLE_ROW_CELL_ATTR_FORMULA                 },
        { XML_NAMESPACE_OFFICE, XML_CURRENCY,                       XML_TOK_TABLE_ROW_CELL_ATTR_CURRENCY                },
        XML_TOKEN_MAP_END
    };

    if ( !pTableRowCellAttrTokenMap )
        pTableRowCellAttrTokenMap.reset(new SvXMLTokenMap( aTableRowCellAttrTokenMap ));
    return *pTableRowCellAttrTokenMap;
}

namespace {

// NB: virtually inherit so we can multiply inherit properly
//     in ScXMLFlatDocContext_Impl
class ScXMLDocContext_Impl : public virtual SvXMLImportContext
{
protected:
    ScXMLImport& GetScImport() { return static_cast<ScXMLImport&>(GetImport()); }

public:
    ScXMLDocContext_Impl( ScXMLImport& rImport );

    virtual css::uno::Reference< css::xml::sax::XFastContextHandler > SAL_CALL
        createFastChildContext( sal_Int32 nElement,
        const css::uno::Reference<css::xml::sax::XFastAttributeList>& xAttrList ) override;

    virtual void SAL_CALL startFastElement (sal_Int32 nElement,
        const css::uno::Reference< css::xml::sax::XFastAttributeList >& xAttrList) override;

    virtual void SAL_CALL characters(const OUString & aChars) override;

    virtual void SAL_CALL endFastElement(sal_Int32 nElement) override;
};

}

ScXMLDocContext_Impl::ScXMLDocContext_Impl( ScXMLImport& rImport ) :
SvXMLImportContext( rImport )
{
}

namespace {

// context for flat file xml format
class ScXMLFlatDocContext_Impl
    : public ScXMLDocContext_Impl, public SvXMLMetaDocumentContext
{
public:

    ScXMLFlatDocContext_Impl( ScXMLImport& i_rImport,
        const uno::Reference<document::XDocumentProperties>& i_xDocProps);

    virtual void SAL_CALL startFastElement (sal_Int32 nElement,
        const css::uno::Reference< css::xml::sax::XFastAttributeList >& xAttrList) override;

    virtual void SAL_CALL endFastElement(sal_Int32 nElement) override;

    virtual void SAL_CALL characters( const OUString& aChars ) override;

    virtual css::uno::Reference< css::xml::sax::XFastContextHandler > SAL_CALL
        createFastChildContext( sal_Int32 nElement,
        const css::uno::Reference<css::xml::sax::XFastAttributeList>& xAttrList ) override;
};

}

ScXMLFlatDocContext_Impl::ScXMLFlatDocContext_Impl( ScXMLImport& i_rImport,
                                                   const uno::Reference<document::XDocumentProperties>& i_xDocProps) :
SvXMLImportContext(i_rImport),
ScXMLDocContext_Impl(i_rImport),
SvXMLMetaDocumentContext(i_rImport, i_xDocProps)
{
}

uno::Reference< xml::sax::XFastContextHandler > SAL_CALL
    ScXMLFlatDocContext_Impl::createFastChildContext( sal_Int32 nElement,
    const uno::Reference< xml::sax::XFastAttributeList > & xAttrList )
{
    if ( nElement == XML_ELEMENT( OFFICE, XML_META ) )
        return SvXMLMetaDocumentContext::createFastChildContext( nElement, xAttrList );
    else
        return ScXMLDocContext_Impl::createFastChildContext( nElement, xAttrList );
}

void SAL_CALL ScXMLFlatDocContext_Impl::startFastElement(sal_Int32 nElement,
    const uno::Reference< xml::sax::XFastAttributeList > & xAttrList)
{
    SvXMLMetaDocumentContext::startFastElement( nElement, xAttrList );
}

void SAL_CALL ScXMLFlatDocContext_Impl::endFastElement(sal_Int32 nElement)
{
    SvXMLMetaDocumentContext::endFastElement( nElement );
}

void SAL_CALL ScXMLFlatDocContext_Impl::characters(const OUString& rChars)
{
    SvXMLMetaDocumentContext::characters(rChars);
}

namespace {

class ScXMLBodyContext_Impl : public ScXMLImportContext
{
public:
    ScXMLBodyContext_Impl( ScXMLImport& rImport );

    virtual css::uno::Reference< css::xml::sax::XFastContextHandler > SAL_CALL
        createFastChildContext( sal_Int32 nElement,
        const css::uno::Reference<css::xml::sax::XFastAttributeList>& xAttrList ) override;
};

}

ScXMLBodyContext_Impl::ScXMLBodyContext_Impl( ScXMLImport& rImport ) :
ScXMLImportContext( rImport )
{
}

uno::Reference< xml::sax::XFastContextHandler > SAL_CALL
    ScXMLBodyContext_Impl::createFastChildContext( sal_Int32 /*nElement*/,
    const uno::Reference< xml::sax::XFastAttributeList > & xAttrList )
{
    sax_fastparser::FastAttributeList *pAttribList =
        &sax_fastparser::castToFastAttributeList( xAttrList );
    return GetScImport().CreateBodyContext( pAttribList );
}

uno::Reference< xml::sax::XFastContextHandler > SAL_CALL
    ScXMLDocContext_Impl::createFastChildContext( sal_Int32 nElement,
    const uno::Reference< xml::sax::XFastAttributeList > & /*xAttrList*/ )
{
    SvXMLImportContext *pContext(nullptr);

    switch( nElement )
    {
        case XML_ELEMENT( OFFICE, XML_BODY ):
        if (GetScImport().getImportFlags() & SvXMLImportFlags::CONTENT)
            pContext = new ScXMLBodyContext_Impl( GetScImport() );
        break;
        case XML_ELEMENT( OFFICE, XML_SCRIPTS ):
        if (GetScImport().getImportFlags() & SvXMLImportFlags::SCRIPTS)
            pContext = GetScImport().CreateScriptContext();
        break;
        case XML_ELEMENT( OFFICE, XML_SETTINGS ):
        if (GetScImport().getImportFlags() & SvXMLImportFlags::SETTINGS)
            pContext = new XMLDocumentSettingsContext(GetScImport());
        break;
        case XML_ELEMENT(OFFICE, XML_STYLES):
            if (GetScImport().getImportFlags() & SvXMLImportFlags::STYLES)
                pContext = GetScImport().CreateStylesContext( false);
            break;
        case XML_ELEMENT(OFFICE, XML_AUTOMATIC_STYLES):
            if (GetScImport().getImportFlags() & SvXMLImportFlags::AUTOSTYLES)
                pContext = GetScImport().CreateStylesContext( true);
            break;
        case XML_ELEMENT(OFFICE, XML_FONT_FACE_DECLS):
            if (GetScImport().getImportFlags() & SvXMLImportFlags::FONTDECLS)
                pContext = GetScImport().CreateFontDeclsContext();
            break;
        case XML_ELEMENT(OFFICE, XML_MASTER_STYLES):
            if (GetScImport().getImportFlags() & SvXMLImportFlags::MASTERSTYLES)
                pContext = new ScXMLMasterStylesContext( GetImport() );
            break;
        case XML_ELEMENT(OFFICE, XML_META):
            SAL_INFO("sc", "XML_ELEMENT(OFFICE, XML_META): should not have come here, maybe document is invalid?");
            break;
    }

    return pContext;
}

void SAL_CALL ScXMLDocContext_Impl::startFastElement(sal_Int32 /*nElement*/,
    const uno::Reference< xml::sax::XFastAttributeList > & /*xAttrList*/)
{
}

void SAL_CALL ScXMLDocContext_Impl::endFastElement(sal_Int32 /*nElement*/)
{
}

void SAL_CALL ScXMLDocContext_Impl::characters(const OUString &)
{
}

const SvXMLTokenMap& ScXMLImport::GetTableElemTokenMap()
{
    if( !pTableElemTokenMap )
    {
        static const SvXMLTokenMapEntry aTableTokenMap[] =
        {
            { XML_NAMESPACE_TABLE,  XML_NAMED_EXPRESSIONS,    XML_TOK_TABLE_NAMED_EXPRESSIONS },
            { XML_NAMESPACE_TABLE,  XML_TABLE_COLUMN_GROUP,   XML_TOK_TABLE_COL_GROUP       },
            { XML_NAMESPACE_TABLE,  XML_TABLE_HEADER_COLUMNS, XML_TOK_TABLE_HEADER_COLS },
            { XML_NAMESPACE_TABLE,  XML_TABLE_COLUMNS,        XML_TOK_TABLE_COLS            },
            { XML_NAMESPACE_TABLE,  XML_TABLE_COLUMN,         XML_TOK_TABLE_COL         },
            { XML_NAMESPACE_TABLE,  XML_TABLE_PROTECTION,     XML_TOK_TABLE_PROTECTION    },
            { XML_NAMESPACE_LO_EXT, XML_TABLE_PROTECTION,     XML_TOK_TABLE_PROTECTION_EXT  },
            { XML_NAMESPACE_OFFICE_EXT, XML_TABLE_PROTECTION, XML_TOK_TABLE_PROTECTION_EXT  },
            { XML_NAMESPACE_TABLE,  XML_TABLE_ROW_GROUP,      XML_TOK_TABLE_ROW_GROUP       },
            { XML_NAMESPACE_TABLE,  XML_TABLE_HEADER_ROWS,    XML_TOK_TABLE_HEADER_ROWS },
            { XML_NAMESPACE_TABLE,  XML_TABLE_ROWS,           XML_TOK_TABLE_ROWS            },
            { XML_NAMESPACE_TABLE,  XML_TABLE_ROW,            XML_TOK_TABLE_ROW         },
            { XML_NAMESPACE_TABLE,  XML_TABLE_SOURCE,         XML_TOK_TABLE_SOURCE      },
            { XML_NAMESPACE_TABLE,  XML_SCENARIO,             XML_TOK_TABLE_SCENARIO        },
            { XML_NAMESPACE_TABLE,  XML_SHAPES,               XML_TOK_TABLE_SHAPES      },
            { XML_NAMESPACE_OFFICE, XML_FORMS,                XML_TOK_TABLE_FORMS           },
            { XML_NAMESPACE_OFFICE, XML_EVENT_LISTENERS,      XML_TOK_TABLE_EVENT_LISTENERS },
            { XML_NAMESPACE_OFFICE_EXT, XML_EVENT_LISTENERS,  XML_TOK_TABLE_EVENT_LISTENERS_EXT },
            { XML_NAMESPACE_CALC_EXT, XML_CONDITIONAL_FORMATS, XML_TOK_TABLE_CONDFORMATS },
            XML_TOKEN_MAP_END
        };

        pTableElemTokenMap.reset(new SvXMLTokenMap( aTableTokenMap ));
    } // if( !pTableElemTokenMap )

    return *pTableElemTokenMap;
}

const SvXMLTokenMap& ScXMLImport::GetTableRowsElemTokenMap()
{
    if( !pTableRowsElemTokenMap )
    {
        static const SvXMLTokenMapEntry aTableRowsElemTokenMap[] =
        {
            { XML_NAMESPACE_TABLE, XML_TABLE_ROW_GROUP,     XML_TOK_TABLE_ROWS_ROW_GROUP    },
            { XML_NAMESPACE_TABLE, XML_TABLE_HEADER_ROWS,   XML_TOK_TABLE_ROWS_HEADER_ROWS  },
            { XML_NAMESPACE_TABLE, XML_TABLE_ROWS,          XML_TOK_TABLE_ROWS_ROWS         },
            { XML_NAMESPACE_TABLE, XML_TABLE_ROW,           XML_TOK_TABLE_ROWS_ROW          },
            XML_TOKEN_MAP_END
        };

        pTableRowsElemTokenMap.reset(new SvXMLTokenMap( aTableRowsElemTokenMap ));
    } // if( !pTableRowsElemTokenMap )

    return *pTableRowsElemTokenMap;
}

const SvXMLTokenMap& ScXMLImport::GetTableRowElemTokenMap()
{
    if( !pTableRowElemTokenMap )
    {
        static const SvXMLTokenMapEntry aTableRowTokenMap[] =
        {
            { XML_NAMESPACE_TABLE, XML_TABLE_CELL,      XML_TOK_TABLE_ROW_CELL              },
            { XML_NAMESPACE_TABLE, XML_COVERED_TABLE_CELL,  XML_TOK_TABLE_ROW_COVERED_CELL      },
            XML_TOKEN_MAP_END
        };

        pTableRowElemTokenMap.reset(new SvXMLTokenMap( aTableRowTokenMap ));
    } // if( !pTableRowElemTokenMap )

    return *pTableRowElemTokenMap;
}

const SvXMLTokenMap& ScXMLImport::GetTableRowAttrTokenMap()
{
    if( !pTableRowAttrTokenMap )
    {
        static const SvXMLTokenMapEntry aTableRowAttrTokenMap[] =
        {
            { XML_NAMESPACE_TABLE, XML_STYLE_NAME,                  XML_TOK_TABLE_ROW_ATTR_STYLE_NAME           },
            { XML_NAMESPACE_TABLE, XML_VISIBILITY,                  XML_TOK_TABLE_ROW_ATTR_VISIBILITY           },
            { XML_NAMESPACE_TABLE, XML_NUMBER_ROWS_REPEATED,        XML_TOK_TABLE_ROW_ATTR_REPEATED             },
            { XML_NAMESPACE_TABLE, XML_DEFAULT_CELL_STYLE_NAME,     XML_TOK_TABLE_ROW_ATTR_DEFAULT_CELL_STYLE_NAME },
            //  { XML_NAMESPACE_TABLE, XML_USE_OPTIMAL_HEIGHT,          XML_TOK_TABLE_ROW_ATTR_USE_OPTIMAL_HEIGHT   },
            XML_TOKEN_MAP_END
        };

        pTableRowAttrTokenMap.reset(new SvXMLTokenMap( aTableRowAttrTokenMap ));
    } // if( !pTableRowAttrTokenMap )

    return *pTableRowAttrTokenMap;
}

const SvXMLTokenMap& ScXMLImport::GetTableRowCellElemTokenMap()
{
    if( !pTableRowCellElemTokenMap )
    {
        static const SvXMLTokenMapEntry aTableRowCellTokenMap[] =
        {
            { XML_NAMESPACE_TEXT,   XML_P,                  XML_TOK_TABLE_ROW_CELL_P                    },
            { XML_NAMESPACE_TABLE,  XML_SUB_TABLE,          XML_TOK_TABLE_ROW_CELL_TABLE                },
            { XML_NAMESPACE_OFFICE, XML_ANNOTATION,         XML_TOK_TABLE_ROW_CELL_ANNOTATION           },
            { XML_NAMESPACE_TABLE,  XML_DETECTIVE,          XML_TOK_TABLE_ROW_CELL_DETECTIVE            },
            { XML_NAMESPACE_TABLE,  XML_CELL_RANGE_SOURCE,  XML_TOK_TABLE_ROW_CELL_CELL_RANGE_SOURCE    },
            XML_TOKEN_MAP_END
        };

        pTableRowCellElemTokenMap.reset(new SvXMLTokenMap( aTableRowCellTokenMap ));
    } // if( !pTableRowCellElemTokenMap )

    return *pTableRowCellElemTokenMap;
}

const SvXMLTokenMap& ScXMLImport::GetTableAnnotationAttrTokenMap()
{
    if( !pTableAnnotationAttrTokenMap )
    {
        static const SvXMLTokenMapEntry aTableAnnotationAttrTokenMap[] =
        {
            { XML_NAMESPACE_OFFICE, XML_AUTHOR,                 XML_TOK_TABLE_ANNOTATION_ATTR_AUTHOR                },
            { XML_NAMESPACE_OFFICE, XML_CREATE_DATE,            XML_TOK_TABLE_ANNOTATION_ATTR_CREATE_DATE           },
            { XML_NAMESPACE_OFFICE, XML_CREATE_DATE_STRING,     XML_TOK_TABLE_ANNOTATION_ATTR_CREATE_DATE_STRING    },
            { XML_NAMESPACE_OFFICE, XML_DISPLAY,                XML_TOK_TABLE_ANNOTATION_ATTR_DISPLAY               },
            { XML_NAMESPACE_SVG,    XML_X,                      XML_TOK_TABLE_ANNOTATION_ATTR_X                     },
            { XML_NAMESPACE_SVG,    XML_Y,                      XML_TOK_TABLE_ANNOTATION_ATTR_Y                     },
            XML_TOKEN_MAP_END
        };

        pTableAnnotationAttrTokenMap.reset(new SvXMLTokenMap( aTableAnnotationAttrTokenMap ));
    } // if( !pTableAnnotationAttrTokenMap )

    return *pTableAnnotationAttrTokenMap;
}


void ScXMLImport::SetPostProcessData( sc::ImportPostProcessData* p )
{
    mpPostProcessData = p;
}

sc::PivotTableSources& ScXMLImport::GetPivotTableSources()
{
    if (!mpPivotSources)
        mpPivotSources.reset(new sc::PivotTableSources);

    return *mpPivotSources;
}

SvXMLImportContext *ScXMLImport::CreateFastContext( sal_Int32 nElement,
        const uno::Reference< xml::sax::XFastAttributeList >& /*xAttrList*/ )
{
    SvXMLImportContext *pContext = nullptr;

    switch( nElement )
    {
    case XML_ELEMENT( OFFICE, XML_DOCUMENT_STYLES ):
    case XML_ELEMENT( OFFICE, XML_DOCUMENT_CONTENT ):
    case XML_ELEMENT( OFFICE, XML_DOCUMENT_SETTINGS ):
        pContext = new ScXMLDocContext_Impl( *this );
        break;

    case XML_ELEMENT( OFFICE, XML_DOCUMENT_META ):
        pContext = CreateMetaContext(nElement);
        break;

    case XML_ELEMENT( OFFICE, XML_DOCUMENT ):
    {
        uno::Reference<document::XDocumentPropertiesSupplier> xDPS(
            GetModel(), uno::UNO_QUERY_THROW);
        // flat OpenDocument file format
        pContext = new ScXMLFlatDocContext_Impl( *this,
            xDPS->getDocumentProperties());
        break;
    }

    }

    return pContext;
}

constexpr OUStringLiteral gsNumberFormat(u"" SC_UNONAME_NUMFMT);
constexpr OUStringLiteral gsLocale(u"" SC_LOCALE);
constexpr OUStringLiteral gsCellStyle(u"" SC_UNONAME_CELLSTYL);

ScXMLImport::ScXMLImport(
    const css::uno::Reference< css::uno::XComponentContext >& rContext,
    OUString const & implementationName, SvXMLImportFlags nImportFlag,
    const css::uno::Sequence< OUString > & sSupportedServiceNames)
:   SvXMLImport( rContext, implementationName, nImportFlag, sSupportedServiceNames ),
    pDoc( nullptr ),
    mpPostProcessData(nullptr),
    aTables(*this),
    sPrevStyleName(),
    sPrevCurrency(),
    nSolarMutexLocked(0),
    nProgressCount(0),
    nPrevCellType(0),
    bLoadDoc( true ),
    bNullDateSetted(false),
    bSelfImportingXMLSet(false),
    mbLockSolarMutex(true),
    mbImportStyles(true),
    mbHasNewCondFormatData(false)
{
    pStylesImportHelper.reset(new ScMyStylesImportHelper(*this));

    xScPropHdlFactory = new XMLScPropHdlFactory;
    xCellStylesPropertySetMapper = new XMLPropertySetMapper(aXMLScCellStylesProperties, xScPropHdlFactory, false);
    xColumnStylesPropertySetMapper = new XMLPropertySetMapper(aXMLScColumnStylesProperties, xScPropHdlFactory, false);
    xRowStylesPropertySetMapper = new XMLPropertySetMapper(aXMLScRowStylesImportProperties, xScPropHdlFactory, false);
    xTableStylesPropertySetMapper = new XMLPropertySetMapper(aXMLScTableStylesImportProperties, xScPropHdlFactory, false);

    // #i66550# needed for 'presentation:event-listener' element for URLs in shapes
    GetNamespaceMap().Add(
        GetXMLToken( XML_NP_PRESENTATION ),
        GetXMLToken( XML_N_PRESENTATION ),
        XML_NAMESPACE_PRESENTATION );
}

ScXMLImport::~ScXMLImport() throw()
{
    //  delete pI18NMap;
    pTableElemTokenMap.reset();
    pTableRowsElemTokenMap.reset();
    pTableRowElemTokenMap.reset();
    pTableRowAttrTokenMap.reset();
    pTableRowCellElemTokenMap.reset();
    pTableRowCellAttrTokenMap.reset();
    pTableAnnotationAttrTokenMap.reset();

    pChangeTrackingImportHelper.reset();
    pNumberFormatAttributesExportHelper.reset();
    pStyleNumberFormats.reset();
    pStylesImportHelper.reset();

    m_pMyNamedExpressions.reset();
    pMyLabelRanges.reset();
    pValidations.reset();
    pDetectiveOpArray.reset();

    //call SvXMLImport dtor contents before deleting pSolarMutexGuard
    cleanup();

    pSolarMutexGuard.reset();
}

void ScXMLImport::initialize( const css::uno::Sequence<css::uno::Any>& aArguments )
{
    SvXMLImport::initialize(aArguments);

    uno::Reference<beans::XPropertySet> xInfoSet = getImportInfo();
    if (!xInfoSet.is())
        return;

    uno::Reference<beans::XPropertySetInfo> xInfoSetInfo = xInfoSet->getPropertySetInfo();
    if (!xInfoSetInfo.is())
        return;

    if (xInfoSetInfo->hasPropertyByName(SC_UNO_ODS_LOCK_SOLAR_MUTEX))
        xInfoSet->getPropertyValue(SC_UNO_ODS_LOCK_SOLAR_MUTEX) >>= mbLockSolarMutex;

    if (xInfoSetInfo->hasPropertyByName(SC_UNO_ODS_IMPORT_STYLES))
        xInfoSet->getPropertyValue(SC_UNO_ODS_IMPORT_STYLES) >>= mbImportStyles;
}

SvXMLImportContext *ScXMLImport::CreateFontDeclsContext()
{
    XMLFontStylesContext *pFSContext = new XMLFontStylesContext(
        *this, osl_getThreadTextEncoding());
    SetFontDecls(pFSContext);
    SvXMLImportContext* pContext = pFSContext;
    return pContext;
}

SvXMLImportContext *ScXMLImport::CreateStylesContext( bool bIsAutoStyle )
{
    SvXMLImportContext* pContext = new XMLTableStylesContext(
        *this, bIsAutoStyle);

    if (bIsAutoStyle)
        SetAutoStyles(static_cast<SvXMLStylesContext*>(pContext));
    else
        SetStyles(static_cast<SvXMLStylesContext*>(pContext));

    return pContext;
}

SvXMLImportContext *ScXMLImport::CreateBodyContext(const rtl::Reference<sax_fastparser::FastAttributeList>& rAttrList)
{
    return new ScXMLBodyContext(*this, rAttrList);
}

SvXMLImportContext *ScXMLImport::CreateMetaContext(
    const sal_Int32 /*nElement*/ )
{
    SvXMLImportContext* pContext = nullptr;

    if (getImportFlags() & SvXMLImportFlags::META)
    {
        uno::Reference<document::XDocumentPropertiesSupplier> xDPS(
            GetModel(), uno::UNO_QUERY_THROW);
        uno::Reference<document::XDocumentProperties> const xDocProps(
            (IsStylesOnlyMode()) ? nullptr : xDPS->getDocumentProperties());
        pContext = new SvXMLMetaDocumentContext(*this, xDocProps);
    }

    return pContext;
}

SvXMLImportContext *ScXMLImport::CreateScriptContext()
{
    SvXMLImportContext* pContext = nullptr;

    if( !(IsStylesOnlyMode()) )
    {
        pContext = new XMLScriptContext( *this, GetModel() );
    }

    return pContext;
}

void ScXMLImport::SetStatistics(const uno::Sequence<beans::NamedValue> & i_rStats)
{
    static const char* s_stats[] =
    { "TableCount", "CellCount", "ObjectCount", nullptr };

    SvXMLImport::SetStatistics(i_rStats);

    sal_uInt32 nCount(0);
    for (const auto& rStat : i_rStats) {
        for (const char** pStat = s_stats; *pStat != nullptr; ++pStat) {
            if (rStat.Name.equalsAscii(*pStat)) {
                sal_Int32 val = 0;
                if (rStat.Value >>= val) {
                    nCount += val;
                } else {
                    OSL_FAIL("ScXMLImport::SetStatistics: invalid entry");
                }
            }
        }
    }

    if (nCount)
    {
        GetProgressBarHelper()->SetReference(nCount);
        GetProgressBarHelper()->SetValue(0);
    }
}

ScDocumentImport& ScXMLImport::GetDoc()
{
    return *mpDocImport;
}

sal_Int16 ScXMLImport::GetCellType(const char* rStrValue, const sal_Int32 nStrLength)
{
    sal_Int16 nCellType = util::NumberFormat::UNDEFINED;
    if (rStrValue != nullptr)
    {
        switch (rStrValue[0])
        {
            case 'b':
                if (nStrLength == 7 && !strcmp(rStrValue, "boolean"))
                    nCellType = util::NumberFormat::LOGICAL;
            break;
            case 'c':
                if (nStrLength == 8 && !strcmp(rStrValue, "currency"))
                    nCellType = util::NumberFormat::CURRENCY;
            break;
            case 'd':
                if (nStrLength == 4 && !strcmp(rStrValue, "date"))
                    nCellType = util::NumberFormat::DATETIME;
            break;
            case 'f':
                if (nStrLength == 5 && !strcmp(rStrValue, "float"))
                    nCellType = util::NumberFormat::NUMBER;
            break;
            case 'p':
                if (nStrLength == 10 && !strcmp(rStrValue, "percentage"))
                    nCellType = util::NumberFormat::PERCENT;
            break;
            case 's':
                if (nStrLength == 6 && !strcmp(rStrValue, "string"))
                    nCellType = util::NumberFormat::TEXT;
            break;
            case 't':
                if (nStrLength == 4 && !strcmp(rStrValue, "time"))
                    nCellType = util::NumberFormat::TIME;
            break;
        }
    }

    return nCellType;
}

XMLShapeImportHelper* ScXMLImport::CreateShapeImport()
{
    return new XMLTableShapeImportHelper(*this);
}

bool ScXMLImport::GetValidation(const OUString& sName, ScMyImportValidation& aValidation)
{
    if (pValidations)
    {
        auto aItr = std::find_if(pValidations->begin(), pValidations->end(),
            [&sName](const ScMyImportValidation& rValidation) { return rValidation.sName == sName; });
        if (aItr != pValidations->end())
        {
            // source position must be set as string,
            // so sBaseCellAddress no longer has to be converted here
            aValidation = *aItr;
            return true;
        }
    }
    return false;
}

void ScXMLImport::AddNamedExpression(SCTAB nTab, ScMyNamedExpression* pNamedExp)
{
    ::std::unique_ptr<ScMyNamedExpression> p(pNamedExp);
    SheetNamedExpMap::iterator itr = m_SheetNamedExpressions.find(nTab);
    if (itr == m_SheetNamedExpressions.end())
    {
        // No chain exists for this sheet.  Create one.
        ::std::pair<SheetNamedExpMap::iterator, bool> r =
            m_SheetNamedExpressions.insert(std::make_pair(nTab, std::make_unique<ScMyNamedExpressions>()));
        if (!r.second)
            // insertion failed.
            return;

        itr = r.first;
    }
    ScMyNamedExpressions& r = *itr->second;
    r.push_back(std::move(p));
}

ScXMLChangeTrackingImportHelper* ScXMLImport::GetChangeTrackingImportHelper()
{
    if (!pChangeTrackingImportHelper)
        pChangeTrackingImportHelper.reset(new ScXMLChangeTrackingImportHelper());
    return pChangeTrackingImportHelper.get();
}

void ScXMLImport::InsertStyles()
{
    GetStyles()->CopyStylesToDoc(true);

    // if content is going to be loaded with the same import, set bLatinDefaultStyle flag now
    if ( getImportFlags() & SvXMLImportFlags::CONTENT )
        ExamineDefaultStyle();
}

void ScXMLImport::ExamineDefaultStyle()
{
    if (pDoc)
    {
        // #i62435# after inserting the styles, check if the default style has a latin-script-only
        // number format (then, value cells can be pre-initialized with western script type)

        const ScPatternAttr* pDefPattern = pDoc->GetDefPattern();
        if (pDefPattern && sc::NumFmtUtil::isLatinScript(*pDefPattern, *pDoc))
            mpDocImport->setDefaultNumericScript(SvtScriptType::LATIN);
    }
}

void ScXMLImport::SetChangeTrackingViewSettings(const css::uno::Sequence<css::beans::PropertyValue>& rChangeProps)
{
    if (!pDoc)
        return;

    if (!rChangeProps.hasElements())
        return;

    ScXMLImport::MutexGuard aGuard(*this);
    sal_Int16 nTemp16(0);
    std::unique_ptr<ScChangeViewSettings> pViewSettings(new ScChangeViewSettings());
    for (const auto& rChangeProp : rChangeProps)
    {
        OUString sName(rChangeProp.Name);
        if (sName == "ShowChanges")
            pViewSettings->SetShowChanges(::cppu::any2bool(rChangeProp.Value));
        else if (sName == "ShowAcceptedChanges")
            pViewSettings->SetShowAccepted(::cppu::any2bool(rChangeProp.Value));
        else if (sName == "ShowRejectedChanges")
            pViewSettings->SetShowRejected(::cppu::any2bool(rChangeProp.Value));
        else if (sName == "ShowChangesByDatetime")
            pViewSettings->SetHasDate(::cppu::any2bool(rChangeProp.Value));
        else if (sName == "ShowChangesByDatetimeMode")
        {
            if (rChangeProp.Value >>= nTemp16)
                pViewSettings->SetTheDateMode(static_cast<SvxRedlinDateMode>(nTemp16));
        }
        else if (sName == "ShowChangesByDatetimeFirstDatetime")
        {
            util::DateTime aDateTime;
            if (rChangeProp.Value >>= aDateTime)
            {
                pViewSettings->SetTheFirstDateTime(::DateTime(aDateTime));
            }
        }
        else if (sName == "ShowChangesByDatetimeSecondDatetime")
        {
            util::DateTime aDateTime;
            if (rChangeProp.Value >>= aDateTime)
            {
                pViewSettings->SetTheLastDateTime(::DateTime(aDateTime));
            }
        }
        else if (sName == "ShowChangesByAuthor")
            pViewSettings->SetHasAuthor(::cppu::any2bool(rChangeProp.Value));
        else if (sName == "ShowChangesByAuthorName")
        {
            OUString sOUName;
            if (rChangeProp.Value >>= sOUName)
            {
                pViewSettings->SetTheAuthorToShow(sOUName);
            }
        }
        else if (sName == "ShowChangesByComment")
            pViewSettings->SetHasComment(::cppu::any2bool(rChangeProp.Value));
        else if (sName == "ShowChangesByCommentText")
        {
            OUString sOUComment;
            if (rChangeProp.Value >>= sOUComment)
            {
                pViewSettings->SetTheComment(sOUComment);
            }
        }
        else if (sName == "ShowChangesByRanges")
            pViewSettings->SetHasRange(::cppu::any2bool(rChangeProp.Value));
        else if (sName == "ShowChangesByRangesList")
        {
            OUString sRanges;
            if ((rChangeProp.Value >>= sRanges) && !sRanges.isEmpty())
            {
                ScRangeList aRangeList;
                ScRangeStringConverter::GetRangeListFromString(
                    aRangeList, sRanges, *pDoc, FormulaGrammar::CONV_OOO);
                pViewSettings->SetTheRangeList(aRangeList);
            }
        }
    }
    pDoc->SetChangeViewSettings(*pViewSettings);
}

void ScXMLImport::SetViewSettings(const uno::Sequence<beans::PropertyValue>& aViewProps)
{
    sal_Int32 nHeight(0);
    sal_Int32 nLeft(0);
    sal_Int32 nTop(0);
    sal_Int32 nWidth(0);
    for (const auto& rViewProp : aViewProps)
    {
        OUString sName(rViewProp.Name);
        if (sName == "VisibleAreaHeight")
            rViewProp.Value >>= nHeight;
        else if (sName == "VisibleAreaLeft")
            rViewProp.Value >>= nLeft;
        else if (sName == "VisibleAreaTop")
            rViewProp.Value >>= nTop;
        else if (sName == "VisibleAreaWidth")
            rViewProp.Value >>= nWidth;
        else if (sName == "TrackedChangesViewSettings")
        {
            uno::Sequence<beans::PropertyValue> aChangeProps;
            if(rViewProp.Value >>= aChangeProps)
                SetChangeTrackingViewSettings(aChangeProps);
        }
    }
    if (!(nHeight && nWidth && GetModel().is()))
        return;

    ScModelObj* pDocObj(comphelper::getUnoTunnelImplementation<ScModelObj>( GetModel() ));
    if (!pDocObj)
        return;

    SfxObjectShell* pEmbeddedObj = pDocObj->GetEmbeddedObject();
    if (pEmbeddedObj)
    {
        tools::Rectangle aRect;
        aRect.setX( nLeft );
        aRect.setY( nTop );
        aRect.setWidth( nWidth );
        aRect.setHeight( nHeight );
        pEmbeddedObj->SetVisArea(aRect);
    }
}

void ScXMLImport::SetConfigurationSettings(const uno::Sequence<beans::PropertyValue>& aConfigProps)
{
    if (!GetModel().is())
        return;

    uno::Reference <lang::XMultiServiceFactory> xMultiServiceFactory(GetModel(), uno::UNO_QUERY);
    if (!xMultiServiceFactory.is())
        return;

    sal_Int32 nCount(aConfigProps.getLength());
    css::uno::Sequence<css::beans::PropertyValue> aFilteredProps(nCount);
    sal_Int32 nFilteredPropsLen = 0;
    for (sal_Int32 i = nCount - 1; i >= 0; --i)
    {
        if (aConfigProps[i].Name == "TrackedChangesProtectionKey")
        {
            OUString sKey;
            if (aConfigProps[i].Value >>= sKey)
            {
                uno::Sequence<sal_Int8> aPass;
                ::comphelper::Base64::decode(aPass, sKey);
                if (aPass.hasElements())
                {
                    if (pDoc->GetChangeTrack())
                        pDoc->GetChangeTrack()->SetProtection(aPass);
                    else
                    {
                        std::set<OUString> aUsers;
                        std::unique_ptr<ScChangeTrack> pTrack( new ScChangeTrack(*pDoc, aUsers) );
                        pTrack->SetProtection(aPass);
                        pDoc->SetChangeTrack(std::move(pTrack));
                    }
                }
            }
        }
        // store the following items for later use (after document is loaded)
        else if ((aConfigProps[i].Name == "VBACompatibilityMode") || (aConfigProps[i].Name == "ScriptConfiguration"))
        {
            uno::Reference< beans::XPropertySet > xImportInfo = getImportInfo();
            if (xImportInfo.is())
            {
                uno::Reference< beans::XPropertySetInfo > xPropertySetInfo = xImportInfo->getPropertySetInfo();
                if (xPropertySetInfo.is() && xPropertySetInfo->hasPropertyByName(aConfigProps[i].Name))
                    xImportInfo->setPropertyValue( aConfigProps[i].Name, aConfigProps[i].Value );
            }
        }
        if (aConfigProps[i].Name != "LinkUpdateMode")
        {
            aFilteredProps[nFilteredPropsLen++] = aConfigProps[i];
        }
    }
    aFilteredProps.realloc(nFilteredPropsLen);
    uno::Reference <uno::XInterface> xInterface = xMultiServiceFactory->createInstance("com.sun.star.comp.SpreadsheetSettings");
    uno::Reference <beans::XPropertySet> xProperties(xInterface, uno::UNO_QUERY);
    if (xProperties.is())
        SvXMLUnitConverter::convertPropertySet(xProperties, aFilteredProps);
}

sal_Int32 ScXMLImport::SetCurrencySymbol(const sal_Int32 nKey, const OUString& rCurrency)
{
    uno::Reference <util::XNumberFormatsSupplier> xNumberFormatsSupplier(GetNumberFormatsSupplier());
    if (xNumberFormatsSupplier.is())
    {
        uno::Reference <util::XNumberFormats> xLocalNumberFormats(xNumberFormatsSupplier->getNumberFormats());
        if (xLocalNumberFormats.is())
        {
            OUString sFormatString;
            try
            {
                uno::Reference <beans::XPropertySet> xProperties(xLocalNumberFormats->getByKey(nKey));
                if (xProperties.is())
                {
                    lang::Locale aLocale;
                    if (GetDocument() && (xProperties->getPropertyValue(gsLocale) >>= aLocale))
                    {
                        {
                            ScXMLImport::MutexGuard aGuard(*this);
                            LocaleDataWrapper aLocaleData( comphelper::getProcessComponentContext(), LanguageTag( aLocale) );
                            OUStringBuffer aBuffer(15);
                            aBuffer.append("#");
                            aBuffer.append( aLocaleData.getNumThousandSep() );
                            aBuffer.append("##0");
                            aBuffer.append( aLocaleData.getNumDecimalSep() );
                            aBuffer.append("00 [$");
                            aBuffer.append(rCurrency);
                            aBuffer.append("]");
                            sFormatString = aBuffer.makeStringAndClear();
                        }
                        sal_Int32 nNewKey = xLocalNumberFormats->queryKey(sFormatString, aLocale, true);
                        if (nNewKey == -1)
                            nNewKey = xLocalNumberFormats->addNew(sFormatString, aLocale);
                        return nNewKey;
                    }
                }
            }
            catch ( const util::MalformedNumberFormatException& rException )
            {
                OUString sErrorMessage ="Error in Formatstring " +
                    sFormatString + " at position " +
                    OUString::number(rException.CheckPos);
                uno::Sequence<OUString> aSeq { sErrorMessage };
                uno::Reference<xml::sax::XLocator> xLocator;
                SetError(XMLERROR_API | XMLERROR_FLAG_ERROR, aSeq, rException.Message, xLocator);
            }
        }
    }
    return nKey;
}

bool ScXMLImport::IsCurrencySymbol(const sal_Int32 nNumberFormat, const OUString& sCurrentCurrency, const OUString& sBankSymbol)
{
    uno::Reference <util::XNumberFormatsSupplier> xNumberFormatsSupplier(GetNumberFormatsSupplier());
    if (xNumberFormatsSupplier.is())
    {
        uno::Reference <util::XNumberFormats> xLocalNumberFormats(xNumberFormatsSupplier->getNumberFormats());
        if (xLocalNumberFormats.is())
        {
            try
            {
                uno::Reference <beans::XPropertySet> xNumberPropertySet(xLocalNumberFormats->getByKey(nNumberFormat));
                if (xNumberPropertySet.is())
                {
                    OUString sTemp;
                    if ( xNumberPropertySet->getPropertyValue(SC_CURRENCYSYMBOL) >>= sTemp)
                    {
                        if (sCurrentCurrency == sTemp)
                            return true;
                        // A release that saved an unknown currency may have
                        // saved the currency symbol of the number format
                        // instead of an ISO code bank symbol. In another
                        // release we may have a match for that. In this case
                        // sCurrentCurrency is the ISO code obtained through
                        // XMLNumberFormatAttributesExportHelper::GetCellType()
                        // and sBankSymbol is the currency symbol.
                        if (sCurrentCurrency.getLength() == 3 && sBankSymbol == sTemp)
                            return true;
                        // #i61657# This may be a legacy currency symbol that changed in the meantime.
                        if (SvNumberFormatter::GetLegacyOnlyCurrencyEntry( sCurrentCurrency, sBankSymbol) != nullptr)
                            return true;
                        // In the rare case that sCurrentCurrency is not the
                        // currency symbol, but a matching ISO code
                        // abbreviation instead that was obtained through
                        // XMLNumberFormatAttributesExportHelper::GetCellType(),
                        // check with the number format's symbol. This happens,
                        // for example, in the es_BO locale, where a legacy
                        // B$,BOB matched B$->BOP, which leads to
                        // sCurrentCurrency being BOP, and the previous call
                        // with BOP,BOB didn't find an entry, but B$,BOB will.
                        return SvNumberFormatter::GetLegacyOnlyCurrencyEntry( sTemp, sBankSymbol) != nullptr;
                    }
                }
            }
            catch ( uno::Exception& )
            {
                OSL_FAIL("Numberformat not found");
            }
        }
    }
    return false;
}

void ScXMLImport::SetType(const uno::Reference <beans::XPropertySet>& rProperties,
                          sal_Int32& rNumberFormat,
                          const sal_Int16 nCellType,
                          const OUString& rCurrency)
{
    if (!mbImportStyles)
        return;

    if ((nCellType == util::NumberFormat::TEXT) || (nCellType == util::NumberFormat::UNDEFINED))
        return;

    if (rNumberFormat == -1)
        rProperties->getPropertyValue( gsNumberFormat ) >>= rNumberFormat;
    OSL_ENSURE(rNumberFormat != -1, "no NumberFormat");
    bool bIsStandard;
    // sCurrentCurrency may be the ISO code abbreviation if the currency
    // symbol matches such, or if no match found the symbol itself!
    OUString sCurrentCurrency;
    sal_Int32 nCurrentCellType(
        GetNumberFormatAttributesExportHelper()->GetCellType(
            rNumberFormat, sCurrentCurrency, bIsStandard) & ~util::NumberFormat::DEFINED);
    // If the (numeric) cell type (number, currency, date, time, boolean)
    // is different from the format type then for some combinations we may
    // have to apply a format, e.g. in case the generator deduced format
    // from type and did not apply a format but we don't keep a dedicated
    // type internally. Specifically this is necessary if the cell type is
    // not number but the format type is (i.e. General). Currency cells
    // need extra attention, see calls of ScXMLImport::IsCurrencySymbol()
    // and description within there and ScXMLImport::SetCurrencySymbol().
    if ((nCellType != nCurrentCellType) &&
            (nCellType != util::NumberFormat::NUMBER) &&
            (bIsStandard || (nCellType == util::NumberFormat::CURRENCY)))
    {
        if (!xNumberFormats.is())
        {
            uno::Reference <util::XNumberFormatsSupplier> xNumberFormatsSupplier(GetNumberFormatsSupplier());
            if (xNumberFormatsSupplier.is())
                xNumberFormats.set(xNumberFormatsSupplier->getNumberFormats());
        }
        if (xNumberFormats.is())
        {
            try
            {
                uno::Reference < beans::XPropertySet> xNumberFormatProperties(xNumberFormats->getByKey(rNumberFormat));
                if (xNumberFormatProperties.is())
                {
                    if (nCellType != util::NumberFormat::CURRENCY)
                    {
                        lang::Locale aLocale;
                        if ( xNumberFormatProperties->getPropertyValue(gsLocale) >>= aLocale )
                        {
                            if (!xNumberFormatTypes.is())
                                xNumberFormatTypes.set(uno::Reference <util::XNumberFormatTypes>(xNumberFormats, uno::UNO_QUERY));
                            rProperties->setPropertyValue( gsNumberFormat, uno::makeAny(xNumberFormatTypes->getStandardFormat(nCellType, aLocale)) );
                        }
                    }
                    else if (!rCurrency.isEmpty() && !sCurrentCurrency.isEmpty())
                    {
                        if (sCurrentCurrency != rCurrency)
                            if (!IsCurrencySymbol(rNumberFormat, sCurrentCurrency, rCurrency))
                                rProperties->setPropertyValue( gsNumberFormat, uno::makeAny(SetCurrencySymbol(rNumberFormat, rCurrency)));
                    }
                }
            }
            catch ( uno::Exception& )
            {
                OSL_FAIL("Numberformat not found");
            }
        }
    }
    else
    {
        if ((nCellType == util::NumberFormat::CURRENCY) && !rCurrency.isEmpty() && !sCurrentCurrency.isEmpty() &&
            sCurrentCurrency != rCurrency && !IsCurrencySymbol(rNumberFormat, sCurrentCurrency, rCurrency))
            rProperties->setPropertyValue( gsNumberFormat, uno::makeAny(SetCurrencySymbol(rNumberFormat, rCurrency)));
    }
}

void ScXMLImport::SetStyleToRanges()
{
    if (!mbImportStyles)
        return;

    if (!sPrevStyleName.isEmpty())
    {
        uno::Reference <beans::XPropertySet> xProperties (xSheetCellRanges, uno::UNO_QUERY);
        if (xProperties.is())
        {
            XMLTableStylesContext *pStyles(static_cast<XMLTableStylesContext *>(GetAutoStyles()));
            XMLTableStyleContext* pStyle = nullptr;
            if ( pStyles )
                pStyle = const_cast<XMLTableStyleContext*>(static_cast<const XMLTableStyleContext *>(pStyles->FindStyleChildContext(
                        XmlStyleFamily::TABLE_CELL, sPrevStyleName, true)));
            if (pStyle)
            {
                pStyle->FillPropertySet(xProperties);
                // here needs to be the cond format import method
                sal_Int32 nNumberFormat(pStyle->GetNumberFormat());
                SetType(xProperties, nNumberFormat, nPrevCellType, sPrevCurrency);

                css::uno::Any aAny = xProperties->getPropertyValue("FormatID");
                sal_uInt64 nKey = 0;
                if ((aAny >>= nKey) && nKey)
                {
                    ScFormatSaveData* pFormatSaveData = comphelper::getUnoTunnelImplementation<ScModelObj>(GetModel())->GetFormatSaveData();
                    pFormatSaveData->maIDToName.insert(std::pair<sal_uInt64, OUString>(nKey, sPrevStyleName));
                }

                // store first cell of first range for each style, once per sheet
                uno::Sequence<table::CellRangeAddress> aAddresses(xSheetCellRanges->getRangeAddresses());
                pStyle->ApplyCondFormat(aAddresses);
                if ( aAddresses.hasElements() )
                {
                    const table::CellRangeAddress& rRange = aAddresses[0];
                    if ( rRange.Sheet != pStyle->GetLastSheet() )
                    {
                        ScSheetSaveData* pSheetData = comphelper::getUnoTunnelImplementation<ScModelObj>(GetModel())->GetSheetSaveData();
                        pSheetData->AddCellStyle( sPrevStyleName,
                            ScAddress( static_cast<SCCOL>(rRange.StartColumn), static_cast<SCROW>(rRange.StartRow), static_cast<SCTAB>(rRange.Sheet) ) );
                        pStyle->SetLastSheet(rRange.Sheet);
                    }
                }
            }
            else
            {
                xProperties->setPropertyValue(gsCellStyle, uno::makeAny(GetStyleDisplayName( XmlStyleFamily::TABLE_CELL, sPrevStyleName )));
                sal_Int32 nNumberFormat(GetStyleNumberFormats()->GetStyleNumberFormat(sPrevStyleName));
                bool bInsert(nNumberFormat == -1);
                SetType(xProperties, nNumberFormat, nPrevCellType, sPrevCurrency);
                if (bInsert)
                    GetStyleNumberFormats()->AddStyleNumberFormat(sPrevStyleName, nNumberFormat);
            }
        }
    }
    if (GetModel().is())
    {
        uno::Reference <lang::XMultiServiceFactory> xMultiServiceFactory(GetModel(), uno::UNO_QUERY);
        if (xMultiServiceFactory.is())
            xSheetCellRanges.set(uno::Reference <sheet::XSheetCellRangeContainer>(
            xMultiServiceFactory->createInstance("com.sun.star.sheet.SheetCellRanges"),
            uno::UNO_QUERY));
    }
    OSL_ENSURE(xSheetCellRanges.is(), "didn't get SheetCellRanges");
}

void ScXMLImport::SetStyleToRanges(const ScRangeList& rRanges, const OUString* pStyleName,
                                  const sal_Int16 nCellType, const OUString* pCurrency)
{
    if (!mbImportStyles)
        return;

    if (sPrevStyleName.isEmpty())
    {
        nPrevCellType = nCellType;
        if (pStyleName)
            sPrevStyleName = *pStyleName;
        if (pCurrency)
            sPrevCurrency = *pCurrency;
        else if (!sPrevCurrency.isEmpty())
            sPrevCurrency.clear();
    }
    else if ((nCellType != nPrevCellType) ||
        ((pStyleName && *pStyleName != sPrevStyleName) ||
        (!pStyleName && !sPrevStyleName.isEmpty())) ||
        ((pCurrency && *pCurrency != sPrevCurrency) ||
        (!pCurrency && !sPrevCurrency.isEmpty())))
    {
        SetStyleToRanges();
        nPrevCellType = nCellType;
        if (pStyleName)
            sPrevStyleName = *pStyleName;
        else if(!sPrevStyleName.isEmpty())
            sPrevStyleName.clear();
        if (pCurrency)
            sPrevCurrency = *pCurrency;
        else if(!sPrevCurrency.isEmpty())
            sPrevCurrency.clear();
    }

    if (!xSheetCellRanges.is() && GetModel().is())
    {
        uno::Reference <lang::XMultiServiceFactory> xMultiServiceFactory(GetModel(), uno::UNO_QUERY);
        if (xMultiServiceFactory.is())
            xSheetCellRanges.set(uno::Reference <sheet::XSheetCellRangeContainer>(xMultiServiceFactory->createInstance("com.sun.star.sheet.SheetCellRanges"), uno::UNO_QUERY));
        OSL_ENSURE(xSheetCellRanges.is(), "didn't get SheetCellRanges");

    }
    static_cast<ScCellRangesObj*>(xSheetCellRanges.get())->SetNewRanges(rRanges);
}

bool ScXMLImport::SetNullDateOnUnitConverter()
{
    if (!bNullDateSetted)
        bNullDateSetted = GetMM100UnitConverter().setNullDate(GetModel());
    OSL_ENSURE(bNullDateSetted, "could not set the null date");
    return bNullDateSetted;
}

XMLNumberFormatAttributesExportHelper* ScXMLImport::GetNumberFormatAttributesExportHelper()
{
    if (!pNumberFormatAttributesExportHelper)
        pNumberFormatAttributesExportHelper.reset(new XMLNumberFormatAttributesExportHelper(GetNumberFormatsSupplier()));
    return pNumberFormatAttributesExportHelper.get();
}

ScMyStyleNumberFormats* ScXMLImport::GetStyleNumberFormats()
{
    if (!pStyleNumberFormats)
        pStyleNumberFormats.reset(new ScMyStyleNumberFormats);
    return pStyleNumberFormats.get();
}

void ScXMLImport::SetStylesToRangesFinished()
{
    SetStyleToRanges();
    sPrevStyleName.clear();
}

// XImporter
void SAL_CALL ScXMLImport::setTargetDocument( const css::uno::Reference< css::lang::XComponent >& xDoc )
{
    ScXMLImport::MutexGuard aGuard(*this);
    SvXMLImport::setTargetDocument( xDoc );

    uno::Reference<frame::XModel> xModel(xDoc, uno::UNO_QUERY);
    pDoc = ScXMLConverter::GetScDocument( xModel );
    OSL_ENSURE( pDoc, "ScXMLImport::setTargetDocument - no ScDocument!" );
    if (!pDoc)
        throw lang::IllegalArgumentException();

    mpDocImport.reset(new ScDocumentImport(*pDoc));
    mpComp.reset(new ScCompiler(*pDoc, ScAddress(), formula::FormulaGrammar::GRAM_ODFF));

    uno::Reference<document::XActionLockable> xActionLockable(xDoc, uno::UNO_QUERY);
    if (xActionLockable.is())
        xActionLockable->addActionLock();
}

// css::xml::sax::XDocumentHandler
void SAL_CALL ScXMLImport::startDocument()
{
    ScXMLImport::MutexGuard aGuard(*this);
    SvXMLImport::startDocument();
    if (pDoc && !pDoc->IsImportingXML())
    {
        comphelper::getUnoTunnelImplementation<ScModelObj>(GetModel())->BeforeXMLLoading();
        bSelfImportingXMLSet = true;
    }

    // if content and styles are loaded with separate imports,
    // set bLatinDefaultStyle flag at the start of the content import
    SvXMLImportFlags nFlags = getImportFlags();
    if ( ( nFlags & SvXMLImportFlags::CONTENT ) && !( nFlags & SvXMLImportFlags::STYLES ) )
        ExamineDefaultStyle();

    if (getImportFlags() & SvXMLImportFlags::CONTENT)
    {
        if (GetModel().is())
        {
            // store initial namespaces, to find the ones that were added from the file later
            ScSheetSaveData* pSheetData = comphelper::getUnoTunnelImplementation<ScModelObj>(GetModel())->GetSheetSaveData();
            const SvXMLNamespaceMap& rNamespaces = GetNamespaceMap();
            pSheetData->StoreInitialNamespaces(rNamespaces);
        }
    }

    uno::Reference< beans::XPropertySet > const xImportInfo( getImportInfo() );
    uno::Reference< beans::XPropertySetInfo > const xPropertySetInfo(
            xImportInfo.is() ? xImportInfo->getPropertySetInfo() : nullptr);
    if (xPropertySetInfo.is())
    {
        OUString const sOrganizerMode(
            "OrganizerMode");
        if (xPropertySetInfo->hasPropertyByName(sOrganizerMode))
        {
            bool bStyleOnly(false);
            if (xImportInfo->getPropertyValue(sOrganizerMode) >>= bStyleOnly)
            {
                bLoadDoc = !bStyleOnly;
            }
        }
    }

    UnlockSolarMutex();
}

sal_Int32 ScXMLImport::GetRangeType(const OUString& sRangeType)
{
    sal_Int32 nRangeType(0);
    OUStringBuffer sBuffer;
    sal_Int32 i = 0;
    while (i <= sRangeType.getLength())
    {
        if ((i == sRangeType.getLength()) || (sRangeType[i] == ' '))
        {
            OUString sTemp = sBuffer.makeStringAndClear();
            if (sTemp == "repeat-column")
                nRangeType |= sheet::NamedRangeFlag::COLUMN_HEADER;
            else if (sTemp == SC_REPEAT_ROW)
                nRangeType |= sheet::NamedRangeFlag::ROW_HEADER;
            else if (sTemp == SC_FILTER)
                nRangeType |= sheet::NamedRangeFlag::FILTER_CRITERIA;
            else if (sTemp == SC_PRINT_RANGE)
                nRangeType |= sheet::NamedRangeFlag::PRINT_AREA;
        }
        else if (i < sRangeType.getLength())
            sBuffer.append(sRangeType[i]);
        ++i;
    }
    return nRangeType;
}

void ScXMLImport::SetLabelRanges()
{
    if (!pMyLabelRanges)
        return;

    uno::Reference <beans::XPropertySet> xPropertySet (GetModel(), uno::UNO_QUERY);
    if (!xPropertySet.is())
        return;

    uno::Any aColAny = xPropertySet->getPropertyValue(SC_UNO_COLLABELRNG);
    uno::Any aRowAny = xPropertySet->getPropertyValue(SC_UNO_ROWLABELRNG);

    uno::Reference< sheet::XLabelRanges > xColRanges;
    uno::Reference< sheet::XLabelRanges > xRowRanges;

    if ( !(( aColAny >>= xColRanges ) && ( aRowAny >>= xRowRanges )) )
        return;

    table::CellRangeAddress aLabelRange;
    table::CellRangeAddress aDataRange;

    for (const auto& rxLabelRange : *pMyLabelRanges)
    {
        sal_Int32 nOffset1(0);
        sal_Int32 nOffset2(0);
        FormulaGrammar::AddressConvention eConv = FormulaGrammar::CONV_OOO;

        assert(pDoc);
        if (ScRangeStringConverter::GetRangeFromString( aLabelRange, rxLabelRange->sLabelRangeStr, *pDoc, eConv, nOffset1 ) &&
            ScRangeStringConverter::GetRangeFromString( aDataRange, rxLabelRange->sDataRangeStr, *pDoc, eConv, nOffset2 ))
        {
            if ( rxLabelRange->bColumnOrientation )
                xColRanges->addNew( aLabelRange, aDataRange );
            else
                xRowRanges->addNew( aLabelRange, aDataRange );
        }
    }

    pMyLabelRanges->clear();
}

namespace {

class RangeNameInserter
{
    ScDocument&  mrDoc;
    ScRangeName& mrRangeName;

public:
    RangeNameInserter(ScDocument& rDoc, ScRangeName& rRangeName) :
        mrDoc(rDoc), mrRangeName(rRangeName) {}

    void operator() (const std::unique_ptr<ScMyNamedExpression>& p) const
    {
        using namespace formula;

        const OUString& aType = p->sRangeType;
        sal_uInt32 nUnoType = ScXMLImport::GetRangeType(aType);

        ScRangeData::Type nNewType = ScRangeData::Type::Name;
        if ( nUnoType & sheet::NamedRangeFlag::FILTER_CRITERIA )    nNewType |= ScRangeData::Type::Criteria;
        if ( nUnoType & sheet::NamedRangeFlag::PRINT_AREA )         nNewType |= ScRangeData::Type::PrintArea;
        if ( nUnoType & sheet::NamedRangeFlag::COLUMN_HEADER )      nNewType |= ScRangeData::Type::ColHeader;
        if ( nUnoType & sheet::NamedRangeFlag::ROW_HEADER )         nNewType |= ScRangeData::Type::RowHeader;

        // Insert a new name.
        ScAddress aPos;
        sal_Int32 nOffset = 0;
        bool bSuccess = ScRangeStringConverter::GetAddressFromString(
            aPos, p->sBaseCellAddress, mrDoc, FormulaGrammar::CONV_OOO, nOffset);

        if (bSuccess)
        {
            OUString aContent = p->sContent;
            if (!p->bIsExpression)
                ScXMLConverter::ConvertCellRangeAddress(aContent);

            ScRangeData* pData = new ScRangeData(
                mrDoc, p->sName, aContent, aPos, nNewType, p->eGrammar);
            mrRangeName.insert(pData);
        }
    }
};

}

void ScXMLImport::SetNamedRanges()
{
    if (!m_pMyNamedExpressions)
        return;

    if (!pDoc)
        return;

    // Insert the namedRanges
    ScRangeName* pRangeNames = pDoc->GetRangeName();
    ::std::for_each(m_pMyNamedExpressions->begin(), m_pMyNamedExpressions->end(), RangeNameInserter(*pDoc, *pRangeNames));
}

void ScXMLImport::SetSheetNamedRanges()
{
    if (!pDoc)
        return;

    for (auto const& itr : m_SheetNamedExpressions)
    {
        const SCTAB nTab = itr.first;
        ScRangeName* pRangeNames = pDoc->GetRangeName(nTab);
        if (!pRangeNames)
            continue;

        const ScMyNamedExpressions& rNames = *itr.second;
        ::std::for_each(rNames.begin(), rNames.end(), RangeNameInserter(*pDoc, *pRangeNames));
    }
}

void ScXMLImport::SetStringRefSyntaxIfMissing()
{
    if (!pDoc)
        return;

    ScCalcConfig aCalcConfig = pDoc->GetCalcConfig();

    // Has any string ref syntax been imported?
    // If not, we need to take action
    if ( !aCalcConfig.mbHasStringRefSyntax )
    {
        aCalcConfig.meStringRefAddressSyntax = formula::FormulaGrammar::CONV_A1_XL_A1;
        pDoc->SetCalcConfig(aCalcConfig);
    }
}

void SAL_CALL ScXMLImport::endDocument()
{
    ScXMLImport::MutexGuard aGuard(*this);
    if (getImportFlags() & SvXMLImportFlags::CONTENT)
    {
        if (GetModel().is())
        {
            mpDocImport->finalize();

            uno::Reference<document::XViewDataSupplier> xViewDataSupplier(GetModel(), uno::UNO_QUERY);
            if (xViewDataSupplier.is())
            {
                uno::Reference<container::XIndexAccess> xIndexAccess(xViewDataSupplier->getViewData());
                if (xIndexAccess.is() && xIndexAccess->getCount() > 0)
                {
                    uno::Sequence< beans::PropertyValue > aSeq;
                    if (xIndexAccess->getByIndex(0) >>= aSeq)
                    {
                        for (const auto& rProp : std::as_const(aSeq))
                        {
                            OUString sName(rProp.Name);
                            if (sName == SC_ACTIVETABLE)
                            {
                                OUString sTabName;
                                if(rProp.Value >>= sTabName)
                                {
                                    SCTAB nTab(0);
                                    if (pDoc->GetTable(sTabName, nTab))
                                    {
                                        pDoc->SetVisibleTab(nTab);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            SetLabelRanges();
            SetNamedRanges();
            SetSheetNamedRanges();
            SetStringRefSyntaxIfMissing();
            if (mpPivotSources)
                // Process pivot table sources after the named ranges have been set.
                mpPivotSources->process();
        }
        GetProgressBarHelper()->End();  // make room for subsequent SfxProgressBars
        if (pDoc)
        {
            pDoc->CompileXML();

            // After CompileXML, links must be completely changed to the new URLs.
            // Otherwise, hasExternalFile for API wouldn't work (#i116940#),
            // and typing a new formula would create a second link with the same "real" file name.
            if (pDoc->HasExternalRefManager())
                pDoc->GetExternalRefManager()->updateAbsAfterLoad();
        }

        // If the stream contains cells outside of the current limits, the styles can't be re-created,
        // so stream copying is disabled then.
        if (pDoc && GetModel().is() && !pDoc->HasRangeOverflow())
        {
            // set "valid stream" flags after loading (before UpdateRowHeights, so changed formula results
            // in UpdateRowHeights can already clear the flags again)
            ScSheetSaveData* pSheetData = comphelper::getUnoTunnelImplementation<ScModelObj>(GetModel())->GetSheetSaveData();

            SCTAB nTabCount = pDoc->GetTableCount();
            for (SCTAB nTab=0; nTab<nTabCount; ++nTab)
            {
                pDoc->SetDrawPageSize(nTab);
                if (!pSheetData->IsSheetBlocked( nTab ))
                    pDoc->SetStreamValid( nTab, true );
            }
        }

        // There are rows with optimal height which need to be updated
        if (pDoc && !maRecalcRowRanges.empty())
        {
            bool bLockHeight = pDoc->IsAdjustHeightLocked();
            if (bLockHeight)
            {
                pDoc->UnlockAdjustHeight();
            }

            ScSizeDeviceProvider aProv(static_cast<ScDocShell*>(pDoc->GetDocumentShell()));
            ScDocRowHeightUpdater aUpdater(*pDoc, aProv.GetDevice(), aProv.GetPPTX(), aProv.GetPPTY(), &maRecalcRowRanges);
            aUpdater.update();

            if (bLockHeight)
            {
                pDoc->LockAdjustHeight();
            }
        }

        aTables.FixupOLEs();
    }
    if (GetModel().is())
    {
        uno::Reference<document::XActionLockable> xActionLockable(GetModel(), uno::UNO_QUERY);
        if (xActionLockable.is())
            xActionLockable->removeActionLock();
    }
    SvXMLImport::endDocument();

    if (pDoc)
    {
        pDoc->BroadcastUno(SfxHint(SfxHintId::ScClearCache));
    }

    if(pDoc && bSelfImportingXMLSet)
        comphelper::getUnoTunnelImplementation<ScModelObj>(GetModel())->AfterXMLLoading();
}

// XEventListener
void ScXMLImport::DisposingModel()
{
    SvXMLImport::DisposingModel();
    pDoc = nullptr;
}

ScXMLImport::MutexGuard::MutexGuard(ScXMLImport& rImport) :
    mrImport(rImport)
{
    mrImport.LockSolarMutex();
}

ScXMLImport::MutexGuard::~MutexGuard()
{
    mrImport.UnlockSolarMutex();
}

void ScXMLImport::LockSolarMutex()
{
    // #i62677# When called from DocShell/Wrapper, the SolarMutex is already locked,
    // so there's no need to allocate (and later delete) the SolarMutexGuard.
    if (!mbLockSolarMutex)
    {
        DBG_TESTSOLARMUTEX();
        return;
    }

    if (nSolarMutexLocked == 0)
    {
        OSL_ENSURE(!pSolarMutexGuard, "Solar Mutex is locked");
        pSolarMutexGuard.reset(new SolarMutexGuard());
    }
    ++nSolarMutexLocked;
}

void ScXMLImport::UnlockSolarMutex()
{
    if (nSolarMutexLocked > 0)
    {
        nSolarMutexLocked--;
        if (nSolarMutexLocked == 0)
        {
            OSL_ENSURE(pSolarMutexGuard, "Solar Mutex is always unlocked");
            pSolarMutexGuard.reset();
        }
    }
}

sal_Int32 ScXMLImport::GetByteOffset() const
{
    sal_Int32 nOffset = -1;
    uno::Reference<xml::sax::XLocator> xLocator = GetLocator();
    uno::Reference<io::XSeekable> xSeek( xLocator, uno::UNO_QUERY );        //! should use different interface
    if ( xSeek.is() )
        nOffset = static_cast<sal_Int32>(xSeek->getPosition());
    return nOffset;
}

void ScXMLImport::SetRangeOverflowType(ErrCode nType)
{
    //  #i31130# Overflow is stored in the document, because the ScXMLImport object
    //  isn't available in ScXMLImportWrapper::ImportFromComponent when using the
    //  OOo->Oasis transformation.

    if ( pDoc )
        pDoc->SetRangeOverflowType( nType );
}

void ScXMLImport::ProgressBarIncrement()
{
    nProgressCount++;
    if (nProgressCount > 100)
    {
        GetProgressBarHelper()->Increment(nProgressCount);
        nProgressCount = 0;
    }
}

void ScXMLImport::ExtractFormulaNamespaceGrammar(
        OUString& rFormula, OUString& rFormulaNmsp, FormulaGrammar::Grammar& reGrammar,
        const OUString& rAttrValue, bool bRestrictToExternalNmsp ) const
{
    // parse the attribute value, extract namespace ID, literal namespace, and formula string
    rFormulaNmsp.clear();
    sal_uInt16 nNsId = GetNamespaceMap().GetKeyByQName(rAttrValue, nullptr, &rFormula, &rFormulaNmsp, SvXMLNamespaceMap::QNameMode::AttrValue);

    // check if we have an ODF formula namespace
    if( !bRestrictToExternalNmsp ) switch( nNsId )
    {
        case XML_NAMESPACE_OOOC:
            rFormulaNmsp.clear();  // remove namespace string for built-in grammar
            reGrammar = FormulaGrammar::GRAM_PODF;
            return;
        case XML_NAMESPACE_OF:
            rFormulaNmsp.clear();  // remove namespace string for built-in grammar
            reGrammar = FormulaGrammar::GRAM_ODFF;
            return;
    }

    /*  Find default grammar for formulas without namespace. There may be
        documents in the wild that stored no namespace in ODF 1.0/1.1. Use
        GRAM_PODF then (old style ODF 1.0/1.1 formulas). The default for ODF
        1.2 and later without namespace is GRAM_ODFF (OpenFormula). */
    FormulaGrammar::Grammar eDefaultGrammar =
        (GetDocument()->GetStorageGrammar() == FormulaGrammar::GRAM_PODF) ?
            FormulaGrammar::GRAM_PODF : FormulaGrammar::GRAM_ODFF;

    /*  Check if we have no namespace at all. The value XML_NAMESPACE_NONE
        indicates that there is no colon. If the first character of the
        attribute value is the equality sign, the value XML_NAMESPACE_UNKNOWN
        indicates that there is a colon somewhere in the formula string. */
    if( (nNsId == XML_NAMESPACE_NONE) || ((nNsId == XML_NAMESPACE_UNKNOWN) && (rAttrValue.toChar() == '=')) )
    {
        rFormula = rAttrValue;          // return entire string as formula
        reGrammar = eDefaultGrammar;
        return;
    }

    /*  Check if a namespace URL could be resolved from the attribute value.
        Use that namespace only, if the Calc document knows an associated
        external formula parser. This prevents that the range operator in
        conjunction with defined names is confused as namespaces prefix, e.g.
        in the expression 'table:A1' where 'table' is a named reference. */
    if( ((nNsId & XML_NAMESPACE_UNKNOWN_FLAG) != 0) && !rFormulaNmsp.isEmpty() &&
        GetDocument()->GetFormulaParserPool().hasFormulaParser( rFormulaNmsp ) )
    {
        reGrammar = FormulaGrammar::GRAM_EXTERNAL;
        return;
    }

    /*  All attempts failed (e.g. no namespace and no leading equality sign, or
        an invalid namespace prefix), continue with the entire attribute value. */
    rFormula = rAttrValue;
    rFormulaNmsp.clear();  // remove any namespace string
    reGrammar = eDefaultGrammar;
}

FormulaError ScXMLImport::GetFormulaErrorConstant( const OUString& rStr ) const
{
    if (!mpComp)
        return FormulaError::NONE;

    return mpComp->GetErrorConstant(rStr);
}

ScEditEngineDefaulter* ScXMLImport::GetEditEngine()
{
    if (!mpEditEngine)
    {
        mpEditEngine.reset(new ScEditEngineDefaulter(pDoc->GetEnginePool()));
        mpEditEngine->SetRefMapMode(MapMode(MapUnit::Map100thMM));
        mpEditEngine->SetEditTextObjectPool(pDoc->GetEditPool());
        mpEditEngine->SetUpdateMode(false);
        mpEditEngine->EnableUndo(false);
        mpEditEngine->SetControlWord(mpEditEngine->GetControlWord() & ~EEControlBits::ALLOWBIGOBJS);
    }
    return mpEditEngine.get();
}

const ScXMLEditAttributeMap& ScXMLImport::GetEditAttributeMap() const
{
    if (!mpEditAttrMap)
        mpEditAttrMap.reset(new ScXMLEditAttributeMap);
    return *mpEditAttrMap;
}

void ScXMLImport::NotifyEmbeddedFontRead()
{
    if (pDoc)
        pDoc->SetEmbedFonts(true);
}

ScMyImpDetectiveOpArray* ScXMLImport::GetDetectiveOpArray()
{
    if (!pDetectiveOpArray)
        pDetectiveOpArray.reset(new ScMyImpDetectiveOpArray());
    return pDetectiveOpArray.get();
}

extern "C" SAL_DLLPUBLIC_EXPORT bool TestImportFODS(SvStream &rStream)
{
    ScDLL::Init();

    SfxObjectShellLock xDocSh(new ScDocShell);
    xDocSh->DoInitNew();
    uno::Reference<frame::XModel> xModel(xDocSh->GetModel());

    uno::Reference<lang::XMultiServiceFactory> xMultiServiceFactory(comphelper::getProcessServiceFactory());
    uno::Reference<io::XInputStream> xStream(new ::utl::OSeekableInputStreamWrapper(rStream));
    uno::Reference<uno::XInterface> xInterface(xMultiServiceFactory->createInstance("com.sun.star.comp.Writer.XmlFilterAdaptor"), uno::UNO_SET_THROW);

    css::uno::Sequence<OUString> aUserData(7);
    aUserData[0] = "com.sun.star.comp.filter.OdfFlatXml";
    aUserData[2] = "com.sun.star.comp.Calc.XMLOasisImporter";
    aUserData[3] = "com.sun.star.comp.Calc.XMLOasisExporter";
    aUserData[6] = "true";
    uno::Sequence<beans::PropertyValue> aAdaptorArgs(comphelper::InitPropertySequence(
    {
        { "UserData", uno::Any(aUserData) },
    }));
    css::uno::Sequence<uno::Any> aOuterArgs(1);
    aOuterArgs[0] <<= aAdaptorArgs;

    uno::Reference<lang::XInitialization> xInit(xInterface, uno::UNO_QUERY_THROW);
    xInit->initialize(aOuterArgs);

    uno::Reference<document::XImporter> xImporter(xInterface, uno::UNO_QUERY_THROW);
    uno::Sequence<beans::PropertyValue> aArgs(comphelper::InitPropertySequence(
    {
        { "InputStream", uno::Any(xStream) },
        { "URL", uno::Any(OUString("private:stream")) },
    }));
    xImporter->setTargetDocument(xModel);

    uno::Reference<document::XFilter> xFilter(xInterface, uno::UNO_QUERY_THROW);
    //SetLoading hack because the document properties will be re-initted
    //by the xml filter and during the init, while it's considered uninitialized,
    //setting a property will inform the document it's modified, which attempts
    //to update the properties, which throws cause the properties are uninitialized
    xDocSh->SetLoading(SfxLoadedFlags::NONE);
    bool ret = xFilter->filter(aArgs);
    xDocSh->SetLoading(SfxLoadedFlags::ALL);

    xDocSh->DoClose();

    return ret;
}

extern "C" SAL_DLLPUBLIC_EXPORT bool TestImportXLSX(SvStream &rStream)
{
    ScDLL::Init();

    SfxObjectShellLock xDocSh(new ScDocShell);
    xDocSh->DoInitNew();
    uno::Reference<frame::XModel> xModel(xDocSh->GetModel());

    uno::Reference<lang::XMultiServiceFactory> xMultiServiceFactory(comphelper::getProcessServiceFactory());
    uno::Reference<io::XInputStream> xStream(new utl::OSeekableInputStreamWrapper(rStream));

    uno::Reference<document::XFilter> xFilter(xMultiServiceFactory->createInstance("com.sun.star.comp.oox.xls.ExcelFilter"), uno::UNO_QUERY_THROW);

    uno::Reference<document::XImporter> xImporter(xFilter, uno::UNO_QUERY_THROW);
    uno::Sequence<beans::PropertyValue> aArgs(comphelper::InitPropertySequence(
    {
        { "InputStream", uno::makeAny(xStream) },
        { "InputMode", uno::makeAny(true) },
    }));
    xImporter->setTargetDocument(xModel);

    //SetLoading hack because the document properties will be re-initted
    //by the xml filter and during the init, while it's considered uninitialized,
    //setting a property will inform the document it's modified, which attempts
    //to update the properties, which throws cause the properties are uninitialized
    xDocSh->SetLoading(SfxLoadedFlags::NONE);
    bool ret = false;
    try
    {
        ret = xFilter->filter(aArgs);
    }
    catch (const css::io::IOException&)
    {
    }
    catch (const css::lang::WrappedTargetRuntimeException&)
    {
    }
    xDocSh->SetLoading(SfxLoadedFlags::ALL);

    xDocSh->DoClose();

    return ret;
}

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