summaryrefslogtreecommitdiff
path: root/filter/source/config/cache/filtercache.cxx
blob: 29c7174915884988a3ac099ddf521b9771f470d0 (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
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
/* -*- 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 <memory>
#include "filtercache.hxx"
#include "constant.hxx"
#include "cacheupdatelistener.hxx"

/*TODO see using below ... */
#define AS_ENABLE_FILTER_UINAMES

#include <com/sun/star/configuration/theDefaultProvider.hpp>
#include <com/sun/star/util/XChangesBatch.hpp>
#include <com/sun/star/container/XHierarchicalNameAccess.hpp>
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#include <com/sun/star/beans/NamedValue.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/beans/XPropertyAccess.hpp>
#include <com/sun/star/beans/XMultiPropertySet.hpp>
#include <com/sun/star/beans/XProperty.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/beans/Property.hpp>
#include <com/sun/star/beans/PropertyAttribute.hpp>
#include <com/sun/star/document/CorruptedFilterConfigurationException.hpp>
#include <comphelper/sequence.hxx>
#include <comphelper/processfactory.hxx>

#include <unotools/configmgr.hxx>
#include <unotools/configpaths.hxx>
#include <rtl/ustrbuf.hxx>
#include <rtl/uri.hxx>
#include <sal/log.hxx>
#include <tools/urlobj.hxx>
#include <tools/wldcrd.hxx>
#include <i18nlangtag/languagetag.hxx>

#include <officecfg/Setup.hxx>


namespace filter{
    namespace config{

FilterCache::FilterCache()
    : BaseLock    (                                        )
    , m_eFillState(E_CONTAINS_NOTHING                      )
{
    int i = 0;
    OUString sStandardProps[10];

    sStandardProps[i++] = PROPNAME_USERDATA;
    sStandardProps[i++] = PROPNAME_TEMPLATENAME;
    sStandardProps[i++] = PROPNAME_ENABLED;
    // E_READ_UPDATE only above
    sStandardProps[i++] = PROPNAME_TYPE;
    sStandardProps[i++] = PROPNAME_FILEFORMATVERSION;
    sStandardProps[i++] = PROPNAME_UICOMPONENT;
    sStandardProps[i++] = PROPNAME_FILTERSERVICE;
    sStandardProps[i++] = PROPNAME_DOCUMENTSERVICE;
    sStandardProps[i++] = PROPNAME_EXPORTEXTENSION;
    sStandardProps[i++] = PROPNAME_FLAGS; // must be last.
    assert(i == SAL_N_ELEMENTS(sStandardProps));

    // E_READ_NOTHING -> creative nothingness.
    m_aStandardProps[E_READ_STANDARD] =
        css::uno::Sequence< OUString >(sStandardProps + 3, 7);
    m_aStandardProps[E_READ_UPDATE] =
        css::uno::Sequence< OUString >(sStandardProps, 3);
    m_aStandardProps[E_READ_ALL] =
        css::uno::Sequence< OUString >(sStandardProps,
                                       SAL_N_ELEMENTS(sStandardProps));

    i = 0;
    OUString sTypeProps[7];
    sTypeProps[i++] = PROPNAME_MEDIATYPE;
    // E_READ_UPDATE only above
    sTypeProps[i++] = PROPNAME_PREFERREDFILTER;
    sTypeProps[i++] = PROPNAME_DETECTSERVICE;
    sTypeProps[i++] = PROPNAME_URLPATTERN;
    sTypeProps[i++] = PROPNAME_EXTENSIONS;
    sTypeProps[i++] = PROPNAME_PREFERRED;
    sTypeProps[i++] = PROPNAME_CLIPBOARDFORMAT;
    assert(i == SAL_N_ELEMENTS(sTypeProps));

    // E_READ_NOTHING -> more creative nothingness.
    m_aTypeProps[E_READ_STANDARD] =
        css::uno::Sequence< OUString >(sTypeProps + 1, 6);
    m_aTypeProps[E_READ_UPDATE] =
        css::uno::Sequence< OUString >(sTypeProps, 1);
    m_aTypeProps[E_READ_ALL] =
        css::uno::Sequence< OUString >(sTypeProps,
                                       SAL_N_ELEMENTS(sTypeProps));
}


FilterCache::~FilterCache()
{
    if (m_xTypesChglisteners.is())
        m_xTypesChglisteners->stopListening();
    if (m_xFiltersChgListener.is())
        m_xFiltersChgListener->stopListening();
}


std::unique_ptr<FilterCache> FilterCache::clone() const
{
    // SAFE -> ----------------------------------
    osl::MutexGuard aLock(m_aLock);

    auto pClone = std::make_unique<FilterCache>();

    // Don't copy the configuration access points here.
    // They will be created on demand inside the cloned instance,
    // if they are needed.

    pClone->m_lTypes                     = m_lTypes;
    pClone->m_lFilters                   = m_lFilters;
    pClone->m_lFrameLoaders              = m_lFrameLoaders;
    pClone->m_lContentHandlers           = m_lContentHandlers;
    pClone->m_lExtensions2Types          = m_lExtensions2Types;
    pClone->m_lURLPattern2Types          = m_lURLPattern2Types;

    pClone->m_sActLocale                 = m_sActLocale;

    pClone->m_eFillState                 = m_eFillState;

    pClone->m_lChangedTypes              = m_lChangedTypes;
    pClone->m_lChangedFilters            = m_lChangedFilters;
    pClone->m_lChangedFrameLoaders       = m_lChangedFrameLoaders;
    pClone->m_lChangedContentHandlers    = m_lChangedContentHandlers;

    return pClone;
    // <- SAFE ----------------------------------
}


void FilterCache::takeOver(const FilterCache& rClone)
{
    // SAFE -> ----------------------------------
    osl::MutexGuard aLock(m_aLock);

    // a)
    // Don't copy the configuration access points here!
    // We must use our own ones...

    // b)
    // Further we can ignore the uno service manager.
    // We should already have a valid instance.

    // c)
    // Take over only changed items!
    // Otherwise we risk the following scenario:
    // c1) clone_1 contains changed filters
    // c2) clone_2 container changed types
    // c3) clone_1 take over changed filters and unchanged types
    // c4) clone_2 take over unchanged filters(!) and changed types(!)
    // c5) c4 overwrites c3!

    if (!rClone.m_lChangedTypes.empty())
        m_lTypes = rClone.m_lTypes;
    if (!rClone.m_lChangedFilters.empty())
        m_lFilters = rClone.m_lFilters;
    if (!rClone.m_lChangedFrameLoaders.empty())
        m_lFrameLoaders = rClone.m_lFrameLoaders;
    if (!rClone.m_lChangedContentHandlers.empty())
        m_lContentHandlers = rClone.m_lContentHandlers;

    m_lChangedTypes.clear();
    m_lChangedFilters.clear();
    m_lChangedFrameLoaders.clear();
    m_lChangedContentHandlers.clear();

    m_sActLocale     = rClone.m_sActLocale;

    m_eFillState     = rClone.m_eFillState;

    // renew all dependencies and optimizations
    // Because we can't be sure, that changed filters on one clone
    // and changed types of another clone work together.
    // But here we can check against the later changes...
    impl_validateAndOptimize();
    // <- SAFE ----------------------------------
}

void FilterCache::load(EFillState eRequired)
{
    // SAFE -> ----------------------------------
    osl::MutexGuard aLock(m_aLock);

    // check if required fill state is already reached ...
    // There is nothing to do then.
    if ((m_eFillState & eRequired) == eRequired)
        return;

    // Otherwise load the missing items.


    // a) load some const values from configuration.
    //    These values are needed there for loading
    //    config items ...
    //    Further we load some std items from the
    //    configuration so we can try to load the first
    //    office document with a minimal set of values.
    if (m_eFillState == E_CONTAINS_NOTHING)
    {
        impl_getDirectCFGValue(CFGDIRECTKEY_OFFICELOCALE) >>= m_sActLocale;
        if (m_sActLocale.isEmpty())
        {
            m_sActLocale = DEFAULT_OFFICELOCALE;
        }

        // Support the old configuration support. Read it only one times during office runtime!
        impl_readOldFormat();
    }


    // b) If the required fill state was not reached
    //    but std values was already loaded ...
    //    we must load some further missing items.
    impl_load(eRequired);
    // <- SAFE
}

bool FilterCache::isFillState(FilterCache::EFillState eState) const
{
    // SAFE ->
    osl::MutexGuard aLock(m_aLock);
    return ((m_eFillState & eState) == eState);
    // <- SAFE
}


std::vector<OUString> FilterCache::getMatchingItemsByProps(      EItemType  eType  ,
                                                  const CacheItem& lIProps,
                                                  const CacheItem& lEProps) const
{
    // SAFE ->
    osl::MutexGuard aLock(m_aLock);

    // search for right list
    // An exception is thrown - "eType" is unknown.
    // => rList will be valid everytimes next line is reached.
    const CacheItemList& rList = impl_getItemList(eType);

    std::vector<OUString> lKeys;

    // search items, which provides all needed properties of set "lIProps"
    // but not of set "lEProps"!
    for (auto const& elem : rList)
    {
        if (
            (elem.second.haveProps(lIProps)    ) &&
            (elem.second.dontHaveProps(lEProps))
           )
        {
            lKeys.push_back(elem.first);
        }
    }

    return lKeys;
    // <- SAFE
}


bool FilterCache::hasItems(EItemType eType) const
{
    // SAFE ->
    osl::MutexGuard aLock(m_aLock);

    // search for right list
    // An exception is thrown - "eType" is unknown.
    // => rList will be valid everytimes next line is reached.
    const CacheItemList& rList = impl_getItemList(eType);

    return !rList.empty();
    // <- SAFE
}


std::vector<OUString> FilterCache::getItemNames(EItemType eType) const
{
    // SAFE ->
    osl::MutexGuard aLock(m_aLock);

    // search for right list
    // An exception is thrown - "eType" is unknown.
    // => rList will be valid everytimes next line is reached.
    const CacheItemList& rList = impl_getItemList(eType);

    std::vector<OUString> lKeys;
    for (auto const& elem : rList)
    {
        lKeys.push_back(elem.first);
    }
    return lKeys;
    // <- SAFE
}


bool FilterCache::hasItem(      EItemType        eType,
                              const OUString& sItem)
{
    // SAFE ->
    osl::MutexGuard aLock(m_aLock);

    // search for right list
    // An exception is thrown - "eType" is unknown.
    // => rList will be valid everytimes next line is reached.
    const CacheItemList& rList = impl_getItemList(eType);

    // if item could not be found - check if it can be loaded
    // from the underlying configuration layer. Might it was not already
    // loaded into this FilterCache object before.
    CacheItemList::const_iterator pIt = rList.find(sItem);
    if (pIt != rList.end())
        return true;

    try
    {
        impl_loadItemOnDemand(eType, sItem);
        // no exception => item could be loaded!
        return true;
    }
    catch(const css::container::NoSuchElementException&)
    {}

    return false;
    // <- SAFE
}


CacheItem FilterCache::getItem(      EItemType        eType,
                               const OUString& sItem)
{
    // SAFE ->
    osl::MutexGuard aLock(m_aLock);

    // search for right list
    // An exception is thrown if "eType" is unknown.
    // => rList will be valid everytimes next line is reached.
    CacheItemList& rList = impl_getItemList(eType);

    // check if item exists ...
    CacheItemList::iterator pIt = rList.find(sItem);
    if (pIt == rList.end())
    {
        // ... or load it on demand from the
        // underlying configuration layer.
        // Note: NoSuchElementException is thrown automatically here if
        // item could not be loaded!
        pIt = impl_loadItemOnDemand(eType, sItem);
    }

    /* Workaround for #137955#
       Draw types and filters are installed ... but draw was disabled during setup.
       We must suppress accessing these filters. Otherwise the office can crash.
       Solution for the next major release: do not install those filters !
     */
    if (eType == E_FILTER)
    {
        CacheItem& rFilter = pIt->second;
        OUString sDocService;
        rFilter[PROPNAME_DOCUMENTSERVICE] >>= sDocService;

        // In Standalone-Impress the module WriterWeb is not installed
        // but it is there to load help pages
        bool bIsHelpFilter = sItem == "writer_web_HTML_help";

        if ( !bIsHelpFilter && !impl_isModuleInstalled(sDocService) )
        {
            OUString sMsg("The requested filter '" + sItem +
                          "' exists ... but it should not; because the corresponding LibreOffice module was not installed.");
            throw css::container::NoSuchElementException(sMsg, css::uno::Reference< css::uno::XInterface >());
        }
    }

    return pIt->second;
    // <- SAFE
}


void FilterCache::removeItem(      EItemType        eType,
                             const OUString& sItem)
{
    // SAFE ->
    osl::MutexGuard aLock(m_aLock);

    // search for right list
    // An exception is thrown - "eType" is unknown.
    // => rList will be valid everytimes next line is reached.
    CacheItemList& rList = impl_getItemList(eType);

    CacheItemList::iterator pItem = rList.find(sItem);
    if (pItem == rList.end())
        pItem = impl_loadItemOnDemand(eType, sItem); // throws NoSuchELementException!
    rList.erase(pItem);

    impl_addItem2FlushList(eType, sItem);
}


void FilterCache::setItem(      EItemType        eType ,
                          const OUString& sItem ,
                          const CacheItem&       aValue)
{
    // SAFE ->
    osl::MutexGuard aLock(m_aLock);

    // search for right list
    // An exception is thrown - "eType" is unknown.
    // => rList will be valid everytimes next line is reached.
    CacheItemList& rList = impl_getItemList(eType);

    // name must be part of the property set too ... otherwise our
    // container query can't work correctly
    CacheItem aItem = aValue;
    aItem[PROPNAME_NAME] <<= sItem;
    aItem.validateUINames(m_sActLocale);

    // remove implicit properties as e.g. FINALIZED or MANDATORY
    // They can't be saved here and must be read on demand later, if they are needed.
    removeStatePropsFromItem(aItem);

    rList[sItem] = aItem;

    impl_addItem2FlushList(eType, sItem);
}


void FilterCache::refreshItem(      EItemType        eType,
                              const OUString& sItem)
{
    // SAFE ->
    osl::MutexGuard aLock(m_aLock);
    impl_loadItemOnDemand(eType, sItem);
}


void FilterCache::addStatePropsToItem(      EItemType        eType,
                                      const OUString& sItem,
                                            CacheItem&       rItem)
{
    // SAFE ->
    osl::MutexGuard aLock(m_aLock);

    // Note: Opening of the configuration layer throws some exceptions
    // if it failed. So we mustn't check any reference here...
    css::uno::Reference< css::container::XNameAccess > xPackage;
    css::uno::Reference< css::container::XNameAccess > xSet;
    switch(eType)
    {
        case E_TYPE :
            {
                xPackage.set(impl_openConfig(E_PROVIDER_TYPES), css::uno::UNO_QUERY_THROW);
                xPackage->getByName(CFGSET_TYPES) >>= xSet;
            }
            break;

        case E_FILTER :
            {
                xPackage.set(impl_openConfig(E_PROVIDER_FILTERS), css::uno::UNO_QUERY_THROW);
                xPackage->getByName(CFGSET_FILTERS) >>= xSet;
            }
            break;

        case E_FRAMELOADER :
            {
                /* TODO
                    Hack -->
                        The default frame loader can't be located inside the normal set of frame loaders.
                        It's an atomic property inside the misc cfg package. So we can't retrieve the information
                        about FINALIZED and MANDATORY very easy ... :-(
                        => set it to readonly/required everytimes :-)
                */
                css::uno::Any   aDirectValue       = impl_getDirectCFGValue(CFGDIRECTKEY_DEFAULTFRAMELOADER);
                OUString sDefaultFrameLoader;
                if (
                    (aDirectValue >>= sDefaultFrameLoader) &&
                    (!sDefaultFrameLoader.isEmpty()      ) &&
                    (sItem == sDefaultFrameLoader   )
                   )
                {
                    rItem[PROPNAME_FINALIZED] <<= true;
                    rItem[PROPNAME_MANDATORY] <<= true;
                    return;
                }
                /* <-- HACK */

                xPackage.set(impl_openConfig(E_PROVIDER_OTHERS), css::uno::UNO_QUERY_THROW);
                xPackage->getByName(CFGSET_FRAMELOADERS) >>= xSet;
            }
            break;

        case E_CONTENTHANDLER :
            {
                xPackage.set(impl_openConfig(E_PROVIDER_OTHERS), css::uno::UNO_QUERY_THROW);
                xPackage->getByName(CFGSET_CONTENTHANDLERS) >>= xSet;
            }
            break;
        default: break;
    }

    try
    {
        css::uno::Reference< css::beans::XProperty > xItem;
        xSet->getByName(sItem) >>= xItem;
        css::beans::Property aDescription = xItem->getAsProperty();

        bool bFinalized = ((aDescription.Attributes & css::beans::PropertyAttribute::READONLY  ) == css::beans::PropertyAttribute::READONLY  );
        bool bMandatory = ((aDescription.Attributes & css::beans::PropertyAttribute::REMOVABLE) != css::beans::PropertyAttribute::REMOVABLE);

        rItem[PROPNAME_FINALIZED] <<= bFinalized;
        rItem[PROPNAME_MANDATORY] <<= bMandatory;
    }
    catch(const css::container::NoSuchElementException&)
    {
        /*  Ignore exceptions for missing elements inside configuration.
            May by the following reason exists:
                -   The item does not exists inside the new configuration package org.openoffice.TypeDetection - but
                    we got it from the old package org.openoffice.Office/TypeDetection. We don't migrate such items
                    automatically to the new format. Because it will disturb e.g. the deinstallation of an external filter
                    package. Because such external filter can remove the old file - but not the automatically created new one ...

            => mark item as FINALIZED / MANDATORY, we don't support writing to the old format
        */
        rItem[PROPNAME_FINALIZED] <<= true;
        rItem[PROPNAME_MANDATORY] <<= true;
    }

    // <- SAFE
}


void FilterCache::removeStatePropsFromItem(CacheItem& rItem)
{
    CacheItem::iterator pIt = rItem.find(PROPNAME_FINALIZED);
    if (pIt != rItem.end())
        rItem.erase(pIt);
    pIt = rItem.find(PROPNAME_MANDATORY);
    if (pIt != rItem.end())
        rItem.erase(pIt);
}


void FilterCache::flush()
{
    // SAFE ->
    osl::MutexGuard aLock(m_aLock);

    // renew all dependencies and optimizations
    impl_validateAndOptimize();

    if (!m_lChangedTypes.empty())
    {
        css::uno::Reference< css::container::XNameAccess > xConfig(impl_openConfig(E_PROVIDER_TYPES), css::uno::UNO_QUERY_THROW);
        css::uno::Reference< css::container::XNameAccess > xSet   ;

        xConfig->getByName(CFGSET_TYPES) >>= xSet;
        impl_flushByList(xSet, E_TYPE, m_lTypes, m_lChangedTypes);

        css::uno::Reference< css::util::XChangesBatch > xFlush(xConfig, css::uno::UNO_QUERY);
        xFlush->commitChanges();
    }

    if (!m_lChangedFilters.empty())
    {
        css::uno::Reference< css::container::XNameAccess > xConfig(impl_openConfig(E_PROVIDER_FILTERS), css::uno::UNO_QUERY_THROW);
        css::uno::Reference< css::container::XNameAccess > xSet   ;

        xConfig->getByName(CFGSET_FILTERS) >>= xSet;
        impl_flushByList(xSet, E_FILTER, m_lFilters, m_lChangedFilters);

        css::uno::Reference< css::util::XChangesBatch > xFlush(xConfig, css::uno::UNO_QUERY);
        xFlush->commitChanges();
    }

    /*TODO FrameLoader/ContentHandler must be flushed here too ... */
}


void FilterCache::impl_flushByList(const css::uno::Reference< css::container::XNameAccess >& xSet  ,
                                         EItemType                                           eType ,
                                   const CacheItemList&                                      rCache,
                                   const std::vector<OUString>&                              lItems)
{
    css::uno::Reference< css::container::XNameContainer >   xAddRemoveSet(xSet, css::uno::UNO_QUERY);
    css::uno::Reference< css::lang::XSingleServiceFactory > xFactory(xSet, css::uno::UNO_QUERY);

    for (auto const& item : lItems)
    {
        EItemFlushState  eState = impl_specifyFlushOperation(xSet, rCache, item);
        switch(eState)
        {
            case E_ITEM_REMOVED :
            {
                xAddRemoveSet->removeByName(item);
            }
            break;

            case E_ITEM_ADDED :
            {
                css::uno::Reference< css::container::XNameReplace > xItem (xFactory->createInstance(), css::uno::UNO_QUERY);

                // special case. no exception - but not a valid item => set must be finalized or mandatory!
                // Reject flush operation by throwing an exception. At least one item couldn't be flushed.
                if (!xItem.is())
                    throw css::uno::Exception("Can not add item. Set is finalized or mandatory!",
                                              css::uno::Reference< css::uno::XInterface >());

                CacheItemList::const_iterator pItem = rCache.find(item);
                impl_saveItem(xItem, eType, pItem->second);
                xAddRemoveSet->insertByName(item, css::uno::makeAny(xItem));
            }
            break;

            case E_ITEM_CHANGED :
            {
                css::uno::Reference< css::container::XNameReplace > xItem;
                xSet->getByName(item) >>= xItem;

                // special case. no exception - but not a valid item => it must be finalized or mandatory!
                // Reject flush operation by throwing an exception. At least one item couldn't be flushed.
                if (!xItem.is())
                    throw css::uno::Exception("Can not change item. Its finalized or mandatory!",
                                              css::uno::Reference< css::uno::XInterface >());

                CacheItemList::const_iterator pItem = rCache.find(item);
                impl_saveItem(xItem, eType, pItem->second);
            }
            break;
            default: break;
        }
    }
}


void FilterCache::detectFlatForURL(const css::util::URL& aURL      ,
                                         FlatDetection&  rFlatTypes) const
{
    // extract extension from URL, so it can be used directly as key into our hash map!
    // Note further: It must be converted to lower case, because the optimize hash
    // (which maps extensions to types) work with lower case key strings!
    INetURLObject   aParser    (aURL.Main);
    OUString sExtension = aParser.getExtension(INetURLObject::LAST_SEGMENT       ,
                                                      true                          ,
                                                      INetURLObject::DecodeMechanism::WithCharset);
    sExtension = sExtension.toAsciiLowerCase();

    // SAFE -> ----------------------------------
    osl::MutexGuard aLock(m_aLock);


    // i) Step over all well known URL pattern
    //    and add registered types to the return list too
    //    Do it as first one - because: if a type match by a
    //    pattern a following deep detection can be suppressed!
    //    Further we can stop after first match ...
    for (auto const& pattern : m_lURLPattern2Types)
    {
        WildCard aPatternCheck(pattern.first);
        if (aPatternCheck.Matches(aURL.Main))
        {
            const std::vector<OUString>& rTypesForPattern = pattern.second;

            FlatDetectionInfo aInfo;
            aInfo.sType = *(rTypesForPattern.begin());
            aInfo.bMatchByPattern = true;

            rFlatTypes.push_back(aInfo);
//          return;
        }
    }


    // ii) search types matching to the given extension.
    //     Copy every matching type without changing its order!
    //     Because preferred types was added as first one during
    //     loading configuration.
    CacheItemRegistration::const_iterator pExtReg = m_lExtensions2Types.find(sExtension);
    if (pExtReg != m_lExtensions2Types.end())
    {
        const std::vector<OUString>& rTypesForExtension = pExtReg->second;
        for (auto const& elem : rTypesForExtension)
        {
            FlatDetectionInfo aInfo;
            aInfo.sType             = elem;
            aInfo.bMatchByExtension = true;

            rFlatTypes.push_back(aInfo);
        }
    }

    // <- SAFE ----------------------------------
}

const CacheItemList& FilterCache::impl_getItemList(EItemType eType) const
{
    // SAFE -> ----------------------------------
    osl::MutexGuard aLock(m_aLock);

    switch(eType)
    {
        case E_TYPE           : return m_lTypes          ;
        case E_FILTER         : return m_lFilters        ;
        case E_FRAMELOADER    : return m_lFrameLoaders   ;
        case E_CONTENTHANDLER : return m_lContentHandlers;

    }

    throw css::uno::RuntimeException("unknown sub container requested.",
                                            css::uno::Reference< css::uno::XInterface >());
    // <- SAFE ----------------------------------
}

CacheItemList& FilterCache::impl_getItemList(EItemType eType)
{
    // SAFE -> ----------------------------------
    osl::MutexGuard aLock(m_aLock);

    switch(eType)
    {
        case E_TYPE           : return m_lTypes          ;
        case E_FILTER         : return m_lFilters        ;
        case E_FRAMELOADER    : return m_lFrameLoaders   ;
        case E_CONTENTHANDLER : return m_lContentHandlers;

    }

    throw css::uno::RuntimeException("unknown sub container requested.",
                                            css::uno::Reference< css::uno::XInterface >());
    // <- SAFE ----------------------------------
}

css::uno::Reference< css::uno::XInterface > FilterCache::impl_openConfig(EConfigProvider eProvider)
{
    osl::MutexGuard aLock(m_aLock);

    OUString                              sPath      ;
    css::uno::Reference< css::uno::XInterface >* pConfig = nullptr;
    css::uno::Reference< css::uno::XInterface >  xOld       ;
    OString                               sRtlLog    ;

    switch(eProvider)
    {
        case E_PROVIDER_TYPES :
        {
            if (m_xConfigTypes.is())
                return m_xConfigTypes;
            sPath           = CFGPACKAGE_TD_TYPES;
            pConfig         = &m_xConfigTypes;
            sRtlLog         = "impl_openconfig(E_PROVIDER_TYPES)";
        }
        break;

        case E_PROVIDER_FILTERS :
        {
            if (m_xConfigFilters.is())
                return m_xConfigFilters;
            sPath           = CFGPACKAGE_TD_FILTERS;
            pConfig         = &m_xConfigFilters;
            sRtlLog         = "impl_openconfig(E_PROVIDER_FILTERS)";
        }
        break;

        case E_PROVIDER_OTHERS :
        {
            if (m_xConfigOthers.is())
                return m_xConfigOthers;
            sPath   = CFGPACKAGE_TD_OTHERS;
            pConfig = &m_xConfigOthers;
            sRtlLog = "impl_openconfig(E_PROVIDER_OTHERS)";
        }
        break;

        case E_PROVIDER_OLD :
        {
            // This special provider is used to work with
            // the old configuration format only. It's not cached!
            sPath   = CFGPACKAGE_TD_OLD;
            pConfig = &xOld;
            sRtlLog = "impl_openconfig(E_PROVIDER_OLD)";
        }
        break;

        default : throw css::uno::RuntimeException("These configuration node is not supported here for open!", nullptr);
    }

    {
        SAL_INFO( "filter.config", "" << sRtlLog);
        *pConfig = impl_createConfigAccess(sPath    ,
                                           false,   // bReadOnly
                                           true );  // bLocalesMode
    }


    // Start listening for changes on that configuration access.
    switch(eProvider)
    {
        case E_PROVIDER_TYPES:
        {
            m_xTypesChglisteners.set(new CacheUpdateListener(*this, *pConfig, FilterCache::E_TYPE));
            m_xTypesChglisteners->startListening();
        }
        break;
        case E_PROVIDER_FILTERS:
        {
            m_xFiltersChgListener.set(new CacheUpdateListener(*this, *pConfig, FilterCache::E_FILTER));
            m_xFiltersChgListener->startListening();
        }
        break;
        default:
        break;
    }

    return *pConfig;
}

css::uno::Any FilterCache::impl_getDirectCFGValue(const OUString& sDirectKey)
{
    OUString sRoot;
    OUString sKey ;

    if (
        (!::utl::splitLastFromConfigurationPath(sDirectKey, sRoot, sKey)) ||
        (sRoot.isEmpty()                                             ) ||
        (sKey.isEmpty()                                              )
       )
        return css::uno::Any();

    css::uno::Reference< css::uno::XInterface > xCfg = impl_createConfigAccess(sRoot    ,
                                                                               true ,  // bReadOnly
                                                                               false); // bLocalesMode
    if (!xCfg.is())
        return css::uno::Any();

    css::uno::Reference< css::container::XNameAccess > xAccess(xCfg, css::uno::UNO_QUERY);
    if (!xAccess.is())
        return css::uno::Any();

    css::uno::Any aValue;
    try
    {
        aValue = xAccess->getByName(sKey);
    }
    catch(const css::uno::RuntimeException&)
        { throw; }
    catch(const css::uno::Exception& ex)
        {
            SAL_WARN( "filter.config", ex);
            aValue.clear();
        }

    return aValue;
}


css::uno::Reference< css::uno::XInterface > FilterCache::impl_createConfigAccess(const OUString& sRoot       ,
                                                                                       bool         bReadOnly   ,
                                                                                       bool         bLocalesMode)
{
    // SAFE ->
    osl::MutexGuard aLock(m_aLock);

    css::uno::Reference< css::uno::XInterface > xCfg;

    if (!utl::ConfigManager::IsFuzzing())
    {
        try
        {
            css::uno::Reference< css::lang::XMultiServiceFactory > xConfigProvider(
                css::configuration::theDefaultProvider::get( comphelper::getProcessComponentContext() ) );

            ::std::vector< css::uno::Any > lParams;
            css::beans::NamedValue aParam;

            // set root path
            aParam.Name = "nodepath";
            aParam.Value <<= sRoot;
            lParams.push_back(css::uno::makeAny(aParam));

            // enable "all locales mode" ... if required
            if (bLocalesMode)
            {
                aParam.Name = "locale";
                aParam.Value <<= OUString("*");
                lParams.push_back(css::uno::makeAny(aParam));
            }

            // open it
            if (bReadOnly)
                xCfg = xConfigProvider->createInstanceWithArguments(SERVICE_CONFIGURATIONACCESS,
                        comphelper::containerToSequence(lParams));
            else
                xCfg = xConfigProvider->createInstanceWithArguments(SERVICE_CONFIGURATIONUPDATEACCESS,
                        comphelper::containerToSequence(lParams));

            // If configuration could not be opened... but factory method did not throw an exception
            // trigger throwing of our own CorruptedFilterConfigurationException.
            // Let message empty. The normal exception text show enough information to the user.
            if (! xCfg.is())
                throw css::uno::Exception(
                        "Got NULL reference on opening configuration file ... but no exception.",
                        css::uno::Reference< css::uno::XInterface >());
        }
        catch(const css::uno::Exception& ex)
        {
            throw css::document::CorruptedFilterConfigurationException(
                    "filter configuration, caught: " + ex.Message,
                    css::uno::Reference< css::uno::XInterface >(),
                    ex.Message);
        }
    }

    return xCfg;
    // <- SAFE
}


void FilterCache::impl_validateAndOptimize()
{
    // SAFE ->
    osl::MutexGuard aLock(m_aLock);

    // First check if any filter or type could be read
    // from the underlying configuration!
    bool bSomeTypesShouldExist   = ((m_eFillState & E_CONTAINS_STANDARD       ) == E_CONTAINS_STANDARD       );
    bool bAllFiltersShouldExist  = ((m_eFillState & E_CONTAINS_FILTERS        ) == E_CONTAINS_FILTERS        );

#if OSL_DEBUG_LEVEL > 0

    sal_Int32             nWarnings = 0;

//  sal_Bool bAllTypesShouldExist    = ((m_eFillState & E_CONTAINS_TYPES          ) == E_CONTAINS_TYPES          );
    bool bAllLoadersShouldExist  = ((m_eFillState & E_CONTAINS_FRAMELOADERS   ) == E_CONTAINS_FRAMELOADERS   );
    bool bAllHandlersShouldExist = ((m_eFillState & E_CONTAINS_CONTENTHANDLERS) == E_CONTAINS_CONTENTHANDLERS);
#endif

    if (
        (
            bSomeTypesShouldExist && m_lTypes.empty()
        ) ||
        (
            bAllFiltersShouldExist && m_lFilters.empty()
        )
       )
    {
        throw css::document::CorruptedFilterConfigurationException(
                "filter configuration: the list of types or filters is empty",
                css::uno::Reference< css::uno::XInterface >(),
                "The list of types or filters is empty." );
    }

    // Create a log for all detected problems, which
    // occur in the next few lines.
    // If there are some real errors throw a RuntimException!
    // If there are some warnings only, show an assertion.
    sal_Int32             nErrors   = 0;
    OUStringBuffer sLog(256);

    for (auto const& elem : m_lTypes)
    {
        OUString sType = elem.first;
        CacheItem aType = elem.second;

        // get its registration for file Extensions AND(!) URLPattern ...
        // It doesn't matter if these items exists or if our
        // used index access create some default ones ...
        // only in case there is no filled set of Extensions AND
        // no filled set of URLPattern -> we must try to remove this invalid item
        // from this cache!
        css::uno::Sequence< OUString > lExtensions;
        css::uno::Sequence< OUString > lURLPattern;
        aType[PROPNAME_EXTENSIONS] >>= lExtensions;
        aType[PROPNAME_URLPATTERN] >>= lURLPattern;
        sal_Int32 ce = lExtensions.getLength();
        sal_Int32 cu = lURLPattern.getLength();

#if OSL_DEBUG_LEVEL > 0

        OUString sInternalTypeNameCheck;
        aType[PROPNAME_NAME] >>= sInternalTypeNameCheck;
        if (sInternalTypeNameCheck != sType)
        {
            sLog.append("Warning\t:\t" "The type \"").append(sType).append("\" does support the property \"Name\" correctly.\n");
            ++nWarnings;
        }

        if (!ce && !cu)
        {
            sLog.append("Warning\t:\t" "The type \"").append(sType).append("\" does not contain any URL pattern nor any extensions.\n");
            ++nWarnings;
        }
#endif

        // create an optimized registration for this type to
        // its set list of extensions/url pattern. If it's a "normal" type
        // set it at the end of this optimized list. But if its
        // a "Preferred" one - set it to the front of this list.
        // Of course multiple "Preferred" registrations can occur
        // (they shouldn't - but they can!) ... Ignore it. The last
        // preferred type is usable in the same manner then every
        // other type!
        bool bPreferred = false;
        aType[PROPNAME_PREFERRED] >>= bPreferred;

        const OUString* pExtensions = lExtensions.getConstArray();
        for (sal_Int32 e=0; e<ce; ++e)
        {
            // Note: We must be sure that address the right hash entry
            // does not depend from any upper/lower case problems ...
            OUString sNormalizedExtension = pExtensions[e].toAsciiLowerCase();

            std::vector<OUString>& lTypesForExtension = m_lExtensions2Types[sNormalizedExtension];
            if (::std::find(lTypesForExtension.begin(), lTypesForExtension.end(), sType) != lTypesForExtension.end())
                continue;

            if (bPreferred)
                lTypesForExtension.insert(lTypesForExtension.begin(), sType);
            else
                lTypesForExtension.push_back(sType);
        }

        const OUString* pURLPattern = lURLPattern.getConstArray();
        for (sal_Int32 u=0; u<cu; ++u)
        {
            std::vector<OUString>& lTypesForURLPattern = m_lURLPattern2Types[pURLPattern[u]];
            if (::std::find(lTypesForURLPattern.begin(), lTypesForURLPattern.end(), sType) != lTypesForURLPattern.end())
                continue;

            if (bPreferred)
                lTypesForURLPattern.insert(lTypesForURLPattern.begin(), sType);
            else
                lTypesForURLPattern.push_back(sType);
        }

#if OSL_DEBUG_LEVEL > 0

        // Don't check cross references between types and filters, if
        // not all filters read from disk!
        // OK - this cache can read single filters on demand too ...
        // but then the fill state of this cache should not be set to E_CONTAINS_FILTERS!
        if (!bAllFiltersShouldExist)
            continue;

        OUString sPrefFilter;
        aType[PROPNAME_PREFERREDFILTER] >>= sPrefFilter;
        if (sPrefFilter.isEmpty())
        {
            // OK - there is no filter for this type. But that's not an error.
            // Maybe it can be handled by a ContentHandler...
            // But at this time it's not guaranteed that there is any ContentHandler
            // or FrameLoader inside this cache... but on disk...
            bool bReferencedByLoader  = true;
            bool bReferencedByHandler = true;
            if (bAllLoadersShouldExist)
                bReferencedByLoader = !impl_searchFrameLoaderForType(sType).isEmpty();

            if (bAllHandlersShouldExist)
                bReferencedByHandler = !impl_searchContentHandlerForType(sType).isEmpty();

            if (
                (!bReferencedByLoader ) &&
                (!bReferencedByHandler)
               )
            {
                sLog.append("Warning\t:\t" "The type \"").append(sType).append("\" is not used by any filter, loader or content handler.\n");
                ++nWarnings;
            }
        }

        if (!sPrefFilter.isEmpty())
        {
            CacheItemList::const_iterator pIt2 = m_lFilters.find(sPrefFilter);
            if (pIt2 == m_lFilters.end())
            {
                if (bAllFiltersShouldExist)
                {
                    ++nWarnings; // preferred filters can point to a non-installed office module ! no error ... it's a warning only .-(
                    sLog.append("error\t:\t");
                }
                else
                {
                    ++nWarnings;
                    sLog.append("warning\t:\t");
                }

                sLog.append("The type \"").append(sType).append("\" points to an invalid filter \"").append(sPrefFilter).append("\".\n");
                continue;
            }

            CacheItem       aPrefFilter   = pIt2->second;
            OUString sFilterTypeReg;
            aPrefFilter[PROPNAME_TYPE] >>= sFilterTypeReg;
            if (sFilterTypeReg != sType)
            {
                sLog.append("error\t:\t" "The preferred filter \"")
                    .append(sPrefFilter).append("\" of type \"").append(sType)
                    .append("\" is registered for another type \"").append(sFilterTypeReg)
                    .append("\".\n");
                ++nErrors;
            }

            sal_Int32 nFlags = 0;
            aPrefFilter[PROPNAME_FLAGS] >>= nFlags;
            if (!(static_cast<SfxFilterFlags>(nFlags) & SfxFilterFlags::IMPORT))
            {
                sLog.append("error\t:\t" "The preferred filter \"").append(sPrefFilter).append("\" of type \"")
                            .append(sType).append("\" is not an IMPORT filter!\n");
                ++nErrors;
            }

            OUString sInternalFilterNameCheck;
            aPrefFilter[PROPNAME_NAME] >>= sInternalFilterNameCheck;
            if (sInternalFilterNameCheck !=  sPrefFilter)
            {
                sLog.append("Warning\t:\t" "The filter \"").append(sPrefFilter)
                            .append("\" does support the property \"Name\" correctly.\n");
                ++nWarnings;
            }
        }
#endif
    }

    // create dependencies between the global default frame loader
    // and all types (and of course if registered filters), which
    // does not registered for any other loader.
    css::uno::Any   aDirectValue       = impl_getDirectCFGValue(CFGDIRECTKEY_DEFAULTFRAMELOADER);
    OUString sDefaultFrameLoader;

    if (
        (!(aDirectValue >>= sDefaultFrameLoader)) ||
        (sDefaultFrameLoader.isEmpty()       )
       )
    {
        sLog.append("error\t:\t" "There is no valid default frame loader!?\n");
        ++nErrors;
    }

    // a) get list of all well known types
    // b) step over all well known frame loader services
    //    and remove all types from list a), which already
    //    referenced by a loader b)
    std::vector<OUString> lTypes = getItemNames(E_TYPE);
    for (auto & frameLoader : m_lFrameLoaders)
    {
        // Note: of course the default loader must be ignored here.
        // Because we replace its registration later completely with all
        // types, which are not referenced by any other loader.
        // So we can avoid our code against the complexity of a diff!
        OUString sLoader = frameLoader.first;
        if (sLoader == sDefaultFrameLoader)
            continue;

        CacheItem&     rLoader   = frameLoader.second;
        css::uno::Any& rTypesReg = rLoader[PROPNAME_TYPES];
        std::vector<OUString>   lTypesReg (comphelper::sequenceToContainer< std::vector<OUString> >(rTypesReg.get<css::uno::Sequence<OUString> >()));

        for (auto const& typeReg : lTypesReg)
        {
            auto pTypeCheck = ::std::find(lTypes.begin(), lTypes.end(), typeReg);
            if (pTypeCheck != lTypes.end())
                lTypes.erase(pTypeCheck);
        }
    }

    CacheItem& rDefaultLoader = m_lFrameLoaders[sDefaultFrameLoader];
    rDefaultLoader[PROPNAME_NAME ] <<= sDefaultFrameLoader;
    rDefaultLoader[PROPNAME_TYPES] <<= comphelper::containerToSequence(lTypes);

    OUString sLogOut = sLog.makeStringAndClear();
    OSL_ENSURE(!nErrors, OUStringToOString(sLogOut,RTL_TEXTENCODING_UTF8).getStr());
    if (nErrors>0)
        throw css::document::CorruptedFilterConfigurationException(
                "filter configuration: " + sLogOut,
                css::uno::Reference< css::uno::XInterface >(),
                sLogOut);
#if OSL_DEBUG_LEVEL > 0
    OSL_ENSURE(!nWarnings, OUStringToOString(sLogOut,RTL_TEXTENCODING_UTF8).getStr());
#endif

    // <- SAFE
}

void FilterCache::impl_addItem2FlushList(      EItemType        eType,
                                         const OUString& sItem)
{
    std::vector<OUString>* pList = nullptr;
    switch(eType)
    {
        case E_TYPE :
                pList = &m_lChangedTypes;
                break;

        case E_FILTER :
                pList = &m_lChangedFilters;
                break;

        case E_FRAMELOADER :
                pList = &m_lChangedFrameLoaders;
                break;

        case E_CONTENTHANDLER :
                pList = &m_lChangedContentHandlers;
                break;

        default : throw css::uno::RuntimeException("unsupported item type", nullptr);
    }

    auto pItem = ::std::find(pList->cbegin(), pList->cend(), sItem);
    if (pItem == pList->cend())
        pList->push_back(sItem);
}

FilterCache::EItemFlushState FilterCache::impl_specifyFlushOperation(const css::uno::Reference< css::container::XNameAccess >& xSet ,
                                                                     const CacheItemList&                                      rList,
                                                                     const OUString&                                    sItem)
{
    bool bExistsInConfigLayer = xSet->hasByName(sItem);
    bool bExistsInMemory      = (rList.find(sItem) != rList.end());

    EItemFlushState eState( E_ITEM_UNCHANGED );

    // !? ... such situation can occur, if an item was added and(!) removed before it was flushed :-)
    if (!bExistsInConfigLayer && !bExistsInMemory)
        eState = E_ITEM_UNCHANGED;
    else if (!bExistsInConfigLayer && bExistsInMemory)
        eState = E_ITEM_ADDED;
    else if (bExistsInConfigLayer && bExistsInMemory)
        eState = E_ITEM_CHANGED;
    else if (bExistsInConfigLayer && !bExistsInMemory)
        eState = E_ITEM_REMOVED;

    return eState;
}

void FilterCache::impl_load(EFillState eRequiredState)
{
    // SAFE ->
    osl::MutexGuard aLock(m_aLock);

    // Attention: Detect services are part of the standard set!
    // So there is no need to handle it separately.


    // a) The standard set of config value is needed.
    if (
        ((eRequiredState & E_CONTAINS_STANDARD) == E_CONTAINS_STANDARD) &&
        ((m_eFillState   & E_CONTAINS_STANDARD) != E_CONTAINS_STANDARD)
       )
    {
        // Attention! If config couldn't be opened successfully
        // and exception os thrown automatically and must be forwarded
        // to our caller...
        css::uno::Reference< css::container::XNameAccess > xTypes(impl_openConfig(E_PROVIDER_TYPES), css::uno::UNO_QUERY_THROW);
        {
            SAL_INFO( "filter.config", "FilterCache::load std");
            impl_loadSet(xTypes, E_TYPE, E_READ_STANDARD, &m_lTypes);
        }
    }


    // b) We need all type information ...
    if (
        ((eRequiredState & E_CONTAINS_TYPES) == E_CONTAINS_TYPES) &&
        ((m_eFillState   & E_CONTAINS_TYPES) != E_CONTAINS_TYPES)
       )
    {
        // Attention! If config couldn't be opened successfully
        // and exception os thrown automatically and must be forwarded
        // to our call...
        css::uno::Reference< css::container::XNameAccess > xTypes(impl_openConfig(E_PROVIDER_TYPES), css::uno::UNO_QUERY_THROW);
        {
            SAL_INFO( "filter.config", "FilterCache::load all types");
            impl_loadSet(xTypes, E_TYPE, E_READ_UPDATE, &m_lTypes);
        }
    }


    // c) We need all filter information ...
    if (
        ((eRequiredState & E_CONTAINS_FILTERS) == E_CONTAINS_FILTERS) &&
        ((m_eFillState   & E_CONTAINS_FILTERS) != E_CONTAINS_FILTERS)
       )
    {
        // Attention! If config couldn't be opened successfully
        // and exception os thrown automatically and must be forwarded
        // to our call...
        css::uno::Reference< css::container::XNameAccess > xFilters(impl_openConfig(E_PROVIDER_FILTERS), css::uno::UNO_QUERY_THROW);
        {
            SAL_INFO( "filter.config", "FilterCache::load all filters");
            impl_loadSet(xFilters, E_FILTER, E_READ_ALL, &m_lFilters);
        }
    }


    // c) We need all frame loader information ...
    if (
        ((eRequiredState & E_CONTAINS_FRAMELOADERS) == E_CONTAINS_FRAMELOADERS) &&
        ((m_eFillState   & E_CONTAINS_FRAMELOADERS) != E_CONTAINS_FRAMELOADERS)
       )
    {
        // Attention! If config couldn't be opened successfully
        // and exception os thrown automatically and must be forwarded
        // to our call...
        css::uno::Reference< css::container::XNameAccess > xLoaders(impl_openConfig(E_PROVIDER_OTHERS), css::uno::UNO_QUERY_THROW);
        {
            SAL_INFO( "filter.config", "FilterCache::load all frame loader");
            impl_loadSet(xLoaders, E_FRAMELOADER, E_READ_ALL, &m_lFrameLoaders);
        }
    }


    // d) We need all content handler information...
    if (
        ((eRequiredState & E_CONTAINS_CONTENTHANDLERS) == E_CONTAINS_CONTENTHANDLERS) &&
        ((m_eFillState   & E_CONTAINS_CONTENTHANDLERS) != E_CONTAINS_CONTENTHANDLERS)
       )
    {
        // Attention! If config couldn't be opened successfully
        // and exception os thrown automatically and must be forwarded
        // to our call...
        css::uno::Reference< css::container::XNameAccess > xHandlers(impl_openConfig(E_PROVIDER_OTHERS), css::uno::UNO_QUERY_THROW);
        {
            SAL_INFO( "filter.config", "FilterCache::load all content handler");
            impl_loadSet(xHandlers, E_CONTENTHANDLER, E_READ_ALL, &m_lContentHandlers);
        }
    }

    // update fill state. Note: it's a bit field, which combines different parts.
    m_eFillState = static_cast<EFillState>(static_cast<sal_Int32>(m_eFillState) | static_cast<sal_Int32>(eRequiredState));

    // any data read?
    // yes! => validate it and update optimized structures.
    impl_validateAndOptimize();

    // <- SAFE
}

void FilterCache::impl_loadSet(const css::uno::Reference< css::container::XNameAccess >& xConfig,
                                     EItemType                                           eType  ,
                                     EReadOption                                         eOption,
                                     CacheItemList*                                      pCache )
{
    // get access to the right configuration set
    OUString sSetName;
    switch(eType)
    {
        case E_TYPE :
            sSetName = CFGSET_TYPES;
            break;

        case E_FILTER :
            sSetName = CFGSET_FILTERS;
            break;

        case E_FRAMELOADER :
            sSetName = CFGSET_FRAMELOADERS;
            break;

        case E_CONTENTHANDLER :
            sSetName = CFGSET_CONTENTHANDLERS;
            break;
        default: break;
    }

    css::uno::Reference< css::container::XNameAccess > xSet;
    css::uno::Sequence< OUString >              lItems;

    try
    {
        css::uno::Any aVal = xConfig->getByName(sSetName);
        if (!(aVal >>= xSet) || !xSet.is())
        {
            OUString sMsg("Could not open configuration set \"" + sSetName + "\".");
            throw css::uno::Exception(sMsg, css::uno::Reference< css::uno::XInterface >());
        }
        lItems = xSet->getElementNames();
    }
    catch(const css::uno::Exception& ex)
    {
        throw css::document::CorruptedFilterConfigurationException(
                "filter configuration, caught: " + ex.Message,
                css::uno::Reference< css::uno::XInterface >(),
                ex.Message);
    }

    // get names of all existing sub items of this set
    // step over it and fill internal cache structures.

    // But don't update optimized structures like e.g. hash
    // for mapping extensions to its types!

    const OUString* pItems = lItems.getConstArray();
    sal_Int32       c      = lItems.getLength();
    for (sal_Int32 i=0; i<c; ++i)
    {
        CacheItemList::iterator pItem = pCache->find(pItems[i]);
        switch(eOption)
        {
            // a) read a standard set of properties only or read all
            case E_READ_STANDARD :
            case E_READ_ALL      :
            {
                try
                {
                    (*pCache)[pItems[i]] = impl_loadItem(xSet, eType, pItems[i], eOption);
                }
                catch(const css::uno::Exception& ex)
                {
                    throw css::document::CorruptedFilterConfigurationException(
                            "filter configuration, caught: " + ex.Message,
                            css::uno::Reference< css::uno::XInterface >(),
                            ex.Message);
                }
            }
            break;

            // b) read optional properties only!
            //    All items must already exist inside our cache.
            //    But they must be updated.
            case E_READ_UPDATE :
            {
                if (pItem == pCache->end())
                {
                    OUString sMsg("item \"" + pItems[i] + "\" not found for update!");
                    throw css::uno::Exception(sMsg, css::uno::Reference< css::uno::XInterface >());
                }
                try
                {
                    CacheItem aItem = impl_loadItem(xSet, eType, pItems[i], eOption);
                    pItem->second.update(aItem);
                }
                catch(const css::uno::Exception& ex)
                {
                    throw css::document::CorruptedFilterConfigurationException(
                            "filter configuration, caught: " + ex.Message,
                            css::uno::Reference< css::uno::XInterface >(),
                            ex.Message);
                }
            }
            break;
            default: break;
        }
    }
}

void FilterCache::impl_readPatchUINames(const css::uno::Reference< css::container::XNameAccess >& xNode,
                                              CacheItem&                                          rItem)
{

    // SAFE -> ----------------------------------
    osl::ClearableMutexGuard aLock(m_aLock);
    OUString sActLocale     = m_sActLocale    ;
    aLock.clear();
    // <- SAFE ----------------------------------

    css::uno::Any aVal = xNode->getByName(PROPNAME_UINAME);
    css::uno::Reference< css::container::XNameAccess > xUIName;
    if (!(aVal >>= xUIName) && !xUIName.is())
        return;

    const ::std::vector< OUString >                 lLocales(comphelper::sequenceToContainer< ::std::vector< OUString >>(
                                                                xUIName->getElementNames()));
    ::std::vector< OUString >::const_iterator pLocale ;
    ::comphelper::SequenceAsHashMap           lUINames;

    for (auto const& locale : lLocales)
    {
        OUString sValue;
        xUIName->getByName(locale) >>= sValue;

        lUINames[locale] <<= sValue;
    }

    aVal <<= lUINames.getAsConstPropertyValueList();
    rItem[PROPNAME_UINAMES] = aVal;

    // find right UIName for current office locale
    // Use fallbacks too!
    pLocale = LanguageTag::getFallback(lLocales, sActLocale);
    if (pLocale == lLocales.end())
    {
#if OSL_DEBUG_LEVEL > 0
        if ( sActLocale == "en-US" )
            return;
        OUString sName = rItem.getUnpackedValueOrDefault(PROPNAME_NAME, OUString());

        SAL_WARN("filter.config", "Fallback scenario for filter or type '" << sName << "' and locale '" <<
                      sActLocale << "' failed. Please check your filter configuration.");
#endif
        return;
    }

    const OUString& sLocale = *pLocale;
    ::comphelper::SequenceAsHashMap::const_iterator pUIName = lUINames.find(sLocale);
    if (pUIName != lUINames.end())
        rItem[PROPNAME_UINAME] = pUIName->second;
}

void FilterCache::impl_savePatchUINames(const css::uno::Reference< css::container::XNameReplace >& xNode,
                                        const CacheItem&                                           rItem)
{
    css::uno::Reference< css::container::XNameContainer > xAdd  (xNode, css::uno::UNO_QUERY);
    css::uno::Reference< css::container::XNameAccess >    xCheck(xNode, css::uno::UNO_QUERY);

    css::uno::Sequence< css::beans::PropertyValue > lUINames = rItem.getUnpackedValueOrDefault(PROPNAME_UINAMES, css::uno::Sequence< css::beans::PropertyValue >());
    sal_Int32                                       c        = lUINames.getLength();
    const css::beans::PropertyValue*                pUINames = lUINames.getConstArray();

    for (sal_Int32 i=0; i<c; ++i)
    {
        if (xCheck->hasByName(pUINames[i].Name))
            xNode->replaceByName(pUINames[i].Name, pUINames[i].Value);
        else
            xAdd->insertByName(pUINames[i].Name, pUINames[i].Value);
    }
}

/*-----------------------------------------------
    TODO
        clarify, how the real problem behind the
        wrong constructed CacheItem instance (which
        will force a crash during destruction)
        can be solved ...
-----------------------------------------------*/
CacheItem FilterCache::impl_loadItem(const css::uno::Reference< css::container::XNameAccess >& xSet   ,
                                           EItemType                                           eType  ,
                                     const OUString&                                    sItem  ,
                                           EReadOption                                         eOption)
{
    // try to get an API object, which points directly to the
    // requested item. If it fail an exception should occur and
    // break this operation. Of course returned API object must be
    // checked too.
    css::uno::Reference< css::container::XNameAccess > xItem;
    css::uno::Any aVal = xSet->getByName(sItem);
    if (!(aVal >>= xItem) || !xItem.is())
    {
        throw css::uno::RuntimeException("found corrupted item \"" + sItem + "\".",
                                         css::uno::Reference< css::uno::XInterface >());
    }

    // set too. Of course it's already used as key into the e.g. outside
    // used hash map... but some of our API methods provide
    // this property set as result only. But the user of this CacheItem
    // should know, which value the key names has :-) IT'S IMPORTANT!
    CacheItem aItem;
    aItem[PROPNAME_NAME] <<= sItem;
    switch(eType)
    {
        case E_TYPE :
        {
            assert(eOption >= 0 && eOption <= E_READ_ALL);
            css::uno::Sequence< OUString > &rNames = m_aTypeProps[eOption];

            // read standard properties of a filter
            if (rNames.getLength() > 0)
            {
                css::uno::Reference< css::beans::XMultiPropertySet >
                    xPropSet( xItem, css::uno::UNO_QUERY_THROW);
                css::uno::Sequence< css::uno::Any > aValues = xPropSet->getPropertyValues(rNames);

                for (sal_Int32 i = 0; i < aValues.getLength(); i++)
                    aItem[rNames[i]] = aValues[i];
            }

            // read optional properties of a type
            // no else here! Is an additional switch ...
            if (eOption == E_READ_UPDATE || eOption == E_READ_ALL)
                impl_readPatchUINames(xItem, aItem);
        }
        break;


        case E_FILTER :
        {
            assert(eOption >= 0 && eOption <= E_READ_ALL);
            css::uno::Sequence< OUString > &rNames = m_aStandardProps[eOption];

            // read standard properties of a filter
            if (rNames.getLength() > 0)
            {
                css::uno::Reference< css::beans::XMultiPropertySet >
                    xPropSet( xItem, css::uno::UNO_QUERY_THROW);
                css::uno::Sequence< css::uno::Any > aValues = xPropSet->getPropertyValues(rNames);

                for (sal_Int32 i = 0; i < rNames.getLength(); i++)
                {
                    OUString &rPropName = rNames[i];
                    if (i != rNames.getLength() - 1 || rPropName != PROPNAME_FLAGS)
                        aItem[rPropName] = aValues[i];
                    else
                    {
                        assert(rPropName == PROPNAME_FLAGS);
                        // special handling for flags! Convert it from a list of names to its
                        // int representation ...
                        css::uno::Sequence< OUString > lFlagNames;
                        if (aValues[i] >>= lFlagNames)
                            aItem[rPropName] <<= static_cast<sal_Int32>(FilterCache::impl_convertFlagNames2FlagField(lFlagNames));
                    }
                }
            }
//TODO remove it if moving of filter uinames to type uinames
//       will be finished really
#ifdef AS_ENABLE_FILTER_UINAMES
            if (eOption == E_READ_UPDATE || eOption == E_READ_ALL)
                impl_readPatchUINames(xItem, aItem);
#endif // AS_ENABLE_FILTER_UINAMES
        }
        break;

        case E_FRAMELOADER :
        case E_CONTENTHANDLER :
            aItem[PROPNAME_TYPES] = xItem->getByName(PROPNAME_TYPES);
            break;
        default: break;
    }

    return aItem;
}

CacheItemList::iterator FilterCache::impl_loadItemOnDemand(      EItemType        eType,
                                                           const OUString& sItem)
{
    CacheItemList*                              pList   = nullptr;
    css::uno::Reference< css::uno::XInterface > xConfig    ;
    OUString                             sSet       ;

    switch(eType)
    {
        case E_TYPE :
        {
            pList   = &m_lTypes;
            xConfig = impl_openConfig(E_PROVIDER_TYPES);
            sSet    = CFGSET_TYPES;
        }
        break;

        case E_FILTER :
        {
            pList   = &m_lFilters;
            xConfig = impl_openConfig(E_PROVIDER_FILTERS);
            sSet    = CFGSET_FILTERS;
        }
        break;

        case E_FRAMELOADER :
        {
            pList   = &m_lFrameLoaders;
            xConfig = impl_openConfig(E_PROVIDER_OTHERS);
            sSet    = CFGSET_FRAMELOADERS;
        }
        break;

        case E_CONTENTHANDLER :
        {
            pList   = &m_lContentHandlers;
            xConfig = impl_openConfig(E_PROVIDER_OTHERS);
            sSet    = CFGSET_CONTENTHANDLERS;
        }
        break;
    }

    if (!pList)
        throw css::container::NoSuchElementException();

    css::uno::Reference< css::container::XNameAccess > xRoot(xConfig, css::uno::UNO_QUERY_THROW);
    css::uno::Reference< css::container::XNameAccess > xSet ;
    xRoot->getByName(sSet) >>= xSet;

    CacheItemList::iterator pItemInCache  = pList->find(sItem);
    bool                bItemInConfig = xSet->hasByName(sItem);

    if (bItemInConfig)
    {
        (*pList)[sItem] = impl_loadItem(xSet, eType, sItem, E_READ_ALL);
    }
    else
    {
        if (pItemInCache != pList->end())
            pList->erase(pItemInCache);
        // OK - this item does not exists inside configuration.
        // And we already updated our internal cache.
        // But the outside code needs this NoSuchElementException
        // to know, that this item does notexists.
        // Nobody checks the iterator!
        throw css::container::NoSuchElementException();
    }

    return pList->find(sItem);
}

void FilterCache::impl_saveItem(const css::uno::Reference< css::container::XNameReplace >& xItem,
                                      EItemType                                            eType,
                                const CacheItem & aItem)
{
    // This function changes the properties of aItem one-by-one; but it also
    // listens to the configuration changes and reloads the whole item from the
    // configuration on change, so use a copy of aItem throughout:
    CacheItem copiedItem(aItem);

    CacheItem::const_iterator pIt;
    switch(eType)
    {

        case E_TYPE :
        {
            pIt = copiedItem.find(PROPNAME_PREFERREDFILTER);
            if (pIt != copiedItem.end())
                xItem->replaceByName(PROPNAME_PREFERREDFILTER, pIt->second);
            pIt = copiedItem.find(PROPNAME_DETECTSERVICE);
            if (pIt != copiedItem.end())
                xItem->replaceByName(PROPNAME_DETECTSERVICE, pIt->second);
            pIt = copiedItem.find(PROPNAME_URLPATTERN);
            if (pIt != copiedItem.end())
                xItem->replaceByName(PROPNAME_URLPATTERN, pIt->second);
            pIt = copiedItem.find(PROPNAME_EXTENSIONS);
            if (pIt != copiedItem.end())
                xItem->replaceByName(PROPNAME_EXTENSIONS, pIt->second);
            pIt = copiedItem.find(PROPNAME_PREFERRED);
            if (pIt != copiedItem.end())
                xItem->replaceByName(PROPNAME_PREFERRED, pIt->second);
            pIt = copiedItem.find(PROPNAME_MEDIATYPE);
            if (pIt != copiedItem.end())
                xItem->replaceByName(PROPNAME_MEDIATYPE, pIt->second);
            pIt = copiedItem.find(PROPNAME_CLIPBOARDFORMAT);
            if (pIt != copiedItem.end())
                xItem->replaceByName(PROPNAME_CLIPBOARDFORMAT, pIt->second);

            css::uno::Reference< css::container::XNameReplace > xUIName;
            xItem->getByName(PROPNAME_UINAME) >>= xUIName;
            impl_savePatchUINames(xUIName, copiedItem);
        }
        break;


        case E_FILTER :
        {
            pIt = copiedItem.find(PROPNAME_TYPE);
            if (pIt != copiedItem.end())
                xItem->replaceByName(PROPNAME_TYPE, pIt->second);
            pIt = copiedItem.find(PROPNAME_FILEFORMATVERSION);
            if (pIt != copiedItem.end())
                xItem->replaceByName(PROPNAME_FILEFORMATVERSION, pIt->second);
            pIt = copiedItem.find(PROPNAME_UICOMPONENT);
            if (pIt != copiedItem.end())
                xItem->replaceByName(PROPNAME_UICOMPONENT, pIt->second);
            pIt = copiedItem.find(PROPNAME_FILTERSERVICE);
            if (pIt != copiedItem.end())
                xItem->replaceByName(PROPNAME_FILTERSERVICE, pIt->second);
            pIt = copiedItem.find(PROPNAME_DOCUMENTSERVICE);
            if (pIt != copiedItem.end())
                xItem->replaceByName(PROPNAME_DOCUMENTSERVICE, pIt->second);
            pIt = copiedItem.find(PROPNAME_USERDATA);
            if (pIt != copiedItem.end())
                xItem->replaceByName(PROPNAME_USERDATA, pIt->second);
            pIt = copiedItem.find(PROPNAME_TEMPLATENAME);
            if (pIt != copiedItem.end())
                xItem->replaceByName(PROPNAME_TEMPLATENAME, pIt->second);

            // special handling for flags! Convert it from an integer flag field back
            // to a list of names ...
            pIt = copiedItem.find(PROPNAME_FLAGS);
            if (pIt != copiedItem.end())
            {
                sal_Int32 nFlags = 0;
                pIt->second >>= nFlags;
                css::uno::Any aFlagNameList;
                aFlagNameList <<= FilterCache::impl_convertFlagField2FlagNames(static_cast<SfxFilterFlags>(nFlags));
                xItem->replaceByName(PROPNAME_FLAGS, aFlagNameList);
            }

//TODO remove it if moving of filter uinames to type uinames
//       will be finished really
#ifdef AS_ENABLE_FILTER_UINAMES
            css::uno::Reference< css::container::XNameReplace > xUIName;
            xItem->getByName(PROPNAME_UINAME) >>= xUIName;
            impl_savePatchUINames(xUIName, copiedItem);
#endif //  AS_ENABLE_FILTER_UINAMES
        }
        break;


        case E_FRAMELOADER :
        case E_CONTENTHANDLER :
        {
            pIt = copiedItem.find(PROPNAME_TYPES);
            if (pIt != copiedItem.end())
                xItem->replaceByName(PROPNAME_TYPES, pIt->second);
        }
        break;
        default: break;
    }
}

/*-----------------------------------------------
    static! => no locks necessary
-----------------------------------------------*/
css::uno::Sequence< OUString > FilterCache::impl_convertFlagField2FlagNames(SfxFilterFlags nFlags)
{
    std::vector<OUString> lFlagNames;

    if (nFlags & SfxFilterFlags::STARONEFILTER    ) lFlagNames.emplace_back(FLAGNAME_3RDPARTYFILTER   );
    if (nFlags & SfxFilterFlags::ALIEN            ) lFlagNames.emplace_back(FLAGNAME_ALIEN            );
    if (nFlags & SfxFilterFlags::CONSULTSERVICE   ) lFlagNames.emplace_back(FLAGNAME_CONSULTSERVICE   );
    if (nFlags & SfxFilterFlags::DEFAULT          ) lFlagNames.emplace_back(FLAGNAME_DEFAULT          );
    if (nFlags & SfxFilterFlags::ENCRYPTION       ) lFlagNames.emplace_back(FLAGNAME_ENCRYPTION       );
    if (nFlags & SfxFilterFlags::EXPORT           ) lFlagNames.emplace_back(FLAGNAME_EXPORT           );
    if (nFlags & SfxFilterFlags::IMPORT           ) lFlagNames.emplace_back(FLAGNAME_IMPORT           );
    if (nFlags & SfxFilterFlags::INTERNAL         ) lFlagNames.emplace_back(FLAGNAME_INTERNAL         );
    if (nFlags & SfxFilterFlags::NOTINFILEDLG     ) lFlagNames.emplace_back(FLAGNAME_NOTINFILEDIALOG  );
    if (nFlags & SfxFilterFlags::MUSTINSTALL      ) lFlagNames.emplace_back(FLAGNAME_NOTINSTALLED     );
    if (nFlags & SfxFilterFlags::OWN              ) lFlagNames.emplace_back(FLAGNAME_OWN              );
    if (nFlags & SfxFilterFlags::PACKED           ) lFlagNames.emplace_back(FLAGNAME_PACKED           );
    if (nFlags & SfxFilterFlags::PASSWORDTOMODIFY ) lFlagNames.emplace_back(FLAGNAME_PASSWORDTOMODIFY );
    if (nFlags & SfxFilterFlags::PREFERED         ) lFlagNames.emplace_back(FLAGNAME_PREFERRED        );
    if (nFlags & SfxFilterFlags::STARTPRESENTATION) lFlagNames.emplace_back(FLAGNAME_STARTPRESENTATION);
    if (nFlags & SfxFilterFlags::OPENREADONLY     ) lFlagNames.emplace_back(FLAGNAME_READONLY         );
    if (nFlags & SfxFilterFlags::SUPPORTSSELECTION) lFlagNames.emplace_back(FLAGNAME_SUPPORTSSELECTION);
    if (nFlags & SfxFilterFlags::TEMPLATE         ) lFlagNames.emplace_back(FLAGNAME_TEMPLATE         );
    if (nFlags & SfxFilterFlags::TEMPLATEPATH     ) lFlagNames.emplace_back(FLAGNAME_TEMPLATEPATH     );
    if (nFlags & SfxFilterFlags::COMBINED         ) lFlagNames.emplace_back(FLAGNAME_COMBINED         );
    if (nFlags & SfxFilterFlags::SUPPORTSSIGNING) lFlagNames.emplace_back(FLAGNAME_SUPPORTSSIGNING);
    if (nFlags & SfxFilterFlags::GPGENCRYPTION) lFlagNames.emplace_back(FLAGNAME_GPGENCRYPTION);
    if (nFlags & SfxFilterFlags::EXOTIC) lFlagNames.emplace_back(FLAGNAME_EXOTIC);

    return comphelper::containerToSequence(lFlagNames);
}

/*-----------------------------------------------
    static! => no locks necessary
-----------------------------------------------*/
SfxFilterFlags FilterCache::impl_convertFlagNames2FlagField(const css::uno::Sequence< OUString >& lNames)
{
    SfxFilterFlags nField = SfxFilterFlags::NONE;

    const OUString* pNames = lNames.getConstArray();
    sal_Int32       c      = lNames.getLength();
    for (sal_Int32 i=0; i<c; ++i)
    {
        if (pNames[i] == FLAGNAME_3RDPARTYFILTER)
        {
            nField |= SfxFilterFlags::STARONEFILTER;
            continue;
        }
        if (pNames[i] == FLAGNAME_ALIEN)
        {
            nField |= SfxFilterFlags::ALIEN;
            continue;
        }
        if (pNames[i] == FLAGNAME_CONSULTSERVICE)
        {
            nField |= SfxFilterFlags::CONSULTSERVICE;
            continue;
        }
        if (pNames[i] == FLAGNAME_DEFAULT)
        {
            nField |= SfxFilterFlags::DEFAULT;
            continue;
        }
        if (pNames[i] == FLAGNAME_ENCRYPTION)
        {
            nField |= SfxFilterFlags::ENCRYPTION;
            continue;
        }
        if (pNames[i] == FLAGNAME_EXOTIC)
        {
            nField |= SfxFilterFlags::EXOTIC;
            continue;
        }
        if (pNames[i] == FLAGNAME_EXPORT)
        {
            nField |= SfxFilterFlags::EXPORT;
            continue;
        }
        if (pNames[i] == FLAGNAME_GPGENCRYPTION)
        {
            nField |= SfxFilterFlags::GPGENCRYPTION;
            continue;
        }
        if (pNames[i] == FLAGNAME_IMPORT)
        {
            nField |= SfxFilterFlags::IMPORT;
            continue;
        }
        if (pNames[i] == FLAGNAME_INTERNAL)
        {
            nField |= SfxFilterFlags::INTERNAL;
            continue;
        }
        if (pNames[i] == FLAGNAME_NOTINFILEDIALOG)
        {
            nField |= SfxFilterFlags::NOTINFILEDLG;
            continue;
        }
        if (pNames[i] == FLAGNAME_NOTINSTALLED)
        {
            nField |= SfxFilterFlags::MUSTINSTALL;
            continue;
        }
        if (pNames[i] == FLAGNAME_OWN)
        {
            nField |= SfxFilterFlags::OWN;
            continue;
        }
        if (pNames[i] == FLAGNAME_PACKED)
        {
            nField |= SfxFilterFlags::PACKED;
            continue;
        }
        if (pNames[i] == FLAGNAME_PASSWORDTOMODIFY)
        {
            nField |= SfxFilterFlags::PASSWORDTOMODIFY;
            continue;
        }
        if (pNames[i] == FLAGNAME_PREFERRED)
        {
            nField |= SfxFilterFlags::PREFERED;
            continue;
        }
        if (pNames[i] == FLAGNAME_STARTPRESENTATION)
        {
            nField |= SfxFilterFlags::STARTPRESENTATION;
            continue;
        }
        if (pNames[i] == FLAGNAME_SUPPORTSSIGNING)
        {
            nField |= SfxFilterFlags::SUPPORTSSIGNING;
            continue;
        }
        if (pNames[i] == FLAGNAME_READONLY)
        {
            nField |= SfxFilterFlags::OPENREADONLY;
            continue;
        }
        if (pNames[i] == FLAGNAME_SUPPORTSSELECTION)
        {
            nField |= SfxFilterFlags::SUPPORTSSELECTION;
            continue;
        }
        if (pNames[i] == FLAGNAME_TEMPLATE)
        {
            nField |= SfxFilterFlags::TEMPLATE;
            continue;
        }
        if (pNames[i] == FLAGNAME_TEMPLATEPATH)
        {
            nField |= SfxFilterFlags::TEMPLATEPATH;
            continue;
        }
        if (pNames[i] == FLAGNAME_COMBINED)
        {
            nField |= SfxFilterFlags::COMBINED;
            continue;
        }
    }

    return nField;
}


void FilterCache::impl_interpretDataVal4Type(const OUString& sValue,
                                                   sal_Int32        nProp ,
                                                   CacheItem&       rItem )
{
    switch(nProp)
    {
        // Preferred
        case 0:     rItem[PROPNAME_PREFERRED] <<= (sValue.toInt32() == 1);
                    break;
        // MediaType
        case 1:     rItem[PROPNAME_MEDIATYPE] <<= ::rtl::Uri::decode(sValue, rtl_UriDecodeWithCharset, RTL_TEXTENCODING_UTF8);
                    break;
        // ClipboardFormat
        case 2:     rItem[PROPNAME_CLIPBOARDFORMAT] <<= ::rtl::Uri::decode(sValue, rtl_UriDecodeWithCharset, RTL_TEXTENCODING_UTF8);
                    break;
        // URLPattern
        case 3:     rItem[PROPNAME_URLPATTERN] <<= comphelper::containerToSequence(impl_tokenizeString(sValue, ';'));
                    break;
        // Extensions
        case 4:     rItem[PROPNAME_EXTENSIONS] <<= comphelper::containerToSequence(impl_tokenizeString(sValue, ';'));
                    break;
    }
}


void FilterCache::impl_interpretDataVal4Filter(const OUString& sValue,
                                                     sal_Int32        nProp ,
                                                     CacheItem&       rItem )
{
    switch(nProp)
    {
        // Order
        case 0:     {
                        sal_Int32 nOrder = sValue.toInt32();
                        if (nOrder > 0)
                        {
                            SAL_WARN( "filter.config", "FilterCache::impl_interpretDataVal4Filter()\nCan not move Order value from filter to type on demand!");
                        }
                    }
                    break;
        // Type
        case 1:     rItem[PROPNAME_TYPE] <<= ::rtl::Uri::decode(sValue, rtl_UriDecodeWithCharset, RTL_TEXTENCODING_UTF8);
                    break;
        // DocumentService
        case 2:     rItem[PROPNAME_DOCUMENTSERVICE] <<= ::rtl::Uri::decode(sValue, rtl_UriDecodeWithCharset, RTL_TEXTENCODING_UTF8);
                    break;
        // FilterService
        case 3:     rItem[PROPNAME_FILTERSERVICE] <<= ::rtl::Uri::decode(sValue, rtl_UriDecodeWithCharset, RTL_TEXTENCODING_UTF8);
                    break;
        // Flags
        case 4:     rItem[PROPNAME_FLAGS] <<= sValue.toInt32();
                    break;
        // UserData
        case 5:     rItem[PROPNAME_USERDATA] <<= comphelper::containerToSequence(impl_tokenizeString(sValue, ';'));
                    break;
        // FileFormatVersion
        case 6:     rItem[PROPNAME_FILEFORMATVERSION] <<= sValue.toInt32();
                    break;
        // TemplateName
        case 7:     rItem[PROPNAME_TEMPLATENAME] <<= ::rtl::Uri::decode(sValue, rtl_UriDecodeWithCharset, RTL_TEXTENCODING_UTF8);
                    break;
        // [optional!] UIComponent
        case 8:     rItem[PROPNAME_UICOMPONENT] <<= ::rtl::Uri::decode(sValue, rtl_UriDecodeWithCharset, RTL_TEXTENCODING_UTF8);
                    break;
    }
}

/*-----------------------------------------------
    TODO work on a cache copy first, which can be flushed afterwards
         That would be useful to guarantee a consistent cache.
-----------------------------------------------*/
void FilterCache::impl_readOldFormat()
{
    // Attention: Opening/Reading of this old configuration format has to be handled gracefully.
    // Its optional and should not disturb our normal work!
    // E.g. we must check, if the package exists ...
    try
    {
        css::uno::Reference< css::uno::XInterface > xInt = impl_openConfig(E_PROVIDER_OLD);
        css::uno::Reference< css::container::XNameAccess > xCfg =
            css::uno::Reference< css::container::XNameAccess >(xInt, css::uno::UNO_QUERY_THROW);

        OUString TYPES_SET("Types");

        // May be there is no type set ...
        if (xCfg->hasByName(TYPES_SET))
        {
            css::uno::Reference< css::container::XNameAccess > xSet;
            xCfg->getByName(TYPES_SET) >>= xSet;
            const css::uno::Sequence< OUString > lItems = xSet->getElementNames();
            const OUString*                      pItems = lItems.getConstArray();
            for (sal_Int32 i=0; i<lItems.getLength(); ++i)
                m_lTypes[pItems[i]] = impl_readOldItem(xSet, E_TYPE, pItems[i]);
        }

        OUString FILTER_SET("Filters");
        // May be there is no filter set ...
        if (xCfg->hasByName(FILTER_SET))
        {
            css::uno::Reference< css::container::XNameAccess > xSet;
            xCfg->getByName(FILTER_SET) >>= xSet;
            const css::uno::Sequence< OUString > lItems = xSet->getElementNames();
            const OUString*                      pItems = lItems.getConstArray();
            for (sal_Int32 i=0; i<lItems.getLength(); ++i)
                m_lFilters[pItems[i]] = impl_readOldItem(xSet, E_FILTER, pItems[i]);
        }
    }
    /* corrupt filter addon? Because it's external (optional) code.. we can ignore it. Addon won't work then...
       but that seems to be acceptable.
       see #139088# for further information
    */
    catch(const css::uno::Exception&)
    {
    }
}

CacheItem FilterCache::impl_readOldItem(const css::uno::Reference< css::container::XNameAccess >& xSet ,
                                              EItemType                                           eType,
                                        const OUString&                                    sItem)
{
    css::uno::Reference< css::container::XNameAccess > xItem;
    xSet->getByName(sItem) >>= xItem;
    if (!xItem.is())
        throw css::uno::Exception("Can not read old item.", css::uno::Reference< css::uno::XInterface >());

    CacheItem aItem;
    aItem[PROPNAME_NAME] <<= sItem;

    // Installed flag ...
    // Isn't used any longer!

    // UIName
    impl_readPatchUINames(xItem, aItem);

    // Data
    OUString sData;
    std::vector<OUString>    lData;
    xItem->getByName( "Data" ) >>= sData;
    lData = impl_tokenizeString(sData, ',');
    if (
        (sData.isEmpty()) ||
        (lData.empty()    )
       )
    {
        throw css::uno::Exception( "Can not read old item property DATA.", css::uno::Reference< css::uno::XInterface >());
    }

    sal_Int32 nProp = 0;
    for (auto const& prop : lData)
    {
        switch(eType)
        {
            case E_TYPE :
                impl_interpretDataVal4Type(prop, nProp, aItem);
                break;

            case E_FILTER :
                impl_interpretDataVal4Filter(prop, nProp, aItem);
                break;
            default: break;
        }
        ++nProp;
    }

    return aItem;
}


std::vector<OUString> FilterCache::impl_tokenizeString(const OUString& sData     ,
                                                    sal_Unicode      cSeparator)
{
    std::vector<OUString> lData  ;
    sal_Int32    nToken = 0;
    do
    {
        OUString sToken = sData.getToken(0, cSeparator, nToken);
        lData.push_back(sToken);
    }
    while(nToken >= 0);
    return lData;
}

#if OSL_DEBUG_LEVEL > 0


OUString FilterCache::impl_searchFrameLoaderForType(const OUString& sType) const
{
    for (auto const& frameLoader : m_lFrameLoaders)
    {
        const OUString& sItem = frameLoader.first;
        ::comphelper::SequenceAsHashMap lProps(frameLoader.second);
        std::vector<OUString>           lTypes(
                comphelper::sequenceToContainer< std::vector<OUString> >(lProps[PROPNAME_TYPES].get<css::uno::Sequence<OUString> >()));

        if (::std::find(lTypes.begin(), lTypes.end(), sType) != lTypes.end())
            return sItem;
    }

    return OUString();
}


OUString FilterCache::impl_searchContentHandlerForType(const OUString& sType) const
{
    for (auto const& contentHandler : m_lContentHandlers)
    {
        const OUString& sItem = contentHandler.first;
        ::comphelper::SequenceAsHashMap lProps(contentHandler.second);
        std::vector<OUString>           lTypes(
                comphelper::sequenceToContainer< std::vector<OUString> >( lProps[PROPNAME_TYPES].get<css::uno::Sequence<OUString> >() ));
        if (::std::find(lTypes.begin(), lTypes.end(), sType) != lTypes.end())
            return sItem;
    }

    return OUString();
}
#endif


bool FilterCache::impl_isModuleInstalled(const OUString& sModule)
{
    css::uno::Reference< css::container::XNameAccess > xCfg;

    // SAFE ->
    {
        osl::MutexGuard aLock(m_aLock);
        if (!m_xModuleCfg.is())
        {
            m_xModuleCfg = officecfg::Setup::Office::Factories::get();
        }

        xCfg = m_xModuleCfg;
    }
    // <- SAFE

    if (xCfg.is())
        return xCfg->hasByName(sModule);

    return false;
}

    } // namespace config
} // namespace filter

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