summaryrefslogtreecommitdiff
path: root/sfx2/source/doc/objstor.cxx
blob: 317a2c24ddb8120904ec39963cbe78f2187736f4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
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
/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: objstor.cxx,v $
 *
 *  $Revision: 1.186 $
 *
 *  last change: $Author: kz $ $Date: 2006-11-08 12:07:05 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sfx2.hxx"

#ifndef _MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _ZCODEC_HXX //autogen
#include <tools/zcodec.hxx>
#endif
#ifndef _COM_SUN_STAR_FRAME_XSTORABLE_HPP_
#include <com/sun/star/frame/XStorable.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif

#ifndef _COM_SUN_STAR_DOCUMENT_XFILTER_HPP_
#include <com/sun/star/document/XFilter.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XIMPORTER_HPP_
#include <com/sun/star/document/XImporter.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XEXPORTER_HPP_
#include <com/sun/star/document/XExporter.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_FILTEROPTIONSREQUEST_HPP_
#include <com/sun/star/document/FilterOptionsRequest.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XINTERACTIONFILTEROPTIONS_HPP_
#include <com/sun/star/document/XInteractionFilterOptions.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XINTERACTIONHANDLER_HPP_
#include <com/sun/star/task/XInteractionHandler.hpp>
#endif

#ifndef  _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif

#ifndef _COM_SUN_STAR_DOCUMENT_MACROEXECMODE_HPP_
#include <com/sun/star/document/MacroExecMode.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERCONTROLACCESS_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_XFILEPICKER_HPP_
#include <com/sun/star/ui/dialogs/XFilePicker.hpp>
#endif
#ifndef  _COM_SUN_STAR_BEANS_XPROPERTYSETINFO_HPP_
#include <com/sun/star/beans/XPropertySetInfo.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYACCESS_HPP_
#include <com/sun/star/beans/XPropertyAccess.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XSET_HPP_
#include <com/sun/star/container/XSet.hpp>
#endif

#ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_
#include <com/sun/star/embed/ElementModes.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_EMBEDSTATES_HPP_
#include <com/sun/star/embed/EmbedStates.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_ASPECTS_HPP_
#include <com/sun/star/embed/Aspects.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XTRANSACTEDOBJECT_HPP_
#include <com/sun/star/embed/XTransactedObject.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XEMBEDPERSIST_HPP_
#include <com/sun/star/embed/XEmbedPersist.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XLINKAGESUPPORT_HPP_
#include <com/sun/star/embed/XLinkageSupport.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_ENTRYINITMODES_HPP_
#include <com/sun/star/embed/EntryInitModes.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XOPTIMIZEDSTORAGE_HPP_
#include <com/sun/star/embed/XOptimizedStorage.hpp>
#endif

#ifndef _COM_SUN_STAR_IO_XTRUNCATE_HPP_
#include <com/sun/star/io/XTruncate.hpp>
#endif

#ifndef _COM_SUN_STAR_UTIL_XMODIFIABLE_HPP_
#include <com/sun/star/util/XModifiable.hpp>
#endif

#ifndef _COM_SUN_STAR_SECURITY_XDOCUMENTDIGITALSIGNATURES_HPP_
#include <com/sun/star/security/XDocumentDigitalSignatures.hpp>
#endif


#ifndef _UNOTOOLS_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#ifndef _SFXECODE_HXX
#include <svtools/sfxecode.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_SECURITYOPTIONS_HXX
#include <svtools/securityoptions.hxx>
#endif

#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#ifndef _CACHESTR_HXX
#include <tools/cachestr.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_ADDXMLTOSTORAGEOPTIONS_HXX
#include <svtools/addxmltostorageoptions.hxx>
#endif
#ifndef _UTL_STREAM_WRAPPER_HXX_
#include <unotools/streamwrap.hxx>
#endif

#include <svtools/saveopt.hxx>
#include <svtools/useroptions.hxx>
#include <svtools/pathoptions.hxx>
#include <tools/urlobj.hxx>
#include <unotools/localfilehelper.hxx>
#include <unotools/ucbhelper.hxx>
#include <unotools/tempfile.hxx>
#include <ucbhelper/content.hxx>
#include <sot/storinfo.hxx>
#include <sot/exchange.hxx>
#include <sot/formats.hxx>
#include <shell/systemshell.hxx>
#include <comphelper/storagehelper.hxx>
#include <comphelper/seqstream.hxx>
#include <comphelper/documentconstants.hxx>
#include <vcl/bitmapex.hxx>
#include <svtools/embedhlp.hxx>
#include <rtl/logfile.hxx>

#include "app.hxx"
#include "objsh.hxx"
#include "childwin.hxx"
#include "request.hxx"
#include "sfxresid.hxx"
#include "docfile.hxx"
#include "fltfnc.hxx"
#include "docfilt.hxx"
#include "docinf.hxx"
#include "docfac.hxx"
#include "objshimp.hxx"
#include "sfxtypes.hxx"
#include "doc.hrc"
#include "sfxsids.hrc"
#include "module.hxx"
#include "dispatch.hxx"
#include "openflag.hxx"
#include "helper.hxx"
#include "filedlghelper.hxx"
#include "event.hxx"
#include "fltoptint.hxx"
#include "viewfrm.hxx"
#include "graphhelp.hxx"
#include "modsizeexceeded.hxx"
#include "appbaslib.hxx"

#include "../appl/app.hrc"

extern sal_uInt32 CheckPasswd_Impl( SfxObjectShell*, SfxItemPool&, SfxMedium* );

using namespace ::com::sun::star;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::ui::dialogs;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::ucb;
using namespace ::com::sun::star::task;
using namespace ::com::sun::star::document;
using namespace ::rtl;
using namespace ::cppu;

using ::basic::SfxLibraryContainer;

namespace css = ::com::sun::star;

//=========================================================================
void impl_addToModelCollection(const css::uno::Reference< css::frame::XModel >& xModel)
{
    if (!xModel.is())
        return;

    css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = ::comphelper::getProcessServiceFactory();
    css::uno::Reference< css::container::XSet > xModelCollection(
        xSMGR->createInstance(::rtl::OUString::createFromAscii("com.sun.star.frame.GlobalEventBroadcaster")),
        css::uno::UNO_QUERY);
    if (xModelCollection.is())
    {
        try
        {
            xModelCollection->insert(css::uno::makeAny(xModel));
        }
        catch ( uno::Exception& )
        {
            OSL_ENSURE( sal_False, "The document seems to be in the collection already!\n" );
        }
    }
}

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

sal_Bool SfxObjectShell::Save()
{
    return SaveChildren();
}

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

sal_Bool SfxObjectShell::SaveAs( SfxMedium& rMedium )
{
    return SaveAsChildren( rMedium );
}

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

sal_Bool GetPasswd_Impl( const SfxItemSet* pSet, String& rPasswd )
{
    const SfxPoolItem* pItem = NULL;
    if ( pSet && SFX_ITEM_SET == pSet->GetItemState( SID_PASSWORD, sal_True, &pItem ) )
    {
        DBG_ASSERT( pItem->IsA( TYPE(SfxStringItem) ), "wrong item type" );
        rPasswd = ( (const SfxStringItem*)pItem )->GetValue();
        return sal_True;
    }
    return sal_False;
}

//-------------------------------------------------------------------------
sal_Bool SfxObjectShell::NoDependencyFromManifest_Impl( const uno::Reference< embed::XStorage >& xStorage )
{
    uno::Sequence< ::rtl::OUString > aElements = xStorage->getElementNames();
    for ( sal_Int32 nInd = 0; nInd < aElements.getLength(); nInd++ )
    {
        if ( xStorage->isStorageElement( aElements[nInd] ) )
        {
            // if there are other standard elements that do not need manifest.xml the following
            // list can be extended
            if ( !aElements[nInd].equals( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Pictures" ) ) )
              && !aElements[nInd].equals( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Configurations" ) ) )
              && !aElements[nInd].equals( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Configurations2" ) ) )
              && !aElements[nInd].equals( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Thumbnails" ) ) )
              && !aElements[nInd].equals( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Basic" ) ) ) )
            {
                // the substorage is not know as one that does not need manifest.xml
                return sal_False;
            }
        }
    }

    return sal_True;
}

//-------------------------------------------------------------------------
sal_Bool SfxObjectShell::PutURLContentsToVersionStream_Impl(
                                            ::rtl::OUString aURL,
                                            const uno::Reference< embed::XStorage >& xDocStorage,
                                            ::rtl::OUString aStreamName )
{
    sal_Bool bResult = sal_False;
    try
    {
        uno::Reference< embed::XStorage > xVersion = xDocStorage->openStorageElement(
                                                        ::rtl::OUString::createFromAscii( "Versions" ),
                                                        embed::ElementModes::READWRITE );

        DBG_ASSERT( xVersion.is(),
                "The method must throw an exception if the storage can not be opened!\n" );
        if ( !xVersion.is() )
            throw uno::RuntimeException();

        uno::Reference< io::XStream > xVerStream = xVersion->openStreamElement(
                                                                aStreamName,
                                                                embed::ElementModes::READWRITE );
        DBG_ASSERT( xVerStream.is(), "The method must throw an exception if the storage can not be opened!\n" );
        if ( !xVerStream.is() )
            throw uno::RuntimeException();

        uno::Reference< io::XOutputStream > xOutStream = xVerStream->getOutputStream();
        uno::Reference< io::XTruncate > xTrunc( xOutStream, uno::UNO_QUERY );

        DBG_ASSERT( xTrunc.is(), "The output stream must exist and implement XTruncate interface!\n" );
        if ( !xTrunc.is() )
            throw RuntimeException();

        uno::Reference< io::XInputStream > xTmpInStream =
            ::comphelper::OStorageHelper::GetInputStreamFromURL( aURL );
        DBG_ASSERT( xTmpInStream.is(), "The method must create the stream or throw an exception!\n" );
        if ( !xTmpInStream.is() )
            throw uno::RuntimeException();

        xTrunc->truncate();
        ::comphelper::OStorageHelper::CopyInputToOutput( xTmpInStream, xOutStream );
        xOutStream->closeOutput();

        uno::Reference< embed::XTransactedObject > xTransact( xVersion, uno::UNO_QUERY );
        DBG_ASSERT( xTransact.is(), "The storage must implement XTransacted interface!\n" );
        if ( xTransact.is() )
            xTransact->commit();

        bResult = sal_True;
    }
    catch( uno::Exception& )
    {
        // TODO/LATER: handle the error depending on exception
        SetError( ERRCODE_IO_GENERAL );
    }

    return bResult;
}

//-------------------------------------------------------------------------
::rtl::OUString SfxObjectShell::CreateTempCopyOfStorage_Impl( const uno::Reference< embed::XStorage >& xStorage )
{
    ::rtl::OUString aTempURL = ::utl::TempFile().GetURL();

    DBG_ASSERT( aTempURL.getLength(), "Can't create a temporary file!\n" );
    if ( aTempURL.getLength() )
    {
        try
        {
            uno::Reference< embed::XStorage > xTempStorage =
                ::comphelper::OStorageHelper::GetStorageFromURL( aTempURL, embed::ElementModes::READWRITE );

            // the password will be transfered from the xStorage to xTempStorage by storage implemetation
            xStorage->copyToStorage( xTempStorage );

            // the temporary storage was commited by the previous method and it will die by refcount
        }
        catch ( uno::Exception& )
        {
            DBG_ERROR( "Creation of a storage copy is failed!" );
            ::utl::UCBContentHelper::Kill( aTempURL );

            aTempURL = ::rtl::OUString();

            // TODO/LATER: may need error code setting based on exception
            SetError( ERRCODE_IO_GENERAL );
        }
    }

    return aTempURL;
}

//-------------------------------------------------------------------------
SvGlobalName SfxObjectShell::GetClassName() const
{
    return GetFactory().GetClassId();
}

//-------------------------------------------------------------------------
void SfxObjectShell::SetupStorage( const uno::Reference< embed::XStorage >& xStorage,
                                   sal_Int32 nVersion,
                                   sal_Bool bTemplate ) const
{
    uno::Reference< beans::XPropertySet > xProps( xStorage, uno::UNO_QUERY );

    if ( xProps.is() )
    {
        SvGlobalName aName;
        String aFullTypeName, aShortTypeName, aAppName;
        sal_uInt32 nClipFormat=0;

        FillClass( &aName, &nClipFormat, &aAppName, &aFullTypeName, &aShortTypeName, nVersion );
        if ( nClipFormat )
        {
            // basic doesn't have a ClipFormat
            // without MediaType the storage is not really usable, but currently the BasicIDE still
            // is an SfxObjectShell and so we can't take this as an error
            datatransfer::DataFlavor aDataFlavor;
            SotExchange::GetFormatDataFlavor( nClipFormat, aDataFlavor );
            if ( aDataFlavor.MimeType.getLength() )
            {
                if ( bTemplate )
                {
                    // TODO/LATER: this is a temporary solution for BETA to avoid incompatible change
                    if ( aDataFlavor.MimeType.equals( MIMETYPE_OASIS_OPENDOCUMENT_TEXT ) )
                        aDataFlavor.MimeType = MIMETYPE_OASIS_OPENDOCUMENT_TEXT_TEMPLATE;
                    else if ( aDataFlavor.MimeType.equals( MIMETYPE_OASIS_OPENDOCUMENT_DRAWING ) )
                        aDataFlavor.MimeType = MIMETYPE_OASIS_OPENDOCUMENT_DRAWING_TEMPLATE;
                    else if ( aDataFlavor.MimeType.equals( MIMETYPE_OASIS_OPENDOCUMENT_PRESENTATION ) )
                        aDataFlavor.MimeType = MIMETYPE_OASIS_OPENDOCUMENT_PRESENTATION_TEMPLATE;
                    else if ( aDataFlavor.MimeType.equals( MIMETYPE_OASIS_OPENDOCUMENT_SPREADSHEET ) )
                        aDataFlavor.MimeType = MIMETYPE_OASIS_OPENDOCUMENT_SPREADSHEET_TEMPLATE;
                    else if ( aDataFlavor.MimeType.equals( MIMETYPE_OASIS_OPENDOCUMENT_CHART ) )
                        aDataFlavor.MimeType = MIMETYPE_OASIS_OPENDOCUMENT_CHART_TEMPLATE;
                    else if ( aDataFlavor.MimeType.equals( MIMETYPE_OASIS_OPENDOCUMENT_FORMULA ) )
                        aDataFlavor.MimeType = MIMETYPE_OASIS_OPENDOCUMENT_FORMULA_TEMPLATE;
                }

                try
                {
                    xProps->setPropertyValue( ::rtl::OUString::createFromAscii( "MediaType" ), uno::makeAny( aDataFlavor.MimeType ) );
                }
                catch( uno::Exception& )
                {
                    // TODO/LATER: ErrorHandling
                }
            }
        }
    }
}

//-------------------------------------------------------------------------
void SfxObjectShell::PrepareSecondTryLoad_Impl()
{
    // only for internal use
    pImp->m_xDocStorage = uno::Reference< embed::XStorage >();
    pImp->m_bIsInit = sal_False;
    ResetError();
}

//-------------------------------------------------------------------------
sal_Bool SfxObjectShell::GeneralInit_Impl( const uno::Reference< embed::XStorage >& xStorage,
                                            sal_Bool bTypeMustBeSetAlready )
{
    if ( pImp->m_bIsInit )
        return sal_False;

    pImp->m_bIsInit = sal_True;
    if ( xStorage.is() )
    {
        // no notification is required the storage is set the first time
        pImp->m_xDocStorage = xStorage;

        try {
            uno::Reference < beans::XPropertySet > xPropSet( xStorage, uno::UNO_QUERY_THROW );
            Any a = xPropSet->getPropertyValue( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "MediaType" ) ) );
            ::rtl::OUString aMediaType;
            if ( !(a>>=aMediaType) || !aMediaType.getLength() )
            {
                if ( bTypeMustBeSetAlready )
                {
                    SetError( ERRCODE_IO_BROKENPACKAGE );
                    return sal_False;
                }

                SetupStorage( xStorage, SOFFICE_FILEFORMAT_CURRENT, sal_False );
            }
        }
        catch ( uno::Exception& )
        {
            OSL_ENSURE( sal_False, "Can't check storage's mediatype!\n" );
        }
    }
    else
        pImp->m_bCreateTempStor = sal_True;

    return sal_True;
}

//-------------------------------------------------------------------------
sal_Bool SfxObjectShell::InitNew( const uno::Reference< embed::XStorage >& xStorage )
{
    return GeneralInit_Impl( xStorage, sal_False );
}

//-------------------------------------------------------------------------
sal_Bool SfxObjectShell::Load( SfxMedium& rMedium )
{
    return GeneralInit_Impl( rMedium.GetStorage(), sal_True );
}

//-------------------------------------------------------------------------
sal_Bool SfxObjectShell::DoInitNew_Impl( const ::rtl::OUString& rName )

/*  [Beschreibung]
*/

{
    if ( rName.getLength() )
    {
//REMOVE            ModifyBlocker_Impl aBlock( this );
//REMOVE            pMedium = new SfxMedium( rName, SFX_STREAM_READONLY_MAKECOPY, sal_False );
//REMOVE            if ( InitNew( pMedium->GetStorage() ) )
//REMOVE            {
//REMOVE                bIsTmp = !( pMedium->GetStorage() );
//REMOVE                if ( SFX_CREATE_MODE_EMBEDDED == eCreateMode )
//REMOVE                    SetTitle( String( SfxResId( STR_NONAME ) ));
//REMOVE
//REMOVE                uno::Reference< frame::XModel >  xModel ( GetModel(), uno::UNO_QUERY );
//REMOVE                if ( xModel.is() )
//REMOVE                {
//REMOVE                    SfxItemSet *pSet = GetMedium()->GetItemSet();
//REMOVE                    uno::Sequence< beans::PropertyValue > aArgs;
//REMOVE                    TransformItems( SID_OPENDOC, *pSet, aArgs );
//REMOVE                    sal_Int32 nLength = aArgs.getLength();
//REMOVE                    aArgs.realloc( nLength + 1 );
//REMOVE                    aArgs[nLength].Name = DEFINE_CONST_UNICODE("Title");
//REMOVE                    aArgs[nLength].Value <<= ::rtl::OUString( GetTitle( SFX_TITLE_DETECT ) );
//REMOVE                    xModel->attachResource( ::rtl::OUString(), aArgs );
//REMOVE                }
//REMOVE
//REMOVE                SetActivateEvent_Impl( SFX_EVENT_CREATEDOC );
//REMOVE                return sal_True;
//REMOVE            }
//REMOVE            return sal_False;

        DBG_ERROR( "This code is intended to be removed, the caller part must be checked!\n" );
        return DoInitNew(0);
    }
    else
        return DoInitNew(0);
}


sal_Bool SfxObjectShell::DoInitNew( SfxMedium* pMed )
/*  [Beschreibung]

    Diese von SvPersist geerbte virtuelle Methode wird gerufen, um
    die SfxObjectShell-Instanz aus einem Storage (pStor != 0) bzw.
    (pStor == 0) ganz neu zu initialisieren.

    Wie alle Do...-Methoden liegt hier eine Steuerung vor, die eigentliche
    Implementierung erfolgt, indem die ebenfalls virtuellen Methode
    InitNew(SvStorate*) von der SfxObjectShell-Subclass implementiert wird.

    F"ur pStor == 0 wird ein die SfxObjectShell-Instanz mit einem leeren
    SfxMedium verbunden, sonst mit einem SfxMedium, welches auf den
    als Parameter "ubergeben SvStorage verweist.

    Erst nach InitNew() oder Load() ist das Objekt korrekt initialisiert.

    [R"uckgabewert]
    sal_True            Das Objekt wurde initialisiert.
    sal_False           Das Objekt konnte nicht initialisiert werden
*/

{
    ModifyBlocker_Impl aBlock( this );
    pMedium = pMed;
    if ( !pMedium )
    {
        bIsTmp = sal_True;
        pMedium = new SfxMedium;
    }

    pMedium->CanDisposeStorage_Impl( sal_True );

    if ( InitNew( pMed ? pMed->GetStorage() : uno::Reference < embed::XStorage >() ) )
    {
        // empty documents always get their macros from the user, so there is no reason to restrict access
        pImp->nMacroMode = MacroExecMode::ALWAYS_EXECUTE_NO_WARN;
        if ( SFX_CREATE_MODE_EMBEDDED == eCreateMode )
            SetTitle( String( SfxResId( STR_NONAME ) ));

        uno::Reference< frame::XModel >  xModel ( GetModel(), uno::UNO_QUERY );
        if ( xModel.is() )
        {
            SfxItemSet *pSet = GetMedium()->GetItemSet();
            uno::Sequence< beans::PropertyValue > aArgs;
            TransformItems( SID_OPENDOC, *pSet, aArgs );
            sal_Int32 nLength = aArgs.getLength();
            aArgs.realloc( nLength + 1 );
            aArgs[nLength].Name = DEFINE_CONST_UNICODE("Title");
            aArgs[nLength].Value <<= ::rtl::OUString( GetTitle( SFX_TITLE_DETECT ) );
            xModel->attachResource( ::rtl::OUString(), aArgs );
            impl_addToModelCollection(xModel);
        }

        pImp->bInitialized = sal_True;
        SetActivateEvent_Impl( SFX_EVENT_CREATEDOC );
        SFX_APP()->NotifyEvent( SfxEventHint( SFX_EVENT_DOCCREATED, this ) );
        return sal_True;
    }

    return sal_False;
}

//REMOVE    //-------------------------------------------------------------------------
//REMOVE
//REMOVE    void SfxObjectShell::DoHandsOffNoMediumClose()
//REMOVE    {
//REMOVE        const SfxFilter *pFilter = pMedium->GetFilter();
//REMOVE        if( !pFilter || pFilter->IsOwnFormat() || ( pFilter->GetFilterFlags() & SFX_FILTER_PACKED ) )
//REMOVE            HandsOff();
//REMOVE
//REMOVE        // Force document library containers to release storage
//REMOVE        SotStorageRef xDummyStorage;
//REMOVE        pImp->pBasicManager->setStorage( SfxBasicManagerHolder::DIALOGS, xDummyStorage );
//REMOVE        pImp->pBasicManager->setStorage( SfxBasicManagerHolder::SCRIPTS, xDummyStorage );
//REMOVE    }

//REMOVE    //-------------------------------------------------------------------------
//REMOVE
//REMOVE    void SfxObjectShell::DoHandsOff()
//REMOVE
//REMOVE    /*  [Beschreibung]
//REMOVE
//REMOVE        Diese von SvPersist geerbte virtuelle Methode wird gerufen, um
//REMOVE        das Objekt aufzufordern, den ihm zugeteilten SvStorage freizugeben,
//REMOVE        insbesondere Substorages und Streams zu schlie"sen.
//REMOVE
//REMOVE        Als Do...-Methode liegt hier nur die Steuerung. Der Implementierer
//REMOVE        von Subclasses kann die ebenfalls virtuelle Methode HandsOff()
//REMOVE        implementieren, um seine Substorages und Streams zu schlie"sen.
//REMOVE
//REMOVE        Nach dem Aufruf dieser Methode, ist dem Objekt kein SfxMedium mehr
//REMOVE        zugeordnet, bis SaveCompleted() durchlaufen ist.
//REMOVE    */
//REMOVE
//REMOVE    {
//REMOVE        DoHandsOffNoMediumClose();
//REMOVE        pMedium->Close();
//REMOVE    //  DELETEZ( pMedium );
//REMOVE    }

//REMOVE    //-------------------------------------------------------------------------
//REMOVE
//REMOVE    sal_Bool SfxObjectShell::DoLoad(
//REMOVE        const String& rFileName, StreamMode nStreamMode, StorageMode nStorageMode)
//REMOVE    {
//REMOVE        // Es wird nur die IPersistStorage-Schnittstelle angeboten
//REMOVE        ModifyBlocker_Impl aBlock( this );
//REMOVE        SvStorageRef xStor = new SvStorage( rFileName, nStreamMode | STREAM_WRITE, nStorageMode );
//REMOVE        if( !xStor.Is() )
//REMOVE            xStor = new SvStorage( rFileName, nStreamMode, nStorageMode );
//REMOVE
//REMOVE        if ( SVSTREAM_OK == xStor->GetError() )
//REMOVE        {
//REMOVE            SfxMedium* pMedium = new SfxMedium( xStor );
//REMOVE            pMedium->SetName( rFileName );
//REMOVE            pMedium->Init_Impl();
//REMOVE
//REMOVE            // Muss !!!
//REMOVE            SetFileName( rFileName );
//REMOVE
//REMOVE            if( DoLoad( pMedium ) )
//REMOVE            {
//REMOVE                if ( SFX_CREATE_MODE_EMBEDDED == eCreateMode )
//REMOVE                    SetTitle( rFileName );
//REMOVE                return sal_True;
//REMOVE            }
//REMOVE        }
//REMOVE        return sal_False;
//REMOVE    }

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

sal_Bool SfxObjectShell::DoLoad( SfxMedium *pMed )

/*  [Beschreibung]

    Diese Methode steuert das Laden des Objektes aus dem von dem
    "ubergebenen SfxMedium beschriebenen Medium. Hinterher ist das Objekt
    mit diesem SfxMedium verbunden.

    Handelt es sich bei dem SfxMedium um einen Storage im eigenen Format,
    wird die virtuelle Methode SvPersit::Load(SvStorage*) gerufen, welche
    die Implementierer von Subclasses "uberladen m"ussen, um das Objekt
    aus einem eigenen Storage zu laden (=> Swapping m"oeglich).

    Handelt es sich bei dem SfxMedium um einen Storage in einem fremden
    Format, oder um ein Flat-File, dann wird die virtuelle Methode
    <SfxObjectShell::ConvertFrom(SfxMedium*)> gerufen, welche die
    Implementierer von Subclasses "uberladen m"ussen, um das Objekt
    aus dem SfxMedium zu konvertieren. W"ahrend der Bearbeitung ist
    das Objekt dann mit einem tempor"aren SvStorage verbunden.

    Erst nach InitNew() oder Load() ist das Objekt korrekt
    initialisiert.

    [R"uckgabewert]
    sal_True                Das Objekt wurde geladen.
    sal_False           Das Objekt konnte nicht geladen werden
*/

{
    ModifyBlocker_Impl aBlock( this );

    if ( SFX_CREATE_MODE_EMBEDDED != eCreateMode )
        GetpApp()->ShowStatusText( SfxResId(STR_DOC_LOADING) );

    pMedium = pMed;
    pMedium->CanDisposeStorage_Impl( sal_True );

    sal_Bool bOk = sal_False;
    const SfxFilter* pFilter = pMed->GetFilter();
    SfxItemSet* pSet = pMedium->GetItemSet();
    if( !pImp->nEventId )
    {
        SFX_ITEMSET_ARG(
            pSet, pTemplateItem, SfxBoolItem,
            SID_TEMPLATE, sal_False);
        SetActivateEvent_Impl(
            ( pTemplateItem && pTemplateItem->GetValue() )
            ? SFX_EVENT_CREATEDOC : SFX_EVENT_OPENDOC );
    }


    SFX_ITEMSET_ARG( pSet, pBaseItem, SfxStringItem,
                     SID_BASEURL, sal_False);
    String aBaseURL;
    SFX_ITEMSET_ARG( pMedium->GetItemSet(), pSalvageItem, SfxStringItem, SID_DOC_SALVAGE, sal_False);
    if( pBaseItem )
        aBaseURL = pBaseItem->GetValue();
    else
    {
        if ( pSalvageItem )
        {
            String aName( pMed->GetPhysicalName() );
            ::utl::LocalFileHelper::ConvertPhysicalNameToURL( aName, aBaseURL );
        }
        else
            aBaseURL = pMed->GetBaseURL();
    }

    pImp->nLoadedFlags = 0;
    pImp->bModelInitialized = sal_False;

    //TODO/LATER: make a clear strategy how to handle "UsesStorage" etc.
    sal_Bool bOwnStorageFormat = IsOwnStorageFormat_Impl( *pMedium );
    sal_Bool bHasStorage = IsPackageStorageFormat_Impl( *pMedium );
    if ( pMedium->GetFilter() )
    {
        sal_uInt32 nError = HandleFilter( pMedium, this );
        if ( nError != ERRCODE_NONE )
            SetError( nError );
    }

    EnableSetModified( sal_False );

    if ( GetError() == ERRCODE_NONE && bOwnStorageFormat && ( !pFilter || !( pFilter->GetFilterFlags() & SFX_FILTER_STARONEFILTER ) ) )
    {
        uno::Reference< embed::XStorage > xStorage = pMed->GetStorage();
        if( xStorage.is() && pMed->GetLastStorageCreationState() == ERRCODE_NONE )
        {
            DBG_ASSERT( pFilter, "No filter for storage found!" );

            try
            {
                sal_Bool bWarnMediaTypeFallback = sal_False;
                SFX_ITEMSET_ARG( pMedium->GetItemSet(), pRepairPackageItem, SfxBoolItem, SID_REPAIRPACKAGE, sal_False);

                // treat the package as broken if the mediatype was retrieved as a fallback
                uno::Reference< beans::XPropertySet > xStorProps( xStorage, uno::UNO_QUERY_THROW );
                xStorProps->getPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "MediaTypeFallbackUsed" ) ) )
                                                                    >>= bWarnMediaTypeFallback;

                if ( bWarnMediaTypeFallback && pRepairPackageItem && pRepairPackageItem->GetValue() )
                {
                    // the mediatype was retrieved by using fallback solution but this is a repairing mode
                    // so it is acceptable to open the document if there is no contents that required manifest.xml
                    bWarnMediaTypeFallback = sal_False; //!NoDependencyFromManifest_Impl( xStorage );
                }

                if ( bWarnMediaTypeFallback || !xStorage->getElementNames().getLength() )
                    SetError( ERRCODE_IO_BROKENPACKAGE );
            }
            catch( uno::Exception& )
            {
                // TODO/LATER: may need error code setting based on exception
                SetError( ERRCODE_IO_GENERAL );
            }

            // Load
            if ( !GetError() )
            {
                pImp->nLoadedFlags = 0;
                pImp->bModelInitialized = sal_False;
                bOk = xStorage.is() && LoadOwnFormat( *pMed );
                if ( bOk )
                {
                    SfxDocumentInfo& rDocInfo = GetDocInfo();
//REMOVE                        GetDocInfo().Load( xStor );
                    bHasName = sal_True;

                    // --> PB 2004-08-20 #i33095#
                    if ( !IsReadOnly() && rDocInfo.IsLoadReadonly() )
                        SetReadOnlyUI();
                    // <--
                }
                else
                    SetError( ERRCODE_ABORT );
            }
        }
        else
            SetError( pMed->GetLastStorageCreationState() );
    }
    else if ( GetError() == ERRCODE_NONE && InitNew(0) )
    {
        // Name vor ConvertFrom setzen, damit GetSbxObject() schon funktioniert
        bHasName = sal_True;
        SetName( SfxResId( STR_NONAME ) );

        if( !bHasStorage )
            pMedium->GetInStream();
        else
            pMedium->GetStorage();

        if ( GetError() == ERRCODE_NONE )
        {
            pImp->nLoadedFlags = 0;
            pImp->bModelInitialized = sal_False;
            if ( pMedium->GetFilter() && ( pMedium->GetFilter()->GetFilterFlags() & SFX_FILTER_STARONEFILTER ) )
            {
                uno::Reference < beans::XPropertySet > xSet( GetModel(), uno::UNO_QUERY );
                ::rtl::OUString sLockUpdates(::rtl::OUString::createFromAscii("LockUpdates"));
                bool bSetProperty = true;
                try
                {
                    xSet->setPropertyValue( sLockUpdates, makeAny( (sal_Bool) sal_True ) );
                }
                catch(const beans::UnknownPropertyException& )
                {
                    bSetProperty = false;
                }
                bOk = ImportFrom(*pMedium);
                if(bSetProperty)
                {
                    try
                    {
                        xSet->setPropertyValue( sLockUpdates, makeAny( (sal_Bool) sal_False ) );
                    }
                    catch(const beans::UnknownPropertyException& )
                    {}
                }
                UpdateLinks();
                FinishedLoading( SFX_LOADED_ALL );
            }
            else
            {
                bOk = ConvertFrom(*pMedium);
                InitOwnModel_Impl();
            }
        }
    }

    if ( bOk )
    {
        try
        {
            ::ucb::Content aContent( pMedium->GetName(), com::sun::star::uno::Reference < XCommandEnvironment >() );
            com::sun::star::uno::Reference < XPropertySetInfo > xProps = aContent.getProperties();
            if ( xProps.is() )
            {
                ::rtl::OUString aAuthor( RTL_CONSTASCII_USTRINGPARAM("Author") );
                ::rtl::OUString aKeywords( RTL_CONSTASCII_USTRINGPARAM("Keywords") );
                ::rtl::OUString aSubject( RTL_CONSTASCII_USTRINGPARAM("Subject") );
                Any aAny;
                ::rtl::OUString aValue;
                SfxDocumentInfo& rInfo = GetDocInfo();
                if ( xProps->hasPropertyByName( aAuthor ) )
                {
                    aAny = aContent.getPropertyValue( aAuthor );
                    if ( ( aAny >>= aValue ) )
                        rInfo.SetCreated( SfxStamp( String( aValue ) ) );
                }
                if ( xProps->hasPropertyByName( aKeywords ) )
                {
                    aAny = aContent.getPropertyValue( aKeywords );
                    if ( ( aAny >>= aValue ) )
                        rInfo.SetKeywords( aValue );
                }
                if ( xProps->hasPropertyByName( aSubject ) )
                {
                    aAny = aContent.getPropertyValue( aSubject );
                    if ( ( aAny >>= aValue ) )
                        rInfo.SetTheme( aValue );
                }
            }
        }
        catch( Exception& )
        {
        }

        // Falls nicht asynchron geladen wird selbst FinishedLoading aufrufen
        if ( !( pImp->nLoadedFlags & SFX_LOADED_MAINDOCUMENT ) &&
            ( !pMedium->GetFilter() || pMedium->GetFilter()->UsesStorage() )
            )
            FinishedLoading( SFX_LOADED_MAINDOCUMENT );

        if( IsOwnStorageFormat_Impl(*pMed) && pMed->GetFilter() )
        {
//???? dv           DirEntry aDirEntry( pMed->GetPhysicalName() );
//???? dv           SetFileName( aDirEntry.GetFull() );
        }
        Broadcast( SfxSimpleHint(SFX_HINT_NAMECHANGED) );

        if ( SFX_CREATE_MODE_EMBEDDED != eCreateMode )
        {
            GetpApp()->HideStatusText();

            SFX_ITEMSET_ARG( pMedium->GetItemSet(), pAsTempItem, SfxBoolItem, SID_TEMPLATE, sal_False);
            SFX_ITEMSET_ARG( pMedium->GetItemSet(), pPreviewItem, SfxBoolItem, SID_PREVIEW, sal_False);
            SFX_ITEMSET_ARG( pMedium->GetItemSet(), pHiddenItem, SfxBoolItem, SID_HIDDEN, sal_False);
            if( bOk && pMedium->GetOrigURL().Len()
            && !( pAsTempItem && pAsTempItem->GetValue() )
            && !( pPreviewItem && pPreviewItem->GetValue() )
            && !( pHiddenItem && pHiddenItem->GetValue() ) )
            {
                INetURLObject aUrl( pMedium->GetOrigURL() );

                if ( aUrl.GetProtocol() == INET_PROT_FILE )
                {
                    const SfxFilter* pOrgFilter = pMedium->GetOrigFilter();
                    SystemShell::AddToRecentDocumentList(
                        aUrl.GetURLNoPass( INetURLObject::NO_DECODE ),
                        (pOrgFilter) ? pOrgFilter->GetMimeType() : String() );
                }
            }
        }
    }
    else
        GetpApp()->HideStatusText();

    return bOk;
}

sal_uInt32 SfxObjectShell::HandleFilter( SfxMedium* pMedium, SfxObjectShell* pDoc )
{
    sal_uInt32 nError = ERRCODE_NONE;
    SfxItemSet* pSet = pMedium->GetItemSet();
    SFX_ITEMSET_ARG( pSet, pOptions, SfxStringItem, SID_FILE_FILTEROPTIONS, sal_False );
    SFX_ITEMSET_ARG( pSet, pData, SfxUnoAnyItem, SID_FILTER_DATA, sal_False );
    if ( !pData && !pOptions )
    {
        com::sun::star::uno::Reference< XMultiServiceFactory > xServiceManager = ::comphelper::getProcessServiceFactory();
        com::sun::star::uno::Reference< XNameAccess > xFilterCFG;
        if( xServiceManager.is() )
        {
            xFilterCFG = com::sun::star::uno::Reference< XNameAccess >(
                xServiceManager->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.document.FilterFactory" ) ),
                UNO_QUERY );
        }

        if( xFilterCFG.is() )
        {
            BOOL bAbort = FALSE;
            try {
                const SfxFilter* pFilter = pMedium->GetFilter();
                Sequence < PropertyValue > aProps;
                Any aAny = xFilterCFG->getByName( pFilter->GetName() );
                if ( aAny >>= aProps )
                {
                    sal_Int32 nPropertyCount = aProps.getLength();
                    for( sal_Int32 nProperty=0; nProperty < nPropertyCount; ++nProperty )
                        if( aProps[nProperty].Name.equals( ::rtl::OUString::createFromAscii("UIComponent")) )
                        {
                            ::rtl::OUString aServiceName;
                            aProps[nProperty].Value >>= aServiceName;
                            if( aServiceName.getLength() )
                            {
                                com::sun::star::uno::Reference< XInteractionHandler > rHandler = pMedium->GetInteractionHandler();
                                if( rHandler.is() )
                                {
                                    // we need some properties in the media descriptor, so we have to make sure that they are in
                                    Any aStreamAny;
                                    aStreamAny <<= pMedium->GetInputStream();
                                    if ( pSet->GetItemState( SID_INPUTSTREAM ) < SFX_ITEM_SET )
                                        pSet->Put( SfxUnoAnyItem( SID_INPUTSTREAM, aStreamAny ) );
                                    if ( pSet->GetItemState( SID_FILE_NAME ) < SFX_ITEM_SET )
                                        pSet->Put( SfxStringItem( SID_FILE_NAME, pMedium->GetName() ) );
                                    if ( pSet->GetItemState( SID_FILTER_NAME ) < SFX_ITEM_SET )
                                        pSet->Put( SfxStringItem( SID_FILTER_NAME, pFilter->GetName() ) );

                                    Sequence< PropertyValue > rProperties;
                                    TransformItems( SID_OPENDOC, *pSet, rProperties, NULL );
                                    RequestFilterOptions* pFORequest = new RequestFilterOptions( pDoc->GetModel(), rProperties );

                                    com::sun::star::uno::Reference< XInteractionRequest > rRequest( pFORequest );
                                    rHandler->handle( rRequest );

                                    if ( !pFORequest->isAbort() )
                                    {
                                           SfxAllItemSet aNewParams( pDoc->GetPool() );
                                           TransformParameters( SID_OPENDOC,
                                                             pFORequest->getFilterOptions(),
                                                             aNewParams,
                                                             NULL );

                                           SFX_ITEMSET_ARG( &aNewParams,
                                                         pFilterOptions,
                                                         SfxStringItem,
                                                         SID_FILE_FILTEROPTIONS,
                                                         sal_False );
                                           if ( pFilterOptions )
                                               pSet->Put( *pFilterOptions );

                                           SFX_ITEMSET_ARG( &aNewParams,
                                                         pFilterData,
                                                         SfxUnoAnyItem,
                                                         SID_FILTER_DATA,
                                                         sal_False );
                                           if ( pFilterData )
                                               pSet->Put( *pFilterData );
                                    }
                                    else
                                        bAbort = TRUE;
                                }
                            }

                            break;
                        }
                }

                if( bAbort )
                {
                    // filter options were not entered
                    nError = ERRCODE_ABORT;
                }
            }
            catch( NoSuchElementException& )
            {
                // the filter name is unknown
                nError = ERRCODE_IO_INVALIDPARAMETER;
            }
            catch( Exception& )
            {
                nError = ERRCODE_ABORT;
            }
        }
    }

    return nError;
}

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

sal_Bool SfxObjectShell::IsOwnStorageFormat_Impl(const SfxMedium &rMedium) const
{
    return !rMedium.GetFilter() || // Embedded
           ( rMedium.GetFilter()->IsOwnFormat() &&
             rMedium.GetFilter()->UsesStorage() &&
             rMedium.GetFilter()->GetVersion() >= SOFFICE_FILEFORMAT_60 );
}

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

sal_Bool SfxObjectShell::IsPackageStorageFormat_Impl(const SfxMedium &rMedium) const
{
    return !rMedium.GetFilter() || // Embedded
           ( rMedium.GetFilter()->UsesStorage() &&
             rMedium.GetFilter()->GetVersion() >= SOFFICE_FILEFORMAT_60 );
}

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

sal_Bool SfxObjectShell::DoSave()
// DoSave wird nur noch ueber OLE aufgerufen. Sichern eigener Dokumente im SFX
// laeuft uber DoSave_Impl, um das Anlegen von Backups zu ermoeglichen.
// Save in eigenes Format jetzt auch wieder Hierueber
{
    sal_Bool bOk = sal_False ;
    {
        ModifyBlocker_Impl aBlock( this );

        pImp->bIsSaving = sal_True;

        String aPasswd;
        if ( IsPackageStorageFormat_Impl( *GetMedium() ) )
        {
            if ( GetPasswd_Impl( GetMedium()->GetItemSet(), aPasswd ) )
            {
                try
                {
                    //TODO/MBA: GetOutputStorage?! Special mode, because it's "Save"?!
                    ::comphelper::OStorageHelper::SetCommonStoragePassword( GetMedium()->GetStorage(), aPasswd );
                    bOk = sal_True;
                }
                catch( uno::Exception& )
                {
                    SetError( ERRCODE_IO_GENERAL );
                }

                DBG_ASSERT( bOk, "The root storage must allow to set common password!\n" );
            }
            else
                bOk = sal_True;

            try
            {
                // The basic and dialogs related contents are still not able to proceed with save operation ( saveTo only )
                // so since the document storage is locked a workaround has to be used

                uno::Reference< embed::XStorage > xTmpStorage = ::comphelper::OStorageHelper::GetTemporaryStorage();
                DBG_ASSERT( xTmpStorage.is(), "If a storage can not be created an exception must be thrown!\n" );
                if ( !xTmpStorage.is() )
                    throw uno::RuntimeException();

                ::rtl::OUString aBasicStorageName( RTL_CONSTASCII_USTRINGPARAM( "Basic" ) );
                ::rtl::OUString aDialogsStorageName( RTL_CONSTASCII_USTRINGPARAM( "Dialogs" ) );
                if ( GetMedium()->GetStorage()->hasByName( aBasicStorageName ) )
                    GetMedium()->GetStorage()->copyElementTo( aBasicStorageName, xTmpStorage, aBasicStorageName );
                if ( GetMedium()->GetStorage()->hasByName( aDialogsStorageName ) )
                    GetMedium()->GetStorage()->copyElementTo( aDialogsStorageName, xTmpStorage, aDialogsStorageName );

                GetBasicManager();

                // disconnect from the current storage
                pImp->pBasicManager->setStorage( xTmpStorage );

                // store to the current storage
                pImp->pBasicManager->storeLibrariesToStorage( GetMedium()->GetStorage() );

                // connect to the current storage back
                pImp->pBasicManager->setStorage( GetMedium()->GetStorage() );
            }
            catch( uno::Exception& )
            {
                SetError( ERRCODE_IO_GENERAL );
                bOk = sal_False;
            }
        }

        if ( bOk )
            bOk = Save();

        bOk = pMedium->Commit();
    }

//#88046
//    if ( bOk )
//        SetModified( sal_False );
    return bOk;
}

void Lock_Impl( SfxObjectShell* pDoc, BOOL bLock )
{
    SfxViewFrame *pFrame= SfxViewFrame::GetFirst( pDoc );
    while ( pFrame )
    {
        pFrame->GetDispatcher()->Lock( bLock );
        pFrame->Enable( !bLock );
        pFrame = SfxViewFrame::GetNext( *pFrame, pDoc );
    }

}

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

sal_Bool SfxObjectShell::SaveTo_Impl
(
     SfxMedium &rMedium, // Medium, in das gespeichert werden soll
     const SfxItemSet* pSet
)

/*  [Beschreibung]

    Schreibt den aktuellen Inhalt in das Medium rMedium.
    Ist das Zielmedium kein Storage, so wird ueber ein temporaeres
    Medium gespeichert, sonst direkt, da das Medium transacted
    geschaltet ist, wenn wir es selbst geoeffnet haben und falls wir
    Server sind entweder der Container einen transacted Storage zur
    Verfuegung stellt oder selbst einen temporaeren Storage erzeugt hat.
*/

{
    RTL_LOGFILE_CONTEXT( aLog, "sfx2 (mv76033) SfxObjectShell::SaveTo_Impl" );

    ModifyBlocker_Impl aMod(this);

    const SfxFilter *pFilter = rMedium.GetFilter();
    if ( !pFilter )
    {
        // if no filter was set, use the default filter
        // this should be changed in the feature, it should be an error!
        DBG_ERROR("No filter set!");
        pFilter = GetFactory().GetFilterContainer()->GetAnyFilter( SFX_FILTER_IMPORT | SFX_FILTER_EXPORT );
        rMedium.SetFilter(pFilter);
    }

    sal_Bool bStorageBasedSource = IsPackageStorageFormat_Impl( *pMedium );
    sal_Bool bStorageBasedTarget = IsPackageStorageFormat_Impl( rMedium );
    sal_Bool bOwnSource = IsOwnStorageFormat_Impl( *pMedium );
    sal_Bool bOwnTarget = IsOwnStorageFormat_Impl( rMedium );

    // Examine target format to determine whether to query if any password
    // protected libraries exceed the size we can handler
    if ( bOwnTarget && !QuerySaveSizeExceededModules_Impl( rMedium.GetInteractionHandler() ) )
    {
        SetError( ERRCODE_IO_ABORT );
        return sal_False;
    }

    sal_Bool bNeedsDisconnectionOnFail = sal_False;

    sal_Bool bStoreToSameLocation = sal_False;

    // the detection whether the script is changed should be done before saving
    sal_Bool bTryToPreservScriptSignature = sal_False;
    if ( bOwnSource && bOwnTarget
      && ( pImp->nScriptingSignatureState == SIGNATURESTATE_SIGNATURES_OK
        || pImp->nScriptingSignatureState == SIGNATURESTATE_SIGNATURES_NOTVALIDATED
        || pImp->nScriptingSignatureState == SIGNATURESTATE_SIGNATURES_INVALID ) )
    {
        // the checking of the library modified state iterates over the libraries, should be done only when required
        bTryToPreservScriptSignature = !pImp->pBasicManager->isAnyContainerModified();
    }

    // use UCB for case sensitive/insensitive file name comparison
    if ( pMedium
      && pMedium->GetName().CompareIgnoreCaseToAscii( "private:stream", 14 ) != COMPARE_EQUAL
      && rMedium.GetName().CompareIgnoreCaseToAscii( "private:stream", 14 ) != COMPARE_EQUAL
      && SfxMedium::EqualURLs( pMedium->GetName(), rMedium.GetName() ) )
    {
        bStoreToSameLocation = sal_True;

        // before we overwrite the original file, we will make a backup if there is a demand for that
        // if the backup is not created here it will be created internally and will be removed in case of successful saving
        const sal_Bool bDoBackup = SvtSaveOptions().IsBackup();
        if ( bDoBackup )
        {
            rMedium.DoBackup_Impl();
            if ( rMedium.GetError() )
            {
                SetError( rMedium.GetErrorCode() );
                rMedium.ResetError();
            }
        }

        if ( bStorageBasedSource && bStorageBasedTarget )
        {
            // The active storage must be switched. The simple saving is not enough.
            // The problem is that the target medium contains target MediaDescriptor.

                // In future the switch of the persistance could be done on stream level:
                // a new wrapper service will be implemented that allows to exchange
                // persistance on the fly. So the real persistance will be set
                // to that stream only after successful commit of the storage.
                // TODO/LATER:
                // create wrapper stream based on the URL
                // create a new storage based on this stream
                // store to this new storage
                // commit the new storage
                // call saveCompleted based with this new storage ( get rid of old storage and "frees" URL )
                // commit the wrapper stream ( the stream will connect the URL only on commit, after that it will hold it )
                // if the last step is failed the stream should stay to be transacted and should be commited on any flush
                // so we can forget the stream in any way and the next storage commit will flush it
            bNeedsDisconnectionOnFail = DisconnectStorage_Impl(
                *pMedium, rMedium );
            if ( bNeedsDisconnectionOnFail
              || ConnectTmpStorage_Impl( pMedium->GetStorage(), pMedium ) )
            {
                pMedium->CloseAndRelease();

                // TODO/LATER: for now the medium must be closed since it can already contain streams from old medium
                //             in future those streams should not be copied in case a valid target url is provided,
                //             if the url is not provided ( means the document is based on a stream ) this code is not
                //             reachable.
                rMedium.CloseAndRelease();
                rMedium.GetOutputStorage();
            }
        }
        else if ( !bStorageBasedSource && !bStorageBasedTarget )
        {
            // the source and the target formats are alien
            // just disconnect the stream from the source format
            // so that the target medium can use it
            pMedium->CloseAndRelease();
            rMedium.CloseAndRelease();
            rMedium.CreateTempFileNoCopy();
            rMedium.GetOutStream();
        }
        else if ( !bStorageBasedSource && bStorageBasedTarget )
        {
            // the source format is an alien one but the target
            // format is an own one so just disconnect the source
            // medium
            pMedium->CloseAndRelease();
            rMedium.CloseAndRelease();
            rMedium.GetOutputStorage();
        }
        else // means if ( bStorageBasedSource && !bStorageBasedTarget )
        {
            // the source format is an own one but the target is
            // an alien format, just connect the source to temporary
            // storage
            bNeedsDisconnectionOnFail = DisconnectStorage_Impl(
                *pMedium, rMedium );
            if ( bNeedsDisconnectionOnFail
              || ConnectTmpStorage_Impl( pMedium->GetStorage(), pMedium ) )
            {
                pMedium->CloseAndRelease();
                rMedium.CloseAndRelease();
                rMedium.CreateTempFileNoCopy();
                rMedium.GetOutStream();
            }
        }
    }

    // TODO/LATER: error handling
    if( rMedium.GetErrorCode() || pMedium->GetErrorCode() || GetErrorCode() )
        return sal_False;

    if ( bStorageBasedTarget )
    {
        rMedium.GetOutputStorage();

        // If the filter is a "cross export" filter ( f.e. a filter for exporting an impress document from
        // a draw document ), the ClassId of the destination storage is different from the ClassId of this
        // document. It can be retrieved from the default filter for the desired target format
        long nFormat = rMedium.GetFilter()->GetFormat();
        SfxFilterMatcher& rMatcher = SFX_APP()->GetFilterMatcher();
        const SfxFilter *pFilt = rMatcher.GetFilter4ClipBoardId( nFormat );
        if ( pFilt )
        {
            if ( pFilt->GetServiceName() != rMedium.GetFilter()->GetServiceName() )
            {
//REMOVE            rMedium.GetStorage()->SetClass( SvFactory::GetServerName( nFormat ), nFormat, pFilt->GetTypeName() );
                datatransfer::DataFlavor aDataFlavor;
                SotExchange::GetFormatDataFlavor( nFormat, aDataFlavor );

                try
                {
                    uno::Reference< beans::XPropertySet > xProps( rMedium.GetStorage(), uno::UNO_QUERY );
                    DBG_ASSERT( xProps.is(), "The storage implementation must implement XPropertySet!" );
                    if ( !xProps.is() )
                        throw uno::RuntimeException();

                    xProps->setPropertyValue( ::rtl::OUString::createFromAscii( "MediaType" ),
                                            uno::makeAny( aDataFlavor.MimeType ) );
                }
                catch( uno::Exception& )
                {
                }
            }
        }
    }

    // TODO/LATER: error handling
    if( rMedium.GetErrorCode() || pMedium->GetErrorCode() || GetErrorCode() )
        return sal_False;

    sal_Bool bOldStat = pImp->bForbidReload;
    pImp->bForbidReload = sal_True;

    // lock user interface while saving the document
    Lock_Impl( this, sal_True );

    sal_Bool bOk = sal_False;
    // TODO/LATER: get rid of bOk

    sal_Bool bCopyTo = sal_False;
    SfxItemSet *pMedSet = rMedium.GetItemSet();
    if( pMedSet )
    {
        SFX_ITEMSET_ARG( pMedSet, pSaveToItem, SfxBoolItem, SID_SAVETO, sal_False );
        bCopyTo =   GetCreateMode() == SFX_CREATE_MODE_EMBEDDED ||
                    pSaveToItem && pSaveToItem->GetValue();
    }

    if( bOwnTarget && !( pFilter->GetFilterFlags() & SFX_FILTER_STARONEFILTER ) )
    {
        uno::Reference< embed::XStorage > xMedStorage = rMedium.GetStorage();
        if ( !xMedStorage.is() )
        {
            // no saving without storage, unlock UI and return
            Lock_Impl( this, sal_False );
            pImp->bForbidReload = bOldStat;
            return sal_False;
        }

        // transfer password from the parameters to the storage
        String aPasswd;
        sal_Bool bPasswdProvided = sal_False;
        if ( GetPasswd_Impl( rMedium.GetItemSet(), aPasswd ) )
        {
            bPasswdProvided = sal_True;
            try {
                ::comphelper::OStorageHelper::SetCommonStoragePassword( xMedStorage, aPasswd );
                bOk = sal_True;
            }
            catch( uno::Exception& )
            {
                DBG_ERROR( "Setting of common encryption key failed!" );
                SetError( ERRCODE_IO_GENERAL );
            }
        }
        else
            bOk = sal_True;

        pFilter = rMedium.GetFilter();

        const SfxStringItem *pVersionItem = pSet ? (const SfxStringItem*)
                SfxRequest::GetItem( pSet, SID_DOCINFO_COMMENTS, sal_False, TYPE(SfxStringItem) ) : NULL;
        ::rtl::OUString aTmpVersionURL;

        if ( bOk )
        {
            bOk = sal_False;
            // currently the case that the storage is the same should be impossible
            if ( xMedStorage == GetStorage() )
            {
                OSL_ENSURE( !pVersionItem, "This scenario is impossible currently!\n" );
                // usual save procedure
                bOk = Save();
            }
            else
            {
                // save to target
                bOk = SaveAsOwnFormat( rMedium );
                if ( bOk && pVersionItem )
                {
                    aTmpVersionURL = CreateTempCopyOfStorage_Impl( xMedStorage );
                    bOk = ( aTmpVersionURL.getLength() > 0 );
                }
            }
        }


        if ( bOk && GetCreateMode() != SFX_CREATE_MODE_EMBEDDED )
        {
            // store the thumbnail representation image
            // TODO: handle the case when document is encrypted and/or signed
            if ( !GenerateAndStoreThumbnail( bPasswdProvided,
                                            sal_False,
                                            pFilter->IsOwnTemplateFormat(),
                                            xMedStorage ) )
            {
                // TODO: error handling
                OSL_ENSURE( sal_False, "Couldn't store thumbnail representation!" );
            }
        }

        if ( bOk )
        {
            if ( pImp->bIsSaving || pImp->bPreserveVersions )
            {
                try
                {
                    Sequence < util::RevisionTag > aVersions = rMedium.GetVersionList();
                    if ( aVersions.getLength() )
                    {
                        // copy the version streams
                        ::rtl::OUString aVersionsName( RTL_CONSTASCII_USTRINGPARAM( "Versions" ) );
                        uno::Reference< embed::XStorage > xNewVerStor = xMedStorage->openStorageElement(
                                                        aVersionsName,
                                                        embed::ElementModes::READWRITE );
                        uno::Reference< embed::XStorage > xOldVerStor = GetStorage()->openStorageElement(
                                                        aVersionsName,
                                                        embed::ElementModes::READ );
                        if ( !xNewVerStor.is() || !xOldVerStor.is() )
                            throw uno::RuntimeException();

                        for ( sal_Int32 n=0; n<aVersions.getLength(); n++ )
                        {
                            if ( xOldVerStor->hasByName( aVersions[n].Identifier ) )
                                xOldVerStor->copyElementTo( aVersions[n].Identifier, xNewVerStor, aVersions[n].Identifier );
                        }

                        uno::Reference< embed::XTransactedObject > xTransact( xNewVerStor, uno::UNO_QUERY );
                        if ( xTransact.is() )
                            xTransact->commit();
                    }
                }
                catch( uno::Exception& )
                {
                    DBG_ERROR( "Couldn't copy versions!\n" );
                    bOk = sal_False;
                    // TODO/LATER: a specific error could be set
                }
            }

            if ( bOk && pVersionItem )
            {
                // store a version also
                const SfxStringItem *pAuthorItem = pSet ? (const SfxStringItem*)
                    SfxRequest::GetItem( pSet, SID_DOCINFO_AUTHOR, sal_False, TYPE(SfxStringItem) ) : NULL;

                // version comment
                util::RevisionTag aInfo;
                aInfo.Comment = pVersionItem->GetValue();

                // version author
                String aAuthor;
                if ( pAuthorItem )
                    aInfo.Author = pAuthorItem->GetValue();
                else
                    // if not transferred as a parameter, get it from user settings
                    aInfo.Author = SvtUserOptions().GetFullName();

                TimeStamp aStamp;
                DateTime aTime = aStamp.GetTime();
                aInfo.TimeStamp.Day = aTime.GetDay();
                aInfo.TimeStamp.Month = aTime.GetMonth();
                aInfo.TimeStamp.Year = aTime.GetYear();
                aInfo.TimeStamp.Hours = aTime.GetHour();
                aInfo.TimeStamp.Minutes = aTime.GetMin();
                aInfo.TimeStamp.Seconds = aTime.GetSec();

                if ( bOk )
                {
                    // add new version information into the versionlist and save the versionlist
                    // the version list must have been transferred from the "old" medium before
                    rMedium.AddVersion_Impl( aInfo );
                    rMedium.SaveVersionList_Impl( sal_True );
                    bOk = PutURLContentsToVersionStream_Impl( aTmpVersionURL, xMedStorage, aInfo.Identifier );
                }
            }
            else if ( bOk && ( pImp->bIsSaving || pImp->bPreserveVersions ) )
            {
                rMedium.SaveVersionList_Impl( sal_True );
            }
        }

        if ( aTmpVersionURL.getLength() )
            ::utl::UCBContentHelper::Kill( aTmpVersionURL );
    }
    else
    {
        // it's a "SaveAs" in an alien format
        if ( rMedium.GetFilter() && ( rMedium.GetFilter()->GetFilterFlags() & SFX_FILTER_STARONEFILTER ) )
            bOk = ExportTo( rMedium );
        else
            bOk = ConvertTo( rMedium );

        // after saving the document, the temporary object storage must be updated
        // if the old object storage was not a temporary one, it will be updated also, because it will be used
        // as a source for copying the objects into the new temporary storage that will be created below
        // updating means: all child objects must be stored into it
        // ( same as on loading, where these objects are copied to the temporary storage )
        // but don't commit these changes, because in the case when the old object storage is not a temporary one,
        // all changes will be written into the original file !

        if( bOk && !bCopyTo )
            // we also don't touch any graphical replacements here
            bOk = SaveChildren( TRUE );
    }

    uno::Reference< security::XDocumentDigitalSignatures > xDDSigns;
    sal_Bool bScriptSignatureIsCopied = sal_False;
    if ( bOk && bTryToPreservScriptSignature )
    {
        // if the scripting code was not changed and it is signed the signature should be preserved
        // unfortunately at this point we have only information whether the basic code has changed or not
        // so the only way is to check the signature if the basic was not changed
        try
        {
            xDDSigns = uno::Reference< security::XDocumentDigitalSignatures >(
                comphelper::getProcessServiceFactory()->createInstance(
                    rtl::OUString(
                        RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.security.DocumentDigitalSignatures" ) ) ),
                    uno::UNO_QUERY_THROW );

            ::rtl::OUString aScriptSignName = xDDSigns->getScriptingContentSignatureDefaultStreamName();

            if ( aScriptSignName.getLength() )
            {
                uno::Reference< embed::XStorage > xMetaInf = GetStorage()->openStorageElement(
                            ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "META-INF" ) ),
                            embed::ElementModes::READ );
                uno::Reference< embed::XStorage > xTargetMetaInf = rMedium.GetStorage()->openStorageElement(
                            ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "META-INF" ) ),
                            embed::ElementModes::WRITE );

                if ( xMetaInf.is() && xTargetMetaInf.is() )
                {
                    xMetaInf->copyElementTo( aScriptSignName, xTargetMetaInf, aScriptSignName );

                    // after loading the UseCommonStoragePassword property might be set to true
                    // set it to false here, since this is a rare case when it must be so
                    // TODO/LATER: in future it should be done on loading probably
                    uno::Reference< beans::XPropertySet > xTargetSignPropSet(
                        xTargetMetaInf->openStreamElement( aScriptSignName, embed::ElementModes::WRITE ),
                        uno::UNO_QUERY_THROW );
                    xTargetSignPropSet->setPropertyValue(
                        ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "UseCommonStoragePasswordEncryption" ) ),
                        uno::makeAny( (sal_Bool)sal_False ) );

                    uno::Reference< embed::XTransactedObject > xTransact( xTargetMetaInf, uno::UNO_QUERY );
                    if ( xTransact.is() )
                        xTransact->commit();
                    bScriptSignatureIsCopied = sal_True;
                }
            }
        }
        catch( uno::Exception& )
        {
        }
    }

    if ( bOk )
    {
        // transfer data to its destinated location
        // the medium commits the storage or the stream it is based on
        RegisterTransfer( rMedium );
        bOk = rMedium.Commit();

        if ( bOk && bScriptSignatureIsCopied )
        {
            // if the script signature was copied it should be checked now
            // usually it should be ok, so no additional actions will be done
            // but if for any reasong ( f.e. binshell change ) it is broken it should be removed here
            // in result the behaviour will work in optimized way in most cases, means in case of signed basic scripts
            OSL_ENSURE( !bScriptSignatureIsCopied || xDDSigns.is(), "The signing could not be done without the service!\n" );
            if ( xDDSigns.is() )
            {
                try
                {
                    bOk = sal_False;
                    ::com::sun::star::uno::Sequence< security::DocumentSignatureInformation > aInfos =
                        xDDSigns->verifyScriptingContentSignatures( rMedium.GetLastCommitReadStorage_Impl(),
                                                                    uno::Reference< io::XInputStream >() );
                    sal_uInt16 nState = ImplCheckSignaturesInformation( aInfos );
                    if ( nState == SIGNATURESTATE_SIGNATURES_OK || nState == SIGNATURESTATE_SIGNATURES_NOTVALIDATED )
                    {
                        rMedium.SetCachedSignatureState_Impl( nState );
                        bOk = sal_True;
                    }
                    else
                    {
                        // the signature is broken, remove it
                        rMedium.SetCachedSignatureState_Impl( SIGNATURESTATE_NOSIGNATURES );
                        uno::Reference< embed::XStorage > xTargetMetaInf = rMedium.GetStorage()->openStorageElement(
                            ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "META-INF" ) ),
                            embed::ElementModes::WRITE );

                        if ( xTargetMetaInf.is() )
                        {
                            xTargetMetaInf->removeElement( xDDSigns->getScriptingContentSignatureDefaultStreamName() );
                            uno::Reference< embed::XTransactedObject > xTransact( xTargetMetaInf, uno::UNO_QUERY );
                            if ( xTransact.is() )
                                xTransact->commit();

                            bOk = rMedium.Commit();
                        }
                    }
                }
                catch( uno::Exception )
                {
                    OSL_ENSURE( sal_False, "This exception must not happen!" );
                }
            }
        }

        if ( bOk )
        {
            // if the target medium is an alien format and the "old" medium was an own format and the "old" medium
            // has a name, the object storage must be exchanged, because now we need a new temporary storage
            // as object storage
            if ( !bCopyTo && bStorageBasedSource && !bStorageBasedTarget )
            {
                if ( bStoreToSameLocation )
                {
                    // if the old medium already disconnected from document storage, the storage still must
                    // be switched if backup file is used
                    if ( bNeedsDisconnectionOnFail )
                        ConnectTmpStorage_Impl( pImp->m_xDocStorage, NULL );
                }
                else if ( pMedium->GetName().Len()
                  || ( pMedium->HasStorage_Impl() && pMedium->WillDisposeStorageOnClose_Impl() ) )
                {
                    OSL_ENSURE( pMedium->GetName().Len(), "Fallback is used, the medium without name should not dispose the storage!\n" );
                    // copy storage of old medium to new temporary storage and take this over
                    if( !ConnectTmpStorage_Impl( pMedium->GetStorage(), pMedium ) )
                        bOk = sal_False;
                }
            }
        }
        else
        {
            // in case the document storage was connected to backup temporarely it must be disconnected now
            if ( bNeedsDisconnectionOnFail )
                ConnectTmpStorage_Impl( pImp->m_xDocStorage, NULL );
        }
    }

    // unlock user interface
    Lock_Impl( this, sal_False );
    pImp->bForbidReload = bOldStat;

    if ( bOk )
    {
        try
        {
            ::ucb::Content aContent( rMedium.GetName(), com::sun::star::uno::Reference < XCommandEnvironment >() );
            com::sun::star::uno::Reference < XPropertySetInfo > xProps = aContent.getProperties();
            if ( xProps.is() )
            {
                ::rtl::OUString aAuthor( RTL_CONSTASCII_USTRINGPARAM("Author") );
                ::rtl::OUString aKeywords( RTL_CONSTASCII_USTRINGPARAM("Keywords") );
                ::rtl::OUString aSubject( RTL_CONSTASCII_USTRINGPARAM("Subject") );
                Any aAny;
                if ( xProps->hasPropertyByName( aAuthor ) )
                {
                    aAny <<= ::rtl::OUString( GetDocInfo().GetCreated().GetName() );
                    aContent.setPropertyValue( aAuthor, aAny );
                }
                if ( xProps->hasPropertyByName( aKeywords ) )
                {
                    aAny <<= ::rtl::OUString( GetDocInfo().GetKeywords() );
                    aContent.setPropertyValue( aKeywords, aAny );
                }
                if ( xProps->hasPropertyByName( aSubject ) )
                {
                    aAny <<= ::rtl::OUString( GetDocInfo().GetTheme() );
                    aContent.setPropertyValue( aSubject, aAny );
                }
            }
        }
        catch( Exception& )
        {
        }
    }

    return bOk;
}

//------------------------------------------------------------------------
sal_Bool SfxObjectShell::DisconnectStorage_Impl( SfxMedium& rSrcMedium, SfxMedium& rTargetMedium )
{
    RTL_LOGFILE_CONTEXT( aLog, "sfx2 (mv76033) SfxObjectShell::DisconnectStorage_Impl" );

    // this method disconnects the storage from source medium, and attaches it to the backup created by the target medium

    uno::Reference< embed::XStorage > xStorage = rSrcMedium.GetStorage();

    sal_Bool bResult = sal_False;
    if ( xStorage == pImp->m_xDocStorage )
    {
        try
        {
            uno::Reference< embed::XOptimizedStorage > xOptStorage( xStorage, uno::UNO_QUERY_THROW );
            ::rtl::OUString aBackupURL = rTargetMedium.GetBackup_Impl();
            if ( aBackupURL.getLength() )
            {
                // the following call will only compare stream sizes
                // TODO/LATER: this is a very risky part, since if the URL contents are different from the storage
                // contents, the storag will be broken
                xOptStorage->attachToURL( aBackupURL, sal_True );

                // the storage is successfuly attached to backup, thus it it owned by the document not by the medium
                rSrcMedium.CanDisposeStorage_Impl( sal_False );
                bResult = sal_True;
            }
        }
        catch ( uno::Exception& )
        {}
    }

    OSL_ENSURE( bResult, "Storage disconnecting has failed - affects performance!" );

    return bResult;
}

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

sal_Bool SfxObjectShell::ConnectTmpStorage_Impl(
    const uno::Reference< embed::XStorage >& xStorage,
    SfxMedium* pMediumArg )

/*   [Beschreibung]

     Arbeitet die Applikation auf einem temporaeren Storage,
     so darf der temporaere Storage nicht aus dem SaveCompleted
     genommen werden. Daher wird in diesem Fall schon hier an
     den neuen Storage connected. SaveCompleted tut dann nichts.

     */

{
    RTL_LOGFILE_CONTEXT( aLog, "sfx2 (mv76033) SfxObjectShell::ConnectTmpStorage_Impl" );

    sal_Bool bResult = sal_False;

    if ( xStorage.is() )
    {
        try
        {
            // the empty argument means that the storage will create temporary stream itself
            uno::Reference< embed::XOptimizedStorage > xOptStorage( xStorage, uno::UNO_QUERY_THROW );
            xOptStorage->writeAndAttachToStream( uno::Reference< io::XStream >() );

            // the storage is successfuly disconnected from the original sources, thus the medium must not dispose it
            if ( pMediumArg )
                pMediumArg->CanDisposeStorage_Impl( sal_False );

            bResult = sal_True;
        }
        catch( uno::Exception& )
        {
        }

        // if switching of the storage does not work for any reason ( nonroot storage for example ) use the old method
        if ( !bResult ) try
        {
            uno::Reference< embed::XStorage > xTmpStorage = ::comphelper::OStorageHelper::GetTemporaryStorage();

            DBG_ASSERT( xTmpStorage.is(), "If a storage can not be created an exception must be thrown!\n" );
            if ( !xTmpStorage.is() )
                throw uno::RuntimeException();

            // TODO/LATER: may be it should be done in SwitchPersistence also
            // TODO/LATER: find faster way to copy storage; perhaps sharing with backup?!
            xStorage->copyToStorage( xTmpStorage );
            //CopyStoragesOfUnknownMediaType( xStorage, xTmpStorage );
            bResult = SaveCompleted( xTmpStorage );

            if ( bResult )
                pImp->pBasicManager->setStorage( xTmpStorage );
        }
        catch( uno::Exception& )
        {}

        if ( !bResult )
        {
            // TODO/LATER: may need error code setting based on exception
            SetError( ERRCODE_IO_GENERAL );
        }
    }

    return bResult;
}

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

sal_Bool SfxObjectShell::DoSaveObjectAs( SfxMedium& rMedium, BOOL bCommit )
{
    sal_Bool bOk = sal_False;
    {
        ModifyBlocker_Impl aBlock( this );

        uno::Reference < embed::XStorage > xNewStor = rMedium.GetStorage();
        if ( !xNewStor.is() )
            return sal_False;

        uno::Reference < beans::XPropertySet > xPropSet( xNewStor, uno::UNO_QUERY );
        if ( xPropSet.is() )
        {
            Any a = xPropSet->getPropertyValue( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "MediaType" ) ) );
            ::rtl::OUString aMediaType;
            if ( !(a>>=aMediaType) || !aMediaType.getLength() )
            {
                OSL_ENSURE( sal_False, "The mediatype must be set already!\n" );
                SetupStorage( xNewStor, SOFFICE_FILEFORMAT_CURRENT, sal_False );
            }

            pImp->bIsSaving = sal_False;
            bOk = SaveAsOwnFormat( rMedium );

            if ( bCommit )
            {
                try {
                    uno::Reference< embed::XTransactedObject > xTransact( xNewStor, uno::UNO_QUERY_THROW );
                    xTransact->commit();
                }
                catch( uno::Exception& )
                {
                    DBG_ERROR( "The strotage was not commited on DoSaveAs!\n" );
                }
            }
        }
    }

    return bOk;
}

//-------------------------------------------------------------------------
// TODO/LATER: may be the call must be removed completelly
sal_Bool SfxObjectShell::DoSaveAs( SfxMedium& rMedium )
{
    // hier kommen nur Root-Storages rein, die via Temp-File gespeichert werden
    rMedium.CreateTempFileNoCopy();
    SetError(rMedium.GetErrorCode());
    if ( GetError() )
        return sal_False;

    // copy version list from "old" medium to target medium, so it can be used on saving
    if ( pImp->bPreserveVersions )
        rMedium.TransferVersionList_Impl( *pMedium );

    sal_Bool bRet = SaveTo_Impl( rMedium, NULL );
    if ( !bRet )
        SetError(rMedium.GetErrorCode());
    return bRet;
}

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

sal_Bool SfxObjectShell::DoSaveCompleted( SfxMedium* pNewMed )
{
    RTL_LOGFILE_CONTEXT( aLog, "sfx2 (mv76033) SfxObjectShell::DoSaveCompleted" );

    sal_Bool bOk = sal_True;
    sal_Bool bMedChanged = pNewMed && pNewMed!=pMedium;
/*  sal_Bool bCreatedTempStor = pNewMed && pMedium &&
        IsPackageStorageFormat_Impl(*pMedium) &&
        !IsPackageStorageFormat_Impl(*pNewMed) &&
        pMedium->GetName().Len();
*/
    DBG_ASSERT( !pNewMed || pNewMed->GetError() == ERRCODE_NONE, "DoSaveCompleted: Medium has error!" );

    // delete Medium (and Storage!) after all notifications
    SfxMedium* pOld = pMedium;
    if ( bMedChanged )
    {
        pMedium = pNewMed;
        pMedium->CanDisposeStorage_Impl( sal_True );
    }

    const SfxFilter *pFilter = pMedium ? pMedium->GetFilter() : 0;
    if ( pNewMed )
    {
        if( bMedChanged )
        {
            if( pNewMed->GetName().Len() )
                bHasName = sal_True;
            Broadcast( SfxSimpleHint(SFX_HINT_NAMECHANGED) );
        }

        uno::Reference< embed::XStorage > xStorage;
        if ( !pFilter || IsPackageStorageFormat_Impl( *pMedium ) )
        {
            uno::Reference < embed::XStorage > xOld = GetStorage();
            xStorage = pMedium->GetStorage();
            bOk = SaveCompleted( xStorage );
            if ( bOk && (!pOld || !pOld->HasStorage_Impl() || xOld != pOld->GetStorage() ) )
            {
                // old own storage was not controlled by old Medium -> dispose it
                try {
                    xOld->dispose();
                } catch( uno::Exception& )
                {
                    // the storage is disposed already
                    // can happen during reload scenario when the medium has disposed it during the closing
                    // will be fixed in one of the next milestones
                }
            }
        }
        else
        {
//REMOVE                if( pFilter->UsesStorage() )
//REMOVE                    pMedium->GetStorage();
//REMOVE                else if( pMedium->GetOpenMode() & STREAM_WRITE )
            if( pMedium->GetOpenMode() & STREAM_WRITE )
                pMedium->GetInStream();
            xStorage = GetStorage();
        }

        // TODO/LATER: may be this code will be replaced, but not sure
        // Set storage in document library containers
        pImp->pBasicManager->setStorage( xStorage );
    }
    else
    {
        if( pMedium )
        {
            if( pFilter && !IsPackageStorageFormat_Impl( *pMedium ) && (pMedium->GetOpenMode() & STREAM_WRITE ))
            {
                pMedium->ReOpen();
                bOk = SaveCompletedChildren( sal_False );
            }
            else
                bOk = SaveCompleted( NULL );
        }
        // entweder Save oder ConvertTo
        else
            bOk = SaveCompleted( NULL );
    }

    if ( bOk && pNewMed )
    {
        if( bMedChanged )
        {
            delete pOld;

            uno::Reference< frame::XModel > xModel = GetModel();
            if ( xModel.is() )
            {
                ::rtl::OUString aURL = pNewMed->GetOrigURL();
                uno::Sequence< beans::PropertyValue > aMediaDescr;
                TransformItems( SID_OPENDOC, *pNewMed->GetItemSet(), aMediaDescr );
                try
                {
                    xModel->attachResource( aURL, aMediaDescr );
                }
                catch( uno::Exception& )
                {}
            }

            // before the title regenerated the document must loose the signatures
            pImp->nDocumentSignatureState = SIGNATURESTATE_NOSIGNATURES;
            pImp->nScriptingSignatureState = pNewMed->GetCachedSignatureState_Impl();
            OSL_ENSURE( pImp->nScriptingSignatureState != SIGNATURESTATE_SIGNATURES_BROKEN, "The signature must not be broken at this place" );
            pImp->bSignatureErrorIsShown = sal_False;

            // TODO/LATER: in future the medium must control own signature state, not the document
            pNewMed->SetCachedSignatureState_Impl( SIGNATURESTATE_NOSIGNATURES ); // set the default value back

            // Titel neu setzen
            if ( pNewMed->GetName().Len() && SFX_CREATE_MODE_EMBEDDED != eCreateMode )
                InvalidateName();
            SetModified(sal_False); // nur bei gesetztem Medium zur"ucksetzen
            Broadcast( SfxSimpleHint(SFX_HINT_MODECHANGED) );
        }
    }

    pMedium->ClearBackup_Impl();

    return bOk;
}

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

sal_Bool SfxObjectShell::ConvertFrom
(
    SfxMedium&  /*rMedium*/     /*  <SfxMedium>, welches die Quell-Datei beschreibt
                                (z.B. Dateiname, <SfxFilter>, Open-Modi etc.) */
)

/*  [Beschreibung]

    Diese Methode wird zum Laden von Dokumenten "uber alle Filter gerufen,
    die nicht SFX_FILTER_OWN sind oder f"ur die kein Clipboard-Format
    registriert wurde (also kein Storage-Format benutzen). Mit anderen Worten:
    mit dieser Methode wird importiert.

    Das hier zu "offende File sollte "uber 'rMedium' ge"offnet werden,
    um die richtigen Open-Modi zu gew"ahrleisten. Insbesondere wenn das
    Format beibehalten wird (nur m"oglich bei SFX_FILTER_SIMULATE oder
    SFX_FILTER_ONW) mu\s die Datei STREAM_SHARE_DENYWRITE ge"offnet werden.


    [R"uckgabewert]

    sal_Bool                sal_True
                        Das Dokument konnte geladen werden.

                        sal_False
                        Das Dokument konnte nicht geladen werden, ein
                        Fehlercode ist mit <SvMedium::GetError()const> zu
                        erhalten.


    [Beispiel]

    sal_Bool DocSh::ConvertFrom( SfxMedium &rMedium )
    {
        SvStreamRef xStream = rMedium.GetInStream();
        if( xStream.is() )
        {
            xStream->SetBufferSize(4096);
            *xStream >> ...;

            // NICHT 'rMedium.CloseInStream()' rufen! File gelockt halten!
            return SVSTREAM_OK == rMedium.GetError();
        }

        return sal_False;
    }


    [Querverweise]

    <SfxObjectShell::ConvertTo(SfxMedium&)>
    <SFX_FILTER_REGISTRATION>
*/
{
    return sal_False;
}

sal_Bool SfxObjectShell::ImportFrom( SfxMedium& rMedium )
{
    ::rtl::OUString aTypeName( rMedium.GetFilter()->GetTypeName() );
    ::rtl::OUString aFilterName( rMedium.GetFilter()->GetFilterName() );

    uno::Reference< lang::XMultiServiceFactory >  xMan = ::comphelper::getProcessServiceFactory();
    uno::Reference < lang::XMultiServiceFactory > xFilterFact (
                xMan->createInstance( DEFINE_CONST_UNICODE( "com.sun.star.document.FilterFactory" ) ), uno::UNO_QUERY );

    uno::Sequence < beans::PropertyValue > aProps;
    uno::Reference < container::XNameAccess > xFilters ( xFilterFact, uno::UNO_QUERY );
    if ( xFilters->hasByName( aFilterName ) )
    {
        xFilters->getByName( aFilterName ) >>= aProps;
        rMedium.GetItemSet()->Put( SfxStringItem( SID_FILTER_NAME, aFilterName ) );
    }

    ::rtl::OUString aFilterImplName;
    sal_Int32 nFilterProps = aProps.getLength();
    for ( sal_Int32 nFilterProp = 0; nFilterProp<nFilterProps; nFilterProp++ )
    {
        const beans::PropertyValue& rFilterProp = aProps[nFilterProp];
        if ( rFilterProp.Name.compareToAscii("FilterService") == COMPARE_EQUAL )
        {
            rFilterProp.Value >>= aFilterImplName;
            break;
        }
    }

    uno::Reference< document::XFilter > xLoader;
    if ( aFilterImplName.getLength() )
    {
        try{
        xLoader = uno::Reference< document::XFilter >
            ( xFilterFact->createInstanceWithArguments( aFilterName, uno::Sequence < uno::Any >() ), uno::UNO_QUERY );
        }catch(const uno::Exception&)
            { xLoader.clear(); }
    }
    if ( xLoader.is() )
    {
        // #131744#: it happens that xLoader does not support xImporter!
        try{
        uno::Reference< lang::XComponent >  xComp( GetModel(), uno::UNO_QUERY_THROW );
        uno::Reference< document::XImporter > xImporter( xLoader, uno::UNO_QUERY_THROW );
        xImporter->setTargetDocument( xComp );

        uno::Sequence < beans::PropertyValue > lDescriptor;
        rMedium.GetItemSet()->Put( SfxStringItem( SID_FILE_NAME, rMedium.GetName() ) );
        TransformItems( SID_OPENDOC, *rMedium.GetItemSet(), lDescriptor );

        com::sun::star::uno::Sequence < com::sun::star::beans::PropertyValue > aArgs ( lDescriptor.getLength() );
        com::sun::star::beans::PropertyValue * pNewValue = aArgs.getArray();
        const com::sun::star::beans::PropertyValue * pOldValue = lDescriptor.getConstArray();
        const OUString sInputStream ( RTL_CONSTASCII_USTRINGPARAM ( "InputStream" ) );

        sal_Bool bHasInputStream = sal_False;
        BOOL bHasBaseURL = FALSE;
        sal_Int32 i;
        sal_Int32 nEnd = lDescriptor.getLength();

        for ( i = 0; i < nEnd; i++ )
        {
            pNewValue[i] = pOldValue[i];
            if ( pOldValue [i].Name == sInputStream )
                bHasInputStream = sal_True;
            else if ( pOldValue[i].Name.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( "DocumentBaseURL" ) ) )
                bHasBaseURL = sal_True;
        }

        if ( !bHasInputStream )
        {
            aArgs.realloc ( ++nEnd );
            aArgs[nEnd-1].Name = sInputStream;
            aArgs[nEnd-1].Value <<= com::sun::star::uno::Reference < com::sun::star::io::XInputStream > ( new utl::OSeekableInputStreamWrapper ( *rMedium.GetInStream() ) );
        }

        if ( !bHasBaseURL )
        {
            aArgs.realloc ( ++nEnd );
            aArgs[nEnd-1].Name = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "DocumentBaseURL" ) );
            aArgs[nEnd-1].Value <<= rMedium.GetBaseURL();
        }

        return xLoader->filter( aArgs );
        }catch(const uno::Exception&)
        {}
    }

    return sal_False;
}

sal_Bool SfxObjectShell::ExportTo( SfxMedium& rMedium )
{
    ::rtl::OUString aTypeName( rMedium.GetFilter()->GetTypeName() );
    ::rtl::OUString aFilterName( rMedium.GetFilter()->GetFilterName() );
    uno::Reference< document::XExporter > xExporter;

    {
        uno::Reference< lang::XMultiServiceFactory >  xMan = ::comphelper::getProcessServiceFactory();
        uno::Reference < lang::XMultiServiceFactory > xFilterFact (
                xMan->createInstance( DEFINE_CONST_UNICODE( "com.sun.star.document.FilterFactory" ) ), uno::UNO_QUERY );

        uno::Sequence < beans::PropertyValue > aProps;
        uno::Reference < container::XNameAccess > xFilters ( xFilterFact, uno::UNO_QUERY );
        if ( xFilters->hasByName( aFilterName ) )
            xFilters->getByName( aFilterName ) >>= aProps;

        ::rtl::OUString aFilterImplName;
        sal_Int32 nFilterProps = aProps.getLength();
        for ( sal_Int32 nFilterProp = 0; nFilterProp<nFilterProps; nFilterProp++ )
        {
            const beans::PropertyValue& rFilterProp = aProps[nFilterProp];
            if ( rFilterProp.Name.compareToAscii("FilterService") == COMPARE_EQUAL )
            {
                rFilterProp.Value >>= aFilterImplName;
                break;
            }
        }

        if ( aFilterImplName.getLength() )
        {
            try{
            xExporter = uno::Reference< document::XExporter >
                ( xFilterFact->createInstanceWithArguments( aFilterName, uno::Sequence < uno::Any >() ), uno::UNO_QUERY );
            }catch(const uno::Exception&)
                { xExporter.clear(); }
        }
    }

    if ( xExporter.is() )
    {
        try{
        uno::Reference< lang::XComponent >  xComp( GetModel(), uno::UNO_QUERY_THROW );
        uno::Reference< document::XFilter > xFilter( xExporter, uno::UNO_QUERY_THROW );
        xExporter->setSourceDocument( xComp );

        com::sun::star::uno::Sequence < com::sun::star::beans::PropertyValue > aOldArgs;
        SfxItemSet* pItems = rMedium.GetItemSet();
        TransformItems( SID_SAVEASDOC, *pItems, aOldArgs );

        const com::sun::star::beans::PropertyValue * pOldValue = aOldArgs.getConstArray();
        com::sun::star::uno::Sequence < com::sun::star::beans::PropertyValue > aArgs ( aOldArgs.getLength() );
        com::sun::star::beans::PropertyValue * pNewValue = aArgs.getArray();

        // put in the REAL file name, and copy all PropertyValues
        const OUString sOutputStream ( RTL_CONSTASCII_USTRINGPARAM ( "OutputStream" ) );
        BOOL bHasStream = FALSE;
        BOOL bHasBaseURL = FALSE;
        sal_Int32 i;
        sal_Int32 nEnd = aOldArgs.getLength();

        for ( i = 0; i < nEnd; i++ )
        {
            pNewValue[i] = pOldValue[i];
            if ( pOldValue[i].Name.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( "FileName" ) ) )
                pNewValue[i].Value <<= OUString ( rMedium.GetName() );
            else if ( pOldValue[i].Name == sOutputStream )
                bHasStream = sal_True;
            else if ( pOldValue[i].Name.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( "DocumentBaseURL" ) ) )
                bHasBaseURL = sal_True;
        }

        if ( !bHasStream )
        {
            aArgs.realloc ( ++nEnd );
            aArgs[nEnd-1].Name = sOutputStream;
            aArgs[nEnd-1].Value <<= com::sun::star::uno::Reference < com::sun::star::io::XOutputStream > ( new utl::OOutputStreamWrapper ( *rMedium.GetOutStream() ) );
        }

        if ( !bHasBaseURL )
        {
            aArgs.realloc ( ++nEnd );
            aArgs[nEnd-1].Name = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "DocumentBaseURL" ) );
            aArgs[nEnd-1].Value <<= rMedium.GetBaseURL( sal_True );
        }

        return xFilter->filter( aArgs );
        }catch(const uno::Exception&)
        {}
    }

    return sal_False;
}

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

sal_Bool SfxObjectShell::ConvertTo
(
    SfxMedium&  /*rMedium*/     /*  <SfxMedium>, welches die Ziel-Datei beschreibt
                                (z.B. Dateiname, <SfxFilter>, Open-Modi etc.) */
)

/*  [Beschreibung]

    Diese Methode wird zum Speichern von Dokumenten "uber alle Filter gerufen,
    die nicht SFX_FILTER_OWN sind oder f"ur die kein Clipboard-Format
    registriert wurde (also kein Storage-Format benutzen). Mit anderen Worten:
    mit dieser Methode wird exportiert.

    Das hier zu "offende File sollte "uber 'rMedium' ge"offnet werden,
    um die richtigen Open-Modi zu gew"ahrleisten. Insbesondere wenn das
    Format beibehalten wird (nur m"oglich bei SFX_FILTER_SIMULATE oder
    SFX_FILTER_ONW) mu\s die Datei auch nach dem Speichern im Modus
    STREAM_SHARE_DENYWRITE ge"offnet bleiben.


    [R"uckgabewert]

    sal_Bool                sal_True
                        Das Dokument konnte gespeichert werden.

                        sal_False
                        Das Dokument konnte nicht gespeichert werden, ein
                        Fehlercode ist mit <SvMedium::GetError()const> zu
                        erhalten.


    [Beispiel]

    sal_Bool DocSh::ConvertTo( SfxMedium &rMedium )
    {
        SvStreamRef xStream = rMedium.GetOutStream();
        if ( xStream.is() )
        {
            xStream->SetBufferSize(4096);
            *xStream << ...;

            rMedium.CloseOutStream(); // "offnet automatisch wieder den InStream
            return SVSTREAM_OK == rMedium.GetError();
        }
        return sal_False ;
    }


    [Querverweise]

    <SfxObjectShell::ConvertFrom(SfxMedium&)>
    <SFX_FILTER_REGISTRATION>
*/

{
    return sal_False;
}

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

sal_Bool SfxObjectShell::DoSave_Impl( const SfxItemSet* pArgs )
{
    SfxMedium* pRetrMedium = GetMedium();
    const SfxFilter* pFilter = pRetrMedium->GetFilter();

    // copy the original itemset, but remove the "version" item, because pMediumTmp
    // is a new medium "from scratch", so no version should be stored into it
    SfxItemSet* pSet = pRetrMedium->GetItemSet() ? new SfxAllItemSet(*pRetrMedium->GetItemSet()): 0;
    pSet->ClearItem( SID_VERSION );

    // create a medium as a copy; this medium is only for writingm, because it uses the same name as the original one
    // writing is done through a copy, that will be transferred to the target ( of course after calling HandsOff )
    SfxMedium* pMediumTmp = new SfxMedium( pRetrMedium->GetName(), pRetrMedium->GetOpenMode(), pRetrMedium->IsDirect(), pFilter, pSet );
    pMediumTmp->SetLongName( pRetrMedium->GetLongName() );
//    pMediumTmp->CreateTempFileNoCopy();
    if ( pMediumTmp->GetErrorCode() != ERRCODE_NONE )
    {
        SetError( pMediumTmp->GetError() );
        delete pMediumTmp;
        return sal_False;
    }

    // copy version list from "old" medium to target medium, so it can be used on saving
    pMediumTmp->TransferVersionList_Impl( *pRetrMedium );
/*
    if ( pFilter && ( pFilter->GetFilterFlags() & SFX_FILTER_PACKED ) )
        SetError( GetMedium()->Unpack_Impl( pRetrMedium->GetPhysicalName() ) );
*/

    // an interaction handler here can aquire only in case of GUI Saving
    // and should be removed after the saving is done
    com::sun::star::uno::Reference< XInteractionHandler > xInteract;
    SFX_ITEMSET_ARG( pArgs, pxInteractionItem, SfxUnoAnyItem, SID_INTERACTIONHANDLER, sal_False );
    if ( pxInteractionItem && ( pxInteractionItem->GetValue() >>= xInteract ) && xInteract.is() )
        pMediumTmp->GetItemSet()->Put( SfxUnoAnyItem( SID_INTERACTIONHANDLER, makeAny( xInteract ) ) );

    sal_Bool bSaved = sal_False;
    if( !GetError() && SaveTo_Impl( *pMediumTmp, pArgs ) )
    {
        bSaved = sal_True;

        if( pMediumTmp->GetItemSet() )
        {
            pMediumTmp->GetItemSet()->ClearItem( SID_INTERACTIONHANDLER );
            pMediumTmp->GetItemSet()->ClearItem( SID_PROGRESS_STATUSBAR_CONTROL );
        }

        SetError(pMediumTmp->GetErrorCode());

//REMOVE            if ( !IsHandsOff() )
//REMOVE            pMediumTmp->Close();

        sal_Bool bOpen( sal_False );
        bOpen = DoSaveCompleted( pMediumTmp );
        DBG_ASSERT(bOpen,"Fehlerbehandlung fuer DoSaveCompleted nicht implementiert");
    }
    else
    {
        // transfer error code from medium to objectshell
        SetError( pMediumTmp->GetError() );

        // reconnect to object storage
//REMOVE            if ( IsHandsOff() )
//REMOVE            {
//REMOVE                if ( !DoSaveCompleted( pRetrMedium ) )
//REMOVE                    DBG_ERROR("Case not handled - no way to get a storage!");
//REMOVE            }
//REMOVE            else
            DoSaveCompleted( 0 );

        if( pRetrMedium->GetItemSet() )
        {
            pRetrMedium->GetItemSet()->ClearItem( SID_INTERACTIONHANDLER );
            pRetrMedium->GetItemSet()->ClearItem( SID_PROGRESS_STATUSBAR_CONTROL );
        }

        delete pMediumTmp;
    }

    SetModified( !bSaved );
    return bSaved;
}

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

sal_Bool SfxObjectShell::Save_Impl( const SfxItemSet* pSet )
{
    if ( IsReadOnly() )
    {
        SetError( ERRCODE_SFX_DOCUMENTREADONLY );
        return sal_False;
    }

    DBG_CHKTHIS(SfxObjectShell, 0);

    pImp->bIsSaving = sal_True;
    sal_Bool bSaved = FALSE;
    SFX_ITEMSET_ARG( GetMedium()->GetItemSet(), pSalvageItem, SfxStringItem, SID_DOC_SALVAGE, sal_False);
    if ( pSalvageItem )
    {
        SFX_ITEMSET_ARG( GetMedium()->GetItemSet(), pFilterItem, SfxStringItem, SID_FILTER_NAME, sal_False);
        String aFilterName;
        const SfxFilter *pFilter = NULL;
        if ( pFilterItem )
            pFilter = SfxFilterMatcher( String::CreateFromAscii( GetFactory().GetShortName()) ).GetFilter4FilterName( aFilterName );

        SfxMedium *pMed = new SfxMedium(
            pSalvageItem->GetValue(), STREAM_READWRITE | STREAM_SHARE_DENYWRITE | STREAM_TRUNC, sal_False, pFilter );

        SFX_ITEMSET_ARG( GetMedium()->GetItemSet(), pPasswordItem, SfxStringItem, SID_PASSWORD, sal_False );
        if ( pPasswordItem )
            pMed->GetItemSet()->Put( *pPasswordItem );

        bSaved = DoSaveAs( *pMed );
        if ( bSaved )
            bSaved = DoSaveCompleted( pMed );
        else
            delete pMed;
    }
    else
        bSaved = DoSave_Impl( pSet );
    return bSaved;
}

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

sal_Bool SfxObjectShell::CommonSaveAs_Impl
(
    const INetURLObject&   aURL,
    const String&   aFilterName,
    SfxItemSet*     aParams
)
{
    if( aURL.HasError() )
    {
        SetError( ERRCODE_IO_INVALIDPARAMETER );
        return sal_False;
    }

    if ( aURL != INetURLObject( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "private:stream" ) ) ) )
    {
        // gibt es schon ein Doc mit dem Namen?
        SfxObjectShell* pDoc = 0;
        for ( SfxObjectShell* pTmp = SfxObjectShell::GetFirst();
                pTmp && !pDoc;
                pTmp = SfxObjectShell::GetNext(*pTmp) )
        {
            if( ( pTmp != this ) && pTmp->GetMedium() )
            {
                INetURLObject aCompare( pTmp->GetMedium()->GetName() );
                if ( aCompare == aURL )
                    pDoc = pTmp;
            }
        }
        if ( pDoc )
        {
            // dann Fehlermeldeung: "schon offen"
            SetError(ERRCODE_SFX_ALREADYOPEN);
            return sal_False;
        }
    }

    DBG_ASSERT( aURL.GetProtocol() != INET_PROT_NOT_VALID, "Illegal URL!" );
    DBG_ASSERT( aParams->Count() != 0, "fehlerhafte Parameter");

    SFX_ITEMSET_ARG( aParams, pSaveToItem, SfxBoolItem, SID_SAVETO, sal_False );
    sal_Bool bSaveTo = pSaveToItem ? pSaveToItem->GetValue() : sal_False;

    const SfxFilter* pFilter = GetFactory().GetFilterContainer()->GetFilter4FilterName( aFilterName );
    if ( !pFilter
        || !pFilter->CanExport()
        || !bSaveTo && !pFilter->CanImport() )
    {
        SetError( ERRCODE_IO_INVALIDPARAMETER );
        return sal_False;
    }

    SFX_ITEMSET_ARG( aParams, pCopyStreamItem, SfxBoolItem, SID_COPY_STREAM_IF_POSSIBLE, sal_False );
    if ( bSaveTo && pCopyStreamItem && pCopyStreamItem->GetValue() && !IsModified() )
    {
        if ( pMedium->TryDirectTransfer( aURL.GetMainURL( INetURLObject::NO_DECODE ), *aParams ) )
            return sal_True;
    }
    aParams->ClearItem( SID_COPY_STREAM_IF_POSSIBLE );

    pImp->bPasswd = aParams && SFX_ITEM_SET == aParams->GetItemState(SID_PASSWORD);

    SfxMedium *pActMed = GetMedium();
    const INetURLObject aActName(pActMed->GetName());

    BOOL bWasReadonly = IsReadOnly();

    if ( aURL == aActName && aURL != INetURLObject( OUString::createFromAscii( "private:stream" ) )
        && IsReadOnly() )
    {
        SetError(ERRCODE_SFX_DOCUMENTREADONLY);
        return sal_False;
    }

//REMOVE        if ( aURL == aActName && aURL != INetURLObject( OUString::createFromAscii( "private:stream" ) ) )
//REMOVE        {
//REMOVE            if ( IsReadOnly() )
//REMOVE            {
//REMOVE                SetError(ERRCODE_SFX_DOCUMENTREADONLY);
//REMOVE                return sal_False;
//REMOVE            }
//REMOVE
//REMOVE            // gleicher Filter? -> Save()
//REMOVE            const SfxFilter *pFilter = pActMed->GetFilter();
//REMOVE            if ( pFilter && pFilter->GetFilterName() == aFilterName )
//REMOVE            {
//REMOVE                pImp->bIsSaving=sal_False;
//REMOVE                if ( aParams )
//REMOVE                {
//REMOVE                    SfxItemSet* pSet = pMedium->GetItemSet();
//REMOVE                    pSet->ClearItem( SID_PASSWORD );
//REMOVE                    pSet->Put( *aParams );
//REMOVE                }
//REMOVE
//REMOVE                SFX_APP()->NotifyEvent(SfxEventHint(SFX_EVENT_SAVEDOC,this));
//REMOVE                BOOL bRet = DoSave_Impl();
//REMOVE                SFX_APP()->NotifyEvent(SfxEventHint(SFX_EVENT_SAVEDOCDONE,this));
//REMOVE                return bRet;
//REMOVE            }
//REMOVE        }

    // this notification should be already sent by caller in sfxbasemodel
    // SFX_APP()->NotifyEvent(SfxEventHint( bSaveTo? SFX_EVENT_SAVETODOC : SFX_EVENT_SAVEASDOC,this));

    if( SFX_ITEM_SET != aParams->GetItemState(SID_UNPACK) && SvtSaveOptions().IsSaveUnpacked() )
        aParams->Put( SfxBoolItem( SID_UNPACK, sal_False ) );

    if ( PreDoSaveAs_Impl(aURL.GetMainURL( INetURLObject::NO_DECODE ),aFilterName,aParams))
    {
        pImp->bWaitingForPicklist = sal_True;

        // Daten am Medium updaten
        SfxItemSet *pSet = GetMedium()->GetItemSet();
        pSet->ClearItem( SID_INTERACTIONHANDLER );
        pSet->ClearItem( SID_PROGRESS_STATUSBAR_CONTROL );

        if ( !bSaveTo )
        {
            pSet->ClearItem( SID_REFERER );
            pSet->ClearItem( SID_POSTDATA );
            pSet->ClearItem( SID_TEMPLATE );
            pSet->ClearItem( SID_DOC_READONLY );
            pSet->ClearItem( SID_CONTENTTYPE );
            pSet->ClearItem( SID_CHARSET );
            pSet->ClearItem( SID_FILTER_NAME );
            pSet->ClearItem( SID_OPTIONS );
            //pSet->ClearItem( SID_FILE_FILTEROPTIONS );
            pSet->ClearItem( SID_VERSION );
            //pSet->ClearItem( SID_USE_FILTEROPTIONS );
            pSet->ClearItem( SID_EDITDOC );
            pSet->ClearItem( SID_OVERWRITE );

            SFX_ITEMSET_GET( (*aParams), pFilterItem, SfxStringItem, SID_FILTER_NAME, sal_False );
            if ( pFilterItem )
                pSet->Put( *pFilterItem );

            SFX_ITEMSET_GET( (*aParams), pOptionsItem, SfxStringItem, SID_OPTIONS, sal_False );
            if ( pOptionsItem )
                pSet->Put( *pOptionsItem );

            SFX_ITEMSET_GET( (*aParams), pFilterOptItem, SfxStringItem, SID_FILE_FILTEROPTIONS, sal_False );
            if ( pFilterOptItem )
                pSet->Put( *pFilterOptItem );
        }

        if ( bWasReadonly && !bSaveTo )
            Broadcast( SfxSimpleHint(SFX_HINT_MODECHANGED) );

        return sal_True;
    }
    else
        return sal_False;
}

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

sal_Bool SfxObjectShell::PreDoSaveAs_Impl
(
    const String&   rFileName,
    const String&   aFilterName,
    SfxItemSet*     pParams
)
{
    // copy all items stored in the itemset of the current medium
    SfxAllItemSet* pMergedParams = new SfxAllItemSet( *pMedium->GetItemSet() );

    // in "SaveAs" title and password will be cleared ( maybe the new itemset contains new values, otherwise they will be empty )
    pMergedParams->ClearItem( SID_PASSWORD );
    pMergedParams->ClearItem( SID_DOCINFO_TITLE );

    pMergedParams->ClearItem( SID_INPUTSTREAM );
    pMergedParams->ClearItem( SID_STREAM );
    pMergedParams->ClearItem( SID_CONTENT );
    pMergedParams->ClearItem( SID_DOC_READONLY );

    pMergedParams->ClearItem( SID_REPAIRPACKAGE );

    // "SaveAs" will never store any version information - it's a complete new file !
    pMergedParams->ClearItem( SID_VERSION );

    // merge the new parameters into the copy
    // all values present in both itemsets will be overwritten by the new parameters
    if( pParams )
        pMergedParams->Put( *pParams );
    //DELETEZ( pParams );

#ifdef DBG_UTIL
    if ( pMergedParams->GetItemState( SID_DOC_SALVAGE) >= SFX_ITEM_SET )
        DBG_ERROR("Salvage item present in Itemset, check the parameters!");
#endif

    // should be unneccessary - too hot to handle!
    pMergedParams->ClearItem( SID_DOC_SALVAGE );

    // take over the new merged itemset
    pParams = pMergedParams;

    // create a medium for the target URL
    SfxMedium *pNewFile = new SfxMedium( rFileName, STREAM_READWRITE | STREAM_SHARE_DENYWRITE | STREAM_TRUNC, sal_False, 0, pParams );

    // set filter; if no filter is given, take the default filter of the factory
    if ( aFilterName.Len() )
        pNewFile->SetFilter( GetFactory().GetFilterContainer()->GetFilter4FilterName( aFilterName ) );
    else
        pNewFile->SetFilter( GetFactory().GetFilterContainer()->GetAnyFilter( SFX_FILTER_IMPORT | SFX_FILTER_EXPORT ) );

//REMOVE        // saving is alway done using a temporary file
//REMOVE        pNewFile->CreateTempFileNoCopy();
    if ( pNewFile->GetErrorCode() != ERRCODE_NONE )
    {
        // creating temporary file failed ( f.e. floppy disk not inserted! )
        SetError( pNewFile->GetError() );
        delete pNewFile;
        return sal_False;
    }

    // check if a "SaveTo" is wanted, no "SaveAs"
    SFX_ITEMSET_ARG( pParams, pSaveToItem, SfxBoolItem, SID_SAVETO, sal_False );
    sal_Bool bCopyTo = GetCreateMode() == SFX_CREATE_MODE_EMBEDDED || pSaveToItem && pSaveToItem->GetValue();

    // distinguish between "Save" and "SaveAs"
    pImp->bIsSaving = sal_False;

    // copy version list from "old" medium to target medium, so it can be used on saving
    if ( pImp->bPreserveVersions )
        pNewFile->TransferVersionList_Impl( *pMedium );

/*
    if ( GetMedium()->GetFilter() && ( GetMedium()->GetFilter()->GetFilterFlags() & SFX_FILTER_PACKED ) )
    {
        SfxMedium *pMed = bCopyTo ? pMedium : pNewFile;
        pNewFile->SetError( GetMedium()->Unpack_Impl( pMed->GetPhysicalName() ) );
    }
*/
    // Save the document ( first as temporary file, then transfer to the target URL by committing the medium )
    sal_Bool bOk = sal_False;
    if ( !pNewFile->GetErrorCode() && SaveTo_Impl( *pNewFile, NULL ) )
    {
        bOk = sal_True;

        // transfer a possible error from the medium to the document
        SetError( pNewFile->GetErrorCode() );

        // notify the document that saving was done successfully
//REMOVE            if ( bCopyTo )
//REMOVE            {
//REMOVE                if ( IsHandsOff() )
//REMOVE                    bOk = DoSaveCompleted( pMedium );
//REMOVE            }
//REMOVE            else
        if ( !bCopyTo )
        {
            // Muss !!!
//REMOVE                if ( bToOwnFormat )
//REMOVE                    SetFileName( pNewFile->GetPhysicalName() );

            bOk = DoSaveCompleted( pNewFile );
        }
        else
            bOk = DoSaveCompleted(0);

        if( bOk )
        {
            if( !bCopyTo )
                SetModified( sal_False );
        }
        else
        {
            // TODO/LATER: the code below must be dead since the storage commit makes all the stuff
            //       and the DoSaveCompleted call should not be able to fail in general

            DBG_ASSERT( !bCopyTo, "Error while reconnecting to medium, can't be handled!");
            SetError( pNewFile->GetErrorCode() );

            if ( !bCopyTo )
            {
                // reconnect to the old medium
                BOOL bRet( FALSE );
                bRet = DoSaveCompleted( pMedium );
                DBG_ASSERT( bRet, "Error in DoSaveCompleted, can't be handled!");
            }

            // TODO/LATER: disconnect the new file from the storage for the case when pure saving is done
            //       if storing has corrupted the file, probably it must be restored either here or
            //       by the storage
            DELETEZ( pNewFile );
        }

        // TODO/LATER: there is no need in the following code in case HandsOff is not used,
        //             hope we will not have to introduce it back
//REMOVE            String aPasswd;
//REMOVE            if ( IsOwnStorageFormat_Impl( *GetMedium() ) && GetPasswd_Impl( GetMedium()->GetItemSet(), aPasswd ) )
//REMOVE            {
//REMOVE                try
//REMOVE                {
//REMOVE                    // the following code must throw an exception in case of failure
//REMOVE                    ::comphelper::OStorageHelper::SetCommonStoragePassword( GetMedium->GetStorage(), aPasswd );
//REMOVE                }
//REMOVE                catch( uno::Exception& )
//REMOVE                {
//REMOVE                    // TODO: handle the error
//REMOVE                }
//REMOVE            }
    }
    else
    {
        SetError( pNewFile->GetErrorCode() );

//REMOVE            // reconnect to the old storage
//REMOVE            if ( IsHandsOff() )
//REMOVE                DoSaveCompleted( pMedium );
//REMOVE            else
        DoSaveCompleted( 0 );

        DELETEZ( pNewFile );
    }

    if ( bCopyTo )
        DELETEZ( pNewFile );
    else if( !bOk )
        SetModified( sal_True );

    return bOk;
}

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

sal_Bool SfxObjectShell::LoadFrom( SfxMedium& /*rMedium*/ )
{
    DBG_ERROR( "Base implementation, must not be called in general!" );
    return sal_True;
}

//-------------------------------------------------------------------------
sal_Bool SfxObjectShell::IsInformationLost()
{
    Sequence< PropertyValue > aProps = GetModel()->getArgs();
    ::rtl::OUString aFilterName;
    ::rtl::OUString aPreusedFilterName;
    for ( sal_Int32 nInd = 0; nInd < aProps.getLength(); nInd++ )
    {
        if ( aProps[nInd].Name.equalsAscii( "FilterName" ) )
            aProps[nInd].Value >>= aFilterName;
        else if ( aProps[nInd].Name.equalsAscii( "PreusedFilterName" ) )
            aProps[nInd].Value >>= aPreusedFilterName;
    }

    // if current filter can lead to information loss and it was used
    // for the latest store then the user should be asked to store in own format
    if ( aFilterName.getLength() && aFilterName.equals( aPreusedFilterName ) )
    {
        const SfxFilter *pFilt = GetMedium()->GetFilter();
        DBG_ASSERT( pFilt && aFilterName.equals( pFilt->GetName() ), "MediaDescriptor contains wrong filter!\n" );
        return ( pFilt && pFilt->IsAlienFormat() && !(pFilt->GetFilterFlags() & SFX_FILTER_SILENTEXPORT ) );
    }

    return sal_False;
}

//-------------------------------------------------------------------------
sal_Bool SfxObjectShell::CanReload_Impl()

/*  [Beschreibung]

    Interne Methode zum Feststellen, ob eine erneutes Laden des
    Dokuments (auch als RevertToSaved oder LastVersion bekannt)
    m"oglich ist.
*/

{
    return pMedium && HasName() && !IsInModalMode() && !pImp->bForbidReload;
}

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

sal_uInt16 SfxObjectShell::GetHiddenInformationState( sal_uInt16 nStates )
{
    sal_uInt16 nState = 0;
    if ( nStates & HIDDENINFORMATION_DOCUMENTVERSIONS )
    {
        if ( GetMedium()->GetVersionList().getLength() )
            nState |= HIDDENINFORMATION_DOCUMENTVERSIONS;
    }

    return nState;
}

sal_Int16 SfxObjectShell::QueryHiddenInformation( HiddenWarningFact eFact, Window* pParent )
{
    sal_Int16 nRet = RET_YES;
    USHORT nResId = 0;
    SvtSecurityOptions::EOption eOption = static_cast< SvtSecurityOptions::EOption >( -1 );

    switch ( eFact )
    {
        case WhenSaving :
        {
            nResId = STR_HIDDENINFO_CONTINUE_SAVING;
            eOption = SvtSecurityOptions::E_DOCWARN_SAVEORSEND;
            break;
        }
        case WhenPrinting :
        {
            nResId = STR_HIDDENINFO_CONTINUE_PRINTING;
            eOption = SvtSecurityOptions::E_DOCWARN_PRINT;
            break;
        }
        case WhenSigning :
        {
            nResId = STR_HIDDENINFO_CONTINUE_SIGNING;
            eOption = SvtSecurityOptions::E_DOCWARN_SIGNING;
            break;
        }
        case WhenCreatingPDF :
        {
            nResId = STR_HIDDENINFO_CONTINUE_CREATEPDF;
            eOption = SvtSecurityOptions::E_DOCWARN_CREATEPDF;
            break;
        }
        default:
        {
            DBG_ERRORFILE( "SfxObjectShell::DetectHiddenInformation(): what fact?" );
        }
    }

    if ( eOption != -1 && SvtSecurityOptions().IsOptionSet( eOption ) )
    {
        String sMessage( SfxResId( STR_HIDDENINFO_CONTAINS ) );
        sal_uInt16 nWantedStates = HIDDENINFORMATION_RECORDEDCHANGES | HIDDENINFORMATION_NOTES;
        if ( eFact != WhenPrinting )
            nWantedStates |= HIDDENINFORMATION_DOCUMENTVERSIONS;
        sal_uInt16 nStates = GetHiddenInformationState( nWantedStates );
        bool bWarning = false;

        if ( ( nStates & HIDDENINFORMATION_RECORDEDCHANGES ) == HIDDENINFORMATION_RECORDEDCHANGES )
        {
            sMessage += String( SfxResId( STR_HIDDENINFO_RECORDCHANGES ) );
            sMessage += '\n';
            bWarning = true;
        }
        if ( ( nStates & HIDDENINFORMATION_NOTES ) == HIDDENINFORMATION_NOTES )
        {
            sMessage += String( SfxResId( STR_HIDDENINFO_NOTES ) );
            sMessage += '\n';
            bWarning = true;
        }
        if ( ( nStates & HIDDENINFORMATION_DOCUMENTVERSIONS ) == HIDDENINFORMATION_DOCUMENTVERSIONS )
        {
            sMessage += String( SfxResId( STR_HIDDENINFO_DOCVERSIONS ) );
            sMessage += '\n';
            bWarning = true;
        }

        if ( bWarning )
        {
            sMessage += '\n';
            sMessage += String( SfxResId( nResId ) );
            WarningBox aWBox( pParent, WB_YES_NO | WB_DEF_NO, sMessage );
            nRet = aWBox.Execute();
        }
    }

    return nRet;
}

sal_Bool SfxObjectShell::HasSecurityOptOpenReadOnly() const
{
    return sal_True;
}

sal_Bool SfxObjectShell::IsSecurityOptOpenReadOnly() const
{
    const SfxDocumentInfo& rDocInfo = const_cast< SfxObjectShell* >( this )->GetDocInfo();
    return rDocInfo.IsLoadReadonly();
}

void SfxObjectShell::SetSecurityOptOpenReadOnly( sal_Bool _b )
{
    SfxDocumentInfo& rDocInfo = GetDocInfo();
    if ( rDocInfo.IsLoadReadonly() != _b )
    {
        GetDocInfo().SetLoadReadonly( _b );
        SetModified( sal_True );
    }
}

sal_Bool SfxObjectShell::LoadOwnFormat( SfxMedium& rMedium )
{
    uno::Reference< embed::XStorage > xStorage = rMedium.GetStorage();
    if ( xStorage.is() )
    {
//REMOVE            if ( rMedium.GetFileVersion() )
//REMOVE                xStor->SetVersion( rMedium.GetFileVersion() );

        // Password
        SFX_ITEMSET_ARG( rMedium.GetItemSet(), pPasswdItem, SfxStringItem, SID_PASSWORD, sal_False );
        if ( pPasswdItem || ERRCODE_IO_ABORT != CheckPasswd_Impl( this, SFX_APP()->GetPool(), pMedium ) )
        {
            String aPasswd;
            if ( GetPasswd_Impl(pMedium->GetItemSet(), aPasswd) )
            {
                try
                {
                    // the following code must throw an exception in case of failure
                    ::comphelper::OStorageHelper::SetCommonStoragePassword( xStorage, aPasswd );
                }
                catch( uno::Exception& )
                {
                    // TODO/LATER: handle the error code
                }
            }

            // load document
            return Load( rMedium );
        }
        return sal_False;
    }
    else
        return sal_False;
}

sal_Bool SfxObjectShell::SaveAsOwnFormat( SfxMedium& rMedium )
{
    uno::Reference< embed::XStorage > xStorage = rMedium.GetStorage();
    if( xStorage.is() )
    {
        sal_Int32 nVersion = rMedium.GetFilter()->GetVersion();

        // OASIS templates have own mediatypes ( SO7 also actually, but it is to late to use them here )
        sal_Bool bTemplate = ( rMedium.GetFilter()->IsOwnTemplateFormat() && nVersion > SOFFICE_FILEFORMAT_60 );

        SetupStorage( xStorage, nVersion, bTemplate );

        // Initialize Basic
        GetBasicManager();

        // Save dialog/script container
        pImp->pBasicManager->storeLibrariesToStorage( xStorage );

        return SaveAs( rMedium );
    }
    else return sal_False;
}

uno::Reference< embed::XStorage > SfxObjectShell::GetStorage()
{
    if ( !pImp->m_xDocStorage.is() )
    {
        OSL_ENSURE( pImp->m_bCreateTempStor, "The storage must exist already!\n" );
        try {
            // no notification is required the storage is set the first time
            pImp->m_xDocStorage = ::comphelper::OStorageHelper::GetTemporaryStorage();
            OSL_ENSURE( pImp->m_xDocStorage.is(), "The method must either return storage or throw an exception!" );

            SetupStorage( pImp->m_xDocStorage, SOFFICE_FILEFORMAT_CURRENT, sal_False );
            pImp->m_bCreateTempStor = sal_False;
            SFX_APP()->NotifyEvent( SfxEventHint( SFX_EVENT_STORAGECHANGED, this ) );
        }
        catch( uno::Exception& )
        {
            // TODO/LATER: error handling?
        }
    }

    OSL_ENSURE( pImp->m_xDocStorage.is(), "The document storage must be created!" );
    return pImp->m_xDocStorage;
}

void InsertStreamIntoPicturesStorage_Impl( const uno::Reference< embed::XStorage >& xDocStor,
                                            const uno::Reference< io::XInputStream >& xInStream,
                                            const ::rtl::OUString& aStreamName )
{
    OSL_ENSURE( aStreamName.getLength() && xInStream.is() && xDocStor.is(), "Misuse of the method!\n" );

    try
    {
        uno::Reference< embed::XStorage > xPictures = xDocStor->openStorageElement(
                                    ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Pictures" ) ),
                                    embed::ElementModes::READWRITE );
        uno::Reference< io::XStream > xObjReplStr = xPictures->openStreamElement(
                                    aStreamName,
                                    embed::ElementModes::READWRITE | embed::ElementModes::TRUNCATE );
        uno::Reference< io::XOutputStream > xOutStream(
                                    xObjReplStr->getInputStream(), uno::UNO_QUERY_THROW );

        ::comphelper::OStorageHelper::CopyInputToOutput( xInStream, xOutStream );
        xOutStream->closeOutput();

        uno::Reference< embed::XTransactedObject > xTransact( xPictures, uno::UNO_QUERY );
        if ( xTransact.is() )
            xTransact->commit();
    }
    catch( uno::Exception& )
    {
        OSL_ENSURE( sal_False, "The pictures storage is not available!\n" );
    }
}

sal_Bool SfxObjectShell::SaveChildren( BOOL bObjectsOnly )
{
    RTL_LOGFILE_CONTEXT( aLog, "sfx2 (mv76033) SfxObjectShell::SaveChildren" );

    sal_Bool bResult = sal_True;
    if ( pImp->mpObjectContainer )
    {
        sal_Bool bOasis = ( SotStorage::GetVersion( GetStorage() ) > SOFFICE_FILEFORMAT_60 );
        uno::Sequence < ::rtl::OUString > aNames = GetEmbeddedObjectContainer().GetObjectNames();

        for ( sal_Int32 n=0; n<aNames.getLength(); n++ )
        {
            uno::Reference < embed::XEmbeddedObject > xObj = GetEmbeddedObjectContainer().GetEmbeddedObject( aNames[n] );
            OSL_ENSURE( xObj.is(), "An empty entry in the embedded objects list!\n" );
            if ( xObj.is() )
            {
                sal_Int32 nCurState = xObj->getCurrentState();
                if ( bOasis && nCurState != embed::EmbedStates::LOADED && nCurState != embed::EmbedStates::RUNNING )
                {
                    // means that the object is active
                    // the image must be regenerated
                    ::rtl::OUString aMediaType;

                    // TODO/LATER: another aspect could be used
                    uno::Reference < io::XInputStream > xStream =
                                svt::EmbeddedObjectRef::GetGraphicReplacementStream(
                                                            embed::Aspects::MSOLE_CONTENT,
                                                            xObj,
                                                            &aMediaType );
                    if ( xStream.is() )
                    {
                        if ( !GetEmbeddedObjectContainer().InsertGraphicStreamDirectly( xStream, aNames[n], aMediaType ) )
                               GetEmbeddedObjectContainer().InsertGraphicStream( xStream, aNames[n], aMediaType );
                    }
                }

                // TODO/LATER: currently the object by default does not cache replacement image
                // that means that if somebody loads SO7 document and store its objects using
                // this method the images might be lost.
                // Currently this method is only used on storing to alien formats, that means
                // that SO7 documents storing does not use it, and all other filters are
                // based on OASIS format. But if it changes the method must be fixed. The fix
                // must be done only on demand since it can affect performance.

                uno::Reference< embed::XEmbedPersist > xPersist( xObj, uno::UNO_QUERY );
                if ( xPersist.is() )
                {
                    try
                    {
                        //TODO/LATER: only storing if changed!
                        xPersist->storeOwn();
                    }
                    catch( uno::Exception& )
                    {
                        // TODO/LATER: error handling
                        bResult = sal_False;
                        break;
                    }
                }

                if ( !bOasis && !bObjectsOnly )
                {
                    // copy replacement images for linked objects
                    try
                    {
                        uno::Reference< embed::XLinkageSupport > xLink( xObj, uno::UNO_QUERY );
                        if ( xLink.is() && xLink->isLink() )
                        {
                            ::rtl::OUString aMediaType;
                            uno::Reference < io::XInputStream > xInStream =
                                    GetEmbeddedObjectContainer().GetGraphicStream( xObj, &aMediaType );
                            if ( xInStream.is() )
                                InsertStreamIntoPicturesStorage_Impl( GetStorage(), xInStream, aNames[n] );
                        }
                    }
                    catch( uno::Exception& )
                    {
                    }
                }
            }
        }

        if ( bResult && bOasis )
            bResult = GetEmbeddedObjectContainer().CommitImageSubStorage();

        if ( bResult && !bObjectsOnly )
        {
            try
            {
                GetEmbeddedObjectContainer().ReleaseImageSubStorage();
                ::rtl::OUString aObjReplElement( RTL_CONSTASCII_USTRINGPARAM( "ObjectReplacements" ) );
                if ( !bOasis && GetStorage()->hasByName( aObjReplElement ) && GetStorage()->isStorageElement( aObjReplElement ) )
                    GetStorage()->removeElement( aObjReplElement );
            }
            catch( uno::Exception& )
            {
                // TODO/LATER: error handling
                bResult = sal_False;
            }
        }
    }

    return bResult;
}

sal_Bool SfxObjectShell::SaveAsChildren( SfxMedium& rMedium )
{
    RTL_LOGFILE_CONTEXT( aLog, "sfx2 (mv76033) SfxObjectShell::SaveAsChildren" );

    sal_Bool bResult = sal_True;

    uno::Reference < embed::XStorage > xStorage = rMedium.GetStorage();
    if ( !xStorage.is() )
        return sal_False;

    if ( xStorage == GetStorage() )
        return SaveChildren();

    sal_Bool bOasis = sal_True;
    if ( pImp->mpObjectContainer )
    {
        try
        {
            bOasis = ( SotStorage::GetVersion( xStorage ) > SOFFICE_FILEFORMAT_60 );

            comphelper::EmbeddedObjectContainer aCnt( xStorage );
            uno::Sequence < ::rtl::OUString > aNames = GetEmbeddedObjectContainer().GetObjectNames();
            for ( sal_Int32 n=0; n<aNames.getLength(); n++ )
            {
                uno::Reference < embed::XEmbeddedObject > xObj = GetEmbeddedObjectContainer().GetEmbeddedObject( aNames[n] );
                OSL_ENSURE( xObj.is(), "An empty entry in the embedded objects list!\n" );
                if ( xObj.is() )
                {
                    sal_Bool bSwitchBackToLoaded = sal_False;
                    uno::Reference< embed::XLinkageSupport > xLink( xObj, uno::UNO_QUERY );

                    uno::Reference < io::XInputStream > xStream;
                    ::rtl::OUString aMediaType;

                    sal_Int32 nCurState = xObj->getCurrentState();
                    if ( nCurState == embed::EmbedStates::LOADED || nCurState == embed::EmbedStates::RUNNING )
                    {
                        // means that the object is not active
                        // copy replacement image from old to new container
                        xStream = GetEmbeddedObjectContainer().GetGraphicStream( xObj, &aMediaType );
                    }

                    if ( !xStream.is() )
                    {
                        // the image must be regenerated
                        // TODO/LATER: another aspect could be used
                        if ( xObj->getCurrentState() == embed::EmbedStates::LOADED )
                                bSwitchBackToLoaded = sal_True;

                        xStream = svt::EmbeddedObjectRef::GetGraphicReplacementStream(
                                                                embed::Aspects::MSOLE_CONTENT,
                                                                xObj,
                                                                &aMediaType );
                    }

                    if ( bOasis || xLink.is() && xLink->isLink() )
                    {
                        if ( xStream.is() )
                        {
                            if ( bOasis )
                            {
                                // if it is an embedded object or the optimized inserting fails the normal inserting should be done
                                if ( SFX_CREATE_MODE_EMBEDDED == eCreateMode
                                  || !aCnt.InsertGraphicStreamDirectly( xStream, aNames[n], aMediaType ) )
                                    aCnt.InsertGraphicStream( xStream, aNames[n], aMediaType );
                            }
                            else
                            {
                                // it is a linked object exported into SO7 format
                                InsertStreamIntoPicturesStorage_Impl( xStorage, xStream, aNames[n] );
                            }
                        }
                    }

                    uno::Reference< embed::XEmbedPersist > xPersist( xObj, uno::UNO_QUERY );
                    if ( xPersist.is() )
                    {
                        uno::Sequence< beans::PropertyValue > aArgs( bOasis ? 2 : 3 );
                        aArgs[0].Name = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "StoreVisualReplacement" ) );
                        aArgs[0].Value <<= (sal_Bool)( !bOasis );

                        // if it is an embedded object or the optimized inserting fails the normal inserting should be done
                        aArgs[1].Name = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "CanTryOptimization" ) );
                        aArgs[1].Value <<= (sal_Bool)( !( SFX_CREATE_MODE_EMBEDDED == eCreateMode ) );
                        if ( !bOasis )
                        {
                            // if object has no cached replacement it will use this one
                            aArgs[2].Name = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "VisualReplacement" ) );
                            aArgs[2].Value <<= xStream;
                        }

                        xPersist->storeAsEntry( xStorage,
                                                xPersist->getEntryName(),
                                                uno::Sequence< beans::PropertyValue >(),
                                                aArgs );
                    }

                    if ( bSwitchBackToLoaded )
                        // switch back to loaded state; that way we have a minimum cache confusion
                        xObj->changeState( embed::EmbedStates::LOADED );
                }
            }

            bResult = aCnt.CommitImageSubStorage();

        }
        catch ( uno::Exception& )
        {
            // TODO/LATER: error handling
            bResult = sal_False;
        }

        // the old SO6 format does not store graphical replacements
        if ( !bOasis && bResult )
        {
            try
            {
                // the substorage still can not be locked by the embedded object conteiner
                ::rtl::OUString aObjReplElement( RTL_CONSTASCII_USTRINGPARAM( "ObjectReplacements" ) );
                if ( xStorage->hasByName( aObjReplElement ) && xStorage->isStorageElement( aObjReplElement ) )
                    xStorage->removeElement( aObjReplElement );
            }
            catch ( uno::Exception& )
            {
                // TODO/LATER: error handling;
                bResult = sal_False;
            }
        }
    }

    if ( bResult )
        bResult = CopyStoragesOfUnknownMediaType( GetStorage(), xStorage );

    return bResult;
}

sal_Bool SfxObjectShell::SaveCompletedChildren( sal_Bool bSuccess )
{
    RTL_LOGFILE_CONTEXT( aLog, "sfx2 (mv76033) SfxObjectShell::SaveCompletedChildren" );

    sal_Bool bResult = sal_True;

    if ( pImp->mpObjectContainer )
    {
        uno::Sequence < ::rtl::OUString > aNames = GetEmbeddedObjectContainer().GetObjectNames();
        for ( sal_Int32 n=0; n<aNames.getLength(); n++ )
        {
            uno::Reference < embed::XEmbeddedObject > xObj = GetEmbeddedObjectContainer().GetEmbeddedObject( aNames[n] );
            OSL_ENSURE( xObj.is(), "An empty entry in the embedded objects list!\n" );
            if ( xObj.is() )
            {
                uno::Reference< embed::XEmbedPersist > xPersist( xObj, uno::UNO_QUERY );
                if ( xPersist.is() )
                {
                    try
                    {
                        xPersist->saveCompleted( bSuccess );
                    }
                    catch( uno::Exception& )
                    {
                        // TODO/LATER: error handling
                        bResult = sal_False;
                        break;
                    }
                }
            }
        }
    }

    return bResult;
}

sal_Bool SfxObjectShell::SwitchChildrenPersistance( const uno::Reference< embed::XStorage >& xStorage,
                                                    sal_Bool bForceNonModified )
{
    RTL_LOGFILE_CONTEXT( aLog, "sfx2 (mv76033) SfxObjectShell::SwitchChildrenPersistence" );

    if ( !xStorage.is() )
    {
        // TODO/LATER: error handling
        return sal_False;
    }

    sal_Bool bResult = sal_True;

    if ( pImp->mpObjectContainer )
    {
        uno::Sequence < ::rtl::OUString > aNames = GetEmbeddedObjectContainer().GetObjectNames();
        for ( sal_Int32 n=0; n<aNames.getLength(); n++ )
        {
            uno::Reference < embed::XEmbeddedObject > xObj = GetEmbeddedObjectContainer().GetEmbeddedObject( aNames[n] );
            OSL_ENSURE( xObj.is(), "An empty entry in the embedded objects list!\n" );
            if ( xObj.is() )
            {
                uno::Reference< embed::XEmbedPersist > xPersist( xObj, uno::UNO_QUERY );
                if ( xPersist.is() )
                {
                    try
                    {
                        xPersist->setPersistentEntry( xStorage,
                                                    aNames[n],
                                                    embed::EntryInitModes::NO_INIT,
                                                    uno::Sequence< beans::PropertyValue >(),
                                                    uno::Sequence< beans::PropertyValue >() );

                    }
                    catch( uno::Exception& )
                    {
                        // TODO/LATER: error handling
                        bResult = sal_False;
                        break;
                    }
                }

                if ( bForceNonModified )
                {
                    // if this method is used as part of SaveCompleted the object must stay unmodified after execution
                    try
                    {
                        uno::Reference< util::XModifiable > xModif( xObj->getComponent(), uno::UNO_QUERY_THROW );
                        if ( xModif->isModified() )
                            xModif->setModified( sal_False );
                    }
                    catch( uno::Exception& )
                    {
                    }
                }
            }
        }
    }

    return bResult;
}

// Never call this method directly, always use the DoSaveCompleted call
sal_Bool SfxObjectShell::SaveCompleted( const uno::Reference< embed::XStorage >& xStorage )
{
    RTL_LOGFILE_CONTEXT( aLog, "sfx2 (mv76033) SfxObjectShell::SaveCompleted" );

    sal_Bool bResult = sal_False;
    sal_Bool bSendNotification = sal_False;
    uno::Reference< embed::XStorage > xOldStorageHolder;

#ifdef DBG_UTIL
    // check for wrong creation of object container
    BOOL bHasContainer = ( pImp->mpObjectContainer != 0 );
#endif

    if ( !xStorage.is() || xStorage == GetStorage() )
    {
        // no persistence change
        bResult = SaveCompletedChildren( sal_False );
    }
    else
    {
        if ( pImp->mpObjectContainer )
            GetEmbeddedObjectContainer().SwitchPersistence( xStorage );

        bResult = SwitchChildrenPersistance( xStorage, sal_True );
    }

    if ( bResult )
    {
        if ( xStorage.is() && pImp->m_xDocStorage != xStorage )
        {
            // make sure that until the storage is assigned the object container is not created by accident!
            DBG_ASSERT( bHasContainer == (pImp->mpObjectContainer != 0), "Wrong storage in object container!" );
            xOldStorageHolder = pImp->m_xDocStorage;
            pImp->m_xDocStorage = xStorage;
            bSendNotification = sal_True;

            if ( IsEnableSetModified() )
                SetModified( sal_False );
        }
    }
    else
    {
        if ( pImp->mpObjectContainer )
            GetEmbeddedObjectContainer().SwitchPersistence( pImp->m_xDocStorage );

        // let already successfully connected objects be switched back
        SwitchChildrenPersistance( pImp->m_xDocStorage, sal_True );
    }

    if ( bSendNotification )
    {
        SFX_APP()->NotifyEvent( SfxEventHint( SFX_EVENT_STORAGECHANGED, this ) );
    }

    return bResult;
}


sal_Bool StoragesOfUnknownMediaTypeAreCopied_Impl( const uno::Reference< embed::XStorage >& xSource,
                                                    const uno::Reference< embed::XStorage >& xTarget )
{
    OSL_ENSURE( xSource.is() && xTarget.is(), "Source and/or target storages are not available!\n" );
    if ( !xSource.is() || !xTarget.is() || xSource == xTarget )
        return sal_True;

    try
    {
        uno::Sequence< ::rtl::OUString > aSubElements = xSource->getElementNames();
        for ( sal_Int32 nInd = 0; nInd < aSubElements.getLength(); nInd++ )
        {
            if ( xSource->isStorageElement( aSubElements[nInd] ) )
            {
                ::rtl::OUString aMediaType;
                ::rtl::OUString aMediaTypePropName( RTL_CONSTASCII_USTRINGPARAM( "MediaType" ) );
                sal_Bool bGotMediaType = sal_False;

                try
                {
                    uno::Reference< embed::XOptimizedStorage > xOptStorage( xSource, uno::UNO_QUERY_THROW );
                    bGotMediaType =
                        ( xOptStorage->getElementPropertyValue( aSubElements[nInd], aMediaTypePropName ) >>= aMediaType );
                }
                catch( uno::Exception& )
                {}

                if ( !bGotMediaType )
                {
                    uno::Reference< embed::XStorage > xSubStorage;
                    try {
                        xSubStorage = xSource->openStorageElement( aSubElements[nInd], embed::ElementModes::READ );
                    } catch( uno::Exception& )
                    {}

                    if ( !xSubStorage.is() )
                    {
                        xSubStorage = ::comphelper::OStorageHelper::GetTemporaryStorage();
                        xSource->copyStorageElementLastCommitTo( aSubElements[nInd], xSubStorage );
                    }

                    uno::Reference< beans::XPropertySet > xProps( xSubStorage, uno::UNO_QUERY_THROW );
                    bGotMediaType = ( xProps->getPropertyValue( aMediaTypePropName ) >>= aMediaType );
                }

                // TODO/LATER: there should be a way to detect whether an object with such a MediaType can exist
                //             probably it should be placed in the MimeType-ClassID table or in standalone table
                if ( aMediaType.getLength()
                  && aMediaType.compareToAscii( "application/vnd.sun.star.oleobject" ) != COMPARE_EQUAL )
                {
                    ::com::sun::star::datatransfer::DataFlavor aDataFlavor;
                    aDataFlavor.MimeType = aMediaType;
                    sal_uInt32 nFormat = SotExchange::GetFormat( aDataFlavor );

                    switch ( nFormat )
                    {
                        case SOT_FORMATSTR_ID_STARWRITER_60 :
                        case SOT_FORMATSTR_ID_STARWRITERWEB_60 :
                        case SOT_FORMATSTR_ID_STARWRITERGLOB_60 :
                        case SOT_FORMATSTR_ID_STARDRAW_60 :
                        case SOT_FORMATSTR_ID_STARIMPRESS_60 :
                        case SOT_FORMATSTR_ID_STARCALC_60 :
                        case SOT_FORMATSTR_ID_STARCHART_60 :
                        case SOT_FORMATSTR_ID_STARMATH_60 :
                        case SOT_FORMATSTR_ID_STARWRITER_8:
                        case SOT_FORMATSTR_ID_STARWRITERWEB_8:
                        case SOT_FORMATSTR_ID_STARWRITERGLOB_8:
                        case SOT_FORMATSTR_ID_STARDRAW_8:
                        case SOT_FORMATSTR_ID_STARIMPRESS_8:
                        case SOT_FORMATSTR_ID_STARCALC_8:
                        case SOT_FORMATSTR_ID_STARCHART_8:
                        case SOT_FORMATSTR_ID_STARMATH_8:
                            break;

                        default:
                        {
                            if ( !xTarget->hasByName( aSubElements[nInd] ) )
                                return sal_False;
                        }
                    }
                }
            }
        }
    }
    catch( uno::Exception& )
    {
        OSL_ENSURE( sal_False, "Cant check storage consistency!\n" );
    }

    return sal_True;
}


sal_Bool SfxObjectShell::SwitchPersistance( const uno::Reference< embed::XStorage >& xStorage )
{
    RTL_LOGFILE_CONTEXT( aLog, "sfx2 (mv76033) SfxObjectShell::SwitchPersistance" );

    sal_Bool bResult = sal_False;
#ifdef DBG_UTIL
    // check for wrong creation of object container
    BOOL bHasContainer = ( pImp->mpObjectContainer != 0 );
#endif
    if ( xStorage.is() )
    {
        if ( pImp->mpObjectContainer )
            GetEmbeddedObjectContainer().SwitchPersistence( xStorage );
        bResult = SwitchChildrenPersistance( xStorage );

        // TODO/LATER: substorages that have unknown mimetypes probably should be copied to the target storage here
        OSL_ENSURE( StoragesOfUnknownMediaTypeAreCopied_Impl( pImp->m_xDocStorage, xStorage ),
                    "Some of substorages with unknown mimetypes is lost!" );
    }

    if ( bResult )
    {
        // make sure that until the storage is assigned the object container is not created by accident!
        DBG_ASSERT( bHasContainer == (pImp->mpObjectContainer != 0), "Wrong storage in object container!" );
        if ( pImp->m_xDocStorage != xStorage )
            DoSaveCompleted( new SfxMedium( xStorage, GetMedium()->GetBaseURL() ) );

        if ( IsEnableSetModified() )
            SetModified( sal_True ); // ???
    }

    return bResult;
}

sal_Bool SfxObjectShell::CopyStoragesOfUnknownMediaType( const uno::Reference< embed::XStorage >& xSource,
                                                         const uno::Reference< embed::XStorage >& xTarget )
{
    RTL_LOGFILE_CONTEXT( aLog, "sfx2 (mv76033) SfxObjectShell::CopyStoragesOfUnknownMediaType" );

    // This method does not commit the target storage and should not do it
    sal_Bool bResult = sal_True;

    try
    {
        uno::Sequence< ::rtl::OUString > aSubElements = xSource->getElementNames();
        for ( sal_Int32 nInd = 0; nInd < aSubElements.getLength(); nInd++ )
        {
            if ( aSubElements[nInd].equals( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Configurations" ) ) ) )
            {
                // The workaround for compatibility with SO7, "Configurations" substorage must be preserved
                if ( xSource->isStorageElement( aSubElements[nInd] ) )
                {
                    OSL_ENSURE( !xTarget->hasByName( aSubElements[nInd] ),
                                "The target storage is an output storage, the element should not exist in the target!\n" );

                    xSource->copyElementTo( aSubElements[nInd], xTarget, aSubElements[nInd] );
                }
            }
            else if ( xSource->isStorageElement( aSubElements[nInd] ) )
            {
                ::rtl::OUString aMediaType;
                ::rtl::OUString aMediaTypePropName( RTL_CONSTASCII_USTRINGPARAM( "MediaType" ) );
                sal_Bool bGotMediaType = sal_False;

                try
                {
                    uno::Reference< embed::XOptimizedStorage > xOptStorage( xSource, uno::UNO_QUERY_THROW );
                    bGotMediaType =
                        ( xOptStorage->getElementPropertyValue( aSubElements[nInd], aMediaTypePropName ) >>= aMediaType );
                }
                catch( uno::Exception& )
                {}

                if ( !bGotMediaType )
                {
                    uno::Reference< embed::XStorage > xSubStorage;
                    try {
                        xSubStorage = xSource->openStorageElement( aSubElements[nInd], embed::ElementModes::READ );
                    } catch( uno::Exception& )
                    {}

                    if ( !xSubStorage.is() )
                    {
                        // TODO/LATER: as optimization in future a substorage of target storage could be used
                        //             instead of the temporary storage; this substorage should be removed later
                        //             if the MimeType is wrong
                        xSubStorage = ::comphelper::OStorageHelper::GetTemporaryStorage();
                        xSource->copyStorageElementLastCommitTo( aSubElements[nInd], xSubStorage );
                    }

                    uno::Reference< beans::XPropertySet > xProps( xSubStorage, uno::UNO_QUERY_THROW );
                    bGotMediaType = ( xProps->getPropertyValue( aMediaTypePropName ) >>= aMediaType );
                }

                // TODO/LATER: there should be a way to detect whether an object with such a MediaType can exist
                //             probably it should be placed in the MimeType-ClassID table or in standalone table
                if ( aMediaType.getLength()
                  && aMediaType.compareToAscii( "application/vnd.sun.star.oleobject" ) != COMPARE_EQUAL )
                {
                    ::com::sun::star::datatransfer::DataFlavor aDataFlavor;
                    aDataFlavor.MimeType = aMediaType;
                    sal_uInt32 nFormat = SotExchange::GetFormat( aDataFlavor );

                    switch ( nFormat )
                    {
                        case SOT_FORMATSTR_ID_STARWRITER_60 :
                        case SOT_FORMATSTR_ID_STARWRITERWEB_60 :
                        case SOT_FORMATSTR_ID_STARWRITERGLOB_60 :
                        case SOT_FORMATSTR_ID_STARDRAW_60 :
                        case SOT_FORMATSTR_ID_STARIMPRESS_60 :
                        case SOT_FORMATSTR_ID_STARCALC_60 :
                        case SOT_FORMATSTR_ID_STARCHART_60 :
                        case SOT_FORMATSTR_ID_STARMATH_60 :
                        case SOT_FORMATSTR_ID_STARWRITER_8:
                        case SOT_FORMATSTR_ID_STARWRITERWEB_8:
                        case SOT_FORMATSTR_ID_STARWRITERGLOB_8:
                        case SOT_FORMATSTR_ID_STARDRAW_8:
                        case SOT_FORMATSTR_ID_STARIMPRESS_8:
                        case SOT_FORMATSTR_ID_STARCALC_8:
                        case SOT_FORMATSTR_ID_STARCHART_8:
                        case SOT_FORMATSTR_ID_STARMATH_8:
                            break;

                        default:
                        {
                            OSL_ENSURE(
                                aSubElements[nInd].equalsAscii( "Configurations2" ) || !xTarget->hasByName( aSubElements[nInd] ),
                                "The target storage is an output storage, the element should not exist in the target!\n" );

                            if ( !xTarget->hasByName( aSubElements[nInd] ) )
                            {
                                xSource->copyElementTo( aSubElements[nInd], xTarget, aSubElements[nInd] );
                            }
                        }
                    }
                }
            }
        }
    }
    catch( uno::Exception& )
    {
        bResult = sal_False;
        // TODO/LATER: a specific error could be provided
    }

    return bResult;
}

sal_Bool SfxObjectShell::GenerateAndStoreThumbnail( sal_Bool bEncrypted,
                                                    sal_Bool bSigned,
                                                    sal_Bool bIsTemplate,
                                                    const uno::Reference< embed::XStorage >& xStor )
{
    RTL_LOGFILE_CONTEXT( aLog, "sfx2 (mv76033) SfxObjectShell::GenerateAndStoreThumbnail" );

    sal_Bool bResult = sal_False;

    try {
        uno::Reference< embed::XStorage > xThumbnailStor =
                                        xStor->openStorageElement( ::rtl::OUString::createFromAscii( "Thumbnails" ),
                                                                    embed::ElementModes::READWRITE );
        if ( xThumbnailStor.is() )
        {
            uno::Reference< io::XStream > xStream = xThumbnailStor->openStreamElement(
                                                        ::rtl::OUString::createFromAscii( "thumbnail.png" ),
                                                        embed::ElementModes::READWRITE );

            if ( xStream.is() && WriteThumbnail( bEncrypted, bSigned, bIsTemplate, xStream ) )
            {
                uno::Reference< embed::XTransactedObject > xTransact( xThumbnailStor, uno::UNO_QUERY_THROW );
                xTransact->commit();
                bResult = sal_True;
            }
        }
    }
    catch( uno::Exception& )
    {
    }

    return bResult;
}

sal_Bool SfxObjectShell::WriteThumbnail( sal_Bool bEncrypted,
                                         sal_Bool bSigned,
                                         sal_Bool bIsTemplate,
                                         const uno::Reference< io::XStream >& xStream )
{
    sal_Bool bResult = sal_False;

    if ( xStream.is() )
    {
        try {
            uno::Reference< io::XTruncate > xTruncate( xStream->getOutputStream(), uno::UNO_QUERY_THROW );
            xTruncate->truncate();

            if ( bEncrypted )
            {
                sal_uInt16 nResID = GraphicHelper::getThumbnailReplacementIDByFactoryName_Impl(
                                        ::rtl::OUString::createFromAscii( GetFactory().GetShortName() ),
                                        bIsTemplate );
                if ( nResID )
                {
                    if ( !bSigned )
                    {
                        bResult = GraphicHelper::getThumbnailReplacement_Impl( nResID, xStream );
                    }
                    else
                    {
                        // retrieve the bitmap and write a signature bitmap over it
                        SfxResId aResId( nResID );
                        BitmapEx aThumbBitmap( aResId );
                        bResult = GraphicHelper::getSignedThumbnailFormatFromBitmap_Impl( aThumbBitmap, xStream );
                    }
                }
            }
            else
            {
                GDIMetaFile* pMetaFile = GetPreviewMetaFile( sal_False );
                if ( pMetaFile )
                {
                    bResult = GraphicHelper::getThumbnailFormatFromGDI_Impl( pMetaFile, bSigned, xStream );
                    delete pMetaFile;
                }
            }
        }
        catch( uno::Exception& )
        {}
    }

    return bResult;
}

void SfxObjectShell::UpdateLinks()
{
}

sal_Bool SfxObjectShell::QuerySaveSizeExceededModules_Impl( const uno::Reference< task::XInteractionHandler >& xHandler )
{
    uno::Sequence< rtl::OUString > sModules;
    if ( xHandler.is() )
    {
        SfxScriptLibraryContainer* pBasicCont = pImp->pBasicLibContainer;
        if( pBasicCont && pBasicCont->LegacyPsswdBinaryLimitExceeded( sModules ) )
        {
            ModuleSizeExceeded* pReq =  new ModuleSizeExceeded( sModules );
            uno::Reference< task::XInteractionRequest > xReq( pReq );
            xHandler->handle( xReq );
            return pReq->isApprove();
        }
    }

    // No interaction handler, default is to continue to save
    return sal_True;
}