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
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
/* -*- 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 <config_features.h>

#include <sfx2/sfxbasemodel.hxx>

#include <com/sun/star/datatransfer/UnsupportedFlavorException.hpp>
#include <com/sun/star/task/XInteractionHandler.hpp>
#include <com/sun/star/task/ErrorCodeIOException.hpp>
#include <com/sun/star/task/ErrorCodeRequest.hpp>
#include <com/sun/star/view/XSelectionSupplier.hpp>
#include <com/sun/star/view/XPrintJobListener.hpp>
#include <com/sun/star/lang/DisposedException.hpp>
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#include <com/sun/star/lang/NoSupportException.hpp>
#include <com/sun/star/lang/WrappedTargetRuntimeException.hpp>
#include <com/sun/star/lang/NotInitializedException.hpp>
#include <com/sun/star/frame/Desktop.hpp>
#include <com/sun/star/frame/IllegalArgumentIOException.hpp>
#include <com/sun/star/frame/XUntitledNumbers.hpp>
#include <com/sun/star/frame/DoubleInitializationException.hpp>
#include <com/sun/star/embed/XStorage.hpp>
#include <com/sun/star/document/XStorageChangeListener.hpp>
#include <com/sun/star/document/IndexedPropertyValues.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/beans/XPropertySetInfo.hpp>
#include <com/sun/star/container/XIndexContainer.hpp>
#include <com/sun/star/script/provider/theMasterScriptProviderFactory.hpp>
#include <com/sun/star/script/provider/XScriptProvider.hpp>
#include <com/sun/star/ui/UIConfigurationManager.hpp>
#include <com/sun/star/embed/ElementModes.hpp>
#include <com/sun/star/embed/Aspects.hpp>
#include <com/sun/star/document/DocumentProperties.hpp>
#include <com/sun/star/frame/XTransientDocumentsDocumentContentFactory.hpp>
#include <com/sun/star/ucb/XCommandEnvironment.hpp>
#include <com/sun/star/ucb/ContentCreationException.hpp>
#include <com/sun/star/ucb/CommandAbortedException.hpp>
#include <com/sun/star/util/XCloneable.hpp>
#include <com/sun/star/util/InvalidStateException.hpp>
#include <com/sun/star/util/CloseVetoException.hpp>
#include <comphelper/enumhelper.hxx>

#include <cppuhelper/implbase.hxx>
#include <cppuhelper/interfacecontainer.hxx>
#include <cppuhelper/exc_hlp.hxx>
#include <comphelper/processfactory.hxx>
#include <comphelper/sequenceashashmap.hxx>
#include <comphelper/namedvaluecollection.hxx>
#include <svl/itemset.hxx>
#include <svl/stritem.hxx>
#include <svl/eitem.hxx>
#include <svl/grabbagitem.hxx>
#include <tools/urlobj.hxx>
#include <tools/debug.hxx>
#include <tools/diagnose_ex.h>
#include <tools/svborder.hxx>
#include <unotools/tempfile.hxx>
#include <osl/mutex.hxx>
#include <vcl/errcode.hxx>
#include <vcl/salctype.hxx>
#include <vcl/gdimtf.hxx>
#include <comphelper/fileformat.h>
#include <comphelper/storagehelper.hxx>
#include <toolkit/helper/vclunohelper.hxx>
#include <vcl/transfer.hxx>
#include <svtools/ehdl.hxx>
#include <svtools/sfxecode.hxx>
#include <sal/log.hxx>
#include <framework/configimporter.hxx>
#include <framework/titlehelper.hxx>
#include <comphelper/numberedcollection.hxx>
#include <unotools/ucbhelper.hxx>
#include <ucbhelper/content.hxx>

#include <sfx2/sfxbasecontroller.hxx>
#include <sfx2/viewfac.hxx>
#include <workwin.hxx>
#include <sfx2/signaturestate.hxx>
#include <sfx2/sfxuno.hxx>
#include <objshimp.hxx>
#include <sfx2/viewfrm.hxx>
#include <sfx2/viewsh.hxx>
#include <sfx2/docfile.hxx>
#include <sfx2/docfilt.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/module.hxx>
#include <basic/basmgr.hxx>
#include <sfx2/event.hxx>
#include <eventsupplier.hxx>
#include <sfx2/sfxsids.hrc>
#include <sfx2/strings.hrc>
#include <sfx2/app.hxx>
#include <sfx2/docfac.hxx>
#include <sfx2/fcontnr.hxx>
#include <sfx2/docstoragemodifylistener.hxx>
#include <sfx2/brokenpackageint.hxx>
#include "graphhelp.hxx"
#include <docundomanager.hxx>
#include <openurlhint.hxx>
#include <sfx2/msgpool.hxx>
#include <sfx2/DocumentMetadataAccess.hxx>
#include "printhelper.hxx"
#include <sfx2/sfxresid.hxx>
#include <comphelper/profilezone.hxx>
#include <vcl/threadex.hxx>
#include <unotools/mediadescriptor.hxx>

//  namespaces


using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using ::com::sun::star::beans::PropertyValue;
using ::com::sun::star::document::CmisProperty;
using ::com::sun::star::frame::XFrame;
using ::com::sun::star::frame::XController;
using ::com::sun::star::frame::XController2;
using ::com::sun::star::lang::IllegalArgumentException;
using ::com::sun::star::io::IOException;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::document::XDocumentRecovery;
using ::com::sun::star::document::XUndoManager;
using ::com::sun::star::document::XUndoAction;
using ::com::sun::star::frame::XModel;

namespace {

/** This Listener is used to get notified when the XDocumentProperties of the
    XModel change.
 */
class SfxDocInfoListener_Impl : public ::cppu::WeakImplHelper<
    util::XModifyListener >
{

public:
    SfxObjectShell& m_rShell;

    explicit SfxDocInfoListener_Impl( SfxObjectShell& i_rDoc )
        : m_rShell(i_rDoc)
    { };

    virtual void SAL_CALL disposing( const lang::EventObject& ) override;
    virtual void SAL_CALL modified( const lang::EventObject& ) override;
};

}

void SAL_CALL SfxDocInfoListener_Impl::modified( const lang::EventObject& )
{
    SolarMutexGuard aSolarGuard;

    // notify changes to the SfxObjectShell
    m_rShell.FlushDocInfo();
}

void SAL_CALL SfxDocInfoListener_Impl::disposing( const lang::EventObject& )
{
}


//  impl. declarations


struct IMPL_SfxBaseModel_DataContainer : public ::sfx2::IModifiableDocument
{
    // counter for SfxBaseModel instances created.
    static sal_Int64                                           g_nInstanceCounter       ;
    SfxObjectShellRef                                          m_pObjectShell           ;
    OUString                                                   m_sURL                   ;
    OUString                                                   m_sRuntimeUID            ;
    OUString                                                   m_aPreusedFilterName     ;
    ::cppu::OMultiTypeInterfaceContainerHelper                 m_aInterfaceContainer    ;
    std::unordered_map<css::uno::Reference< css::drawing::XShape >,
                       std::vector<css::uno::Reference< css::document::XShapeEventListener >>> maShapeListeners;
    Reference< XInterface >                                    m_xParent                ;
    Reference< frame::XController >                            m_xCurrent               ;
    Reference< document::XDocumentProperties >                 m_xDocumentProperties    ;
    Reference< script::XStarBasicAccess >                      m_xStarBasicAccess       ;
    Reference< container::XNameReplace >                       m_xEvents                ;
    Sequence< beans::PropertyValue>                            m_seqArguments           ;
    std::vector< Reference< frame::XController > >             m_seqControllers         ;
    Reference< container::XIndexAccess >                       m_contViewData           ;
    sal_uInt16                                                 m_nControllerLockCount   ;
    bool                                                       m_bClosed                ;
    bool                                                       m_bClosing               ;
    bool                                                       m_bSaving                ;
    bool                                                       m_bSuicide               ;
    bool                                                       m_bExternalTitle         ;
    bool                                                       m_bModifiedSinceLastSave ;
    Reference< view::XPrintable>                               m_xPrintable             ;
    Reference< ui::XUIConfigurationManager2 >                  m_xUIConfigurationManager;
    ::rtl::Reference< ::sfx2::DocumentStorageModifyListener >  m_pStorageModifyListen   ;
    OUString                                                   m_sModuleIdentifier      ;
    Reference< frame::XTitle >                                 m_xTitleHelper           ;
    Reference< frame::XUntitledNumbers >                       m_xNumberedControllers   ;
    Reference< rdf::XDocumentMetadataAccess>                   m_xDocumentMetadata      ;
    ::rtl::Reference< ::sfx2::DocumentUndoManager >            m_pDocumentUndoManager   ;
    Sequence< document::CmisProperty>                          m_cmisProperties         ;
    std::shared_ptr<SfxGrabBagItem>                            m_xGrabBagItem           ;

    IMPL_SfxBaseModel_DataContainer( ::osl::Mutex& rMutex, SfxObjectShell* pObjectShell )
            :   m_pObjectShell          ( pObjectShell  )
            ,   m_aInterfaceContainer   ( rMutex        )
            ,   m_nControllerLockCount  ( 0             )
            ,   m_bClosed               ( false     )
            ,   m_bClosing              ( false     )
            ,   m_bSaving               ( false     )
            ,   m_bSuicide              ( false     )
            ,   m_bExternalTitle        ( false     )
            ,   m_bModifiedSinceLastSave( false     )
            ,   m_xTitleHelper          ()
            ,   m_xNumberedControllers  ()
            ,   m_xDocumentMetadata     () // lazy
            ,   m_pDocumentUndoManager  ()
            ,   m_cmisProperties  ()
    {
        // increase global instance counter.
        ++g_nInstanceCounter;
        // set own Runtime UID
        m_sRuntimeUID = OUString::number( g_nInstanceCounter );
    }

    virtual ~IMPL_SfxBaseModel_DataContainer()
    {
    }

    // ::sfx2::IModifiableDocument
    virtual void storageIsModified() override
    {
        if ( m_pObjectShell.is() && !m_pObjectShell->IsModified() )
            m_pObjectShell->SetModified();
    }

    void impl_setDocumentProperties(
            const Reference< document::XDocumentProperties >& );

    Reference<rdf::XDocumentMetadataAccess> GetDMA()
    {
        if (!m_xDocumentMetadata.is())
        {
            OSL_ENSURE(m_pObjectShell.is(), "GetDMA: no object shell?");
            if (!m_pObjectShell.is())
            {
                return nullptr;
            }

            const Reference<XComponentContext> xContext(
                ::comphelper::getProcessComponentContext());
            const Reference<frame::XModel> xModel(
                m_pObjectShell->GetModel());
            const Reference<lang::XMultiComponentFactory> xMsf(
                xContext->getServiceManager());
            const Reference<frame::
                XTransientDocumentsDocumentContentFactory> xTDDCF(
                    xMsf->createInstanceWithContext(
                        "com.sun.star.frame.TransientDocumentsDocumentContentFactory",
                    xContext),
                UNO_QUERY_THROW);
            const Reference<ucb::XContent> xContent(
                xTDDCF->createDocumentContent(xModel) );
            OSL_ENSURE(xContent.is(), "GetDMA: cannot create DocumentContent");
            if (!xContent.is())
            {
                return nullptr;
            }
            OUString uri = xContent->getIdentifier()->getContentIdentifier();
            OSL_ENSURE(!uri.isEmpty(), "GetDMA: empty uri?");
            if (!uri.isEmpty() && !uri.endsWith("/"))
            {
                uri += "/";
            }

            m_xDocumentMetadata = new ::sfx2::DocumentMetadataAccess(
                xContext, *m_pObjectShell, uri);
        }
        return m_xDocumentMetadata;
    }

    Reference<rdf::XDocumentMetadataAccess> CreateDMAUninitialized()
    {
        return (m_pObjectShell.is())
            ? new ::sfx2::DocumentMetadataAccess(
                ::comphelper::getProcessComponentContext(), *m_pObjectShell)
            : nullptr;
    }
};

// static member initialization.
sal_Int64 IMPL_SfxBaseModel_DataContainer::g_nInstanceCounter = 0;

namespace {

// Listener that forwards notifications from the PrintHelper to the "real" listeners
class SfxPrintHelperListener_Impl : public ::cppu::WeakImplHelper< view::XPrintJobListener >
{
public:
    IMPL_SfxBaseModel_DataContainer* m_pData;
    explicit SfxPrintHelperListener_Impl( IMPL_SfxBaseModel_DataContainer* pData )
        : m_pData( pData )
    {}

    virtual void SAL_CALL disposing( const lang::EventObject& aEvent ) override ;
    virtual void SAL_CALL printJobEvent( const view::PrintJobEvent& rEvent ) override;
};

}

void SAL_CALL SfxPrintHelperListener_Impl::disposing( const lang::EventObject& )
{
    m_pData->m_xPrintable = nullptr;
}

void SAL_CALL SfxPrintHelperListener_Impl::printJobEvent( const view::PrintJobEvent& rEvent )
{
    ::cppu::OInterfaceContainerHelper* pContainer = m_pData->m_aInterfaceContainer.getContainer( cppu::UnoType<view::XPrintJobListener>::get());
    if ( pContainer!=nullptr )
    {
        ::cppu::OInterfaceIteratorHelper pIterator(*pContainer);
        while (pIterator.hasMoreElements())
            static_cast<view::XPrintJobListener*>(pIterator.next())->printJobEvent( rEvent );
    }
}

namespace {

// SfxOwnFramesLocker ====================================================================================
// allows to lock all the frames related to the provided SfxObjectShell
class SfxOwnFramesLocker
{
    Sequence< Reference< frame::XFrame > > m_aLockedFrames;

    static vcl::Window* GetVCLWindow( const Reference< frame::XFrame >& xFrame );
public:
    explicit SfxOwnFramesLocker( SfxObjectShell const * ObjechShell );
    ~SfxOwnFramesLocker();
};

}

SfxOwnFramesLocker::SfxOwnFramesLocker( SfxObjectShell const * pObjectShell )
{
    if ( !pObjectShell )
        return;

    for (   SfxViewFrame *pFrame = SfxViewFrame::GetFirst( pObjectShell );
            pFrame;
            pFrame = SfxViewFrame::GetNext( *pFrame, pObjectShell )
        )
    {
        SfxFrame& rSfxFrame = pFrame->GetFrame();
        try
        {
            // get vcl window related to the frame and lock it if it is still not locked
            const Reference< frame::XFrame >& xFrame = rSfxFrame.GetFrameInterface();
            vcl::Window* pWindow = GetVCLWindow( xFrame );
            if ( !pWindow )
                throw RuntimeException();

            if ( pWindow->IsEnabled() )
            {
                pWindow->Disable();

                try
                {
                    sal_Int32 nLen = m_aLockedFrames.getLength();
                    m_aLockedFrames.realloc( nLen + 1 );
                    m_aLockedFrames[nLen] = xFrame;
                }
                catch( Exception& )
                {
                    pWindow->Enable();
                    throw;
                }
            }
        }
        catch( Exception& )
        {
            OSL_FAIL( "Not possible to lock the frame window!" );
        }
    }
}

SfxOwnFramesLocker::~SfxOwnFramesLocker()
{
    for ( auto& rFrame : m_aLockedFrames )
    {
        try
        {
            if ( rFrame.is() )
            {
                // get vcl window related to the frame and unlock it
                vcl::Window* pWindow = GetVCLWindow( rFrame );
                if ( !pWindow )
                    throw RuntimeException();

                pWindow->Enable();

                rFrame.clear();
            }
        }
        catch( Exception& )
        {
            OSL_FAIL( "Can't unlock the frame window!" );
        }
    }
}

vcl::Window* SfxOwnFramesLocker::GetVCLWindow( const Reference< frame::XFrame >& xFrame )
{
    VclPtr<vcl::Window> pWindow;

    if ( xFrame.is() )
    {
        Reference< awt::XWindow > xWindow = xFrame->getContainerWindow();
        if ( xWindow.is() )
               pWindow = VCLUnoHelper::GetWindow( xWindow );
    }

    return pWindow;
}

namespace {

// SfxSaveGuard ====================================================================================
class SfxSaveGuard
{
    private:
        Reference< frame::XModel > m_xModel;
        IMPL_SfxBaseModel_DataContainer* m_pData;
        std::unique_ptr<SfxOwnFramesLocker> m_pFramesLock;

        SfxSaveGuard(SfxSaveGuard const &) = delete;
        void operator =(const SfxSaveGuard&) = delete;

    public:
        SfxSaveGuard(const Reference< frame::XModel >&             xModel                      ,
                           IMPL_SfxBaseModel_DataContainer* pData);
        ~SfxSaveGuard();
};

}

SfxSaveGuard::SfxSaveGuard(const Reference< frame::XModel >&             xModel                      ,
                                 IMPL_SfxBaseModel_DataContainer* pData)
    : m_xModel     ( xModel )
    , m_pData      ( pData )
{
    if ( m_pData->m_bClosed )
        throw lang::DisposedException("Object already disposed.");

    m_pData->m_bSaving = true;
    m_pFramesLock.reset(new SfxOwnFramesLocker( m_pData->m_pObjectShell.get() ));
}

SfxSaveGuard::~SfxSaveGuard()
{
    m_pFramesLock.reset();

    m_pData->m_bSaving = false;

    // m_bSuicide was set e.g. in case someone tried to close a document, while it was used for
    // storing at the same time. Further m_bSuicide was set to sal_True only if close(sal_True) was called.
    // So the ownership was delegated to the place where a veto exception was thrown.
    // Now we have to call close() again and delegate the ownership to the next one, which
    // can't accept that. Close(sal_False) can't work in this case. Because then the document will may be never closed...

    if ( !m_pData->m_bSuicide )
        return;

    // Reset this state. In case the new close() request is not accepted by someone else...
    // it's not a good idea to have two "owners" for close.-)
    m_pData->m_bSuicide = false;
    try
    {
        Reference< util::XCloseable > xClose(m_xModel, UNO_QUERY);
        if (xClose.is())
            xClose->close(true);
    }
    catch(const util::CloseVetoException&)
    {}
}

SfxBaseModel::SfxBaseModel( SfxObjectShell *pObjectShell )
: BaseMutex()
, m_pData( std::make_shared<IMPL_SfxBaseModel_DataContainer>( m_aMutex, pObjectShell ) )
, m_bSupportEmbeddedScripts( pObjectShell && pObjectShell->Get_Impl() && !pObjectShell->Get_Impl()->m_bNoBasicCapabilities )
, m_bSupportDocRecovery( pObjectShell && pObjectShell->Get_Impl() && pObjectShell->Get_Impl()->m_bDocRecoverySupport )
{
    if ( pObjectShell != nullptr )
    {
        StartListening( *pObjectShell ) ;
    }
}

//  destructor
SfxBaseModel::~SfxBaseModel()
{
}

//  XInterface
Any SAL_CALL SfxBaseModel::queryInterface( const uno::Type& rType )
{
    if  (   ( !m_bSupportEmbeddedScripts && rType.equals( cppu::UnoType<document::XEmbeddedScripts>::get() ) )
        ||  ( !m_bSupportDocRecovery && rType.equals( cppu::UnoType<XDocumentRecovery>::get() ) )
        )
        return Any();

    return SfxBaseModel_Base::queryInterface( rType );
}


//  XTypeProvider


namespace
{
    void lcl_stripType( Sequence< uno::Type >& io_rTypes, const uno::Type& i_rTypeToStrip )
    {
        Sequence< uno::Type > aStrippedTypes( io_rTypes.getLength() - 1 );
        ::std::remove_copy_if(
            io_rTypes.begin(),
            io_rTypes.end(),
            aStrippedTypes.getArray(),
            [&i_rTypeToStrip](const uno::Type& aType) { return aType == i_rTypeToStrip; }
        );
        io_rTypes = aStrippedTypes;
    }
}

Sequence< uno::Type > SAL_CALL SfxBaseModel::getTypes()
{
    Sequence< uno::Type > aTypes( SfxBaseModel_Base::getTypes() );

    if ( !m_bSupportEmbeddedScripts )
        lcl_stripType( aTypes, cppu::UnoType<document::XEmbeddedScripts>::get() );

    if ( !m_bSupportDocRecovery )
        lcl_stripType( aTypes, cppu::UnoType<XDocumentRecovery>::get() );

    return aTypes;
}


//  XTypeProvider


Sequence< sal_Int8 > SAL_CALL SfxBaseModel::getImplementationId()
{
    return css::uno::Sequence<sal_Int8>();
}


//  XStarBasicAccess

#if HAVE_FEATURE_SCRIPTING

static Reference< script::XStarBasicAccess > implGetStarBasicAccess( SfxObjectShell const * pObjectShell )
{
    Reference< script::XStarBasicAccess > xRet;

#if !HAVE_FEATURE_SCRIPTING
    (void) pObjectShell;
#else
    if( pObjectShell )
    {
        BasicManager* pMgr = pObjectShell->GetBasicManager();
        xRet = getStarBasicAccess( pMgr );
    }
#endif
    return xRet;
}

#endif

Reference< container::XNameContainer > SAL_CALL SfxBaseModel::getLibraryContainer()
{
#if !HAVE_FEATURE_SCRIPTING
    Reference< container::XNameContainer > dummy;

    return dummy;
#else
    SfxModelGuard aGuard( *this );

    Reference< script::XStarBasicAccess >& rxAccess = m_pData->m_xStarBasicAccess;
    if( !rxAccess.is() && m_pData->m_pObjectShell.is() )
        rxAccess = implGetStarBasicAccess( m_pData->m_pObjectShell.get() );

    Reference< container::XNameContainer > xRet;
    if( rxAccess.is() )
        xRet = rxAccess->getLibraryContainer();
    return xRet;
#endif
}

/**___________________________________________________________________________________________________
    @seealso    XStarBasicAccess
*/
void SAL_CALL SfxBaseModel::createLibrary( const OUString& LibName, const OUString& Password,
    const OUString& ExternalSourceURL, const OUString& LinkTargetURL )
{
#if !HAVE_FEATURE_SCRIPTING
    (void) LibName;
    (void) Password;
    (void) ExternalSourceURL;
    (void) LinkTargetURL;
#else
    SfxModelGuard aGuard( *this );

    Reference< script::XStarBasicAccess >& rxAccess = m_pData->m_xStarBasicAccess;
    if( !rxAccess.is() && m_pData->m_pObjectShell.is() )
        rxAccess = implGetStarBasicAccess( m_pData->m_pObjectShell.get() );

    if( rxAccess.is() )
        rxAccess->createLibrary( LibName, Password, ExternalSourceURL, LinkTargetURL );
#endif
}

/**___________________________________________________________________________________________________
    @seealso    XStarBasicAccess
*/
void SAL_CALL SfxBaseModel::addModule( const OUString& LibraryName, const OUString& ModuleName,
    const OUString& Language, const OUString& Source )
{
#if !HAVE_FEATURE_SCRIPTING
    (void) LibraryName;
    (void) ModuleName;
    (void) Language;
    (void) Source;
#else
    SfxModelGuard aGuard( *this );

    Reference< script::XStarBasicAccess >& rxAccess = m_pData->m_xStarBasicAccess;
    if( !rxAccess.is() && m_pData->m_pObjectShell.is() )
        rxAccess = implGetStarBasicAccess( m_pData->m_pObjectShell.get() );

    if( rxAccess.is() )
        rxAccess->addModule( LibraryName, ModuleName, Language, Source );
#endif
}

/**___________________________________________________________________________________________________
    @seealso    XStarBasicAccess
*/
void SAL_CALL SfxBaseModel::addDialog( const OUString& LibraryName, const OUString& DialogName,
    const Sequence< sal_Int8 >& Data )
{
#if !HAVE_FEATURE_SCRIPTING
    (void) LibraryName;
    (void) DialogName;
    (void) Data;
#else
    SfxModelGuard aGuard( *this );

    Reference< script::XStarBasicAccess >& rxAccess = m_pData->m_xStarBasicAccess;
    if( !rxAccess.is() && m_pData->m_pObjectShell.is() )
        rxAccess = implGetStarBasicAccess( m_pData->m_pObjectShell.get() );

    if( rxAccess.is() )
        rxAccess->addDialog( LibraryName, DialogName, Data );
#endif
}


//  XChild


Reference< XInterface > SAL_CALL SfxBaseModel::getParent()
{
    SfxModelGuard aGuard( *this );

    return m_pData->m_xParent;
}


//  XChild


void SAL_CALL SfxBaseModel::setParent(const Reference< XInterface >& Parent)
{
    SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );
    m_pData->m_xParent = Parent;
}


//  XChild


void SAL_CALL SfxBaseModel::dispose()
{
    SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );

    if  ( !m_pData->m_bClosed )
    {
        // gracefully accept wrong dispose calls instead of close call
        // and try to make it work (may be really disposed later!)
        try
        {
            close( true );
        }
        catch ( util::CloseVetoException& )
        {
        }

        return;
    }

    if ( m_pData->m_pStorageModifyListen.is() )
    {
        m_pData->m_pStorageModifyListen->dispose();
        m_pData->m_pStorageModifyListen = nullptr;
    }

    if ( m_pData->m_pDocumentUndoManager.is() )
    {
        m_pData->m_pDocumentUndoManager->disposing();
        m_pData->m_pDocumentUndoManager = nullptr;
    }

    lang::EventObject aEvent( static_cast<frame::XModel *>(this) );
    m_pData->m_aInterfaceContainer.disposeAndClear( aEvent );

    m_pData->m_xDocumentProperties.clear();

    m_pData->m_xDocumentMetadata.clear();

    if ( m_pData->m_pObjectShell.is() )
    {
        EndListening( *m_pData->m_pObjectShell );
    }

    m_pData->m_xCurrent.clear();
    m_pData->m_seqControllers.clear();

    // m_pData member must be set to zero before delete is called to
    // force disposed exception whenever someone tries to access our
    // instance while in the dtor.
    m_pData.reset();
}


//  XChild


void SAL_CALL SfxBaseModel::addEventListener( const Reference< lang::XEventListener >& aListener )
{
    SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );
    m_pData->m_aInterfaceContainer.addInterface( cppu::UnoType<lang::XEventListener>::get(), aListener );
}


//  XChild


void SAL_CALL SfxBaseModel::removeEventListener( const Reference< lang::XEventListener >& aListener )
{
    SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );
    m_pData->m_aInterfaceContainer.removeInterface( cppu::UnoType<lang::XEventListener>::get(), aListener );
}

void
IMPL_SfxBaseModel_DataContainer::impl_setDocumentProperties(
        const Reference< document::XDocumentProperties >& rxNewDocProps)
{
    m_xDocumentProperties.set(rxNewDocProps, UNO_SET_THROW);
    if (m_pObjectShell.is())
    {
        Reference<util::XModifyBroadcaster> const xMB(
            m_xDocumentProperties, UNO_QUERY_THROW);
        xMB->addModifyListener(new SfxDocInfoListener_Impl(*m_pObjectShell));
    }
}

// document::XDocumentPropertiesSupplier:
Reference< document::XDocumentProperties > SAL_CALL
SfxBaseModel::getDocumentProperties()
{
    SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );
    if ( !m_pData->m_xDocumentProperties.is() )
    {
        Reference< document::XDocumentProperties > xDocProps(
            document::DocumentProperties::create( ::comphelper::getProcessComponentContext() ) );
        m_pData->impl_setDocumentProperties(xDocProps);
    }

    return m_pData->m_xDocumentProperties;
}


//  lang::XEventListener


void SAL_CALL SfxBaseModel::disposing( const lang::EventObject& aObject )
{
    SolarMutexGuard aGuard;
    if ( impl_isDisposed() )
        return;

    Reference< util::XModifyListener >  xMod( aObject.Source, UNO_QUERY );
    Reference< lang::XEventListener >  xListener( aObject.Source, UNO_QUERY );
    Reference< document::XEventListener >  xDocListener( aObject.Source, UNO_QUERY );

    if ( xMod.is() )
        m_pData->m_aInterfaceContainer.removeInterface( cppu::UnoType<util::XModifyListener>::get(), xMod );
    else if ( xListener.is() )
        m_pData->m_aInterfaceContainer.removeInterface( cppu::UnoType<lang::XEventListener>::get(), xListener );
    else if ( xDocListener.is() )
        m_pData->m_aInterfaceContainer.removeInterface( cppu::UnoType<document::XEventListener>::get(), xListener );
}


//  frame::XModel


sal_Bool SAL_CALL SfxBaseModel::attachResource( const   OUString&                   rURL    ,
                                                const   Sequence< beans::PropertyValue >&  rArgs   )
{
    SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );
    if ( rURL.isEmpty() && rArgs.getLength() == 1 && rArgs[0].Name == "SetEmbedded" )
    {
        // allows to set a windowless document to EMBEDDED state
        // but _only_ before load() or initNew() methods
        if ( m_pData->m_pObjectShell.is() && !m_pData->m_pObjectShell->GetMedium() )
        {
            bool bEmb(false);
            if ( ( rArgs[0].Value >>= bEmb ) && bEmb )
                m_pData->m_pObjectShell->SetCreateMode_Impl( SfxObjectCreateMode::EMBEDDED );
        }

        return true;
    }

    if ( m_pData->m_pObjectShell.is() )
    {
        m_pData->m_sURL = rURL;

        SfxObjectShell* pObjectShell = m_pData->m_pObjectShell.get();

        ::comphelper::NamedValueCollection aArgs( rArgs );

        Sequence< sal_Int32 > aWinExtent;
        if ( ( aArgs.get( "WinExtent" ) >>= aWinExtent )&& ( aWinExtent.getLength() == 4 ) )
        {
            tools::Rectangle aVisArea( aWinExtent[0], aWinExtent[1], aWinExtent[2], aWinExtent[3] );
            aVisArea = OutputDevice::LogicToLogic(aVisArea, MapMode(MapUnit::Map100thMM), MapMode(pObjectShell->GetMapUnit()));
            pObjectShell->SetVisArea( aVisArea );
        }

        bool bBreakMacroSign = false;
        if ( aArgs.get( "BreakMacroSignature" ) >>= bBreakMacroSign )
        {
            pObjectShell->BreakMacroSign_Impl( bBreakMacroSign );
        }

        bool bMacroEventRead = false;<--- Assignment 'bMacroEventRead=false', assigned value is 0
        if ((aArgs.get("MacroEventRead") >>= bMacroEventRead) && bMacroEventRead)<--- Condition 'bMacroEventRead' is always false
        {
            pObjectShell->SetMacroCallsSeenWhileLoading();
        }

        aArgs.remove( "WinExtent" );
        aArgs.remove( "BreakMacroSignature" );
        aArgs.remove( "MacroEventRead" );
        aArgs.remove( "Stream" );
        aArgs.remove( "InputStream" );
        aArgs.remove( "URL" );
        aArgs.remove( "Frame" );
        aArgs.remove( "Password" );
        aArgs.remove( "EncryptionData" );

        // TODO/LATER: all the parameters that are accepted by ItemSet of the DocShell must be removed here

        m_pData->m_seqArguments = aArgs.getPropertyValues();

        SfxMedium* pMedium = pObjectShell->GetMedium();
        if ( pMedium )
        {
            SfxAllItemSet aSet( pObjectShell->GetPool() );
            TransformParameters( SID_OPENDOC, rArgs, aSet );

            // the arguments are not allowed to reach the medium
            aSet.ClearItem( SID_FILE_NAME );
            aSet.ClearItem( SID_FILLFRAME );

            pMedium->GetItemSet()->Put( aSet );
            const SfxStringItem* pItem = aSet.GetItem<SfxStringItem>(SID_FILTER_NAME, false);
            if ( pItem )
                pMedium->SetFilter(
                    pObjectShell->GetFactory().GetFilterContainer()->GetFilter4FilterName( pItem->GetValue() ) );

            const SfxStringItem* pTitleItem = aSet.GetItem<SfxStringItem>(SID_DOCINFO_TITLE, false);
            if ( pTitleItem )
            {
                SfxViewFrame* pFrame = SfxViewFrame::GetFirst( pObjectShell );
                if ( pFrame )
                    pFrame->UpdateTitle();
            }
        }
    }

    return true ;
}


//  frame::XModel


OUString SAL_CALL SfxBaseModel::getURL()
{
    SfxModelGuard aGuard( *this );
    return m_pData->m_sURL ;
}


//  frame::XModel


Sequence< beans::PropertyValue > SAL_CALL SfxBaseModel::getArgs()
{
    SfxModelGuard aGuard( *this );

    if (!SfxApplication::Get()) // tdf#113755
    {
        SAL_WARN("sfx.appl", "Unexpected operations on model");
        return m_pData->m_seqArguments;
    }

    if ( m_pData->m_pObjectShell.is() )
    {
        Sequence< beans::PropertyValue > seqArgsNew;
        Sequence< beans::PropertyValue > seqArgsOld;
        SfxAllItemSet aSet( m_pData->m_pObjectShell->GetPool() );

        // we need to know which properties are supported by the transformer
        // hopefully it is a temporary solution, I guess nonconvertable properties
        // should not be supported so then there will be only ItemSet from medium

        TransformItems( SID_OPENDOC, *(m_pData->m_pObjectShell->GetMedium()->GetItemSet()), seqArgsNew );
        TransformParameters( SID_OPENDOC, m_pData->m_seqArguments, aSet );
        TransformItems( SID_OPENDOC, aSet, seqArgsOld );

        sal_Int32 nNewLength = seqArgsNew.getLength();

        // "WinExtent" property should be updated always.
        // We can store it now to overwrite an old value
        // since it is not from ItemSet
        tools::Rectangle aTmpRect = m_pData->m_pObjectShell->GetVisArea( ASPECT_CONTENT );
        aTmpRect = OutputDevice::LogicToLogic(aTmpRect, MapMode(m_pData->m_pObjectShell->GetMapUnit()), MapMode(MapUnit::Map100thMM));

        Sequence< sal_Int32 > aRectSeq(4);
        aRectSeq[0] = aTmpRect.Left();
        aRectSeq[1] = aTmpRect.Top();
        aRectSeq[2] = aTmpRect.IsWidthEmpty() ? aTmpRect.Left() : aTmpRect.Right();
        aRectSeq[3] = aTmpRect.IsHeightEmpty() ? aTmpRect.Top() : aTmpRect.Bottom();

        seqArgsNew.realloc( ++nNewLength );
        seqArgsNew[ nNewLength - 1 ].Name = "WinExtent";
        seqArgsNew[ nNewLength - 1 ].Value <<= aRectSeq;

        if ( !m_pData->m_aPreusedFilterName.isEmpty() )
        {
            seqArgsNew.realloc( ++nNewLength );
            seqArgsNew[ nNewLength - 1 ].Name = "PreusedFilterName";
            seqArgsNew[ nNewLength - 1 ].Value <<= m_pData->m_aPreusedFilterName;
        }

        SfxViewFrame* pFrame = SfxViewFrame::GetFirst( m_pData->m_pObjectShell.get() );
        if ( pFrame )
        {
            SvBorder aBorder = pFrame->GetBorderPixelImpl();

            Sequence< sal_Int32 > aBorderSeq(4);
            aBorderSeq[0] = aBorder.Left();
            aBorderSeq[1] = aBorder.Top();
            aBorderSeq[2] = aBorder.Right();
            aBorderSeq[3] = aBorder.Bottom();

            seqArgsNew.realloc( ++nNewLength );
            seqArgsNew[ nNewLength - 1 ].Name = "DocumentBorder";
            seqArgsNew[ nNewLength - 1 ].Value <<= aBorderSeq;
        }

        // only the values that are not supported by the ItemSet must be cached here
        Sequence< beans::PropertyValue > aFinalCache;
        sal_Int32 nFinalLength = 0;

        for ( const auto& rOrg : std::as_const(m_pData->m_seqArguments) )
        {
            auto bNew = std::none_of(seqArgsOld.begin(), seqArgsOld.end(),
                [&rOrg](const beans::PropertyValue& rOld){ return rOld.Name == rOrg.Name; });
            if ( bNew )
            {
                // the entity with this name should be new for seqArgsNew
                // since it is not supported by transformer

                seqArgsNew.realloc( ++nNewLength );
                seqArgsNew[ nNewLength - 1 ] = rOrg;

                aFinalCache.realloc( ++nFinalLength );
                aFinalCache[ nFinalLength - 1 ] = rOrg;
            }
        }

        m_pData->m_seqArguments = aFinalCache;

        return seqArgsNew;
    }

    return m_pData->m_seqArguments;
}

void SAL_CALL SfxBaseModel::setArgs(const Sequence<beans::PropertyValue>& aArgs)
{
    SfxModelGuard aGuard( *this );

    SfxMedium* pMedium = m_pData->m_pObjectShell->GetMedium();
    if (!pMedium)
    {
        throw util::InvalidStateException(
            "Medium could not be retrieved, unable to execute setArgs");
    }

    for (const auto& rArg : aArgs)
    {
        OUString sValue;
        bool bValue;
        bool ok = false;
        if (rArg.Name == "SuggestedSaveAsName")
        {
            if (rArg.Value >>= sValue)
            {
                pMedium->GetItemSet()->Put(SfxStringItem(SID_SUGGESTEDSAVEASNAME, sValue));
                ok = true;
            }
        }
        else if (rArg.Name == "SuggestedSaveAsDir")
        {
            if (rArg.Value >>= sValue)
            {
                pMedium->GetItemSet()->Put(SfxStringItem(SID_SUGGESTEDSAVEASDIR, sValue));
                ok = true;
            }
        }
        else if (rArg.Name == "LockContentExtraction")
        {
            if (rArg.Value >>= bValue)<--- Uninitialized variable: bValue
            {
                pMedium->GetItemSet()->Put(SfxBoolItem(SID_LOCK_CONTENT_EXTRACTION, bValue));
                ok = true;
            }
        }
        else if (rArg.Name == "LockExport")
        {
            if (rArg.Value >>= bValue)<--- Uninitialized variable: bValue
            {
                pMedium->GetItemSet()->Put(SfxBoolItem(SID_LOCK_EXPORT, bValue));
                ok = true;
            }
        }
        else if (rArg.Name == "LockPrint")
        {
            if (rArg.Value >>= bValue)<--- Uninitialized variable: bValue
            {
                pMedium->GetItemSet()->Put(SfxBoolItem(SID_LOCK_PRINT, bValue));
                ok = true;
            }
        }
        else if (rArg.Name == "LockSave")
        {
            if (rArg.Value >>= bValue)<--- Uninitialized variable: bValue
            {
                pMedium->GetItemSet()->Put(SfxBoolItem(SID_LOCK_SAVE, bValue));
                ok = true;
            }
        }
        else if (rArg.Name == "LockEditDoc")
        {
            if (rArg.Value >>= bValue)<--- Uninitialized variable: bValue
            {
                pMedium->GetItemSet()->Put(SfxBoolItem(SID_LOCK_EDITDOC, bValue));
                ok = true;
            }
        }
        else if (rArg.Name == "Replaceable")
        {
            if (rArg.Value >>= bValue)<--- Uninitialized variable: bValue
            {
                pMedium->GetItemSet()->Put(SfxBoolItem(SID_REPLACEABLE, bValue));
                ok = true;
            }
        }
        else if (rArg.Name == "EncryptionData")
        {
            pMedium->GetItemSet()->Put(SfxUnoAnyItem(SID_ENCRYPTIONDATA, rArg.Value));
            ok = true;
        }
        if (!ok)
        {
            throw lang::IllegalArgumentException("Setting property not supported: " + rArg.Name,
                                                 comphelper::getProcessComponentContext(), 0);
        }
    }
}

//  frame::XModel


void SAL_CALL SfxBaseModel::connectController( const Reference< frame::XController >& xController )
{
    SfxModelGuard aGuard( *this );
    OSL_PRECOND( xController.is(), "SfxBaseModel::connectController: invalid controller!" );
    if ( !xController.is() )
        return;

    m_pData->m_seqControllers.push_back(xController);

    if ( m_pData->m_seqControllers.size() == 1 )
    {
        SfxViewFrame* pViewFrame = SfxViewFrame::Get( xController, GetObjectShell() );
        ENSURE_OR_THROW( pViewFrame, "SFX document without SFX view!?" );
        pViewFrame->UpdateDocument_Impl();
        const OUString sDocumentURL = GetObjectShell()->GetMedium()->GetName();
        if ( !sDocumentURL.isEmpty() )
            SfxGetpApp()->Broadcast( SfxOpenUrlHint( sDocumentURL ) );
    }
}


//  frame::XModel


void SAL_CALL SfxBaseModel::disconnectController( const Reference< frame::XController >& xController )
{
    SfxModelGuard aGuard( *this );

    if ( m_pData->m_seqControllers.empty() )
        return;

    auto& vec = m_pData->m_seqControllers;
    vec.erase(std::remove(vec.begin(), vec.end(), xController), vec.end());

    if ( xController == m_pData->m_xCurrent )
        m_pData->m_xCurrent.clear();
}

namespace
{
    class ControllerLockUndoAction : public ::cppu::WeakImplHelper< XUndoAction >
    {
    public:
        ControllerLockUndoAction( const Reference< XModel >& i_model, const bool i_undoIsUnlock )
            :m_xModel( i_model )
            ,m_bUndoIsUnlock( i_undoIsUnlock )
        {
        }

        // XUndoAction
        virtual OUString SAL_CALL getTitle() override;
        virtual void SAL_CALL undo(  ) override;
        virtual void SAL_CALL redo(  ) override;

    private:
        const Reference< XModel >   m_xModel;
        const bool                  m_bUndoIsUnlock;
    };

    OUString SAL_CALL ControllerLockUndoAction::getTitle()
    {
        // this action is intended to be used within an UndoContext only, so nobody will ever see this title ...
        return OUString();
    }

    void SAL_CALL ControllerLockUndoAction::undo(  )
    {
        if ( m_bUndoIsUnlock )
            m_xModel->unlockControllers();
        else
            m_xModel->lockControllers();
    }

    void SAL_CALL ControllerLockUndoAction::redo(  )
    {
        if ( m_bUndoIsUnlock )
            m_xModel->lockControllers();
        else
            m_xModel->unlockControllers();
    }
}


//  frame::XModel


void SAL_CALL SfxBaseModel::lockControllers()
{
    SfxModelGuard aGuard( *this );

    ++m_pData->m_nControllerLockCount ;

    if  (   m_pData->m_pDocumentUndoManager.is()
        &&  m_pData->m_pDocumentUndoManager->isInContext()
        &&  !m_pData->m_pDocumentUndoManager->isLocked()
        )
    {
        m_pData->m_pDocumentUndoManager->addUndoAction( new ControllerLockUndoAction( this, true ) );
    }
}


//  frame::XModel


void SAL_CALL SfxBaseModel::unlockControllers()
{
    SfxModelGuard aGuard( *this );

    --m_pData->m_nControllerLockCount ;

    if  (   m_pData->m_pDocumentUndoManager.is()
        &&  m_pData->m_pDocumentUndoManager->isInContext()
        &&  !m_pData->m_pDocumentUndoManager->isLocked()
        )
    {
        m_pData->m_pDocumentUndoManager->addUndoAction( new ControllerLockUndoAction( this, false ) );
    }
}


//  frame::XModel


sal_Bool SAL_CALL SfxBaseModel::hasControllersLocked()
{
    SfxModelGuard aGuard( *this );
    return ( m_pData->m_nControllerLockCount != 0 ) ;
}


//  frame::XModel


Reference< frame::XController > SAL_CALL SfxBaseModel::getCurrentController()
{
    SfxModelGuard aGuard( *this );

    // get the last active controller of this model
    if ( m_pData->m_xCurrent.is() )
        return m_pData->m_xCurrent;

    // get the first controller of this model
    return !m_pData->m_seqControllers.empty() ? m_pData->m_seqControllers.front() : m_pData->m_xCurrent;
}


//  frame::XModel


void SAL_CALL SfxBaseModel::setCurrentController( const Reference< frame::XController >& xCurrentController )
{
    SfxModelGuard aGuard( *this );

    m_pData->m_xCurrent = xCurrentController;
}


//  frame::XModel


Reference< XInterface > SAL_CALL SfxBaseModel::getCurrentSelection()
{
    SfxModelGuard aGuard( *this );

    Reference< XInterface >     xReturn;
    Reference< frame::XController >    xController =   getCurrentController()      ;

    if ( xController.is() )
    {
        Reference< view::XSelectionSupplier >  xDocView( xController, UNO_QUERY );
        if ( xDocView.is() )
        {
            Any aSel = xDocView->getSelection();<--- Variable 'aSel' is assigned a value that is never used.
            aSel >>= xReturn ;<--- Variable 'aSel' is assigned a value that is never used.
        }
    }

    return xReturn ;
}


//  XModifiable2


sal_Bool SAL_CALL SfxBaseModel::disableSetModified()
{
    SfxModelGuard aGuard( *this );

    if ( !m_pData->m_pObjectShell.is() )
        throw RuntimeException();

    bool bResult = m_pData->m_pObjectShell->IsEnableSetModified();
    m_pData->m_pObjectShell->EnableSetModified( false );

    return bResult;
}

sal_Bool SAL_CALL SfxBaseModel::enableSetModified()
{
    SfxModelGuard aGuard( *this );

    if ( !m_pData->m_pObjectShell.is() )
        throw RuntimeException();

    bool bResult = m_pData->m_pObjectShell->IsEnableSetModified();
    m_pData->m_pObjectShell->EnableSetModified();

    return bResult;
}

sal_Bool SAL_CALL SfxBaseModel::isSetModifiedEnabled()
{
    SfxModelGuard aGuard( *this );

    if ( !m_pData->m_pObjectShell.is() )
        throw RuntimeException();

    return m_pData->m_pObjectShell->IsEnableSetModified();
}


//  XModifiable


sal_Bool SAL_CALL SfxBaseModel::isModified()
{
    SfxModelGuard aGuard( *this );

    return m_pData->m_pObjectShell.is() && m_pData->m_pObjectShell->IsModified();
}


//  XModifiable


void SAL_CALL SfxBaseModel::setModified( sal_Bool bModified )
{
    SfxModelGuard aGuard( *this );

    if ( m_pData->m_pObjectShell.is() )
        m_pData->m_pObjectShell->SetModified(bModified);
}


//  XModifiable


void SAL_CALL SfxBaseModel::addModifyListener(const Reference< util::XModifyListener >& xListener)
{
    SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );

    m_pData->m_aInterfaceContainer.addInterface( cppu::UnoType<util::XModifyListener>::get(),xListener );
}


//  XModifiable


void SAL_CALL SfxBaseModel::removeModifyListener(const Reference< util::XModifyListener >& xListener)
{
    SfxModelGuard aGuard( *this );

    m_pData->m_aInterfaceContainer.removeInterface( cppu::UnoType<util::XModifyListener>::get(), xListener );
}


//  XCloseable


void SAL_CALL SfxBaseModel::close( sal_Bool bDeliverOwnership )
{
    SolarMutexGuard aGuard;
    if ( impl_isDisposed() || m_pData->m_bClosed || m_pData->m_bClosing )
        return;

    Reference< XInterface > xSelfHold( static_cast< ::cppu::OWeakObject* >(this) );
    lang::EventObject       aSource  ( static_cast< ::cppu::OWeakObject* >(this) );
    ::cppu::OInterfaceContainerHelper* pContainer = m_pData->m_aInterfaceContainer.getContainer( cppu::UnoType<util::XCloseListener>::get());
    if (pContainer!=nullptr)
    {
        ::cppu::OInterfaceIteratorHelper pIterator(*pContainer);
        while (pIterator.hasMoreElements())
        {
            try
            {
                static_cast<util::XCloseListener*>(pIterator.next())->queryClosing( aSource, bDeliverOwnership );
            }
            catch( RuntimeException& )
            {
                pIterator.remove();
            }
        }
    }

    if ( m_pData->m_bSaving )
    {
        if (bDeliverOwnership)
            m_pData->m_bSuicide = true;
        throw util::CloseVetoException(
                "Can not close while saving.",
                static_cast< util::XCloseable* >(this));
    }

    // no own objections against closing!
    m_pData->m_bClosing = true;
    pContainer = m_pData->m_aInterfaceContainer.getContainer( cppu::UnoType<util::XCloseListener>::get());
    if (pContainer!=nullptr)
    {
        ::cppu::OInterfaceIteratorHelper pCloseIterator(*pContainer);
        while (pCloseIterator.hasMoreElements())
        {
            try
            {
                static_cast<util::XCloseListener*>(pCloseIterator.next())->notifyClosing( aSource );
            }
            catch( RuntimeException& )
            {
                pCloseIterator.remove();
            }
        }
    }

    m_pData->m_bClosed = true;
    m_pData->m_bClosing = false;

    dispose();
}


//  XCloseBroadcaster


void SAL_CALL SfxBaseModel::addCloseListener( const Reference< util::XCloseListener >& xListener )
{
    SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );

    m_pData->m_aInterfaceContainer.addInterface( cppu::UnoType<util::XCloseListener>::get(), xListener );
}


//  XCloseBroadcaster


void SAL_CALL SfxBaseModel::removeCloseListener( const Reference< util::XCloseListener >& xListener )
{
    SfxModelGuard aGuard( *this );

    m_pData->m_aInterfaceContainer.removeInterface( cppu::UnoType<util::XCloseListener>::get(), xListener );
}


//  XPrintable


Sequence< beans::PropertyValue > SAL_CALL SfxBaseModel::getPrinter()
{
    SfxModelGuard aGuard( *this );

    impl_getPrintHelper();
    return m_pData->m_xPrintable->getPrinter();
}

void SAL_CALL SfxBaseModel::setPrinter(const Sequence< beans::PropertyValue >& rPrinter)
{
    SfxModelGuard aGuard( *this );

    impl_getPrintHelper();
    m_pData->m_xPrintable->setPrinter( rPrinter );
}

void SAL_CALL SfxBaseModel::print(const Sequence< beans::PropertyValue >& rOptions)
{
    SfxModelGuard aGuard( *this );

    impl_getPrintHelper();

    // tdf#123728 Always print on main thread to avoid deadlocks
    vcl::solarthread::syncExecute([this, &rOptions]() { m_pData->m_xPrintable->print(rOptions); });
}

//  XStorable


sal_Bool SAL_CALL SfxBaseModel::hasLocation()
{
    SfxModelGuard aGuard( *this );

    return m_pData->m_pObjectShell.is() && m_pData->m_pObjectShell->HasName();
}


//  XStorable


OUString SAL_CALL SfxBaseModel::getLocation()
{
    SfxModelGuard aGuard( *this );

    if ( m_pData->m_pObjectShell.is() )
    {
        // TODO/LATER: is it correct that the shared document returns shared file location?
        if ( m_pData->m_pObjectShell->IsDocShared() )
            return m_pData->m_pObjectShell->GetSharedFileURL();
        else
            return m_pData->m_pObjectShell->GetMedium()->GetName();
    }

    return m_pData->m_sURL;
}


//  XStorable


sal_Bool SAL_CALL SfxBaseModel::isReadonly()
{
    SfxModelGuard aGuard( *this );

    return !m_pData->m_pObjectShell.is() || m_pData->m_pObjectShell->IsReadOnly();
}

//  XStorable2


void SAL_CALL SfxBaseModel::storeSelf( const    Sequence< beans::PropertyValue >&  aSeqArgs )
{
    SfxModelGuard aGuard( *this );

    if ( !m_pData->m_pObjectShell.is() )
        return;

    SfxSaveGuard aSaveGuard(this, m_pData.get());

    bool bCheckIn = false;<--- Assignment 'bCheckIn=false', assigned value is 0
    bool bOnMainThread = false;<--- Assignment 'bOnMainThread=false', assigned value is 0
    for ( const auto& rArg : aSeqArgs )
    {
        // check that only acceptable parameters are provided here
        if ( rArg.Name != "VersionComment" && rArg.Name != "Author"
          && rArg.Name != "DontTerminateEdit"
          && rArg.Name != "InteractionHandler" && rArg.Name != "StatusIndicator"
          && rArg.Name != "VersionMajor"
          && rArg.Name != "FailOnWarning"
          && rArg.Name != "CheckIn"
          && rArg.Name != "NoFileSync"
          && rArg.Name != "OnMainThread" )
        {
            const OUString aMessage( "Unexpected MediaDescriptor parameter: " + rArg.Name );
            throw lang::IllegalArgumentException( aMessage, Reference< XInterface >(), 1 );
        }
        else if ( rArg.Name == "CheckIn" )
        {
            rArg.Value >>= bCheckIn;
        }
        else if (rArg.Name == "OnMainThread")
        {
            rArg.Value >>= bOnMainThread;
        }
    }

    // Remove CheckIn property if needed
    sal_uInt16 nSlotId = SID_SAVEDOC;
    Sequence< beans::PropertyValue >  aArgs = aSeqArgs;
    if ( bCheckIn )<--- Condition 'bCheckIn' is always false
    {
        nSlotId = SID_CHECKIN;
        sal_Int32 nLength = aSeqArgs.getLength( );
        aArgs = Sequence< beans::PropertyValue >( nLength - 1 );
        std::copy_if(aSeqArgs.begin(), aSeqArgs.end(), aArgs.begin(),
            [](const beans::PropertyValue& rProp) { return rProp.Name != "CheckIn"; });
    }

    std::unique_ptr<SfxAllItemSet> pParams(new SfxAllItemSet( SfxGetpApp()->GetPool() ));
    TransformParameters( nSlotId, aArgs, *pParams );

    SfxGetpApp()->NotifyEvent( SfxEventHint( SfxEventHintId::SaveDoc, GlobalEventConfig::GetEventName(GlobalEventId::SAVEDOC), m_pData->m_pObjectShell.get() ) );

    bool bRet = false;

    // TODO/LATER: let the embedded case of saving be handled more careful
    if ( m_pData->m_pObjectShell->GetCreateMode() == SfxObjectCreateMode::EMBEDDED )
    {
        // If this is an embedded object that has no URL based location it should be stored to own storage.
        // An embedded object can have a location based on URL in case it is a link, then it should be
        // stored in normal way.
        if ( !hasLocation() || getLocation().startsWith("private:") )
        {
            // actually in this very rare case only UI parameters have sense
            // TODO/LATER: should be done later, after integration of sb19
            bRet = m_pData->m_pObjectShell->DoSave()
                && m_pData->m_pObjectShell->DoSaveCompleted();
        }
        else
        {
            bRet = m_pData->m_pObjectShell->Save_Impl( pParams.get() );
        }
    }
    else
    {
        // Tell the SfxMedium if we are in checkin instead of normal save
        m_pData->m_pObjectShell->GetMedium( )->SetInCheckIn( nSlotId == SID_CHECKIN );
        if (bOnMainThread)<--- Condition 'bOnMainThread' is always false
            bRet = vcl::solarthread::syncExecute(
                [this, &pParams] { return m_pData->m_pObjectShell->Save_Impl(pParams.get()); });
        else
            bRet = m_pData->m_pObjectShell->Save_Impl(pParams.get());
        m_pData->m_pObjectShell->GetMedium( )->SetInCheckIn( nSlotId != SID_CHECKIN );
    }

    pParams.reset();

    ErrCode nErrCode = m_pData->m_pObjectShell->GetError() ? m_pData->m_pObjectShell->GetError()
                                                           : ERRCODE_IO_CANTWRITE;
    m_pData->m_pObjectShell->ResetError();

    if ( bRet )
    {
        m_pData->m_aPreusedFilterName = GetMediumFilterName_Impl();

        SfxGetpApp()->NotifyEvent( SfxEventHint( SfxEventHintId::SaveDocDone, GlobalEventConfig::GetEventName(GlobalEventId::SAVEDOCDONE), m_pData->m_pObjectShell.get() ) );
    }
    else
    {
        // write the contents of the logger to the file
        SfxGetpApp()->NotifyEvent( SfxEventHint( SfxEventHintId::SaveDocFailed, GlobalEventConfig::GetEventName(GlobalEventId::SAVEDOCFAILED), m_pData->m_pObjectShell.get() ) );

        throw task::ErrorCodeIOException(
            "SfxBaseModel::storeSelf: " + nErrCode.toHexString(),
            Reference< XInterface >(), sal_uInt32(nErrCode));
    }
}


//  XStorable


void SAL_CALL SfxBaseModel::store()
{
    comphelper::ProfileZone aZone("store");
    storeSelf( Sequence< beans::PropertyValue >() );
}


//  XStorable


void SAL_CALL SfxBaseModel::storeAsURL( const   OUString&                   rURL    ,
                                        const   Sequence< beans::PropertyValue >&  rArgs   )
{
    SfxModelGuard aGuard( *this );
    comphelper::ProfileZone aZone("storeAs");

    if ( !m_pData->m_pObjectShell.is() )
        return;

    SfxSaveGuard aSaveGuard(this, m_pData.get());

    impl_store( rURL, rArgs, false );

    Sequence< beans::PropertyValue > aSequence ;
    TransformItems( SID_OPENDOC, *m_pData->m_pObjectShell->GetMedium()->GetItemSet(), aSequence );
    attachResource( rURL, aSequence );

    loadCmisProperties( );

#if OSL_DEBUG_LEVEL > 0
    const SfxStringItem* pPasswdItem = SfxItemSet::GetItem<SfxStringItem>(m_pData->m_pObjectShell->GetMedium()->GetItemSet(), SID_PASSWORD, false);
    OSL_ENSURE( !pPasswdItem, "There should be no Password property in the document MediaDescriptor!" );
#endif
}


//  XUndoManagerSupplier

Reference< XUndoManager > SAL_CALL SfxBaseModel::getUndoManager(  )
{
    SfxModelGuard aGuard( *this );
    if ( !m_pData->m_pDocumentUndoManager.is() )
        m_pData->m_pDocumentUndoManager.set( new ::sfx2::DocumentUndoManager( *this ) );
    return m_pData->m_pDocumentUndoManager.get();
}


//  XStorable


void SAL_CALL SfxBaseModel::storeToURL( const   OUString&                   rURL    ,
                                        const   Sequence< beans::PropertyValue >&  rArgs   )
{
    SfxModelGuard aGuard( *this );
    comphelper::ProfileZone aZone("storeToURL");

    if ( !m_pData->m_pObjectShell.is() )
        return;

    SfxSaveGuard aSaveGuard(this, m_pData.get());
    try {
        utl::MediaDescriptor aDescriptor(rArgs);
        bool bOnMainThread = aDescriptor.getUnpackedValueOrDefault("OnMainThread", false);
        if (bOnMainThread)
            vcl::solarthread::syncExecute([this, rURL, rArgs]() { impl_store(rURL, rArgs, true); });
        else
            impl_store(rURL, rArgs, true);
    }
    catch (const uno::Exception &e)
    {
        // convert to the exception we announce in the throw
        // (eg. neon likes to throw InteractiveAugmentedIOException which
        // is not an io::IOException)
        throw io::IOException(e.Message, e.Context);
    }
}

sal_Bool SAL_CALL SfxBaseModel::wasModifiedSinceLastSave()
{
    SfxModelGuard aGuard( *this );
    return m_pData->m_bModifiedSinceLastSave;
}

void SAL_CALL SfxBaseModel::storeToRecoveryFile( const OUString& i_TargetLocation, const Sequence< PropertyValue >& i_MediaDescriptor )
{
    SfxModelGuard aGuard( *this );

    // delegate
    SfxSaveGuard aSaveGuard( this, m_pData.get() );
    impl_store( i_TargetLocation, i_MediaDescriptor, true );

    // no need for subsequent calls to storeToRecoveryFile, unless we're modified, again
    m_pData->m_bModifiedSinceLastSave = false;
}

void SAL_CALL SfxBaseModel::recoverFromFile( const OUString& i_SourceLocation, const OUString& i_SalvagedFile, const Sequence< PropertyValue >& i_MediaDescriptor )
{
    SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );

    // delegate to our "load" method
    ::comphelper::NamedValueCollection aMediaDescriptor( i_MediaDescriptor );

    // our load implementation expects the SalvagedFile to be in the media descriptor
    OSL_ENSURE( !aMediaDescriptor.has( "SalvagedFile" ) || ( aMediaDescriptor.getOrDefault( "SalvagedFile", OUString() ) == i_SalvagedFile ),
        "SfxBaseModel::recoverFromFile: inconsistent information!" );
    aMediaDescriptor.put( "SalvagedFile", i_SalvagedFile );

    // similar for the to-be-loaded file
    OSL_ENSURE( !aMediaDescriptor.has( "URL" ) || ( aMediaDescriptor.getOrDefault( "URL", OUString() ) == i_SourceLocation ),
        "SfxBaseModel::recoverFromFile: inconsistent information!" );
    aMediaDescriptor.put( "URL", i_SourceLocation );

    load( aMediaDescriptor.getPropertyValues() );

    // Note: The XDocumentRecovery interface specification requires us to do an attachResource after loading.
    // However, we will not do this here, as we know that our load implementation (respectively some method
    // called from there) already did so.
    // In particular, the load process might already have modified some elements of the media
    // descriptor, for instance the MacroExecMode (in case the user was involved to decide about it), and we do
    // not want to overwrite it with the "old" elements passed to this method here.
}


// XLoadable


void SAL_CALL SfxBaseModel::initNew()
{
    SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );
    if ( IsInitialized() )
        throw frame::DoubleInitializationException( OUString(), *this );

    // the object shell should exist always
    DBG_ASSERT( m_pData->m_pObjectShell.is(), "Model is useless without an ObjectShell" );
    if ( !m_pData->m_pObjectShell.is() )
        return;

    if( m_pData->m_pObjectShell->GetMedium() )
        throw frame::DoubleInitializationException();

    bool bRes = m_pData->m_pObjectShell->DoInitNew();
    ErrCode nErrCode = m_pData->m_pObjectShell->GetError() ?
                       m_pData->m_pObjectShell->GetError() : ERRCODE_IO_CANTCREATE;
    m_pData->m_pObjectShell->ResetError();

    if ( !bRes )
        throw task::ErrorCodeIOException(
            "SfxBaseModel::initNew: " + nErrCode.toHexString(),
            Reference< XInterface >(), sal_uInt32(nErrCode));
}

namespace {

OUString getFilterProvider( SfxMedium const & rMedium )
{
    const std::shared_ptr<const SfxFilter>& pFilter = rMedium.GetFilter();
    if (!pFilter)
        return OUString();

    return pFilter->GetProviderName();
}

void setUpdatePickList( SfxMedium* pMedium )
{
    if (!pMedium)
        return;

    bool bHidden = false;
    const SfxBoolItem* pHidItem = SfxItemSet::GetItem<SfxBoolItem>(pMedium->GetItemSet(), SID_HIDDEN, false);
    if (pHidItem)
        bHidden = pHidItem->GetValue();

    pMedium->SetUpdatePickList(!bHidden);
}

}

void SAL_CALL SfxBaseModel::load(   const Sequence< beans::PropertyValue >& seqArguments )
{
    SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );
    if ( IsInitialized() )
        throw frame::DoubleInitializationException( OUString(), *this );

    // the object shell should exist always
    DBG_ASSERT( m_pData->m_pObjectShell.is(), "Model is useless without an ObjectShell" );

    if (!m_pData->m_pObjectShell.is())
        return;

    if( m_pData->m_pObjectShell->GetMedium() )
        // if a Medium is present, the document is already initialized
        throw frame::DoubleInitializationException();

    SfxMedium* pMedium = new SfxMedium( seqArguments );

    ErrCode nError = ERRCODE_NONE;
    if (!getFilterProvider(*pMedium).isEmpty())
    {
        if (!m_pData->m_pObjectShell->DoLoadExternal(pMedium))
            nError = ERRCODE_IO_GENERAL;

        pMedium = handleLoadError(nError, pMedium);
        setUpdatePickList(pMedium);
        return;
    }

    OUString aFilterName;
    const SfxStringItem* pFilterNameItem = SfxItemSet::GetItem<SfxStringItem>(pMedium->GetItemSet(), SID_FILTER_NAME, false);
    if( pFilterNameItem )
        aFilterName = pFilterNameItem->GetValue();
    if( !m_pData->m_pObjectShell->GetFactory().GetFilterContainer()->GetFilter4FilterName( aFilterName ) )
    {
        // filtername is not valid
        delete pMedium;
        throw frame::IllegalArgumentIOException();
    }

    const SfxStringItem* pSalvageItem = SfxItemSet::GetItem<SfxStringItem>(pMedium->GetItemSet(), SID_DOC_SALVAGE, false);
    bool bSalvage = pSalvageItem != nullptr;

    // load document
    if ( !m_pData->m_pObjectShell->DoLoad(pMedium) )
        nError=ERRCODE_IO_GENERAL;

    // QUESTION: if the following happens outside of DoLoad, something important is missing there!
    Reference< task::XInteractionHandler > xHandler = pMedium->GetInteractionHandler();
    if( m_pData->m_pObjectShell->GetErrorCode() )
    {
        nError = m_pData->m_pObjectShell->GetErrorCode();
        if ( nError == ERRCODE_IO_BROKENPACKAGE && xHandler.is() )
        {
            const OUString aDocName( pMedium->GetURLObject().getName( INetURLObject::LAST_SEGMENT, true, INetURLObject::DecodeMechanism::WithCharset ) );
            const SfxBoolItem* pRepairItem = SfxItemSet::GetItem<SfxBoolItem>(pMedium->GetItemSet(), SID_REPAIRPACKAGE, false);
            if ( !pRepairItem || !pRepairItem->GetValue() )
            {
                RequestPackageReparation aRequest( aDocName );
                xHandler->handle( aRequest.GetRequest() );
                if( aRequest.isApproved() )
                {
                    // broken package: try second loading and allow repair
                    pMedium->GetItemSet()->Put( SfxBoolItem( SID_REPAIRPACKAGE, true ) );
                    pMedium->GetItemSet()->Put( SfxBoolItem( SID_TEMPLATE, true ) );
                    pMedium->GetItemSet()->Put( SfxStringItem( SID_DOCINFO_TITLE, aDocName ) );

                    // the error must be reset and the storage must be reopened in new mode
                    pMedium->ResetError();
                    pMedium->CloseStorage();
                    m_pData->m_pObjectShell->PrepareSecondTryLoad_Impl();
                    nError = ERRCODE_NONE;
                    if ( !m_pData->m_pObjectShell->DoLoad(pMedium) )
                        nError=ERRCODE_IO_GENERAL;
                    if (m_pData->m_pObjectShell->GetErrorCode())
                        nError = m_pData->m_pObjectShell->GetErrorCode();
                }
            }

            if ( nError == ERRCODE_IO_BROKENPACKAGE )
            {
                // repair either not allowed or not successful
                NotifyBrokenPackage aRequest( aDocName );
                xHandler->handle( aRequest.GetRequest() );
            }
        }
    }

    if( m_pData->m_pObjectShell->IsAbortingImport() )
        nError = ERRCODE_ABORT;

    if( bSalvage )
    {
        // file recovery: restore original filter
        const SfxStringItem* pFilterItem = SfxItemSet::GetItem<SfxStringItem>(pMedium->GetItemSet(), SID_FILTER_NAME, false);
        SfxFilterMatcher& rMatcher = SfxGetpApp()->GetFilterMatcher();
        std::shared_ptr<const SfxFilter> pSetFilter = rMatcher.GetFilter4FilterName( pFilterItem->GetValue() );
        pMedium->SetFilter( pSetFilter );
        m_pData->m_pObjectShell->SetModified();
    }

    // TODO/LATER: maybe the mode should be retrieved from outside and the preused filter should not be set
    if ( m_pData->m_pObjectShell->GetCreateMode() == SfxObjectCreateMode::EMBEDDED )
    {
        const SfxStringItem* pFilterItem = SfxItemSet::GetItem<SfxStringItem>(pMedium->GetItemSet(), SID_FILTER_NAME, false);
        if ( pFilterItem )
            m_pData->m_aPreusedFilterName = pFilterItem->GetValue();
    }

    if ( !nError )
        nError = pMedium->GetError();

    m_pData->m_pObjectShell->ResetError();

    pMedium = handleLoadError(nError, pMedium);
    loadCmisProperties();
    setUpdatePickList(pMedium);

#if OSL_DEBUG_LEVEL > 0
    const SfxStringItem* pPasswdItem = SfxItemSet::GetItem<SfxStringItem>(pMedium->GetItemSet(), SID_PASSWORD, false);
    OSL_ENSURE( !pPasswdItem, "There should be no Password property in the document MediaDescriptor!" );
#endif
}


// XTransferable


Any SAL_CALL SfxBaseModel::getTransferData( const datatransfer::DataFlavor& aFlavor )
{
    SfxModelGuard aGuard( *this );

    Any aAny;

    if ( m_pData->m_pObjectShell.is() )
    {
        if ( aFlavor.MimeType == "application/x-openoffice-objectdescriptor-xml;windows_formatname=\"Star Object Descriptor (XML)\"" )
        {
            if ( aFlavor.DataType != cppu::UnoType<Sequence< sal_Int8 >>::get() )
                throw datatransfer::UnsupportedFlavorException();

            TransferableObjectDescriptor aDesc;

            aDesc.maClassName = m_pData->m_pObjectShell->GetClassName();
            aDesc.maTypeName = aFlavor.HumanPresentableName;

            // TODO/LATER: ViewAspect needs to be sal_Int64
            aDesc.mnViewAspect = sal::static_int_cast< sal_uInt16 >( embed::Aspects::MSOLE_CONTENT );

            Size aSize = m_pData->m_pObjectShell->GetVisArea().GetSize();

            MapUnit aMapUnit = m_pData->m_pObjectShell->GetMapUnit();
            aDesc.maSize = OutputDevice::LogicToLogic(aSize, MapMode(aMapUnit), MapMode(MapUnit::Map100thMM));
            aDesc.maDragStartPos = Point();
            aDesc.maDisplayName.clear();

            SvMemoryStream aMemStm( 1024, 1024 );
            WriteTransferableObjectDescriptor( aMemStm, aDesc );
            aAny <<= Sequence< sal_Int8 >( static_cast< const sal_Int8* >( aMemStm.GetData() ), aMemStm.Tell() );
        }
        else if ( aFlavor.MimeType == "application/x-openoffice-embed-source;windows_formatname=\"Star EMBS\"" )
        {
            if ( aFlavor.DataType != cppu::UnoType<Sequence< sal_Int8 >>::get() )
                throw datatransfer::UnsupportedFlavorException();

            try
            {
                utl::TempFile aTmp;
                aTmp.EnableKillingFile();
                storeToURL( aTmp.GetURL(), Sequence < beans::PropertyValue >() );
                std::unique_ptr<SvStream> pStream(aTmp.GetStream( StreamMode::READ ));
                const sal_uInt32 nLen = pStream->TellEnd();
                Sequence< sal_Int8 > aSeq( nLen );
                pStream->ReadBytes(aSeq.getArray(), nLen);
                if( aSeq.hasElements() )
                    aAny <<= aSeq;
            }
            catch ( Exception& )
            {
            }
        }
        else if ( aFlavor.MimeType == "application/x-openoffice-gdimetafile;windows_formatname=\"GDIMetaFile\"" )
        {
            if ( aFlavor.DataType != cppu::UnoType<Sequence< sal_Int8 >>::get() )
                throw datatransfer::UnsupportedFlavorException();


            std::shared_ptr<GDIMetaFile> xMetaFile =
                m_pData->m_pObjectShell->GetPreviewMetaFile( true );

            if (xMetaFile)
            {
                SvMemoryStream aMemStm( 65535, 65535 );
                aMemStm.SetVersion( SOFFICE_FILEFORMAT_CURRENT );

                xMetaFile->Write( aMemStm );
                aAny <<= Sequence< sal_Int8 >( static_cast< const sal_Int8* >( aMemStm.GetData() ),
                                                aMemStm.TellEnd() );
            }
        }
        else if ( aFlavor.MimeType == "application/x-openoffice-highcontrast-gdimetafile;windows_formatname=\"GDIMetaFile\"" )
        {
            if ( aFlavor.DataType != cppu::UnoType<Sequence< sal_Int8 >>::get() )
                throw datatransfer::UnsupportedFlavorException();

            std::shared_ptr<GDIMetaFile> xMetaFile =
                m_pData->m_pObjectShell->CreatePreviewMetaFile_Impl( true );

            if (xMetaFile)
            {
                SvMemoryStream aMemStm( 65535, 65535 );
                aMemStm.SetVersion( SOFFICE_FILEFORMAT_CURRENT );

                xMetaFile->Write( aMemStm );
                aAny <<= Sequence< sal_Int8 >( static_cast< const sal_Int8* >( aMemStm.GetData() ),
                                                aMemStm.TellEnd() );
            }
        }
        else if ( aFlavor.MimeType == "application/x-openoffice-emf;windows_formatname=\"Image EMF\"" )
        {
            if ( aFlavor.DataType == cppu::UnoType<Sequence< sal_Int8 >>::get() )
            {
                std::shared_ptr<GDIMetaFile> xMetaFile =
                    m_pData->m_pObjectShell->GetPreviewMetaFile( true );

                if (xMetaFile)
                {
                    std::unique_ptr<SvMemoryStream> xStream(
                        GraphicHelper::getFormatStrFromGDI_Impl(
                            xMetaFile.get(), ConvertDataFormat::EMF ) );
                    if (xStream)
                    {
                        xStream->SetVersion( SOFFICE_FILEFORMAT_CURRENT );
                        aAny <<= Sequence< sal_Int8 >( static_cast< const sal_Int8* >( xStream->GetData() ),
                                                        xStream->TellEnd() );
                    }
                }
            }
            else if ( GraphicHelper::supportsMetaFileHandle_Impl()
              && aFlavor.DataType == cppu::UnoType<sal_uInt64>::get())
            {
                std::shared_ptr<GDIMetaFile> xMetaFile =
                    m_pData->m_pObjectShell->GetPreviewMetaFile( true );

                if (xMetaFile)
                {
                    aAny <<= reinterpret_cast< sal_uInt64 >(
                        GraphicHelper::getEnhMetaFileFromGDI_Impl( xMetaFile.get() ) );
                }
            }
            else
                throw datatransfer::UnsupportedFlavorException();
        }
        else if ( aFlavor.MimeType == "application/x-openoffice-wmf;windows_formatname=\"Image WMF\"" )
        {
            if ( aFlavor.DataType == cppu::UnoType<Sequence< sal_Int8 >>::get() )
            {
                std::shared_ptr<GDIMetaFile> xMetaFile =
                    m_pData->m_pObjectShell->GetPreviewMetaFile( true );

                if (xMetaFile)
                {
                    std::unique_ptr<SvMemoryStream> xStream(
                        GraphicHelper::getFormatStrFromGDI_Impl(
                            xMetaFile.get(), ConvertDataFormat::WMF ) );

                    if (xStream)
                    {
                        xStream->SetVersion( SOFFICE_FILEFORMAT_CURRENT );
                        aAny <<= Sequence< sal_Int8 >( static_cast< const sal_Int8* >( xStream->GetData() ),
                                                        xStream->TellEnd() );
                    }
                }
            }
            else if ( GraphicHelper::supportsMetaFileHandle_Impl()
              && aFlavor.DataType == cppu::UnoType<sal_uInt64>::get())
            {
                // means HGLOBAL handler to memory storage containing METAFILEPICT structure

                std::shared_ptr<GDIMetaFile> xMetaFile =
                    m_pData->m_pObjectShell->GetPreviewMetaFile( true );

                if (xMetaFile)
                {
                    Size aMetaSize = xMetaFile->GetPrefSize();
                    aAny <<= reinterpret_cast< sal_uInt64 >(
                        GraphicHelper::getWinMetaFileFromGDI_Impl(
                            xMetaFile.get(), aMetaSize ) );
                }
            }
            else
                throw datatransfer::UnsupportedFlavorException();
        }
        else if ( aFlavor.MimeType == "application/x-openoffice-bitmap;windows_formatname=\"Bitmap\"" )
        {
            if ( aFlavor.DataType != cppu::UnoType<Sequence< sal_Int8 >>::get() )
                throw datatransfer::UnsupportedFlavorException();

            std::shared_ptr<GDIMetaFile> xMetaFile =
                m_pData->m_pObjectShell->GetPreviewMetaFile( true );

            if (xMetaFile)
            {
                std::unique_ptr<SvMemoryStream> xStream(
                    GraphicHelper::getFormatStrFromGDI_Impl(
                        xMetaFile.get(), ConvertDataFormat::BMP ) );

                if (xStream)
                {
                    xStream->SetVersion( SOFFICE_FILEFORMAT_CURRENT );
                    aAny <<= Sequence< sal_Int8 >( static_cast< const sal_Int8* >( xStream->GetData() ),
                                                    xStream->TellEnd() );
                }
            }
        }
        else if ( aFlavor.MimeType == "image/png" )
        {
            if ( aFlavor.DataType != cppu::UnoType<Sequence< sal_Int8 >>::get() )
                throw datatransfer::UnsupportedFlavorException();

            std::shared_ptr<GDIMetaFile> xMetaFile =
                m_pData->m_pObjectShell->GetPreviewMetaFile( true );

            if (xMetaFile)
            {
                std::unique_ptr<SvMemoryStream> xStream(
                    GraphicHelper::getFormatStrFromGDI_Impl(
                        xMetaFile.get(), ConvertDataFormat::PNG ) );

                if (xStream)
                {
                    xStream->SetVersion( SOFFICE_FILEFORMAT_CURRENT );
                    aAny <<= Sequence< sal_Int8 >( static_cast< const sal_Int8* >( xStream->GetData() ),
                                                    xStream->TellEnd() );
                }
            }
        }
        else
            throw datatransfer::UnsupportedFlavorException();
    }

    return aAny;
}


// XTransferable


Sequence< datatransfer::DataFlavor > SAL_CALL SfxBaseModel::getTransferDataFlavors()
{
    SfxModelGuard aGuard( *this );

    const sal_Int32 nSuppFlavors = GraphicHelper::supportsMetaFileHandle_Impl() ? 10 : 8;
    Sequence< datatransfer::DataFlavor > aFlavorSeq( nSuppFlavors );

    aFlavorSeq[0].MimeType =
        "application/x-openoffice-gdimetafile;windows_formatname=\"GDIMetaFile\"";
    aFlavorSeq[0].HumanPresentableName =  "GDIMetaFile";
    aFlavorSeq[0].DataType = cppu::UnoType<Sequence< sal_Int8 >>::get();

    aFlavorSeq[1].MimeType =
        "application/x-openoffice-highcontrast-gdimetafile;windows_formatname=\"GDIMetaFile\"";
    aFlavorSeq[1].HumanPresentableName = "GDIMetaFile";
    aFlavorSeq[1].DataType = cppu::UnoType<Sequence< sal_Int8 >>::get();

    aFlavorSeq[2].MimeType =
        "application/x-openoffice-emf;windows_formatname=\"Image EMF\"" ;
    aFlavorSeq[2].HumanPresentableName = "Enhanced Windows MetaFile";
    aFlavorSeq[2].DataType = cppu::UnoType<Sequence< sal_Int8 >>::get();

    aFlavorSeq[3].MimeType =
        "application/x-openoffice-wmf;windows_formatname=\"Image WMF\"";
    aFlavorSeq[3].HumanPresentableName = "Windows MetaFile";
    aFlavorSeq[3].DataType = cppu::UnoType<Sequence< sal_Int8 >>::get();

    aFlavorSeq[4].MimeType =
        "application/x-openoffice-objectdescriptor-xml;windows_formatname=\"Star Object Descriptor (XML)\"";
    aFlavorSeq[4].HumanPresentableName = "Star Object Descriptor (XML)";
    aFlavorSeq[4].DataType = cppu::UnoType<Sequence< sal_Int8 >>::get();

    aFlavorSeq[5].MimeType =
        "application/x-openoffice-embed-source-xml;windows_formatname=\"Star Embed Source (XML)\"";
    aFlavorSeq[5].HumanPresentableName = "Star Embed Source (XML)";
    aFlavorSeq[5].DataType = cppu::UnoType<Sequence< sal_Int8 >>::get();

    aFlavorSeq[6].MimeType =
        "application/x-openoffice-bitmap;windows_formatname=\"Bitmap\"";
    aFlavorSeq[6].HumanPresentableName = "Bitmap";
    aFlavorSeq[6].DataType = cppu::UnoType<Sequence< sal_Int8 >>::get();

    aFlavorSeq[7].MimeType = "image/png";
    aFlavorSeq[7].HumanPresentableName = "PNG";
    aFlavorSeq[7].DataType = cppu::UnoType<Sequence< sal_Int8 >>::get();

    if ( nSuppFlavors == 10 )
    {
        aFlavorSeq[8].MimeType =
            "application/x-openoffice-emf;windows_formatname=\"Image EMF\"";
        aFlavorSeq[8].HumanPresentableName = "Enhanced Windows MetaFile";
        aFlavorSeq[8].DataType = cppu::UnoType<sal_uInt64>::get();

        aFlavorSeq[9].MimeType =
            "application/x-openoffice-wmf;windows_formatname=\"Image WMF\"";
        aFlavorSeq[9].HumanPresentableName = "Windows MetaFile";
        aFlavorSeq[9].DataType = cppu::UnoType<sal_uInt64>::get();
    }

    return aFlavorSeq;
}


// XTransferable


sal_Bool SAL_CALL SfxBaseModel::isDataFlavorSupported( const datatransfer::DataFlavor& aFlavor )
{
    SfxModelGuard aGuard( *this );

    if ( aFlavor.MimeType == "application/x-openoffice-gdimetafile;windows_formatname=\"GDIMetaFile\"" )
    {
        if ( aFlavor.DataType == cppu::UnoType<Sequence< sal_Int8 >>::get() )
            return true;
    }
    else if ( aFlavor.MimeType == "application/x-openoffice-highcontrast-gdimetafile;windows_formatname=\"GDIMetaFile\"" )
    {
        if ( aFlavor.DataType == cppu::UnoType<Sequence< sal_Int8 >>::get() )
            return true;
    }
    else if ( aFlavor.MimeType == "application/x-openoffice-emf;windows_formatname=\"Image EMF\"" )
    {
        if ( aFlavor.DataType == cppu::UnoType<Sequence< sal_Int8 >>::get() )
            return true;
        else if ( GraphicHelper::supportsMetaFileHandle_Impl()
          && aFlavor.DataType == cppu::UnoType<sal_uInt64>::get())
            return true;
    }
    else if ( aFlavor.MimeType == "application/x-openoffice-wmf;windows_formatname=\"Image WMF\"" )
    {
        if ( aFlavor.DataType == cppu::UnoType<Sequence< sal_Int8 >>::get() )
            return true;
        else if ( GraphicHelper::supportsMetaFileHandle_Impl()
          && aFlavor.DataType == cppu::UnoType<sal_uInt64>::get())
            return true;
    }
    else if ( aFlavor.MimeType == "application/x-openoffice-objectdescriptor-xml;windows_formatname=\"Star Object Descriptor (XML)\"" )
    {
        if ( aFlavor.DataType == cppu::UnoType<Sequence< sal_Int8 >>::get() )
            return true;
    }
    else if ( aFlavor.MimeType == "application/x-openoffice-embed-source;windows_formatname=\"Star EMBS\"" )
    {
        if ( aFlavor.DataType == cppu::UnoType<Sequence< sal_Int8 >>::get() )
            return true;
    }
    else if ( aFlavor.MimeType == "application/x-openoffice-bitmap;windows_formatname=\"Bitmap\"" )
    {
        if ( aFlavor.DataType == cppu::UnoType<Sequence< sal_Int8 >>::get() )
            return true;
    }
    else if ( aFlavor.MimeType == "image/png" )
    {
        if ( aFlavor.DataType == cppu::UnoType<Sequence< sal_Int8 >>::get() )
            return true;
    }

    return false;
}


//  XEventsSupplier


Reference< container::XNameReplace > SAL_CALL SfxBaseModel::getEvents()
{
    SfxModelGuard aGuard( *this );

    if ( ! m_pData->m_xEvents.is() )
    {
        m_pData->m_xEvents = new SfxEvents_Impl( m_pData->m_pObjectShell.get(), this );
    }

    return m_pData->m_xEvents;
}


//  XEmbeddedScripts


Reference< script::XStorageBasedLibraryContainer > SAL_CALL SfxBaseModel::getBasicLibraries()
{
    SfxModelGuard aGuard( *this );

    Reference< script::XStorageBasedLibraryContainer > xBasicLibraries;
    if ( m_pData->m_pObjectShell.is() )
        xBasicLibraries.set(m_pData->m_pObjectShell->GetBasicContainer(), UNO_QUERY);
    return xBasicLibraries;
}

Reference< script::XStorageBasedLibraryContainer > SAL_CALL SfxBaseModel::getDialogLibraries()
{
    SfxModelGuard aGuard( *this );

    Reference< script::XStorageBasedLibraryContainer > xDialogLibraries;
    if ( m_pData->m_pObjectShell.is() )
        xDialogLibraries.set(m_pData->m_pObjectShell->GetDialogContainer(), UNO_QUERY);
    return xDialogLibraries;
}

sal_Bool SAL_CALL SfxBaseModel::getAllowMacroExecution()
{
    SfxModelGuard aGuard( *this );

    if ( m_pData->m_pObjectShell.is() )
        return m_pData->m_pObjectShell->AdjustMacroMode();
    return false;
}


//  XScriptInvocationContext


Reference< document::XEmbeddedScripts > SAL_CALL SfxBaseModel::getScriptContainer()
{
    SfxModelGuard aGuard( *this );

    Reference< document::XEmbeddedScripts > xDocumentScripts;

    try
    {
        Reference< frame::XModel > xDocument( this );
        xDocumentScripts.set( xDocument, UNO_QUERY );
        while ( !xDocumentScripts.is() && xDocument.is() )
        {
            Reference< container::XChild > xDocAsChild( xDocument, UNO_QUERY );
            if ( !xDocAsChild.is() )
            {
                xDocument = nullptr;
                break;
            }

            xDocument.set( xDocAsChild->getParent(), UNO_QUERY );
            xDocumentScripts.set( xDocument, UNO_QUERY );
        }
    }
    catch( const Exception& )
    {
        DBG_UNHANDLED_EXCEPTION("sfx.doc");
        xDocumentScripts = nullptr;
    }

    return xDocumentScripts;
}


//  XEventBroadcaster


void SAL_CALL SfxBaseModel::addEventListener( const Reference< document::XEventListener >& aListener )
{
    SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );

    m_pData->m_aInterfaceContainer.addInterface( cppu::UnoType<document::XEventListener>::get(), aListener );
}


//  XEventBroadcaster


void SAL_CALL SfxBaseModel::removeEventListener( const Reference< document::XEventListener >& aListener )
{
    SfxModelGuard aGuard( *this );

    m_pData->m_aInterfaceContainer.removeInterface( cppu::UnoType<document::XEventListener>::get(), aListener );
}

//  XShapeEventBroadcaster

void SAL_CALL SfxBaseModel::addShapeEventListener( const css::uno::Reference< css::drawing::XShape >& xShape, const Reference< document::XShapeEventListener >& xListener )
{
    assert(xShape.is() && "no shape?");
    SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );

    m_pData->maShapeListeners[xShape].push_back(xListener);
}


//  XShapeEventBroadcaster


void SAL_CALL SfxBaseModel::removeShapeEventListener( const css::uno::Reference< css::drawing::XShape >& xShape, const Reference< document::XShapeEventListener >& xListener )
{
    SfxModelGuard aGuard( *this );

    auto it = m_pData->maShapeListeners.find(xShape);
    if (it != m_pData->maShapeListeners.end())
    {
        auto rVec = it->second;
        auto it2 = std::find(rVec.begin(), rVec.end(), xListener);
        if (it2 != rVec.end())
        {
            rVec.erase(it2);
            if (rVec.empty())
                m_pData->maShapeListeners.erase(it);
        }
    }
}

//  XDocumentEventBroadcaster


void SAL_CALL SfxBaseModel::addDocumentEventListener( const Reference< document::XDocumentEventListener >& aListener )
{
    SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );
    m_pData->m_aInterfaceContainer.addInterface( cppu::UnoType<document::XDocumentEventListener>::get(), aListener );
}


void SAL_CALL SfxBaseModel::removeDocumentEventListener( const Reference< document::XDocumentEventListener >& aListener )
{
    SfxModelGuard aGuard( *this );
    m_pData->m_aInterfaceContainer.removeInterface( cppu::UnoType<document::XDocumentEventListener>::get(), aListener );
}


void SAL_CALL SfxBaseModel::notifyDocumentEvent( const OUString&, const Reference< frame::XController2 >&, const Any& )
{
    throw lang::NoSupportException("SfxBaseModel controls all the sent notifications itself!" );
}

Sequence<document::CmisProperty> SAL_CALL SfxBaseModel::getCmisProperties()
{
    if (impl_isDisposed())
        return Sequence<document::CmisProperty>();
    return m_pData->m_cmisProperties;
}

void SAL_CALL SfxBaseModel::setCmisProperties( const Sequence< document::CmisProperty >& _cmisproperties )
{
    m_pData->m_cmisProperties = _cmisproperties;
}

void SAL_CALL SfxBaseModel::updateCmisProperties( const Sequence< document::CmisProperty >& aProperties )
{
    SfxMedium* pMedium = m_pData->m_pObjectShell->GetMedium();
    if ( !pMedium )
        return;

    try
    {
        ::ucbhelper::Content aContent( pMedium->GetName( ),
            Reference<ucb::XCommandEnvironment>(),
            comphelper::getProcessComponentContext() );

        aContent.executeCommand( "updateProperties", uno::makeAny( aProperties ) );
        loadCmisProperties( );
    }
    catch (const Exception & e)
    {
        css::uno::Any anyEx = cppu::getCaughtException();
        throw lang::WrappedTargetRuntimeException( e.Message,
                        e.Context, anyEx );
    }

}

void SAL_CALL SfxBaseModel::checkOut(  )
{
    SfxMedium* pMedium = m_pData->m_pObjectShell->GetMedium();
    if ( !pMedium )
        return;

    try
    {
        ::ucbhelper::Content aContent( pMedium->GetName(),
            Reference<ucb::XCommandEnvironment>(),
            comphelper::getProcessComponentContext() );

        Any aResult = aContent.executeCommand( "checkout", Any( ) );
        OUString sURL;
        aResult >>= sURL;

        m_pData->m_pObjectShell->GetMedium( )->SetName( sURL );
        m_pData->m_pObjectShell->GetMedium( )->GetMedium_Impl( );
        m_pData->m_xDocumentProperties->setTitle( getTitle( ) );
        Sequence< beans::PropertyValue > aSequence ;
        TransformItems( SID_OPENDOC, *pMedium->GetItemSet(), aSequence );
        attachResource( sURL, aSequence );

        // Reload the CMIS properties
        loadCmisProperties( );
    }
    catch ( const Exception & e )
    {
        css::uno::Any anyEx = cppu::getCaughtException();
        throw lang::WrappedTargetRuntimeException( e.Message,
                        e.Context, anyEx );
    }
}

void SAL_CALL SfxBaseModel::cancelCheckOut(  )
{
    SfxMedium* pMedium = m_pData->m_pObjectShell->GetMedium();
    if ( !pMedium )
        return;

    try
    {
        ::ucbhelper::Content aContent( pMedium->GetName(),
            Reference<ucb::XCommandEnvironment>(),
            comphelper::getProcessComponentContext() );

        Any aResult = aContent.executeCommand( "cancelCheckout", Any( ) );
        OUString sURL;
        aResult >>= sURL;

        m_pData->m_pObjectShell->GetMedium( )->SetName( sURL );
    }
    catch ( const Exception & e )
    {
        css::uno::Any anyEx = cppu::getCaughtException();
        throw lang::WrappedTargetRuntimeException( e.Message,
                        e.Context, anyEx );
    }
}

void SAL_CALL SfxBaseModel::checkIn( sal_Bool bIsMajor, const OUString& rMessage )
{
    SfxMedium* pMedium = m_pData->m_pObjectShell->GetMedium();
    if ( !pMedium )
        return;

    try
    {
        Sequence< beans::PropertyValue > aProps( 3 );
        aProps[0].Name = "VersionMajor";
        aProps[0].Value <<= bIsMajor;
        aProps[1].Name = "VersionComment";
        aProps[1].Value <<= rMessage;
        aProps[2].Name = "CheckIn";
        aProps[2].Value <<= true;

        const OUString sName( pMedium->GetName( ) );
        storeSelf( aProps );

        // Refresh pMedium as it has probably changed during the storeSelf call
        pMedium = m_pData->m_pObjectShell->GetMedium( );
        const OUString sNewName( pMedium->GetName( ) );

        // URL has changed, update the document
        if ( sName != sNewName )
        {
            m_pData->m_xDocumentProperties->setTitle( getTitle( ) );
            Sequence< beans::PropertyValue > aSequence ;
            TransformItems( SID_OPENDOC, *pMedium->GetItemSet(), aSequence );
            attachResource( sNewName, aSequence );

            // Reload the CMIS properties
            loadCmisProperties( );
        }
    }
    catch ( const Exception & e )
    {
        css::uno::Any anyEx = cppu::getCaughtException();
        throw lang::WrappedTargetRuntimeException( e.Message,
                        e.Context, anyEx );
    }
}

uno::Sequence< document::CmisVersion > SAL_CALL SfxBaseModel::getAllVersions( )
{
    uno::Sequence<document::CmisVersion> aVersions;
    if (impl_isDisposed())
        return aVersions;
    SfxMedium* pMedium = m_pData->m_pObjectShell->GetMedium();
    if ( pMedium )
    {
        try
        {
            ::ucbhelper::Content aContent( pMedium->GetName(),
                Reference<ucb::XCommandEnvironment>(),
                comphelper::getProcessComponentContext() );

            Any aResult = aContent.executeCommand( "getAllVersions", Any( ) );
            aResult >>= aVersions;
        }
        catch ( const Exception & e )
        {
            css::uno::Any anyEx = cppu::getCaughtException();
            throw lang::WrappedTargetRuntimeException( e.Message,
                            e.Context, anyEx );
        }
    }
    return aVersions;
}

bool SfxBaseModel::getBoolPropertyValue( const OUString& rName )
{
    bool bValue = false;
    if ( m_pData->m_pObjectShell.is() )
    {
        SfxMedium* pMedium = m_pData->m_pObjectShell->GetMedium();
        if ( pMedium )
        {
            try
            {
                ::ucbhelper::Content aContent( pMedium->GetName( ),
                    utl::UCBContentHelper::getDefaultCommandEnvironment(),
                    comphelper::getProcessComponentContext() );
                Reference < beans::XPropertySetInfo > xProps = aContent.getProperties();
                if ( xProps->hasPropertyByName( rName ) )
                {
                    aContent.getPropertyValue( rName ) >>= bValue;
                }
            }
            catch ( const Exception & )
            {
                // Simply ignore it: it's likely the document isn't versionable in that case
                bValue = false;
            }
        }
    }
    return bValue;
}

sal_Bool SAL_CALL SfxBaseModel::isVersionable( )
{
    return getBoolPropertyValue( "IsVersionable" );
}

sal_Bool SAL_CALL SfxBaseModel::canCheckOut( )
{
    return getBoolPropertyValue( "CanCheckOut" );
}

sal_Bool SAL_CALL SfxBaseModel::canCancelCheckOut( )
{
    return getBoolPropertyValue( "CanCancelCheckOut" );
}

sal_Bool SAL_CALL SfxBaseModel::canCheckIn( )
{
    return getBoolPropertyValue( "CanCheckIn" );
}

void SfxBaseModel::loadCmisProperties( )
{
    SfxMedium* pMedium = m_pData->m_pObjectShell->GetMedium();
    if ( !pMedium )
        return;

    try
    {
        ::ucbhelper::Content aContent( pMedium->GetName( ),
            utl::UCBContentHelper::getDefaultCommandEnvironment(),
            comphelper::getProcessComponentContext() );
        Reference < beans::XPropertySetInfo > xProps = aContent.getProperties();
        const OUString aCmisProps( "CmisProperties" );
        if ( xProps->hasPropertyByName( aCmisProps ) )
        {
            Sequence< document::CmisProperty> aCmisProperties;
            aContent.getPropertyValue( aCmisProps ) >>= aCmisProperties;
            setCmisProperties( aCmisProperties );
        }
    }
    catch (const ucb::ContentCreationException &)
    {
    }
    catch (const ucb::CommandAbortedException &)
    {
    }
}

SfxMedium* SfxBaseModel::handleLoadError( ErrCode nError, SfxMedium* pMedium )
{
    if (!nError)
    {
        // No error condition.
        return pMedium;
    }

    bool bSilent = false;
    const SfxBoolItem* pSilentItem = SfxItemSet::GetItem<SfxBoolItem>(pMedium->GetItemSet(), SID_SILENT, false);
    if( pSilentItem )
        bSilent = pSilentItem->GetValue();

    bool bWarning = nError.IsWarning();
    if ( nError != ERRCODE_IO_BROKENPACKAGE && !bSilent )
    {
        // broken package was handled already
        if ( SfxObjectShell::UseInteractionToHandleError(pMedium->GetInteractionHandler(), nError) && !bWarning)
        {
            // abort loading (except for warnings)
            nError = ERRCODE_IO_ABORT;
        }
    }

    if ( m_pData->m_pObjectShell->GetMedium() != pMedium )
    {
        // for whatever reason document now has another medium
        OSL_FAIL("Document has rejected the medium?!");
        delete pMedium;
        pMedium = nullptr;
    }

    if ( !bWarning )    // #i30711# don't abort loading if it's only a warning
    {
        nError = nError ? nError : ERRCODE_IO_CANTREAD;
        throw task::ErrorCodeIOException(
            "SfxBaseModel::handleLoadError: 0x" + nError.toHexString(),
            Reference< XInterface >(), sal_uInt32(nError));
    }

    return pMedium;
}


//  SfxListener


static void addTitle_Impl( Sequence < beans::PropertyValue >& rSeq, const OUString& rTitle )
{
    auto pProp = std::find_if(rSeq.begin(), rSeq.end(),
        [](const beans::PropertyValue& rProp) { return rProp.Name == "Title"; });
    if (pProp != rSeq.end())
    {
        pProp->Value <<= rTitle;
    }
    else
    {
        sal_Int32 nCount = rSeq.getLength();
        rSeq.realloc( nCount+1 );
        rSeq[nCount].Name = "Title";
        rSeq[nCount].Value <<= rTitle;
    }
}

void SfxBaseModel::Notify(          SfxBroadcaster& rBC     ,
                             const  SfxHint&        rHint   )
{
    if ( !m_pData )
        return;

    if ( &rBC != m_pData->m_pObjectShell.get() )
        return;

    if ( rHint.GetId() == SfxHintId::DocChanged )
        changing();

    const SfxEventHint* pNamedHint = dynamic_cast<const SfxEventHint*>(&rHint);
    if ( pNamedHint )
    {

        switch ( pNamedHint->GetEventId() )
        {
        case SfxEventHintId::StorageChanged:
        {
            if ( m_pData->m_xUIConfigurationManager.is()
              && m_pData->m_pObjectShell->GetCreateMode() != SfxObjectCreateMode::EMBEDDED )
            {
                Reference< embed::XStorage > xConfigStorage;
                const OUString aUIConfigFolderName( "Configurations2" );

                xConfigStorage = getDocumentSubStorage( aUIConfigFolderName, embed::ElementModes::READWRITE );
                if ( !xConfigStorage.is() )
                    xConfigStorage = getDocumentSubStorage( aUIConfigFolderName, embed::ElementModes::READ );

                if ( xConfigStorage.is() || !m_pData->m_pObjectShell->GetStorage()->hasByName( aUIConfigFolderName ) )
                {
                    // the storage is different, since otherwise it could not be opened, so it must be exchanged
                    m_pData->m_xUIConfigurationManager->setStorage( xConfigStorage );
                }
                else
                {
                    OSL_FAIL( "Unexpected scenario!" );
                }
            }

            ListenForStorage_Impl( m_pData->m_pObjectShell->GetStorage() );
        }
        break;

        case SfxEventHintId::LoadFinished:
        {
            impl_getPrintHelper();
            ListenForStorage_Impl( m_pData->m_pObjectShell->GetStorage() );
            m_pData->m_bModifiedSinceLastSave = false;
        }
        break;

        case SfxEventHintId::SaveAsDocDone:
        {
            m_pData->m_sURL = m_pData->m_pObjectShell->GetMedium()->GetName();

            SfxItemSet *pSet = m_pData->m_pObjectShell->GetMedium()->GetItemSet();
            Sequence< beans::PropertyValue > aArgs;
            TransformItems( SID_SAVEASDOC, *pSet, aArgs );
            addTitle_Impl( aArgs, m_pData->m_pObjectShell->GetTitle() );
            attachResource( m_pData->m_pObjectShell->GetMedium()->GetName(), aArgs );
        }
        break;

        case SfxEventHintId::DocCreated:
        {
            impl_getPrintHelper();
            m_pData->m_bModifiedSinceLastSave = false;
        }
        break;

        case SfxEventHintId::ModifyChanged:
        {
            m_pData->m_bModifiedSinceLastSave = isModified();
        }
        break;
        default: break;
        }

        const SfxViewEventHint* pViewHint = dynamic_cast<const SfxViewEventHint*>(&rHint);
        postEvent_Impl( pNamedHint->GetEventName(), pViewHint ? pViewHint->GetController() : Reference< frame::XController2 >() );
    }

    if ( rHint.GetId() == SfxHintId::TitleChanged )
    {
        addTitle_Impl( m_pData->m_seqArguments, m_pData->m_pObjectShell->GetTitle() );
        postEvent_Impl( GlobalEventConfig::GetEventName( GlobalEventId::TITLECHANGED ) );
    }
    else if ( rHint.GetId() == SfxHintId::ModeChanged )
    {
        postEvent_Impl( GlobalEventConfig::GetEventName( GlobalEventId::MODECHANGED ) );
    }
}


//  public impl.


void SfxBaseModel::NotifyModifyListeners_Impl() const
{
    ::cppu::OInterfaceContainerHelper* pIC = m_pData->m_aInterfaceContainer.getContainer( cppu::UnoType<util::XModifyListener>::get());
    if ( pIC )
    {
        lang::EventObject aEvent( static_cast<frame::XModel *>(const_cast<SfxBaseModel *>(this)) );
        pIC->notifyEach( &util::XModifyListener::modified, aEvent );
    }

    // this notification here is done too generously, we cannot simply assume that we're really modified
    // now, but we need to check it ...
    m_pData->m_bModifiedSinceLastSave = const_cast< SfxBaseModel* >( this )->isModified();
}

void SfxBaseModel::changing()
{
    SfxModelGuard aGuard( *this );

    // the notification should not be sent if the document can not be modified
    if ( !m_pData->m_pObjectShell.is() || !m_pData->m_pObjectShell->IsEnableSetModified() )
        return;

    NotifyModifyListeners_Impl();
}


//  public impl.


SfxObjectShell* SfxBaseModel::GetObjectShell() const
{
    return m_pData ? m_pData->m_pObjectShell.get() : nullptr;
}


//  public impl.


bool SfxBaseModel::IsInitialized() const
{
    if ( !m_pData || !m_pData->m_pObjectShell.is() )
    {
        OSL_FAIL( "SfxBaseModel::IsInitialized: this should have been caught earlier!" );
        return false;
    }

    return m_pData->m_pObjectShell->GetMedium() != nullptr;
}

void SfxBaseModel::MethodEntryCheck( const bool i_mustBeInitialized ) const
{
    if ( impl_isDisposed() )
        throw lang::DisposedException( OUString(), *const_cast< SfxBaseModel* >( this ) );
    if ( i_mustBeInitialized && !IsInitialized() )
        throw lang::NotInitializedException( OUString(), *const_cast< SfxBaseModel* >( this ) );
}

bool SfxBaseModel::impl_isDisposed() const
{
    return ( m_pData == nullptr ) ;
}


//  private impl.


OUString SfxBaseModel::GetMediumFilterName_Impl() const
{
    std::shared_ptr<const SfxFilter> pFilter;
    SfxMedium* pMedium = m_pData->m_pObjectShell->GetMedium();
    if ( pMedium )
        pFilter = pMedium->GetFilter();

    if ( pFilter )
        return pFilter->GetName();

    return OUString();
}

void SfxBaseModel::impl_store(  const   OUString&                   sURL            ,
                                const   Sequence< beans::PropertyValue >&  seqArguments    ,
                                        bool                        bSaveTo         )
{
    if( sURL.isEmpty() )
        throw frame::IllegalArgumentIOException();

    bool bSaved = false;
    if ( !bSaveTo && m_pData->m_pObjectShell.is() && !sURL.isEmpty()
      && !sURL.startsWith( "private:stream" )
      && ::utl::UCBContentHelper::EqualURLs( getLocation(), sURL ) )
    {
        // this is the same file URL as the current document location, try to use storeOwn if possible

        ::comphelper::SequenceAsHashMap aArgHash( seqArguments );
        const OUString aFilterString( "FilterName"  );
        const OUString aFilterName( aArgHash.getUnpackedValueOrDefault( aFilterString, OUString() ) );
        if ( !aFilterName.isEmpty() )
        {
            SfxMedium* pMedium = m_pData->m_pObjectShell->GetMedium();
            if ( pMedium )
            {
                const std::shared_ptr<const SfxFilter>& pFilter = pMedium->GetFilter();
                if ( pFilter && aFilterName == pFilter->GetFilterName() )
                {
                    // #i119366# - If the former file saving with password, do not trying in StoreSelf anyway...
                    bool bFormerPassword = false;
                    {
                        uno::Sequence< beans::NamedValue > aOldEncryptionData;
                        if (GetEncryptionData_Impl( pMedium->GetItemSet(), aOldEncryptionData ))
                        {
                            bFormerPassword = true;
                        }
                    }
                    if ( !bFormerPassword )
                    {
                        aArgHash.erase( aFilterString );
                        aArgHash.erase( "URL" );

                        try
                        {
                            storeSelf( aArgHash.getAsConstPropertyValueList() );
                            bSaved = true;
                        }
                        catch( const lang::IllegalArgumentException& )
                        {
#if HAVE_FEATURE_MULTIUSER_ENVIRONMENT
                            // some additional arguments do not allow to use saving, SaveAs should be done
                            // but only for normal documents, the shared documents would be overwritten in this case
                            // that would mean an information loss
                            // TODO/LATER: need a new interaction for this case
                            if ( m_pData->m_pObjectShell->IsDocShared() )
                            {
                                uno::Sequence< beans::NamedValue > aNewEncryptionData = aArgHash.getUnpackedValueOrDefault("EncryptionData", uno::Sequence< beans::NamedValue >() );
                                if ( !aNewEncryptionData.hasElements() )
                                {
                                    aNewEncryptionData = ::comphelper::OStorageHelper::CreatePackageEncryptionData( aArgHash.getUnpackedValueOrDefault("Password", OUString()) );
                                }

                                uno::Sequence< beans::NamedValue > aOldEncryptionData;
                                (void)GetEncryptionData_Impl( pMedium->GetItemSet(), aOldEncryptionData );

                                if ( !aOldEncryptionData.hasElements() && !aNewEncryptionData.hasElements() )
                                    throw;
                                else
                                {
                                    // if the password is changed a special error should be used in case of shared document
                                    throw task::ErrorCodeIOException("Can not change password for shared document.", uno::Reference< uno::XInterface >(), sal_uInt32(ERRCODE_SFX_SHARED_NOPASSWORDCHANGE) );
                                }
                            }
#endif
                        }
                    }
                }
            }
        }
    }

    if ( !(!bSaved && m_pData->m_pObjectShell.is()) )
        return;

    SfxGetpApp()->NotifyEvent( SfxEventHint( bSaveTo ? SfxEventHintId::SaveToDoc : SfxEventHintId::SaveAsDoc, GlobalEventConfig::GetEventName( bSaveTo ? GlobalEventId::SAVETODOC : GlobalEventId::SAVEASDOC ),
                                            m_pData->m_pObjectShell.get() ) );

    std::unique_ptr<SfxAllItemSet> pItemSet(new SfxAllItemSet(SfxGetpApp()->GetPool()));
    pItemSet->Put(SfxStringItem(SID_FILE_NAME, sURL));
    if ( bSaveTo )
        pItemSet->Put(SfxBoolItem(SID_SAVETO, true));

    TransformParameters(SID_SAVEASDOC, seqArguments, *pItemSet);

    const SfxBoolItem* pCopyStreamItem = pItemSet->GetItem<SfxBoolItem>(SID_COPY_STREAM_IF_POSSIBLE, false);

    if ( pCopyStreamItem && pCopyStreamItem->GetValue() && !bSaveTo )
    {
        throw frame::IllegalArgumentIOException(
                "CopyStreamIfPossible parameter is not acceptable for storeAsURL() call!" );
    }

    sal_uInt32 nModifyPasswordHash = 0;
    Sequence< beans::PropertyValue > aModifyPasswordInfo;
    const SfxUnoAnyItem* pModifyPasswordInfoItem = pItemSet->GetItem<SfxUnoAnyItem>(SID_MODIFYPASSWORDINFO, false);
    if ( pModifyPasswordInfoItem )
    {
        // it contains either a simple hash or a set of PropertyValues
        // TODO/LATER: the sequence of PropertyValue should replace the hash completely in future
        sal_Int32 nMPHTmp = 0;
        pModifyPasswordInfoItem->GetValue() >>= nMPHTmp;
        nModifyPasswordHash = static_cast<sal_uInt32>(nMPHTmp);
        pModifyPasswordInfoItem->GetValue() >>= aModifyPasswordInfo;
    }
    pItemSet->ClearItem(SID_MODIFYPASSWORDINFO);
    sal_uInt32 nOldModifyPasswordHash = m_pData->m_pObjectShell->GetModifyPasswordHash();
    m_pData->m_pObjectShell->SetModifyPasswordHash( nModifyPasswordHash );
    Sequence< beans::PropertyValue > aOldModifyPasswordInfo = m_pData->m_pObjectShell->GetModifyPasswordInfo();
    m_pData->m_pObjectShell->SetModifyPasswordInfo( aModifyPasswordInfo );

    // since saving a document modifies its DocumentProperties, the current
    // DocumentProperties must be saved on "SaveTo", so it can be restored
    // after saving
    bool bCopyTo =  bSaveTo ||
        m_pData->m_pObjectShell->GetCreateMode() == SfxObjectCreateMode::EMBEDDED;
    Reference<document::XDocumentProperties> xOldDocProps;
    if ( bCopyTo )
    {
        xOldDocProps = getDocumentProperties();
        const Reference<util::XCloneable> xCloneable(xOldDocProps,
            UNO_QUERY_THROW);
        const Reference<document::XDocumentProperties> xNewDocProps(
            xCloneable->createClone(), UNO_QUERY_THROW);
        m_pData->m_xDocumentProperties = xNewDocProps;
    }

    bool bRet = m_pData->m_pObjectShell->APISaveAs_Impl(sURL, *pItemSet, seqArguments);

    if ( bCopyTo )
    {
        // restore DocumentProperties if a copy was created
        m_pData->m_xDocumentProperties = xOldDocProps;
    }

    Reference < task::XInteractionHandler > xHandler;
    const SfxUnoAnyItem* pItem = pItemSet->GetItem<SfxUnoAnyItem>(SID_INTERACTIONHANDLER, false);
    if ( pItem )
        pItem->GetValue() >>= xHandler;

    pItemSet.reset();

    ErrCode nErrCode = m_pData->m_pObjectShell->GetErrorCode();
    if ( !bRet && !nErrCode )
    {
        SAL_WARN("sfx.doc", "Storing has failed, no error is set!");
        nErrCode = ERRCODE_IO_CANTWRITE;
    }
    m_pData->m_pObjectShell->ResetError();

    if ( bRet )
    {
        if ( nErrCode )
        {
            // must be a warning - use Interactionhandler if possible or abandon
            if ( xHandler.is() )
            {
                // TODO/LATER: a general way to set the error context should be available
                SfxErrorContext aEc( ERRCTX_SFX_SAVEASDOC, m_pData->m_pObjectShell->GetTitle() );

                task::ErrorCodeRequest aErrorCode;
                aErrorCode.ErrCode = sal_uInt32(nErrCode);
                SfxMedium::CallApproveHandler( xHandler, makeAny( aErrorCode ), false );
            }
        }

        if ( !bSaveTo )
        {
            m_pData->m_aPreusedFilterName = GetMediumFilterName_Impl();
            m_pData->m_pObjectShell->SetModifyPasswordEntered();

            SfxGetpApp()->NotifyEvent( SfxEventHint( SfxEventHintId::SaveAsDocDone, GlobalEventConfig::GetEventName(GlobalEventId::SAVEASDOCDONE), m_pData->m_pObjectShell.get() ) );
        }
        else
        {
            m_pData->m_pObjectShell->SetModifyPasswordHash( nOldModifyPasswordHash );
            m_pData->m_pObjectShell->SetModifyPasswordInfo( aOldModifyPasswordInfo );

            SfxGetpApp()->NotifyEvent( SfxEventHint( SfxEventHintId::SaveToDocDone, GlobalEventConfig::GetEventName(GlobalEventId::SAVETODOCDONE), m_pData->m_pObjectShell.get() ) );
        }
    }
    else
    {
        m_pData->m_pObjectShell->SetModifyPasswordHash( nOldModifyPasswordHash );
        m_pData->m_pObjectShell->SetModifyPasswordInfo( aOldModifyPasswordInfo );


        SfxGetpApp()->NotifyEvent( SfxEventHint( bSaveTo ? SfxEventHintId::SaveToDocFailed : SfxEventHintId::SaveAsDocFailed, GlobalEventConfig::GetEventName( bSaveTo ? GlobalEventId::SAVETODOCFAILED : GlobalEventId::SAVEASDOCFAILED),
                                                m_pData->m_pObjectShell.get() ) );

        std::stringstream aErrCode;
        aErrCode << nErrCode;
        throw task::ErrorCodeIOException(
            "SfxBaseModel::impl_store <" + sURL + "> failed: " + OUString::fromUtf8(aErrCode.str().c_str()),
            Reference< XInterface >(), sal_uInt32(nErrCode));
    }
}


namespace {
template< typename ListenerT, typename EventT >
class NotifySingleListenerIgnoreRE
{
private:
    typedef void ( SAL_CALL ListenerT::*NotificationMethod )( const EventT& );
    NotificationMethod  m_pMethod;
    const EventT&       m_rEvent;
public:
    NotifySingleListenerIgnoreRE( NotificationMethod method, const EventT& event ) : m_pMethod( method ), m_rEvent( event ) { }

    void operator()( const Reference<ListenerT>& listener ) const
    {
        try
        {
            (listener.get()->*m_pMethod)( m_rEvent );
        }
        catch( RuntimeException& )
        {
            // this exception is ignored to avoid problems with invalid listeners, the listener should be probably thrown away in future
        }
    }
};
} // anonymous namespace

void SfxBaseModel::postEvent_Impl( const OUString& aName, const Reference< frame::XController2 >& xController )
{
    // object already disposed?
    if ( impl_isDisposed() )
        return;

    // keep m_pData alive, if notified target would dispose the document
    std::shared_ptr<IMPL_SfxBaseModel_DataContainer> xKeepAlive(m_pData);

    // also make sure this object doesn't self-destruct while notifying
    rtl::Reference<SfxBaseModel> xHoldAlive(this);

    DBG_ASSERT( !aName.isEmpty(), "Empty event name!" );
    if (aName.isEmpty())
        return;

    ::cppu::OInterfaceContainerHelper* pIC =
        m_pData->m_aInterfaceContainer.getContainer( cppu::UnoType<document::XDocumentEventListener>::get());
    if ( pIC )
    {
        SAL_INFO("sfx.doc", "SfxDocumentEvent: " + aName);

        document::DocumentEvent aDocumentEvent( static_cast<frame::XModel*>(this), aName, xController, Any() );

        pIC->forEach< document::XDocumentEventListener, NotifySingleListenerIgnoreRE< document::XDocumentEventListener, document::DocumentEvent > >(
            NotifySingleListenerIgnoreRE< document::XDocumentEventListener, document::DocumentEvent >(
                &document::XDocumentEventListener::documentEventOccured,
                aDocumentEvent ) );
    }

    pIC = m_pData->m_aInterfaceContainer.getContainer( cppu::UnoType<document::XEventListener>::get());
    if ( pIC )
    {
        SAL_INFO("sfx.doc", "SfxEvent: " + aName);

        document::EventObject aEvent( static_cast<frame::XModel*>(this), aName );

        pIC->forEach< document::XEventListener, NotifySingleListenerIgnoreRE< document::XEventListener, document::EventObject > >(
            NotifySingleListenerIgnoreRE< document::XEventListener, document::EventObject >(
                &document::XEventListener::notifyEvent,
                aEvent ) );
    }

}

Reference < container::XIndexAccess > SAL_CALL SfxBaseModel::getViewData()
{
    SfxModelGuard aGuard( *this );

    if ( m_pData->m_pObjectShell.is() && !m_pData->m_contViewData.is() )
    {
        SfxViewFrame *pActFrame = SfxViewFrame::Current();
        if ( !pActFrame || pActFrame->GetObjectShell() != m_pData->m_pObjectShell.get() )
            pActFrame = SfxViewFrame::GetFirst( m_pData->m_pObjectShell.get() );

        if ( !pActFrame || !pActFrame->GetViewShell() )
            // currently no frame for this document at all or View is under construction
            return Reference < container::XIndexAccess >();

        m_pData->m_contViewData = document::IndexedPropertyValues::create( ::comphelper::getProcessComponentContext() );

        if ( !m_pData->m_contViewData.is() )
        {
            // error: no container class available!
            return Reference < container::XIndexAccess >();
        }

        Reference < container::XIndexContainer > xCont( m_pData->m_contViewData, UNO_QUERY );
        sal_Int32 nCount = 0;
        Sequence < beans::PropertyValue > aSeq;
        for ( SfxViewFrame *pFrame = SfxViewFrame::GetFirst( m_pData->m_pObjectShell.get() ); pFrame;
                pFrame = SfxViewFrame::GetNext( *pFrame, m_pData->m_pObjectShell.get() ) )
        {
            bool bIsActive = ( pFrame == pActFrame );
            pFrame->GetViewShell()->WriteUserDataSequence( aSeq );
            xCont->insertByIndex( bIsActive ? 0 : nCount, Any(aSeq) );
            nCount++;
        }
    }

    return m_pData->m_contViewData;
}

void SAL_CALL SfxBaseModel::setViewData( const Reference < container::XIndexAccess >& aData )
{
    SfxModelGuard aGuard( *this );

    m_pData->m_contViewData = aData;
}

/** calls all XEventListeners */
void SfxBaseModel::notifyEvent( const document::EventObject& aEvent ) const
{
    // object already disposed?
    if ( impl_isDisposed() )
        return;

    ::cppu::OInterfaceContainerHelper* pIC = m_pData->m_aInterfaceContainer.getContainer(
                                        cppu::UnoType<document::XEventListener>::get());
    if( !pIC )

        return;

    ::cppu::OInterfaceIteratorHelper aIt( *pIC );
    while( aIt.hasMoreElements() )
    {
        try
        {
            static_cast<document::XEventListener *>(aIt.next())->notifyEvent( aEvent );
        }
        catch( RuntimeException& )
        {
            aIt.remove();
        }
    }
    // for right now, we're only doing the event that this particular performance problem needed
    if (aEvent.EventName == "ShapeModified")
    {
        uno::Reference<drawing::XShape> xShape(aEvent.Source, uno::UNO_QUERY);
        if (xShape.is())
        {
            auto it = m_pData->maShapeListeners.find(xShape);
            if (it != m_pData->maShapeListeners.end())
                for (auto const & rListenerUnoRef : it->second)
                    rListenerUnoRef->notifyShapeEvent(aEvent);
        }
    }
}

/** returns true if someone added a XEventListener to this XEventBroadcaster */
bool SfxBaseModel::hasEventListeners() const
{
    return !impl_isDisposed()
        && ( (nullptr != m_pData->m_aInterfaceContainer.getContainer( cppu::UnoType<document::XEventListener>::get()) )
             || !m_pData->maShapeListeners.empty());
}

void SAL_CALL SfxBaseModel::addPrintJobListener( const Reference< view::XPrintJobListener >& xListener )
{
    SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );

    impl_getPrintHelper();
    Reference < view::XPrintJobBroadcaster > xPJB( m_pData->m_xPrintable, UNO_QUERY );
    if ( xPJB.is() )
        xPJB->addPrintJobListener( xListener );
}

void SAL_CALL SfxBaseModel::removePrintJobListener( const Reference< view::XPrintJobListener >& xListener )
{
    SfxModelGuard aGuard( *this );

    impl_getPrintHelper();
    Reference < view::XPrintJobBroadcaster > xPJB( m_pData->m_xPrintable, UNO_QUERY );
    if ( xPJB.is() )
        xPJB->removePrintJobListener( xListener );
}

sal_Int64 SAL_CALL SfxBaseModel::getSomething( const Sequence< sal_Int8 >& aIdentifier )
{
    SvGlobalName aName( aIdentifier );
    if (aName == SvGlobalName( SFX_GLOBAL_CLASSID ))
    {
        SolarMutexGuard aGuard;
        SfxObjectShell *const pObjectShell(GetObjectShell());
        if (pObjectShell)
        {
            return reinterpret_cast<sal_Int64>(pObjectShell);
        }
    }

    return 0;
}


//  XDocumentSubStorageSupplier


void SfxBaseModel::ListenForStorage_Impl( const Reference< embed::XStorage >& xStorage )
{
    Reference< util::XModifiable > xModifiable( xStorage, UNO_QUERY );
    if ( xModifiable.is() )
    {
        if ( !m_pData->m_pStorageModifyListen.is() )
        {
            m_pData->m_pStorageModifyListen = new ::sfx2::DocumentStorageModifyListener( *m_pData, Application::GetSolarMutex() );
        }

        // no need to deregister the listening for old storage since it should be disposed automatically
        xModifiable->addModifyListener( m_pData->m_pStorageModifyListen.get() );
    }
}

Reference< embed::XStorage > SAL_CALL SfxBaseModel::getDocumentSubStorage( const OUString& aStorageName, sal_Int32 nMode )
{
    SfxModelGuard aGuard( *this );

    Reference< embed::XStorage > xResult;
    if ( m_pData->m_pObjectShell.is() )
    {
        Reference< embed::XStorage > xStorage = m_pData->m_pObjectShell->GetStorage();
        if ( xStorage.is() )
        {
            try
            {
                xResult = xStorage->openStorageElement( aStorageName, nMode );
            }
            catch ( Exception& )
            {
            }
        }
    }

    return xResult;
}

Sequence< OUString > SAL_CALL SfxBaseModel::getDocumentSubStoragesNames()
{
    SfxModelGuard aGuard( *this );

    Sequence< OUString > aResult;
    bool bSuccess = false;
    if ( m_pData->m_pObjectShell.is() )
    {
        Reference < embed::XStorage > xStorage = m_pData->m_pObjectShell->GetStorage();
        if ( xStorage.is() )
        {
            const Sequence< OUString > aTemp = xStorage->getElementNames();
            sal_Int32 nResultSize = 0;
            for ( const auto& rName : aTemp )
            {
                if ( xStorage->isStorageElement( rName ) )
                {
                    aResult.realloc( ++nResultSize );
                    aResult[ nResultSize - 1 ] = rName;
                }
            }

            bSuccess = true;
        }
    }

    if ( !bSuccess )
        throw io::IOException();

    return aResult;
}


//  XScriptProviderSupplier


Reference< script::provider::XScriptProvider > SAL_CALL SfxBaseModel::getScriptProvider()
{
    SfxModelGuard aGuard( *this );

    Reference< script::provider::XScriptProviderFactory > xScriptProviderFactory =
        script::provider::theMasterScriptProviderFactory::get( ::comphelper::getProcessComponentContext() );

    Reference< XScriptInvocationContext > xScriptContext( this );

    Reference< script::provider::XScriptProvider > xScriptProvider(
        xScriptProviderFactory->createScriptProvider( makeAny( xScriptContext ) ),
        UNO_SET_THROW );

    return xScriptProvider;
}


//  XUIConfigurationManagerSupplier


OUString const & SfxBaseModel::getRuntimeUID() const
{
    OSL_ENSURE( !m_pData->m_sRuntimeUID.isEmpty(),
                "SfxBaseModel::getRuntimeUID - ID is empty!" );
    return m_pData->m_sRuntimeUID;
}

bool SfxBaseModel::hasValidSignatures() const
{
    SolarMutexGuard aGuard;
    if ( m_pData->m_pObjectShell.is() )
        return ( m_pData->m_pObjectShell->ImplGetSignatureState() == SignatureState::OK );
    return false;
}

void SfxBaseModel::getGrabBagItem(css::uno::Any& rVal) const
{
    if (m_pData->m_xGrabBagItem)
        m_pData->m_xGrabBagItem->QueryValue(rVal);
    else
        rVal <<= uno::Sequence<beans::PropertyValue>();
}

void SfxBaseModel::setGrabBagItem(const css::uno::Any& rVal)
{
    if (!m_pData->m_xGrabBagItem)
        m_pData->m_xGrabBagItem = std::make_shared<SfxGrabBagItem>();

    m_pData->m_xGrabBagItem->PutValue(rVal, 0);
}

static void GetCommandFromSequence( OUString& rCommand, sal_Int32& nIndex, const Sequence< beans::PropertyValue >& rSeqPropValue )<--- Parameter 'rCommand' can be declared with const
{
    nIndex = -1;

    auto pPropValue = std::find_if(rSeqPropValue.begin(), rSeqPropValue.end(),
        [](const beans::PropertyValue& rPropValue) { return rPropValue.Name == "Command"; });
    if (pPropValue != rSeqPropValue.end())
    {
        pPropValue->Value >>= rCommand;
        nIndex = static_cast<sal_Int32>(std::distance(rSeqPropValue.begin(), pPropValue));
    }
}

static void ConvertSlotsToCommands( SfxObjectShell const * pDoc, Reference< container::XIndexContainer > const & rToolbarDefinition )
{
    if ( !pDoc )
        return;

    SfxModule*    pModule( pDoc->GetFactory().GetModule() );
    Sequence< beans::PropertyValue > aSeqPropValue;

    for ( sal_Int32 i = 0; i < rToolbarDefinition->getCount(); i++ )
    {
        sal_Int32 nIndex( -1 );
        OUString aCommand;

        if ( rToolbarDefinition->getByIndex( i ) >>= aSeqPropValue )
        {
            GetCommandFromSequence( aCommand, nIndex, aSeqPropValue );
            if ( nIndex >= 0 && aCommand.startsWith( "slot:" ) )
            {
                const sal_uInt16 nSlot = aCommand.copy( 5 ).toInt32();

                // We have to replace the old "slot-Command" with our new ".uno:-Command"
                const SfxSlot* pSlot = pModule->GetSlotPool()->GetSlot( nSlot );
                if ( pSlot )
                {
                    OUStringBuffer aStrBuf( ".uno:"  );
                    aStrBuf.appendAscii( pSlot->GetUnoName() );

                    aCommand = aStrBuf.makeStringAndClear();
                    aSeqPropValue[nIndex].Value <<= aCommand;
                    rToolbarDefinition->replaceByIndex( i, Any( aSeqPropValue ));
                }
            }
        }
    }
}

Reference< ui::XUIConfigurationManager > SAL_CALL SfxBaseModel::getUIConfigurationManager()
{
    return Reference< ui::XUIConfigurationManager >( getUIConfigurationManager2(), UNO_QUERY_THROW );
}

Reference< ui::XUIConfigurationManager2 > SfxBaseModel::getUIConfigurationManager2()
{
    SfxModelGuard aGuard( *this );

    if ( !m_pData->m_xUIConfigurationManager.is() )
    {
        Reference< ui::XUIConfigurationManager2 > xNewUIConfMan =
            ui::UIConfigurationManager::create( comphelper::getProcessComponentContext() );

        Reference< embed::XStorage > xConfigStorage;

        OUString aUIConfigFolderName( "Configurations2" );
        // First try to open with READWRITE and then READ
        xConfigStorage = getDocumentSubStorage( aUIConfigFolderName, embed::ElementModes::READWRITE );
        if ( xConfigStorage.is() )
        {
            const OUString aMediaTypeProp( "MediaType" );
            OUString aMediaType;
            Reference< beans::XPropertySet > xPropSet( xConfigStorage, UNO_QUERY );
            Any a = xPropSet->getPropertyValue( aMediaTypeProp );
            if ( !( a >>= aMediaType ) ||  aMediaType.isEmpty())
            {
                xPropSet->setPropertyValue( aMediaTypeProp, Any(OUString("application/vnd.sun.xml.ui.configuration")) );
            }
        }
        else
            xConfigStorage = getDocumentSubStorage( aUIConfigFolderName, embed::ElementModes::READ );

        // initialize ui configuration manager with document substorage
        xNewUIConfMan->setStorage( xConfigStorage );

        // embedded objects did not support local configuration data until OOo 3.0, so there's nothing to
        // migrate
        if ( m_pData->m_pObjectShell->GetCreateMode() != SfxObjectCreateMode::EMBEDDED )
        {
            // Import old UI configuration from OOo 1.x

            // Try to open with READ
            Reference< embed::XStorage > xOOo1ConfigStorage = getDocumentSubStorage( "Configurations", embed::ElementModes::READ );
            if ( xOOo1ConfigStorage.is() )
            {
                Reference< XComponentContext > xContext( ::comphelper::getProcessComponentContext() );
                std::vector< Reference< container::XIndexContainer > > rToolbars;

                bool bImported = framework::UIConfigurationImporterOOo1x::ImportCustomToolbars(
                                        xNewUIConfMan, rToolbars, xContext, xOOo1ConfigStorage );
                if ( bImported )
                {
                    SfxObjectShell* pObjShell = SfxBaseModel::GetObjectShell();

                    for ( size_t i = 0; i < rToolbars.size(); i++ )
                    {
                        const OUString sId(OUString::number( i + 1 ));
                        const OUString aCustomTbxName = "private:resource/toolbar/custom_OOo1x_" + sId;

                        Reference< container::XIndexContainer > xToolbar = rToolbars[i];
                        ConvertSlotsToCommands( pObjShell, xToolbar );
                        if ( !xNewUIConfMan->hasSettings( aCustomTbxName ))
                        {
                            // Set UIName for the toolbar with container property
                            Reference< beans::XPropertySet > xPropSet( xToolbar, UNO_QUERY );
                            if ( xPropSet.is() )
                            {
                                try
                                {
                                    xPropSet->setPropertyValue( "UIName", Any( "Toolbar " + sId ) );
                                }
                                catch ( beans::UnknownPropertyException& )
                                {
                                }
                            }

                            xNewUIConfMan->insertSettings( aCustomTbxName, xToolbar );
                            xNewUIConfMan->store();
                        }
                    }
                }
            }
        }

        m_pData->m_xUIConfigurationManager = xNewUIConfMan;
    }

    return m_pData->m_xUIConfigurationManager;
}


//  XVisualObject


void SAL_CALL SfxBaseModel::setVisualAreaSize( sal_Int64 nAspect, const awt::Size& aSize )
{
    SfxModelGuard aGuard( *this );

    if ( !m_pData->m_pObjectShell.is() )
        throw Exception("no object shell", nullptr); // TODO: error handling

    SfxViewFrame* pViewFrm = SfxViewFrame::GetFirst( m_pData->m_pObjectShell.get(), false );
    if ( pViewFrm && m_pData->m_pObjectShell->GetCreateMode() == SfxObjectCreateMode::EMBEDDED && !pViewFrm->GetFrame().IsInPlace() )
    {
        VclPtr<vcl::Window> pWindow = VCLUnoHelper::GetWindow( pViewFrm->GetFrame().GetFrameInterface()->getContainerWindow() );
        Size aWinSize = pWindow->GetSizePixel();
        awt::Size aCurrent = getVisualAreaSize( nAspect );
        Size aDiff( aSize.Width-aCurrent.Width, aSize.Height-aCurrent.Height );
        aDiff = pViewFrm->GetViewShell()->GetWindow()->LogicToPixel( aDiff );
        aWinSize.AdjustWidth(aDiff.Width() );
        aWinSize.AdjustHeight(aDiff.Height() );
        pWindow->SetSizePixel( aWinSize );
    }
    else
    {
        tools::Rectangle aTmpRect = m_pData->m_pObjectShell->GetVisArea( ASPECT_CONTENT );
        aTmpRect.SetSize( Size( aSize.Width, aSize.Height ) );
        m_pData->m_pObjectShell->SetVisArea( aTmpRect );
    }
}

awt::Size SAL_CALL SfxBaseModel::getVisualAreaSize( sal_Int64 /*nAspect*/ )
{
    SfxModelGuard aGuard( *this );

    if ( !m_pData->m_pObjectShell.is() )
        throw Exception("no object shell", nullptr); // TODO: error handling

    tools::Rectangle aTmpRect = m_pData->m_pObjectShell->GetVisArea( ASPECT_CONTENT );

    return awt::Size( aTmpRect.GetWidth(), aTmpRect.GetHeight() );
}


sal_Int32 SAL_CALL SfxBaseModel::getMapUnit( sal_Int64 /*nAspect*/ )
{
    SfxModelGuard aGuard( *this );

    if ( !m_pData->m_pObjectShell.is() )
        throw Exception("no object shell", nullptr); // TODO: error handling

    return VCLUnoHelper::VCL2UnoEmbedMapUnit( m_pData->m_pObjectShell->GetMapUnit() );
}

embed::VisualRepresentation SAL_CALL SfxBaseModel::getPreferredVisualRepresentation( ::sal_Int64 /*nAspect*/ )
{
    SfxModelGuard aGuard( *this );

    datatransfer::DataFlavor aDataFlavor(
            "application/x-openoffice-gdimetafile;windows_formatname=\"GDIMetaFile\"",
            "GDIMetaFile",
            cppu::UnoType<Sequence< sal_Int8 >>::get() );

    embed::VisualRepresentation aVisualRepresentation;
    aVisualRepresentation.Data = getTransferData( aDataFlavor );
    aVisualRepresentation.Flavor = aDataFlavor;

    return aVisualRepresentation;
}


//  XStorageBasedDocument


void SAL_CALL SfxBaseModel::loadFromStorage( const Reference< embed::XStorage >& xStorage,
                                             const Sequence< beans::PropertyValue >& aMediaDescriptor )
{
    SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );
    if ( IsInitialized() )
        throw frame::DoubleInitializationException( OUString(), *this );

    // after i36090 is fixed the pool from object shell can be used
    // SfxAllItemSet aSet( m_pData->m_pObjectShell->GetPool() );
    SfxAllItemSet aSet( SfxGetpApp()->GetPool() );

    // the BaseURL is part of the ItemSet
    SfxMedium* pMedium = new SfxMedium( xStorage, OUString() );
    TransformParameters( SID_OPENDOC, aMediaDescriptor, aSet );
    pMedium->GetItemSet()->Put( aSet );

    // allow to use an interactionhandler (if there is one)
    pMedium->UseInteractionHandler( true );

    const SfxBoolItem* pTemplateItem = aSet.GetItem<SfxBoolItem>(SID_TEMPLATE, false);
    bool bTemplate = pTemplateItem && pTemplateItem->GetValue();
    m_pData->m_pObjectShell->SetActivateEvent_Impl( bTemplate ? SfxEventHintId::CreateDoc : SfxEventHintId::OpenDoc );
    m_pData->m_pObjectShell->Get_Impl()->bOwnsStorage = false;

    // load document
    if ( !m_pData->m_pObjectShell->DoLoad(pMedium) )
    {
        ErrCode nError = m_pData->m_pObjectShell->GetErrorCode();
        nError = nError ? nError : ERRCODE_IO_CANTREAD;
        throw task::ErrorCodeIOException(
            "SfxBaseModel::loadFromStorage: " + nError.toHexString(),
            Reference< XInterface >(), sal_uInt32(nError));
    }
    loadCmisProperties( );
}

void SAL_CALL SfxBaseModel::storeToStorage( const Reference< embed::XStorage >& xStorage,
                                const Sequence< beans::PropertyValue >& aMediaDescriptor )
{
    SfxModelGuard aGuard( *this );

    if ( !m_pData->m_pObjectShell.is() )
        throw io::IOException(); // TODO:

    auto xSet = std::make_shared<SfxAllItemSet>(m_pData->m_pObjectShell->GetPool());
    TransformParameters( SID_SAVEASDOC, aMediaDescriptor, *xSet );

    // TODO/LATER: maybe a special URL "private:storage" should be used
    const SfxStringItem* pItem = xSet->GetItem<SfxStringItem>(SID_FILTER_NAME, false);
    sal_Int32 nVersion = SOFFICE_FILEFORMAT_CURRENT;
    if( pItem )
    {
        std::shared_ptr<const SfxFilter> pFilter = SfxGetpApp()->GetFilterMatcher().GetFilter4FilterName( pItem->GetValue() );
        if ( pFilter && pFilter->UsesStorage() )
            nVersion = pFilter->GetVersion();
    }

    bool bSuccess = false;
    if ( xStorage == m_pData->m_pObjectShell->GetStorage() )
    {
        // storing to the own storage
        bSuccess = m_pData->m_pObjectShell->DoSave();
    }
    else
    {
        // TODO/LATER: if the provided storage has some data inside the storing might fail, probably the storage must be truncated
        // TODO/LATER: is it possible to have a template here?
        m_pData->m_pObjectShell->SetupStorage( xStorage, nVersion, false );

        // BaseURL is part of the ItemSet
        SfxMedium aMedium( xStorage, OUString(), xSet );
        aMedium.CanDisposeStorage_Impl( false );
        if ( aMedium.GetFilter() )
        {
            // storing without a valid filter will often crash
            bSuccess = m_pData->m_pObjectShell->DoSaveObjectAs( aMedium, true );
            m_pData->m_pObjectShell->DoSaveCompleted();
        }
    }

    ErrCode nError = m_pData->m_pObjectShell->GetErrorCode();
    m_pData->m_pObjectShell->ResetError();

    // the warnings are currently not transported
    if ( !bSuccess )
    {
        nError = nError ? nError : ERRCODE_IO_GENERAL;
        throw task::ErrorCodeIOException(
            "SfxBaseModel::storeToStorage: " + nError.toHexString(),
            Reference< XInterface >(), sal_uInt32(nError));
    }
}

void SAL_CALL SfxBaseModel::switchToStorage( const Reference< embed::XStorage >& xStorage )
{
    SfxModelGuard aGuard( *this );

    if ( !m_pData->m_pObjectShell.is() )
        throw io::IOException(); // TODO:

    // the persistence should be switched only if the storage is different
    if ( xStorage != m_pData->m_pObjectShell->GetStorage() )
    {
        if ( !m_pData->m_pObjectShell->SwitchPersistance( xStorage ) )
        {
            ErrCode nError = m_pData->m_pObjectShell->GetErrorCode();
            nError = nError ? nError : ERRCODE_IO_GENERAL;
            throw task::ErrorCodeIOException(
                "SfxBaseModel::switchToStorage: " + nError.toHexString(),
                Reference< XInterface >(), sal_uInt32(nError));
        }
        else
        {
            // UICfgMgr has a reference to the old storage, update it
            getUIConfigurationManager2()->setStorage( xStorage );
        }
    }
    m_pData->m_pObjectShell->Get_Impl()->bOwnsStorage = false;
}

Reference< embed::XStorage > SAL_CALL SfxBaseModel::getDocumentStorage()
{
    SfxModelGuard aGuard( *this );

    if ( !m_pData->m_pObjectShell.is() )
        throw io::IOException(); // TODO

    return m_pData->m_pObjectShell->GetStorage();
}

void SAL_CALL SfxBaseModel::addStorageChangeListener(
            const Reference< document::XStorageChangeListener >& xListener )
{
    SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );

    m_pData->m_aInterfaceContainer.addInterface(
                                    cppu::UnoType<document::XStorageChangeListener>::get(), xListener );
}

void SAL_CALL SfxBaseModel::removeStorageChangeListener(
            const Reference< document::XStorageChangeListener >& xListener )
{
    SfxModelGuard aGuard( *this );

    m_pData->m_aInterfaceContainer.removeInterface(
                                    cppu::UnoType<document::XStorageChangeListener>::get(), xListener );
}

void SfxBaseModel::impl_getPrintHelper()
{
    if ( m_pData->m_xPrintable.is() )
        return;
    m_pData->m_xPrintable = new SfxPrintHelper();
    Reference < lang::XInitialization > xInit( m_pData->m_xPrintable, UNO_QUERY );
    Sequence < Any > aValues(1);
    aValues[0] <<= Reference < frame::XModel > (static_cast< frame::XModel* >(this), UNO_QUERY );
    xInit->initialize( aValues );
    Reference < view::XPrintJobBroadcaster > xBrd( m_pData->m_xPrintable, UNO_QUERY );
    xBrd->addPrintJobListener( new SfxPrintHelperListener_Impl( m_pData.get() ) );
}


// css.frame.XModule
 void SAL_CALL SfxBaseModel::setIdentifier(const OUString& Identifier)
{
    SfxModelGuard aGuard( *this );
    m_pData->m_sModuleIdentifier = Identifier;
}


// css.frame.XModule
 OUString SAL_CALL SfxBaseModel::getIdentifier()
{
    SfxModelGuard aGuard( *this );
    if (!m_pData->m_sModuleIdentifier.isEmpty())
        return m_pData->m_sModuleIdentifier;
    if (m_pData->m_pObjectShell.is())
        return m_pData->m_pObjectShell->GetFactory().GetDocumentServiceName();
    return OUString();
}


Reference< frame::XTitle > SfxBaseModel::impl_getTitleHelper ()
{
    SfxModelGuard aGuard( *this );

    if ( ! m_pData->m_xTitleHelper.is ())
    {
        Reference< XComponentContext >     xContext = ::comphelper::getProcessComponentContext();
        Reference< frame::XUntitledNumbers >    xDesktop( frame::Desktop::create(xContext), UNO_QUERY_THROW);
        Reference< frame::XModel >              xThis   (static_cast< frame::XModel* >(this), UNO_QUERY_THROW);

        ::framework::TitleHelper* pHelper = new ::framework::TitleHelper(xContext);
        m_pData->m_xTitleHelper.set(static_cast< ::cppu::OWeakObject* >(pHelper), UNO_QUERY_THROW);
        pHelper->setOwner                   (xThis   );
        pHelper->connectWithUntitledNumbers (xDesktop);
    }

    return m_pData->m_xTitleHelper;
}


Reference< frame::XUntitledNumbers > SfxBaseModel::impl_getUntitledHelper ()
{
    SfxModelGuard aGuard( *this );

    if ( ! m_pData->m_xNumberedControllers.is ())
    {
        Reference< frame::XModel > xThis   (static_cast< frame::XModel* >(this), UNO_QUERY_THROW);
        ::comphelper::NumberedCollection*         pHelper = new ::comphelper::NumberedCollection();

        m_pData->m_xNumberedControllers.set(static_cast< ::cppu::OWeakObject* >(pHelper), UNO_QUERY_THROW);

        pHelper->setOwner          (xThis);
        pHelper->setUntitledPrefix (" : ");
    }

    return m_pData->m_xNumberedControllers;
}


// css.frame.XTitle
OUString SAL_CALL SfxBaseModel::getTitle()
{
    // SYNCHRONIZED ->
    SfxModelGuard aGuard( *this );

    OUString aResult = impl_getTitleHelper()->getTitle ();
    if ( !m_pData->m_bExternalTitle && m_pData->m_pObjectShell )
    {
        SfxMedium* pMedium = m_pData->m_pObjectShell->GetMedium();
        if ( pMedium )
        {
            try {
                ::ucbhelper::Content aContent( pMedium->GetName(),
                    utl::UCBContentHelper::getDefaultCommandEnvironment(),
                    comphelper::getProcessComponentContext() );
                const Reference < beans::XPropertySetInfo > xProps
                     = aContent.getProperties();
                if ( xProps.is() )
                {
                    const OUString aServerTitle( "TitleOnServer" );
                    if ( xProps->hasPropertyByName( aServerTitle ) )
                    {
                        Any aAny = aContent.getPropertyValue( aServerTitle );
                        aAny >>= aResult;
                    }
                }
            }
            catch (const ucb::ContentCreationException &)
            {
            }
            catch (const ucb::CommandAbortedException &)
            {
            }
            const SfxBoolItem* pRepairedDocItem = SfxItemSet::GetItem<SfxBoolItem>(pMedium->GetItemSet(), SID_REPAIRPACKAGE, false);
            if ( pRepairedDocItem && pRepairedDocItem->GetValue() )
                aResult += SfxResId(STR_REPAIREDDOCUMENT);
        }

        if ( m_pData->m_pObjectShell->IsReadOnlyUI() || (pMedium && pMedium->IsReadOnly()) )
            aResult += SfxResId(STR_READONLY);
        else if ( m_pData->m_pObjectShell->IsDocShared() )
            aResult += SfxResId(STR_SHARED);

        if ( m_pData->m_pObjectShell->GetDocumentSignatureState() == SignatureState::OK )
            aResult += SfxResId(RID_XMLSEC_DOCUMENTSIGNED);
    }

    return aResult;
}


// css.frame.XTitle
void SAL_CALL SfxBaseModel::setTitle( const OUString& sTitle )
{
    // SYNCHRONIZED ->
    SfxModelGuard aGuard( *this );

    impl_getTitleHelper()->setTitle (sTitle);
    m_pData->m_bExternalTitle = true;
}


// css.frame.XTitleChangeBroadcaster
void SAL_CALL SfxBaseModel::addTitleChangeListener( const Reference< frame::XTitleChangeListener >& xListener )
{
    // SYNCHRONIZED ->
    SfxModelGuard aGuard( *this, SfxModelGuard::E_INITIALIZING );

    Reference< frame::XTitleChangeBroadcaster > xBroadcaster(impl_getTitleHelper(), UNO_QUERY);
    if (xBroadcaster.is ())
        xBroadcaster->addTitleChangeListener (xListener);
}


// css.frame.XTitleChangeBroadcaster
void SAL_CALL SfxBaseModel::removeTitleChangeListener( const Reference< frame::XTitleChangeListener >& xListener )
{
    // SYNCHRONIZED ->
    SfxModelGuard aGuard( *this );

    Reference< frame::XTitleChangeBroadcaster > xBroadcaster(impl_getTitleHelper(), UNO_QUERY);
    if (xBroadcaster.is ())
        xBroadcaster->removeTitleChangeListener (xListener);
}


// css.frame.XUntitledNumbers
::sal_Int32 SAL_CALL SfxBaseModel::leaseNumber( const Reference< XInterface >& xComponent )
{
    SfxModelGuard aGuard( *this );

    return impl_getUntitledHelper ()->leaseNumber (xComponent);
}


// css.frame.XUntitledNumbers
void SAL_CALL SfxBaseModel::releaseNumber( ::sal_Int32 nNumber )
{
    SfxModelGuard aGuard( *this );
    impl_getUntitledHelper ()->releaseNumber (nNumber);
}


// css.frame.XUntitledNumbers
void SAL_CALL SfxBaseModel::releaseNumberForComponent( const Reference< XInterface >& xComponent )
{
    SfxModelGuard aGuard( *this );
    impl_getUntitledHelper ()->releaseNumberForComponent (xComponent);
}


// css.frame.XUntitledNumbers
OUString SAL_CALL SfxBaseModel::getUntitledPrefix()
{
    SfxModelGuard aGuard( *this );
    return impl_getUntitledHelper ()->getUntitledPrefix ();
}


// frame::XModel2
Reference< container::XEnumeration > SAL_CALL SfxBaseModel::getControllers()
{
    SfxModelGuard aGuard( *this );

    sal_Int32 c = m_pData->m_seqControllers.size();
    sal_Int32 i = 0;
    Sequence< Any > lEnum(c);
    for (i=0; i<c; ++i)
        lEnum[i] <<= m_pData->m_seqControllers[i];

    ::comphelper::OAnyEnumeration*                      pEnum = new ::comphelper::OAnyEnumeration(lEnum);
    Reference< container::XEnumeration > xEnum(static_cast< container::XEnumeration* >(pEnum), UNO_QUERY_THROW);
    return xEnum;
}


// frame::XModel2
Sequence< OUString > SAL_CALL SfxBaseModel::getAvailableViewControllerNames()
{
    SfxModelGuard aGuard( *this );

    const SfxObjectFactory& rDocumentFactory = GetObjectShell()->GetFactory();
    const sal_Int16 nViewFactoryCount = rDocumentFactory.GetViewFactoryCount();

    Sequence< OUString > aViewNames( nViewFactoryCount );
    for ( sal_Int16 nViewNo = 0; nViewNo < nViewFactoryCount; ++nViewNo )
        aViewNames[nViewNo] = rDocumentFactory.GetViewFactory( nViewNo ).GetAPIViewName();
    return aViewNames;
}


// frame::XModel2
Reference< frame::XController2 > SAL_CALL SfxBaseModel::createDefaultViewController( const Reference< frame::XFrame >& i_rFrame )
{
    SfxModelGuard aGuard( *this );

    const SfxObjectFactory& rDocumentFactory = GetObjectShell()->GetFactory();
    const OUString sDefaultViewName = rDocumentFactory.GetViewFactory().GetAPIViewName();

    aGuard.clear();

    return createViewController( sDefaultViewName, Sequence< PropertyValue >(), i_rFrame );
}


namespace sfx::intern {

    /** a class which, in its dtor, cleans up various objects (well, at the moment only the frame) collected during
        the creation of a document view, unless the creation was successful.
    */
    class ViewCreationGuard
    {
    public:
        ViewCreationGuard()
            :m_bSuccess( false )
        {
        }

        ~ViewCreationGuard()
        {
            if ( !m_bSuccess && m_aWeakFrame && !m_aWeakFrame->GetCurrentDocument() )
            {
                m_aWeakFrame->SetFrameInterface_Impl( nullptr );
                m_aWeakFrame->DoClose();
            }
        }

        void takeFrameOwnership( SfxFrame* i_pFrame )
        {
            OSL_PRECOND( !m_aWeakFrame, "ViewCreationGuard::takeFrameOwnership: already have a frame!" );
            OSL_PRECOND( i_pFrame != nullptr, "ViewCreationGuard::takeFrameOwnership: invalid frame!" );
            m_aWeakFrame = i_pFrame;
        }

        void    releaseAll()
        {
            m_bSuccess = true;
        }

    private:
        bool             m_bSuccess;
        SfxFrameWeakRef  m_aWeakFrame;
    };
}


SfxViewFrame* SfxBaseModel::FindOrCreateViewFrame_Impl( const Reference< XFrame >& i_rFrame, ::sfx::intern::ViewCreationGuard& i_rGuard ) const
{
    SfxViewFrame* pViewFrame = nullptr;
    for (   pViewFrame = SfxViewFrame::GetFirst( GetObjectShell(), false );
            pViewFrame;
            pViewFrame= SfxViewFrame::GetNext( *pViewFrame, GetObjectShell(), false )
        )
    {
        if ( pViewFrame->GetFrame().GetFrameInterface() == i_rFrame )
            break;
    }
    if ( !pViewFrame )
    {
    #if OSL_DEBUG_LEVEL > 0
        for (   SfxFrame* pCheckFrame = SfxFrame::GetFirst();
                pCheckFrame;
                pCheckFrame = SfxFrame::GetNext( *pCheckFrame )
             )
        {
            if ( pCheckFrame->GetFrameInterface() == i_rFrame )
            {
                if  (   ( pCheckFrame->GetCurrentViewFrame() != nullptr )
                    ||  ( pCheckFrame->GetCurrentDocument() != nullptr )
                    )
                    // Note that it is perfectly legitimate that during loading into an XFrame which already contains
                    // a document, there exist two SfxFrame instances bound to this XFrame - the old one, which will be
                    // destroyed later, and the new one, which we're going to create
                    continue;

                OSL_FAIL( "SfxBaseModel::FindOrCreateViewFrame_Impl: there already is an SfxFrame for the given XFrame, but no view in it!" );
                    // nowadays, we're the only instance allowed to create an SfxFrame for an XFrame, so this case here should not happen
                break;
            }
        }
    #endif

        SfxFrame* pTargetFrame = SfxFrame::Create( i_rFrame );
        ENSURE_OR_THROW( pTargetFrame, "could not create an SfxFrame" );
        i_rGuard.takeFrameOwnership( pTargetFrame );

        // prepare it
        pTargetFrame->PrepareForDoc_Impl( *GetObjectShell() );

        // create view frame
        pViewFrame = new SfxViewFrame( *pTargetFrame, GetObjectShell() );
    }
    return pViewFrame;
}


// frame::XModel2
Reference< frame::XController2 > SAL_CALL SfxBaseModel::createViewController(
        const OUString& i_rViewName, const Sequence< PropertyValue >& i_rArguments, const Reference< XFrame >& i_rFrame )
{
    SfxModelGuard aGuard( *this );

    if ( !i_rFrame.is() )
        throw lang::IllegalArgumentException( OUString(), *this, 3 );

    // find the proper SFX view factory
    SfxViewFactory* pViewFactory = GetObjectShell()->GetFactory().GetViewFactoryByViewName( i_rViewName );
    if ( !pViewFactory )
        throw IllegalArgumentException( OUString(), *this, 1 );

    // determine previous shell (used in some special cases)
    Reference< XController > xPreviousController( i_rFrame->getController() );
    const Reference< XModel > xMe( this );
    if  (   ( xPreviousController.is() )
        &&  ( xMe != xPreviousController->getModel() )
        )
    {
        xPreviousController.clear();
    }
    SfxViewShell* pOldViewShell = SfxViewShell::Get( xPreviousController );
    OSL_ENSURE( !xPreviousController.is() || ( pOldViewShell != nullptr ),
        "SfxBaseModel::createViewController: invalid old controller!" );

    // a guard which will clean up in case of failure
    ::sfx::intern::ViewCreationGuard aViewCreationGuard;

    // determine the ViewFrame belonging to the given XFrame
    SfxViewFrame* pViewFrame = FindOrCreateViewFrame_Impl( i_rFrame, aViewCreationGuard );<--- Assignment 'pViewFrame=FindOrCreateViewFrame_Impl(i_rFrame,aViewCreationGuard)', assigned value is 0
    SAL_WARN_IF( !pViewFrame , "sfx.doc", "SfxBaseModel::createViewController: no frame?" );<--- Assuming that condition '!pViewFrame' is not redundant

    // delegate to SFX' view factory
    pViewFrame->GetBindings().ENTERREGISTRATIONS();<--- Null pointer dereference
    SfxViewShell* pViewShell = pViewFactory->CreateInstance( pViewFrame, pOldViewShell );
    pViewFrame->GetBindings().LEAVEREGISTRATIONS();
    ENSURE_OR_THROW( pViewShell, "invalid view shell provided by factory" );

    // by setting the ViewShell it is prevented that disposing the Controller will destroy this ViewFrame also
    pViewFrame->GetDispatcher()->SetDisableFlags( SfxDisableFlags::NONE );
    pViewFrame->SetViewShell_Impl( pViewShell );

    // remember ViewID
    pViewFrame->SetCurViewId_Impl( pViewFactory->GetOrdinal() );

    // ensure a default controller, if the view shell did not provide an own implementation
    if ( !pViewShell->GetController().is() )
        pViewShell->SetController( new SfxBaseController( pViewShell ) );

    // pass the creation arguments to the controller
    SfxBaseController* pBaseController = pViewShell->GetBaseController_Impl();
    ENSURE_OR_THROW( pBaseController, "invalid controller implementation!" );
    pBaseController->SetCreationArguments_Impl( i_rArguments );

    // some initial view settings, coming from our most recent attachResource call
    ::comphelper::NamedValueCollection aDocumentLoadArgs( getArgs() );
    if ( aDocumentLoadArgs.getOrDefault( "ViewOnly", false ) )
        pViewFrame->GetFrame().SetMenuBarOn_Impl( false );

    const sal_Int16 nPluginMode = aDocumentLoadArgs.getOrDefault( "PluginMode", sal_Int16( 0 ) );
    if ( nPluginMode == 1 )
    {
        pViewFrame->ForceOuterResize_Impl();
        pViewFrame->GetBindings().HidePopups();

        SfxFrame& rFrame = pViewFrame->GetFrame();
        // MBA: layoutmanager of inplace frame starts locked and invisible
        rFrame.GetWorkWindow_Impl()->MakeVisible_Impl( false );
        rFrame.GetWorkWindow_Impl()->Lock_Impl( true );

        rFrame.GetWindow().SetBorderStyle( WindowBorderStyle::NOBORDER );
        pViewFrame->GetWindow().SetBorderStyle( WindowBorderStyle::NOBORDER );
    }

    // tell the guard we were successful
    aViewCreationGuard.releaseAll();

    // outta here
    return pBaseController;
}


// RDF DocumentMetadataAccess

// rdf::XRepositorySupplier:
Reference< rdf::XRepository > SAL_CALL
SfxBaseModel::getRDFRepository()
{
    SfxModelGuard aGuard( *this );

    const Reference<rdf::XDocumentMetadataAccess> xDMA(m_pData->GetDMA());
    if (!xDMA.is()) {
        throw RuntimeException( "model has no document metadata", *this );
    }

    return xDMA->getRDFRepository();
}

// rdf::XNode:
OUString SAL_CALL
SfxBaseModel::getStringValue()
{
    SfxModelGuard aGuard( *this );

    const Reference<rdf::XDocumentMetadataAccess> xDMA(m_pData->GetDMA());
    if (!xDMA.is()) {
        throw RuntimeException( "model has no document metadata", *this );
    }

    return xDMA->getStringValue();
}

// rdf::XURI:
OUString SAL_CALL
SfxBaseModel::getNamespace()
{
    SfxModelGuard aGuard( *this );

    const Reference<rdf::XDocumentMetadataAccess> xDMA(m_pData->GetDMA());
    if (!xDMA.is()) {
        throw RuntimeException( "model has no document metadata", *this );
    }

    return xDMA->getNamespace();
}

OUString SAL_CALL
SfxBaseModel::getLocalName()
{
    SfxModelGuard aGuard( *this );

    const Reference<rdf::XDocumentMetadataAccess> xDMA(m_pData->GetDMA());
    if (!xDMA.is()) {
        throw RuntimeException( "model has no document metadata", *this );
    }

    return xDMA->getLocalName();
}

// rdf::XDocumentMetadataAccess:
Reference< rdf::XMetadatable > SAL_CALL
SfxBaseModel::getElementByMetadataReference(
    const beans::StringPair & i_rReference)
{
    SfxModelGuard aGuard( *this );

    const Reference<rdf::XDocumentMetadataAccess> xDMA(m_pData->GetDMA());
    if (!xDMA.is()) {
        throw RuntimeException( "model has no document metadata", *this );
    }

    return xDMA->getElementByMetadataReference(i_rReference);
}

Reference< rdf::XMetadatable > SAL_CALL
SfxBaseModel::getElementByURI(const Reference< rdf::XURI > & i_xURI)
{
    SfxModelGuard aGuard( *this );

    const Reference<rdf::XDocumentMetadataAccess> xDMA(m_pData->GetDMA());
    if (!xDMA.is()) {
        throw RuntimeException( "model has no document metadata", *this );
    }

    return xDMA->getElementByURI(i_xURI);
}

Sequence< Reference< rdf::XURI > > SAL_CALL
SfxBaseModel::getMetadataGraphsWithType(
    const Reference<rdf::XURI> & i_xType)
{
    SfxModelGuard aGuard( *this );

    const Reference<rdf::XDocumentMetadataAccess> xDMA(m_pData->GetDMA());
    if (!xDMA.is()) {
        throw RuntimeException( "model has no document metadata", *this );
    }

    return xDMA->getMetadataGraphsWithType(i_xType);
}

Reference<rdf::XURI> SAL_CALL
SfxBaseModel::addMetadataFile(const OUString & i_rFileName,
    const Sequence < Reference< rdf::XURI > > & i_rTypes)
{
    SfxModelGuard aGuard( *this );

    const Reference<rdf::XDocumentMetadataAccess> xDMA(m_pData->GetDMA());
    if (!xDMA.is()) {
        throw RuntimeException( "model has no document metadata", *this );
    }

    return xDMA->addMetadataFile(i_rFileName, i_rTypes);
}

Reference<rdf::XURI> SAL_CALL
SfxBaseModel::importMetadataFile(::sal_Int16 i_Format,
    const Reference< io::XInputStream > & i_xInStream,
    const OUString & i_rFileName,
    const Reference< rdf::XURI > & i_xBaseURI,
    const Sequence < Reference< rdf::XURI > > & i_rTypes)
{
    SfxModelGuard aGuard( *this );

    const Reference<rdf::XDocumentMetadataAccess> xDMA(m_pData->GetDMA());
    if (!xDMA.is()) {
        throw RuntimeException( "model has no document metadata", *this );
    }

    return xDMA->importMetadataFile(i_Format,
        i_xInStream, i_rFileName, i_xBaseURI, i_rTypes);
}

void SAL_CALL
SfxBaseModel::removeMetadataFile(
    const Reference< rdf::XURI > & i_xGraphName)
{
    SfxModelGuard aGuard( *this );

    const Reference<rdf::XDocumentMetadataAccess> xDMA(m_pData->GetDMA());
    if (!xDMA.is()) {
        throw RuntimeException( "model has no document metadata", *this );
    }

    return xDMA->removeMetadataFile(i_xGraphName);
}

void SAL_CALL
SfxBaseModel::addContentOrStylesFile(const OUString & i_rFileName)
{
    SfxModelGuard aGuard( *this );

    const Reference<rdf::XDocumentMetadataAccess> xDMA(m_pData->GetDMA());
    if (!xDMA.is()) {
        throw RuntimeException( "model has no document metadata", *this );
    }

    return xDMA->addContentOrStylesFile(i_rFileName);
}

void SAL_CALL
SfxBaseModel::removeContentOrStylesFile(const OUString & i_rFileName)
{
    SfxModelGuard aGuard( *this );

    const Reference<rdf::XDocumentMetadataAccess> xDMA(m_pData->GetDMA());
    if (!xDMA.is()) {
        throw RuntimeException( "model has no document metadata", *this );
    }

    return xDMA->removeContentOrStylesFile(i_rFileName);
}

void SAL_CALL
SfxBaseModel::loadMetadataFromStorage(
    Reference< embed::XStorage > const & i_xStorage,
    Reference<rdf::XURI> const & i_xBaseURI,
    Reference<task::XInteractionHandler> const & i_xHandler)
{
    SfxModelGuard aGuard( *this );

    const Reference<rdf::XDocumentMetadataAccess> xDMA(
        m_pData->CreateDMAUninitialized());
    if (!xDMA.is()) {
        throw RuntimeException( "model has no document metadata", *this );
    }

    try {
        xDMA->loadMetadataFromStorage(i_xStorage, i_xBaseURI, i_xHandler);
    } catch (lang::IllegalArgumentException &) {
        throw; // not initialized
    } catch (Exception &) {
        // UGLY: if it's a RuntimeException, we can't be sure DMA is initialized
        m_pData->m_xDocumentMetadata = xDMA;
        throw;
    }
    m_pData->m_xDocumentMetadata = xDMA;

}

void SAL_CALL
SfxBaseModel::storeMetadataToStorage(
    Reference< embed::XStorage > const & i_xStorage)
{
    SfxModelGuard aGuard( *this );

    const Reference<rdf::XDocumentMetadataAccess> xDMA(m_pData->GetDMA());
    if (!xDMA.is()) {
        throw RuntimeException( "model has no document metadata", *this );
    }

    return xDMA->storeMetadataToStorage(i_xStorage);
}

void SAL_CALL
SfxBaseModel::loadMetadataFromMedium(
    const Sequence< beans::PropertyValue > & i_rMedium)
{
    SfxModelGuard aGuard( *this );

    const Reference<rdf::XDocumentMetadataAccess> xDMA(
        m_pData->CreateDMAUninitialized());
    if (!xDMA.is()) {
        throw RuntimeException( "model has no document metadata", *this );
    }

    try {
        xDMA->loadMetadataFromMedium(i_rMedium);
    } catch (lang::IllegalArgumentException &) {
        throw; // not initialized
    } catch (Exception &) {
        // UGLY: if it's a RuntimeException, we can't be sure DMA is initialized
        m_pData->m_xDocumentMetadata = xDMA;
        throw;
    }
    m_pData->m_xDocumentMetadata = xDMA;
}

void SAL_CALL
SfxBaseModel::storeMetadataToMedium(
    const Sequence< beans::PropertyValue > & i_rMedium)
{
    SfxModelGuard aGuard( *this );

    const Reference<rdf::XDocumentMetadataAccess> xDMA(m_pData->GetDMA());
    if (!xDMA.is()) {
        throw RuntimeException( "model has no document metadata", *this );
    }

    return xDMA->storeMetadataToMedium(i_rMedium);
}


// = SfxModelSubComponent


SfxModelSubComponent::~SfxModelSubComponent()
{
}

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