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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <config_features.h>

#include <tools/inetmsg.hxx>
#include <tools/diagnose_ex.h>
#include <svl/eitem.hxx>
#include <svl/stritem.hxx>
#include <svl/intitem.hxx>
#include <svtools/svparser.hxx>
#include <cppuhelper/exc_hlp.hxx>
#include <sal/log.hxx>

#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/container/XChild.hpp>
#include <com/sun/star/document/XDocumentPropertiesSupplier.hpp>
#include <com/sun/star/document/XDocumentProperties.hpp>
#include <com/sun/star/document/MacroExecMode.hpp>
#include <com/sun/star/document/XScriptInvocationContext.hpp>
#include <com/sun/star/embed/EmbedStates.hpp>
#include <com/sun/star/embed/XEmbeddedObject.hpp>
#include <com/sun/star/script/provider/theMasterScriptProviderFactory.hpp>
#include <com/sun/star/script/provider/XScript.hpp>
#include <com/sun/star/script/provider/XScriptProvider.hpp>
#include <com/sun/star/script/provider/XScriptProviderSupplier.hpp>
#include <com/sun/star/uri/UriReferenceFactory.hpp>
#include <com/sun/star/uri/XVndSunStarScriptUrl.hpp>
#include <com/sun/star/util/XModifiable.hpp>

#include <toolkit/helper/vclunohelper.hxx>

#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/Any.h>
#include <com/sun/star/task/ErrorCodeRequest.hpp>

#include <comphelper/processfactory.hxx>
#include <comphelper/string.hxx>

#include <com/sun/star/security/DocumentDigitalSignatures.hpp>
#include <com/sun/star/task/DocumentMacroConfirmationRequest.hpp>
#include <com/sun/star/task/InteractionClassification.hpp>
#include <com/sun/star/task/XInteractionHandler.hpp>
#include <com/sun/star/frame/XModel.hpp>

#include <basic/basmgr.hxx>
#include <basic/sberrors.hxx>
#include <vcl/weld.hxx>
#include <basic/sbx.hxx>
#include <svtools/sfxecode.hxx>

#include <unotools/ucbhelper.hxx>
#include <tools/urlobj.hxx>
#include <svl/sharecontrolfile.hxx>
#include <rtl/uri.hxx>
#include <vcl/svapp.hxx>
#include <framework/interaction.hxx>
#include <framework/documentundoguard.hxx>
#include <comphelper/interaction.hxx>
#include <comphelper/storagehelper.hxx>
#include <comphelper/documentconstants.hxx>
#include <comphelper/namedvaluecollection.hxx>
#include <officecfg/Office/Common.hxx>

#include <sfx2/signaturestate.hxx>
#include <sfx2/app.hxx>
#include <appdata.hxx>
#include <sfx2/request.hxx>
#include <sfx2/bindings.hxx>
#include <sfx2/sfxresid.hxx>
#include <sfx2/docfile.hxx>
#include <sfx2/docfilt.hxx>
#include <sfx2/objsh.hxx>
#include <objshimp.hxx>
#include <sfx2/event.hxx>
#include <sfx2/viewfrm.hxx>
#include <sfx2/sfxuno.hxx>
#include <sfx2/module.hxx>
#include <sfx2/docfac.hxx>
#include <sfx2/sfxsids.hrc>
#include <sfx2/strings.hrc>
#include <workwin.hxx>
#include <sfx2/sfxdlg.hxx>
#include <sfx2/infobar.hxx>
#include <openflag.hxx>
#include "objstor.hxx"
#include <appopen.hxx>

#include <memory>

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::ucb;
using namespace ::com::sun::star::document;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::script;
using namespace ::com::sun::star::script::provider;
using namespace ::com::sun::star::container;

// class SfxHeaderAttributes_Impl ----------------------------------------

namespace {

class SfxHeaderAttributes_Impl : public SvKeyValueIterator
{
private:
    SfxObjectShell* pDoc;
    SvKeyValueIteratorRef xIter;
    bool bAlert;

public:
    explicit SfxHeaderAttributes_Impl( SfxObjectShell* pSh ) :
        SvKeyValueIterator(), pDoc( pSh ),
        xIter( pSh->GetMedium()->GetHeaderAttributes_Impl() ),
        bAlert( false ) {}

    virtual bool GetFirst( SvKeyValue& rKV ) override { return xIter->GetFirst( rKV ); }
    virtual bool GetNext( SvKeyValue& rKV ) override { return xIter->GetNext( rKV ); }
    virtual void Append( const SvKeyValue& rKV ) override;

    void ClearForSourceView() { xIter = new SvKeyValueIterator; bAlert = false; }
    void SetAttributes();
    void SetAttribute( const SvKeyValue& rKV );
};

}

sal_uInt16 const aTitleMap_Impl[3][2] =
{
                                //  local               remote
    /*  SFX_TITLE_CAPTION   */  {   SFX_TITLE_FILENAME, SFX_TITLE_TITLE },
    /*  SFX_TITLE_PICKLIST  */  {   32,                 SFX_TITLE_FULLNAME },
    /*  SFX_TITLE_HISTORY   */  {   32,                 SFX_TITLE_FULLNAME }
};


bool SfxObjectShell::IsAbortingImport() const
{
    return pImpl->bIsAbortingImport;
}


uno::Reference<document::XDocumentProperties>
SfxObjectShell::getDocProperties() const
{
    uno::Reference<document::XDocumentPropertiesSupplier> xDPS(
        GetModel(), uno::UNO_QUERY_THROW);
    uno::Reference<document::XDocumentProperties> xDocProps(
        xDPS->getDocumentProperties());
    DBG_ASSERT(xDocProps.is(),
        "SfxObjectShell: model has no DocumentProperties");
    return xDocProps;
}


void SfxObjectShell::DoFlushDocInfo()
{
}


// Note: the only thing that calls this is the modification event handler
// that is installed at the XDocumentProperties
void SfxObjectShell::FlushDocInfo()
{
    if ( IsLoading() )
        return;

    SetModified();
    uno::Reference<document::XDocumentProperties> xDocProps(getDocProperties());
    DoFlushDocInfo(); // call template method
    const OUString url(xDocProps->getAutoloadURL());
    sal_Int32 delay(xDocProps->getAutoloadSecs());
    SetAutoLoad( INetURLObject(url), delay * 1000,
                 (delay > 0) || !url.isEmpty() );
}

void SfxObjectShell::AppendInfoBarWhenReady(const OUString& sId, const OUString& sPrimaryMessage,
                                          const OUString& sSecondaryMessage,
                                          InfobarType aInfobarType, bool bShowCloseButton)
{
    InfobarData aInfobarData;
    aInfobarData.msId = sId;
    aInfobarData.msPrimaryMessage = sPrimaryMessage;
    aInfobarData.msSecondaryMessage = sSecondaryMessage;
    aInfobarData.maInfobarType = aInfobarType;
    aInfobarData.mbShowCloseButton = bShowCloseButton;
    Get_Impl()->m_aPendingInfobars.emplace_back(aInfobarData);
}

std::vector<InfobarData>& SfxObjectShell::getPendingInfobars()
{
    return Get_Impl()->m_aPendingInfobars;
}

void SfxObjectShell::SetError(ErrCode lErr)
{
    if (pImpl->lErr==ERRCODE_NONE)
    {
        pImpl->lErr=lErr;
    }
}

ErrCode SfxObjectShell::GetError() const
{
    return GetErrorCode().IgnoreWarning();
}

ErrCode SfxObjectShell::GetErrorCode() const
{
    ErrCode lError=pImpl->lErr;
    if(!lError && GetMedium())
        lError=GetMedium()->GetErrorCode();
    return lError;
}

void SfxObjectShell::ResetError()
{
    pImpl->lErr=ERRCODE_NONE;
    SfxMedium * pMed = GetMedium();
    if( pMed )
        pMed->ResetError();
}

void SfxObjectShell::EnableSetModified( bool bEnable )
{
    SAL_INFO_IF( bEnable == pImpl->m_bEnableSetModified, "sfx", "SFX_PERSIST: EnableSetModified 2x called with the same value" );
    pImpl->m_bEnableSetModified = bEnable;
}


bool SfxObjectShell::IsEnableSetModified() const
{
    return pImpl->m_bEnableSetModified && !IsReadOnly();
}


bool SfxObjectShell::IsModified() const
{
    if ( pImpl->m_bIsModified )
        return true;

    if ( !pImpl->m_xDocStorage.is() || IsReadOnly() )
    {
        // if the document still has no storage and is not set to be modified explicitly it is not modified
        // a readonly document is also not modified

        return false;
    }

    if (pImpl->mpObjectContainer)
    {
        const uno::Sequence < OUString > aNames = GetEmbeddedObjectContainer().GetObjectNames();
        for ( const auto& rName : aNames )
        {
            uno::Reference < embed::XEmbeddedObject > xObj = GetEmbeddedObjectContainer().GetEmbeddedObject( rName );
            OSL_ENSURE( xObj.is(), "An empty entry in the embedded objects list!" );
            if ( xObj.is() )
            {
                try
                {
                    sal_Int32 nState = xObj->getCurrentState();
                    if ( nState != embed::EmbedStates::LOADED )
                    {
                        uno::Reference< util::XModifiable > xModifiable( xObj->getComponent(), uno::UNO_QUERY );
                        if ( xModifiable.is() && xModifiable->isModified() )
                            return true;
                    }
                }
                catch( uno::Exception& )
                {}
            }
        }
    }

    return false;
}


void SfxObjectShell::SetModified( bool bModifiedP )
{
    SAL_INFO_IF( !bModifiedP && !IsEnableSetModified(), "sfx",
        "SFX_PERSIST: SetModified( sal_False ), although IsEnableSetModified() == sal_False" );

    if( !IsEnableSetModified() )
        return;

    if( pImpl->m_bIsModified != bModifiedP )
    {
        pImpl->m_bIsModified = bModifiedP;
        ModifyChanged();
    }
}


void SfxObjectShell::ModifyChanged()
{
    if ( pImpl->bClosing )
        // SetModified dispose of the models!
        return;


    SfxViewFrame* pViewFrame = SfxViewFrame::Current();
    if ( pViewFrame )
        pViewFrame->GetBindings().Invalidate( SID_SAVEDOCS );

    Invalidate( SID_SIGNATURE );
    Invalidate( SID_MACRO_SIGNATURE );
    Broadcast( SfxHint( SfxHintId::TitleChanged ) );    // xmlsec05, signed state might change in title...

    SfxGetpApp()->NotifyEvent( SfxEventHint( SfxEventHintId::ModifyChanged, GlobalEventConfig::GetEventName(GlobalEventId::MODIFYCHANGED), this ) );
}


bool SfxObjectShell::IsReadOnlyUI() const

/*  [Description]

    Returns sal_True if the document for the UI is treated as r/o. This is
    regardless of the actual r/o, which can be checked with <IsReadOnly()>.
*/

{
    return pImpl->bReadOnlyUI;
}


bool SfxObjectShell::IsReadOnlyMedium() const

/*  [Description]

    Returns sal_True when the medium is r/o, for instance when opened as r/o.
*/

{
    if ( !pMedium )
        return true;
    return pMedium->IsReadOnly();
}

bool SfxObjectShell::IsOriginallyReadOnlyMedium() const
{
    return pMedium == nullptr || pMedium->IsOriginallyReadOnly();
}

bool SfxObjectShell::IsOriginallyLoadedReadOnlyMedium() const
{
    return pMedium != nullptr && pMedium->IsOriginallyLoadedReadOnly();
}


void SfxObjectShell::SetReadOnlyUI( bool bReadOnly )

/*  [Description]

    Turns the document in a r/o and r/w state respectively without reloading
    it and without changing the open mode of the medium.
*/

{
    if ( bReadOnly != pImpl->bReadOnlyUI )
    {
        pImpl->bReadOnlyUI = bReadOnly;
        Broadcast( SfxHint(SfxHintId::ModeChanged) );
    }
}


void SfxObjectShell::SetReadOnly()
{
    // Let the document be completely readonly, means that the
    // medium open mode is adjusted accordingly, and the write lock
    // on the file is removed.

    if ( !pMedium || IsReadOnlyMedium() )
        return;

    bool bWasROUI = IsReadOnly();

    pMedium->UnlockFile( false );

    // the storage-based mediums are already based on the temporary file
    // so UnlockFile has already closed the locking stream
    if ( !pMedium->HasStorage_Impl() && IsLoadingFinished() )
        pMedium->CloseInStream();

    pMedium->SetOpenMode( SFX_STREAM_READONLY, true );
    pMedium->GetItemSet()->Put( SfxBoolItem( SID_DOC_READONLY, true ) );

    if ( !bWasROUI )
        Broadcast( SfxHint(SfxHintId::ModeChanged) );
}


bool SfxObjectShell::IsReadOnly() const
{
    return pImpl->bReadOnlyUI || pMedium == nullptr;
}


bool SfxObjectShell::IsInModalMode() const
{
    return pImpl->bModalMode || pImpl->bRunningMacro;
}

bool SfxObjectShell::AcceptStateUpdate() const
{
    return !IsInModalMode();
}


void SfxObjectShell::SetMacroMode_Impl( bool bModal )
{
    if ( !pImpl->bRunningMacro != !bModal )
    {
        pImpl->bRunningMacro = bModal;
        Broadcast( SfxHint( SfxHintId::ModeChanged ) );
    }
}


void SfxObjectShell::SetModalMode_Impl( bool bModal )
{
    // Broadcast only if modified, or otherwise it will possibly go into
    // an endless loop
    if ( pImpl->bModalMode == bModal )
        return;

    // Central count
    sal_uInt16 &rDocModalCount = SfxGetpApp()->Get_Impl()->nDocModalMode;
    if ( bModal )
        ++rDocModalCount;
    else
        --rDocModalCount;

    // Switch
    pImpl->bModalMode = bModal;
    Broadcast( SfxHint( SfxHintId::ModeChanged ) );
}

#if HAVE_FEATURE_MULTIUSER_ENVIRONMENT

bool SfxObjectShell::SwitchToShared( bool bShared, bool bSave )
{
    bool bResult = true;

    if ( bShared != IsDocShared() )
    {
        OUString aOrigURL = GetMedium()->GetURLObject().GetMainURL( INetURLObject::DecodeMechanism::NONE );

        if ( aOrigURL.isEmpty() && bSave )
        {
            // this is a new document, let it be stored before switching to the shared mode;
            // the storing should be done without shared flag, since it is possible that the
            // target location does not allow to create sharing control file;
            // the shared flag will be set later after creation of sharing control file
            SfxViewFrame* pViewFrame = SfxViewFrame::GetFirst( this );

            if ( pViewFrame )
            {
                // TODO/LATER: currently the application guards against the reentrance problem
                const SfxPoolItem* pItem = pViewFrame->GetBindings().ExecuteSynchron( HasName() ? SID_SAVEDOC : SID_SAVEASDOC );
                const SfxBoolItem* pResult = dynamic_cast<const SfxBoolItem*>( pItem  );
                bResult = ( pResult && pResult->GetValue() );
                if ( bResult )
                    aOrigURL = GetMedium()->GetURLObject().GetMainURL( INetURLObject::DecodeMechanism::NONE );
            }
        }

        bool bOldValue = HasSharedXMLFlagSet();
        SetSharedXMLFlag( bShared );

        bool bRemoveEntryOnError = false;
        if ( bResult && bShared )
        {
            try
            {
                ::svt::ShareControlFile aControlFile( aOrigURL );
                aControlFile.InsertOwnEntry();
                bRemoveEntryOnError = true;
            }
            catch( uno::Exception& )
            {
                bResult = false;
            }
        }

        if ( bResult && bSave )
        {
            SfxViewFrame* pViewFrame = SfxViewFrame::GetFirst( this );

            if ( pViewFrame )
            {
                // TODO/LATER: currently the application guards against the reentrance problem
                SetModified(); // the modified flag has to be set to let the document be stored with the shared flag
                const SfxPoolItem* pItem = pViewFrame->GetBindings().ExecuteSynchron( HasName() ? SID_SAVEDOC : SID_SAVEASDOC );
                const SfxBoolItem* pResult = dynamic_cast<const SfxBoolItem*>( pItem  );
                bResult = ( pResult && pResult->GetValue() );
            }
        }

        if ( bResult )
        {
            // TODO/LATER: Is it possible that the following calls fail?
            if ( bShared )
            {
                pImpl->m_aSharedFileURL = aOrigURL;
                GetMedium()->SwitchDocumentToTempFile();
            }
            else
            {
                const OUString aTempFileURL = pMedium->GetURLObject().GetMainURL( INetURLObject::DecodeMechanism::NONE );
                GetMedium()->SwitchDocumentToFile( GetSharedFileURL() );
                pImpl->m_aSharedFileURL.clear();

                // now remove the temporary file the document was based on
                ::utl::UCBContentHelper::Kill( aTempFileURL );

                try
                {
                    // aOrigURL can not be used since it contains an old value
                    ::svt::ShareControlFile aControlFile( GetMedium()->GetURLObject().GetMainURL( INetURLObject::DecodeMechanism::NONE ) );
                    aControlFile.RemoveFile();
                }
                catch( uno::Exception& )
                {
                }
            }
        }
        else
        {
            // the saving has failed!
            if ( bRemoveEntryOnError )
            {
                try
                {
                    ::svt::ShareControlFile aControlFile( aOrigURL );
                    aControlFile.RemoveEntry();
                }
                catch( uno::Exception& )
                {}
            }

            SetSharedXMLFlag( bOldValue );
        }
    }
    else
        bResult = false; // the second switch to the same mode

    if ( bResult )
        SetTitle( "" );

    return bResult;
}


void SfxObjectShell::FreeSharedFile( const OUString& aTempFileURL )
{
    SetSharedXMLFlag( false );

    if ( !IsDocShared() || aTempFileURL.isEmpty()
      || ::utl::UCBContentHelper::EqualURLs( aTempFileURL, GetSharedFileURL() ) )
        return;

    if ( pImpl->m_bAllowShareControlFileClean )
    {
        try
        {
            ::svt::ShareControlFile aControlFile( GetSharedFileURL() );
            aControlFile.RemoveEntry();
        }
        catch( uno::Exception& )
        {
        }
    }

    // the cleaning is forbidden only once
    pImpl->m_bAllowShareControlFileClean = true;

    // now remove the temporary file the document is based currently on
    ::utl::UCBContentHelper::Kill( aTempFileURL );

    pImpl->m_aSharedFileURL.clear();
}


void SfxObjectShell::DoNotCleanShareControlFile()
{
    pImpl->m_bAllowShareControlFileClean = false;
}


void SfxObjectShell::SetSharedXMLFlag( bool bFlag ) const
{
    pImpl->m_bSharedXMLFlag = bFlag;
}


bool SfxObjectShell::HasSharedXMLFlagSet() const
{
    return pImpl->m_bSharedXMLFlag;
}

#endif

bool SfxObjectShell::IsDocShared() const
{
#if HAVE_FEATURE_MULTIUSER_ENVIRONMENT
    return ( !pImpl->m_aSharedFileURL.isEmpty() );
#else
    return false;
#endif
}


OUString SfxObjectShell::GetSharedFileURL() const
{
#if HAVE_FEATURE_MULTIUSER_ENVIRONMENT
    return pImpl->m_aSharedFileURL;
#else
    return OUString();
#endif
}

Size SfxObjectShell::GetFirstPageSize() const
{
    return GetVisArea(ASPECT_THUMBNAIL).GetSize();
}


IndexBitSet& SfxObjectShell::GetNoSet_Impl()
{
    return pImpl->aBitSet;
}


// changes the title of the document

void SfxObjectShell::SetTitle
(
    const OUString& rTitle                // the new Document Title
)

/*  [Description]

    With this method, the title of the document can be set.
    This corresponds initially to the full file name. A setting of the
    title does not affect the file name, but it will be shown in the
    Caption-Bars of the MDI-window.
*/

{

    // Nothing to do?
    if ( ( ( HasName() && pImpl->aTitle == rTitle )
        || ( !HasName() && GetTitle() == rTitle ) )
      && !IsDocShared() )
        return;

    SfxApplication *pSfxApp = SfxGetpApp();

    // If possible release the unnamed number.
    if ( pImpl->bIsNamedVisible && USHRT_MAX != pImpl->nVisualDocumentNumber )
    {
        pSfxApp->ReleaseIndex(pImpl->nVisualDocumentNumber);
        pImpl->bIsNamedVisible = false;
    }

    // Set Title
    pImpl->aTitle = rTitle;

    // Notification
    if ( GetMedium() )
    {
        SfxShell::SetName( GetTitle(SFX_TITLE_APINAME) );
        Broadcast( SfxHint(SfxHintId::TitleChanged) );
    }
}



OUString SfxObjectShell::GetTitle( sal_uInt16  nMaxLength ) const

/*  [Description]

    Returns the title or logical file name of the document, depending on the
    'nMaxLength'.

    If the file name with path is used, the Name shortened by replacing one or
    more directory names with "...", URLs are currently always returned
    in complete form.
*/

{
    SfxMedium *pMed = GetMedium();
    if ( IsLoading() )
        return OUString();

    // Create Title?
    if ( SFX_TITLE_DETECT == nMaxLength && pImpl->aTitle.isEmpty() )
    {
        static bool bRecur = false;
        if ( bRecur )
            return "-not available-";
        bRecur = true;

        OUString aTitle;

        if ( pMed )
        {
            const SfxStringItem* pNameItem = SfxItemSet::GetItem<SfxStringItem>(pMed->GetItemSet(), SID_DOCINFO_TITLE, false);
            if ( pNameItem )
                aTitle = pNameItem->GetValue();
        }

        if ( aTitle.isEmpty() )
            aTitle = GetTitle( SFX_TITLE_FILENAME );

        bRecur = false;
        return aTitle;
    }

    if (SFX_TITLE_APINAME == nMaxLength )
        return GetAPIName();

    // Picklist/Caption is mapped
    if ( pMed && ( nMaxLength == SFX_TITLE_CAPTION || nMaxLength == SFX_TITLE_PICKLIST ) )
    {
        // If a specific title was given at open:
        // important for URLs: use INetProtocol::File for which the set title is not
        // considered. (See below, analysis of aTitleMap_Impl)
        const SfxStringItem* pNameItem = SfxItemSet::GetItem<SfxStringItem>(pMed->GetItemSet(), SID_DOCINFO_TITLE, false);
        if ( pNameItem )
            return pNameItem->GetValue();
    }

    // Still unnamed?
    DBG_ASSERT( !HasName() || pMed, "HasName() but no Medium?!?" );
    if ( !HasName() || !pMed )
    {
        // Title already set?
        if ( !pImpl->aTitle.isEmpty() )
            return pImpl->aTitle;

        // must it be numbered?
        const OUString aNoName(SfxResId(STR_NONAME));
        if (pImpl->bIsNamedVisible)
        {
            // Append number
            return aNoName + " " + OUString::number(pImpl->nVisualDocumentNumber);
        }

        // Document called "Untitled" for the time being
        return aNoName;
    }
    assert(pMed);

    const INetURLObject aURL( IsDocShared() ? GetSharedFileURL() : GetMedium()->GetName() );
    if ( nMaxLength > SFX_TITLE_CAPTION && nMaxLength <= SFX_TITLE_HISTORY )
    {
        sal_uInt16 nRemote;
        if (aURL.GetProtocol() == INetProtocol::File)
            nRemote = 0;
        else
            nRemote = 1;
        nMaxLength = aTitleMap_Impl[nMaxLength-SFX_TITLE_CAPTION][nRemote];
    }

    // Local file?
    if ( aURL.GetProtocol() == INetProtocol::File )
    {
        if ( nMaxLength == SFX_TITLE_FULLNAME )
            return aURL.HasMark() ? INetURLObject( aURL.GetURLNoMark() ).PathToFileName() : aURL.PathToFileName();
        if ( nMaxLength == SFX_TITLE_FILENAME )
            return aURL.getName(INetURLObject::LAST_SEGMENT, true, INetURLObject::DecodeMechanism::WithCharset);
        if ( pImpl->aTitle.isEmpty() )
            pImpl->aTitle = aURL.getBase( INetURLObject::LAST_SEGMENT,
                                         true, INetURLObject::DecodeMechanism::WithCharset );
    }
    else
    {
        if ( nMaxLength >= SFX_TITLE_MAXLEN )
        {
            const OUString aComplete( aURL.GetMainURL( INetURLObject::DecodeMechanism::NONE ) );
            if( aComplete.getLength() > nMaxLength )
                return "..." + aComplete.copy( aComplete.getLength() - nMaxLength + 3, nMaxLength - 3 );
            return aComplete;
        }
        if ( nMaxLength == SFX_TITLE_FILENAME )
        {
            const OUString aName = INetURLObject::decode( aURL.GetBase(), INetURLObject::DecodeMechanism::WithCharset );
            return aName.isEmpty() ? aURL.GetURLNoPass() : aName;
        }
        if ( nMaxLength == SFX_TITLE_FULLNAME )
            return aURL.GetMainURL( INetURLObject::DecodeMechanism::ToIUri );

        // Generate Title from file name if possible
        if ( pImpl->aTitle.isEmpty() )
            pImpl->aTitle = aURL.GetBase();

        // workaround for the case when the name can not be retrieved from URL by INetURLObject
        if ( pImpl->aTitle.isEmpty() )
            pImpl->aTitle = aURL.GetMainURL( INetURLObject::DecodeMechanism::WithCharset );
    }

    // Complete Title
    return pImpl->aTitle;
}


void SfxObjectShell::InvalidateName()

/*  [Description]

    Returns the title of the new document, DocInfo-Title or
    File name. Is required for loading from template or SaveAs.
*/

{
    pImpl->aTitle.clear();
    SetName( GetTitle( SFX_TITLE_APINAME ) );

    Broadcast( SfxHint(SfxHintId::TitleChanged) );
}


void SfxObjectShell::SetNamedVisibility_Impl()
{
    if ( !pImpl->bIsNamedVisible )
    {
        pImpl->bIsNamedVisible = true;
        if ( !HasName() && USHRT_MAX == pImpl->nVisualDocumentNumber && pImpl->aTitle.isEmpty() )
        {
            pImpl->nVisualDocumentNumber = SfxGetpApp()->GetFreeIndex();
            Broadcast( SfxHint(SfxHintId::TitleChanged) );
        }
    }

    SetName( GetTitle(SFX_TITLE_APINAME) );
}

void SfxObjectShell::SetNoName()
{
    bHasName = false;
    GetModel()->attachResource( OUString(), GetModel()->getArgs() );
}


SfxProgress* SfxObjectShell::GetProgress() const
{
    return pImpl->pProgress;
}


void SfxObjectShell::SetProgress_Impl
(
    SfxProgress *pProgress      /* to started <SfxProgress> or 0,
                                   if the progress is to be reset */
)

/*  [Description]

    Internal method to set or reset the Progress modes for
    SfxObjectShell.
*/

{
    DBG_ASSERT( ( !pImpl->pProgress && pProgress ) ||
                ( pImpl->pProgress && !pProgress ),
                "Progress activation/deactivation mismatch" );
    pImpl->pProgress = pProgress;
}


void SfxObjectShell::PostActivateEvent_Impl( SfxViewFrame const * pFrame )
{
    SfxApplication* pSfxApp = SfxGetpApp();
    if ( pSfxApp->IsDowning() || IsLoading() || !pFrame || pFrame->GetFrame().IsClosing_Impl() )
        return;

    const SfxBoolItem* pHiddenItem = SfxItemSet::GetItem<SfxBoolItem>(pMedium->GetItemSet(), SID_HIDDEN, false);
    if ( !pHiddenItem || !pHiddenItem->GetValue() )
    {
        SfxEventHintId nId = pImpl->nEventId;
        pImpl->nEventId = SfxEventHintId::NONE;
        if ( nId == SfxEventHintId::OpenDoc )
            pSfxApp->NotifyEvent(SfxViewEventHint( nId, GlobalEventConfig::GetEventName(GlobalEventId::OPENDOC), this, pFrame->GetFrame().GetController() ), false);
        else if (nId == SfxEventHintId::CreateDoc )
            pSfxApp->NotifyEvent(SfxViewEventHint( nId, GlobalEventConfig::GetEventName(GlobalEventId::CREATEDOC), this, pFrame->GetFrame().GetController() ), false);
    }
}


void SfxObjectShell::SetActivateEvent_Impl(SfxEventHintId nId )
{
    pImpl->nEventId = nId;
}

bool SfxObjectShell::IsAutoLoadLocked() const

/* Returns whether an Autoload is allowed to be executed. Before the
   surrounding FrameSet of the AutoLoad is also taken into account as well.
*/

{
    return !IsReadOnly();
}


void SfxObjectShell::BreakMacroSign_Impl( bool bBreakMacroSign )
{
    pImpl->m_bMacroSignBroken = bBreakMacroSign;
}


void SfxObjectShell::CheckSecurityOnLoading_Impl()
{
    // make sure LO evaluates the macro signatures, so it can be preserved
    GetScriptingSignatureState();

    uno::Reference< task::XInteractionHandler > xInteraction;
    if ( GetMedium() )
        xInteraction = GetMedium()->GetInteractionHandler();

    // check if there is a broken signature...
    CheckForBrokenDocSignatures_Impl();

    CheckEncryption_Impl( xInteraction );

    // check macro security
    pImpl->aMacroMode.checkMacrosOnLoading( xInteraction );
}


void SfxObjectShell::CheckEncryption_Impl( const uno::Reference< task::XInteractionHandler >& xHandler )
{
    OUString aVersion;
    bool bIsEncrypted = false;<--- 'bIsEncrypted' is assigned value 'false' here.
    bool bHasNonEncrypted = false;<--- 'bHasNonEncrypted' is assigned value 'false' here.

    try
    {
        uno::Reference < beans::XPropertySet > xPropSet( GetStorage(), uno::UNO_QUERY_THROW );
        xPropSet->getPropertyValue("Version") >>= aVersion;
        xPropSet->getPropertyValue("HasEncryptedEntries") >>= bIsEncrypted;
        xPropSet->getPropertyValue("HasNonEncryptedEntries") >>= bHasNonEncrypted;
    }
    catch( uno::Exception& )
    {
    }

    if ( aVersion.compareTo( ODFVER_012_TEXT ) < 0 )
        return;

    // this is ODF1.2 or later
    if ( !(bIsEncrypted && bHasNonEncrypted) )
        return;

    if ( !pImpl->m_bIncomplEncrWarnShown )
    {
        // this is an encrypted document with nonencrypted streams inside, show the warning
        css::task::ErrorCodeRequest aErrorCode;
        aErrorCode.ErrCode = sal_uInt32(ERRCODE_SFX_INCOMPLETE_ENCRYPTION);

        SfxMedium::CallApproveHandler( xHandler, uno::makeAny( aErrorCode ), false );
        pImpl->m_bIncomplEncrWarnShown = true;
    }

    // broken signatures imply no macro execution at all
    pImpl->aMacroMode.disallowMacroExecution();
}


void SfxObjectShell::CheckForBrokenDocSignatures_Impl()
{
    SignatureState nSignatureState = GetDocumentSignatureState();
    bool bSignatureBroken = ( nSignatureState == SignatureState::BROKEN );
    if ( !bSignatureBroken )
        return;

    // broken signatures imply no macro execution at all
    pImpl->aMacroMode.disallowMacroExecution();
}


void SfxObjectShell::SetAutoLoad(
    const INetURLObject& rUrl, sal_uInt32 nTime, bool bReload )
{
    pImpl->pReloadTimer.reset();
    if ( bReload )
    {
        pImpl->pReloadTimer.reset(new AutoReloadTimer_Impl(
                                rUrl.GetMainURL( INetURLObject::DecodeMechanism::ToIUri ),
                                nTime, this ));
        pImpl->pReloadTimer->Start();
    }
}

void SfxObjectShell::SetLoading(SfxLoadedFlags nFlags)
{
    pImpl->nLoadedFlags = nFlags;
}

bool SfxObjectShell::IsLoadingFinished() const
{
    return ( pImpl->nLoadedFlags == SfxLoadedFlags::ALL );
}

void SfxObjectShell::InitOwnModel_Impl()
{
    if ( pImpl->bModelInitialized )
        return;

    const SfxStringItem* pSalvageItem = SfxItemSet::GetItem<SfxStringItem>(pMedium->GetItemSet(), SID_DOC_SALVAGE, false);
    if ( pSalvageItem )
    {
        pImpl->aTempName = pMedium->GetPhysicalName();
        pMedium->GetItemSet()->ClearItem( SID_DOC_SALVAGE );
        pMedium->GetItemSet()->ClearItem( SID_FILE_NAME );
        pMedium->GetItemSet()->Put( SfxStringItem( SID_FILE_NAME, pMedium->GetOrigURL() ) );
    }
    else
    {
        pMedium->GetItemSet()->ClearItem( SID_PROGRESS_STATUSBAR_CONTROL );
        pMedium->GetItemSet()->ClearItem( SID_DOCUMENT );
    }

    pMedium->GetItemSet()->ClearItem( SID_REFERER );
    uno::Reference< frame::XModel >  xModel = GetModel();
    if ( xModel.is() )
    {
        SfxItemSet *pSet = GetMedium()->GetItemSet();
        if ( !GetMedium()->IsReadOnly() )
            pSet->ClearItem( SID_INPUTSTREAM );
        uno::Sequence< beans::PropertyValue > aArgs;
        TransformItems( SID_OPENDOC, *pSet, aArgs );
        xModel->attachResource( GetMedium()->GetOrigURL(), aArgs );
        impl_addToModelCollection(xModel);
    }

    pImpl->bModelInitialized = true;
}

void SfxObjectShell::FinishedLoading( SfxLoadedFlags nFlags )
{
    bool bSetModifiedTRUE = false;
    const SfxStringItem* pSalvageItem = SfxItemSet::GetItem<SfxStringItem>(pMedium->GetItemSet(), SID_DOC_SALVAGE, false);
    if( ( nFlags & SfxLoadedFlags::MAINDOCUMENT ) && !(pImpl->nLoadedFlags & SfxLoadedFlags::MAINDOCUMENT )
        && !(pImpl->nFlagsInProgress & SfxLoadedFlags::MAINDOCUMENT ))
    {
        pImpl->nFlagsInProgress |= SfxLoadedFlags::MAINDOCUMENT;
        static_cast<SfxHeaderAttributes_Impl*>(GetHeaderAttributes())->SetAttributes();

        if ( ( GetModifyPasswordHash() || GetModifyPasswordInfo().hasElements() ) && !IsModifyPasswordEntered() )
            SetReadOnly();

        // Salvage
        if ( pSalvageItem )
            bSetModifiedTRUE = true;

        if ( !IsEnableSetModified() )
            EnableSetModified();

        if( !bSetModifiedTRUE && IsEnableSetModified() )
            SetModified( false );

        CheckSecurityOnLoading_Impl();

        bHasName = true; // the document is loaded, so the name should already available
        GetTitle( SFX_TITLE_DETECT );
        InitOwnModel_Impl();
        pImpl->nFlagsInProgress &= ~SfxLoadedFlags::MAINDOCUMENT;
    }

    if( ( nFlags & SfxLoadedFlags::IMAGES ) && !(pImpl->nLoadedFlags & SfxLoadedFlags::IMAGES )
        && !(pImpl->nFlagsInProgress & SfxLoadedFlags::IMAGES ))
    {
        pImpl->nFlagsInProgress |= SfxLoadedFlags::IMAGES;
        uno::Reference<document::XDocumentProperties> xDocProps(
            getDocProperties());
        const OUString url(xDocProps->getAutoloadURL());
        sal_Int32 delay(xDocProps->getAutoloadSecs());
        SetAutoLoad( INetURLObject(url), delay * 1000,
                     (delay > 0) || !url.isEmpty() );
        if( !bSetModifiedTRUE && IsEnableSetModified() )
            SetModified( false );
        Invalidate( SID_SAVEASDOC );
        pImpl->nFlagsInProgress &= ~SfxLoadedFlags::IMAGES;
    }

    pImpl->nLoadedFlags |= nFlags;

    if ( pImpl->nFlagsInProgress != SfxLoadedFlags::NONE )
        return;

    // in case of reentrance calls the first called FinishedLoading() call on the stack
    // should do the notification, in result the notification is done when all the FinishedLoading() calls are finished

    if ( bSetModifiedTRUE )
        SetModified();
    else
        SetModified( false );

    if ( (pImpl->nLoadedFlags & SfxLoadedFlags::MAINDOCUMENT ) && (pImpl->nLoadedFlags & SfxLoadedFlags::IMAGES ) )
    {
        const SfxBoolItem* pTemplateItem = SfxItemSet::GetItem<SfxBoolItem>(pMedium->GetItemSet(), SID_TEMPLATE, false);
        bool bTemplate = pTemplateItem && pTemplateItem->GetValue();

        // closing the streams on loading should be under control of SFX!
        DBG_ASSERT( pMedium->IsOpen(), "Don't close the medium when loading documents!" );

        if ( bTemplate )
        {
            TemplateDisconnectionAfterLoad();
        }
        else
        {
            // if a readonly medium has storage then it's stream is already based on temporary file
            if( !(pMedium->GetOpenMode() & StreamMode::WRITE) && !pMedium->HasStorage_Impl() )
                // don't lock file opened read only
                pMedium->CloseInStream();
        }
    }

    SetInitialized_Impl( false );

    // Title is not available until loading has finished
    Broadcast( SfxHint( SfxHintId::TitleChanged ) );
    if ( pImpl->nEventId != SfxEventHintId::NONE )
        PostActivateEvent_Impl(SfxViewFrame::GetFirst(this));
}

void SfxObjectShell::TemplateDisconnectionAfterLoad()
{
    // document is created from a template
    //TODO/LATER: should the templates always be XML docs!

    SfxMedium* pTmpMedium = pMedium;
    if ( !pTmpMedium )
        return;

    const OUString aName( pTmpMedium->GetName() );
    const SfxStringItem* pTemplNamItem = SfxItemSet::GetItem<SfxStringItem>(pTmpMedium->GetItemSet(), SID_TEMPLATE_NAME, false);
    OUString aTemplateName;
    if ( pTemplNamItem )
        aTemplateName = pTemplNamItem->GetValue();
    else
    {
        // !TODO/LATER: what's this?!
        // Interactive ( DClick, Contextmenu ) no long name is included
        aTemplateName = getDocProperties()->getTitle();
        if ( aTemplateName.isEmpty() )
        {
            INetURLObject aURL( aName );
            aURL.CutExtension();
            aTemplateName = aURL.getName( INetURLObject::LAST_SEGMENT, true, INetURLObject::DecodeMechanism::WithCharset );
        }
    }

    // set medium to noname
    pTmpMedium->SetName( OUString(), true );
    pTmpMedium->Init_Impl();

    // drop resource
    SetNoName();
    InvalidateName();

    if( IsPackageStorageFormat_Impl( *pTmpMedium ) )
    {
        // untitled document must be based on temporary storage
        // the medium should not dispose the storage in this case
        uno::Reference < embed::XStorage > xTmpStor = ::comphelper::OStorageHelper::GetTemporaryStorage();
        GetStorage()->copyToStorage( xTmpStor );

        // the medium should disconnect from the original location
        // the storage should not be disposed since the document is still
        // based on it, but in DoSaveCompleted it will be disposed
        pTmpMedium->CanDisposeStorage_Impl( false );
        pTmpMedium->Close();

        // setting the new storage the medium will be based on
        pTmpMedium->SetStorage_Impl( xTmpStor );

        pMedium = nullptr;
        bool ok = DoSaveCompleted( pTmpMedium );
        assert(pMedium != nullptr);
        if( ok )
        {
            const SfxStringItem* pSalvageItem = SfxItemSet::GetItem<SfxStringItem>(pMedium->GetItemSet(), SID_DOC_SALVAGE, false);
            bool bSalvage = pSalvageItem != nullptr;

            if ( !bSalvage )
            {
                // some further initializations for templates
                SetTemplate_Impl( aName, aTemplateName, this );
            }

            // the medium should not dispose the storage, DoSaveCompleted() has let it to do so
            pTmpMedium->CanDisposeStorage_Impl( false );
        }
        else
        {
            SetError(ERRCODE_IO_GENERAL);
        }
    }
    else
    {
        // some further initializations for templates
        SetTemplate_Impl( aName, aTemplateName, this );
        pTmpMedium->CreateTempFile();
    }

    // templates are never readonly
    pTmpMedium->GetItemSet()->ClearItem( SID_DOC_READONLY );
    pTmpMedium->SetOpenMode( SFX_STREAM_READWRITE, true );

    // notifications about possible changes in readonly state and document info
    Broadcast( SfxHint(SfxHintId::ModeChanged) );

    // created untitled document can't be modified
    SetModified( false );
}


bool SfxObjectShell::IsLoading() const
/*  [Description]

    Has FinishedLoading been called?
*/
{
    return !( pImpl->nLoadedFlags & SfxLoadedFlags::MAINDOCUMENT );
}


void SfxObjectShell::CancelTransfers()
/*  [Description]

    Here can Transfers get canceled, which were not registered
    by RegisterTransfer.
*/
{
    if( ( pImpl->nLoadedFlags & SfxLoadedFlags::ALL ) != SfxLoadedFlags::ALL )
    {
        pImpl->bIsAbortingImport = true;
        if( IsLoading() )
            FinishedLoading();
    }
}


AutoReloadTimer_Impl::AutoReloadTimer_Impl(
    const OUString& rURL, sal_uInt32 nTime, SfxObjectShell* pSh )
    : aUrl( rURL ), pObjSh( pSh )
{
    SetTimeout( nTime );
}


void AutoReloadTimer_Impl::Invoke()
{
    SfxViewFrame *pFrame = SfxViewFrame::GetFirst( pObjSh );

    if ( pFrame )
    {
        // Not possible/meaningful at the moment?
        if ( !pObjSh->CanReload_Impl() || pObjSh->IsAutoLoadLocked() || Application::IsUICaptured() )
        {
            // Allow a retry
            Start();
            return;
        }

        SfxAllItemSet aSet( SfxGetpApp()->GetPool() );
        aSet.Put( SfxBoolItem( SID_AUTOLOAD, true ) );
        if ( !aUrl.isEmpty() )
            aSet.Put(  SfxStringItem( SID_FILE_NAME, aUrl ) );
        if (pObjSh->HasName()) {
            aSet.Put(
                SfxStringItem(SID_REFERER, pObjSh->GetMedium()->GetName()));
        }
        SfxRequest aReq( SID_RELOAD, SfxCallMode::SLOT, aSet );
        // this will delete this
        pObjSh->Get_Impl()->pReloadTimer.reset();
        pFrame->ExecReload_Impl( aReq );
        return;
    }

    // this will delete this
    pObjSh->Get_Impl()->pReloadTimer.reset();
}

SfxModule* SfxObjectShell::GetModule() const
{
    return GetFactory().GetModule();
}

ErrCode SfxObjectShell::CallBasic( const OUString& rMacro,
    const OUString& rBasic, SbxArray* pArgs,
    SbxValue* pRet )
{
    SfxApplication* pApp = SfxGetpApp();
    if( pApp->GetName() != rBasic )
    {
        if ( !AdjustMacroMode() )
            return ERRCODE_IO_ACCESSDENIED;
    }

    BasicManager *pMgr = GetBasicManager();
    if( pApp->GetName() == rBasic )
        pMgr = SfxApplication::GetBasicManager();
    ErrCode nRet = SfxApplication::CallBasic( rMacro, pMgr, pArgs, pRet );
    return nRet;
}

bool SfxObjectShell::isScriptAccessAllowed( const Reference< XInterface >& _rxScriptContext )
{
    try
    {
        Reference< XEmbeddedScripts > xScripts( _rxScriptContext, UNO_QUERY );
        if ( !xScripts.is() )
        {
            Reference< XScriptInvocationContext > xContext( _rxScriptContext, UNO_QUERY_THROW );
            xScripts.set( xContext->getScriptContainer(), UNO_SET_THROW );
        }

        return xScripts->getAllowMacroExecution();
    }
    catch( const Exception& )
    {
        DBG_UNHANDLED_EXCEPTION("sfx.doc");
    }
    return false;
}

// don't allow LibreLogo to be used with our mouseover/etc dom-alike events
bool SfxObjectShell::UnTrustedScript(const OUString& rScriptURL)
{
    if (!rScriptURL.startsWith("vnd.sun.star.script:"))
        return false;

    // ensure URL Escape Codes are decoded
    css::uno::Reference<css::uri::XUriReference> uri(
        css::uri::UriReferenceFactory::create(comphelper::getProcessComponentContext())->parse(rScriptURL));
    css::uno::Reference<css::uri::XVndSunStarScriptUrl> sfUri(uri, css::uno::UNO_QUERY);

    if (!sfUri.is())
        return false;

    // pyuno encodes path separator as |
    OUString sScript = sfUri->getName().replace('|', '/');

    // check if any path portion matches LibreLogo and ban it if it does
    sal_Int32 nIndex = 0;
    do
    {
        OUString aToken = sScript.getToken(0, '/', nIndex);
        if (aToken.startsWithIgnoreAsciiCase("LibreLogo") || aToken.indexOf('~') != -1)
        {
            return true;
        }
    }
    while (nIndex >= 0);

    return false;
}

ErrCode SfxObjectShell::CallXScript( const Reference< XInterface >& _rxScriptContext, const OUString& _rScriptURL,
    const Sequence< Any >& aParams, Any& aRet, Sequence< sal_Int16 >& aOutParamIndex, Sequence< Any >& aOutParam, bool bRaiseError, const css::uno::Any* pCaller )
{
    SAL_INFO("sfx", "in CallXScript" );
    ErrCode nErr = ERRCODE_NONE;

    bool bCaughtException = false;
    Any aException;
    try
    {
        if (!isScriptAccessAllowed(_rxScriptContext))
            return ERRCODE_IO_ACCESSDENIED;

        if ( UnTrustedScript(_rScriptURL) )
            return ERRCODE_IO_ACCESSDENIED;

        // obtain/create a script provider
        Reference< provider::XScriptProvider > xScriptProvider;
        Reference< provider::XScriptProviderSupplier > xSPS( _rxScriptContext, UNO_QUERY );
        if ( xSPS.is() )
            xScriptProvider.set( xSPS->getScriptProvider() );

        if ( !xScriptProvider.is() )
        {
            Reference< provider::XScriptProviderFactory > xScriptProviderFactory =
                provider::theMasterScriptProviderFactory::get( ::comphelper::getProcessComponentContext() );
            xScriptProvider.set( xScriptProviderFactory->createScriptProvider( makeAny( _rxScriptContext ) ), UNO_SET_THROW );
        }

        // ry to protect the invocation context's undo manager (if present), just in case the script tampers with it
        ::framework::DocumentUndoGuard aUndoGuard( _rxScriptContext.get() );

        // obtain the script, and execute it
        Reference< provider::XScript > xScript( xScriptProvider->getScript( _rScriptURL ), UNO_SET_THROW );
        if ( pCaller && pCaller->hasValue() )
        {
            Reference< beans::XPropertySet > xProps( xScript, uno::UNO_QUERY );
            if ( xProps.is() )
            {
                Sequence< uno::Any > aArgs( 1 );
                aArgs[ 0 ] = *pCaller;
                xProps->setPropertyValue("Caller", uno::makeAny( aArgs ) );
            }
        }
        aRet = xScript->invoke( aParams, aOutParamIndex, aOutParam );
    }
    catch ( const uno::Exception& )
    {
        aException = ::cppu::getCaughtException();
        bCaughtException = true;
        nErr = ERRCODE_BASIC_INTERNAL_ERROR;
    }

    if ( bCaughtException && bRaiseError )
    {
        SfxAbstractDialogFactory* pFact = SfxAbstractDialogFactory::Create();
        pFact->ShowAsyncScriptErrorDialog( nullptr, aException );
    }

    SAL_INFO("sfx", "leaving CallXScript" );
    return nErr;
}

// perhaps rename to CallScript once we get rid of the existing CallScript
// and Call, CallBasic, CallStarBasic methods
ErrCode SfxObjectShell::CallXScript( const OUString& rScriptURL,
        const css::uno::Sequence< css::uno::Any >& aParams,
        css::uno::Any& aRet,
        css::uno::Sequence< sal_Int16 >& aOutParamIndex,
        css::uno::Sequence< css::uno::Any >& aOutParam,
        bool bRaiseError,
        const css::uno::Any* pCaller )
{
    return CallXScript( GetModel(), rScriptURL, aParams, aRet, aOutParamIndex, aOutParam, bRaiseError, pCaller );
}

void SfxHeaderAttributes_Impl::SetAttributes()
{
    bAlert = true;
    SvKeyValue aPair;
    for( bool bCont = xIter->GetFirst( aPair ); bCont;
         bCont = xIter->GetNext( aPair ) )
        SetAttribute( aPair );
}

void SfxHeaderAttributes_Impl::SetAttribute( const SvKeyValue& rKV )
{
    const OUString& aValue = rKV.GetValue();
    if( rKV.GetKey().equalsIgnoreAsciiCase("refresh") && !rKV.GetValue().isEmpty() )
    {
        sal_Int32 nIdx{ 0 };
        const sal_Int32 nTime{ aValue.getToken( 0, ';', nIdx ).toInt32() };
        const OUString aURL{ comphelper::string::strip(aValue.getToken( 0, ';', nIdx ), ' ') };
        uno::Reference<document::XDocumentProperties> xDocProps(
            pDoc->getDocProperties());
        if( aURL.startsWithIgnoreAsciiCase( "url=" ) )
        {
            try {
                xDocProps->setAutoloadURL(
                    rtl::Uri::convertRelToAbs(pDoc->GetMedium()->GetName(), aURL.copy( 4 )) );
            } catch (rtl::MalformedUriException &) {
                TOOLS_WARN_EXCEPTION("sfx", "");
            }
        }
        try
        {
            xDocProps->setAutoloadSecs( nTime );
        }
        catch (lang::IllegalArgumentException &)
        {
            // ignore
        }
    }
    else if( rKV.GetKey().equalsIgnoreAsciiCase( "expires" ) )
    {
        DateTime aDateTime( DateTime::EMPTY );
        if( INetMIMEMessage::ParseDateField( rKV.GetValue(), aDateTime ) )
        {
            aDateTime.ConvertToLocalTime();
            pDoc->GetMedium()->SetExpired_Impl( aDateTime );
        }
        else
        {
            pDoc->GetMedium()->SetExpired_Impl( Date( 1, 1, 1970 ) );
        }
    }
}

void SfxHeaderAttributes_Impl::Append( const SvKeyValue& rKV )
{
    xIter->Append( rKV );
    if( bAlert ) SetAttribute( rKV );
}

SvKeyValueIterator* SfxObjectShell::GetHeaderAttributes()
{
    if( !pImpl->xHeaderAttributes.is() )
    {
        DBG_ASSERT( pMedium, "No Medium" );
        pImpl->xHeaderAttributes = new SfxHeaderAttributes_Impl( this );
    }
    return static_cast<SvKeyValueIterator*>( pImpl->xHeaderAttributes.get() );
}

void SfxObjectShell::ClearHeaderAttributesForSourceViewHack()
{
    static_cast<SfxHeaderAttributes_Impl*>(GetHeaderAttributes())
        ->ClearForSourceView();
}


void SfxObjectShell::SetHeaderAttributesForSourceViewHack()
{
    static_cast<SfxHeaderAttributes_Impl*>(GetHeaderAttributes())
        ->SetAttributes();
}

bool SfxObjectShell::IsPreview() const
{
    if ( !pMedium )
        return false;

    bool bPreview = false;
    const SfxStringItem* pFlags = SfxItemSet::GetItem<SfxStringItem>(pMedium->GetItemSet(), SID_OPTIONS, false);
    if ( pFlags )
    {
        // Distributed values among individual items
        const OUString aFileFlags = pFlags->GetValue().toAsciiUpperCase();
        if ( -1 != aFileFlags.indexOf( 'B' ) )
            bPreview = true;
    }

    if ( !bPreview )
    {
        const SfxBoolItem* pItem = SfxItemSet::GetItem<SfxBoolItem>(pMedium->GetItemSet(), SID_PREVIEW, false);
        if ( pItem )
            bPreview = pItem->GetValue();
    }

    return bPreview;
}

void SfxObjectShell::SetWaitCursor( bool bSet ) const
{
    for( SfxViewFrame* pFrame = SfxViewFrame::GetFirst( this ); pFrame; pFrame = SfxViewFrame::GetNext( *pFrame, this ) )
    {
        if ( bSet )
            pFrame->GetFrame().GetWindow().EnterWait();
        else
            pFrame->GetFrame().GetWindow().LeaveWait();
    }
}

OUString SfxObjectShell::GetAPIName() const
{
    INetURLObject aURL( IsDocShared() ? GetSharedFileURL() : GetMedium()->GetName() );
    OUString aName( aURL.GetBase() );
    if( aName.isEmpty() )
        aName = aURL.GetURLNoPass();
    if ( aName.isEmpty() )
        aName = GetTitle( SFX_TITLE_DETECT );
    return aName;
}

void SfxObjectShell::Invalidate( sal_uInt16 nId )
{
    for( SfxViewFrame* pFrame = SfxViewFrame::GetFirst( this ); pFrame; pFrame = SfxViewFrame::GetNext( *pFrame, this ) )
        Invalidate_Impl( pFrame->GetBindings(), nId );
}

bool SfxObjectShell::AdjustMacroMode()
{
    uno::Reference< task::XInteractionHandler > xInteraction;
    if ( pMedium )
        xInteraction = pMedium->GetInteractionHandler();

    CheckForBrokenDocSignatures_Impl();

    CheckEncryption_Impl( xInteraction );

    return pImpl->aMacroMode.adjustMacroMode( xInteraction );
}

vcl::Window* SfxObjectShell::GetDialogParent( SfxMedium const * pLoadingMedium )
{
    VclPtr<vcl::Window> pWindow;
    SfxItemSet* pSet = pLoadingMedium ? pLoadingMedium->GetItemSet() : GetMedium()->GetItemSet();
    const SfxUnoFrameItem* pUnoItem = SfxItemSet::GetItem<SfxUnoFrameItem>(pSet, SID_FILLFRAME, false);
    if ( pUnoItem )
    {
        const uno::Reference < frame::XFrame >& xFrame( pUnoItem->GetFrame() );
        pWindow = VCLUnoHelper::GetWindow( xFrame->getContainerWindow() );
    }

    if ( !pWindow )
    {
        SfxFrame* pFrame = nullptr;
        const SfxFrameItem* pFrameItem = SfxItemSet::GetItem<SfxFrameItem>(pSet, SID_DOCFRAME, false);
        if( pFrameItem && pFrameItem->GetFrame() )
            // get target frame from ItemSet
            pFrame = pFrameItem->GetFrame();
        else
        {
            // try the current frame
            SfxViewFrame* pView = SfxViewFrame::Current();
            if ( !pView || pView->GetObjectShell() != this )
                // get any visible frame
                pView = SfxViewFrame::GetFirst(this);
            if ( pView )
                pFrame = &pView->GetFrame();
        }

        if ( pFrame )
            // get topmost window
            pWindow = VCLUnoHelper::GetWindow( pFrame->GetFrameInterface()->getContainerWindow() );
    }

    if ( pWindow )
    {
        // this frame may be invisible, show it if it is allowed
        const SfxBoolItem* pHiddenItem = SfxItemSet::GetItem<SfxBoolItem>(pSet, SID_HIDDEN, false);
        if ( !pHiddenItem || !pHiddenItem->GetValue() )
        {
            pWindow->Show();
            pWindow->ToTop();
        }
    }

    return pWindow;
}

void SfxObjectShell::SetCreateMode_Impl( SfxObjectCreateMode nMode )
{
    eCreateMode = nMode;
}

bool SfxObjectShell::IsInPlaceActive() const
{
    if ( eCreateMode != SfxObjectCreateMode::EMBEDDED )
        return false;

    SfxViewFrame* pFrame = SfxViewFrame::GetFirst( this );
    return pFrame && pFrame->GetFrame().IsInPlace();
}

bool SfxObjectShell::IsUIActive() const
{
    if ( eCreateMode != SfxObjectCreateMode::EMBEDDED )
        return false;

    SfxViewFrame* pFrame = SfxViewFrame::GetFirst( this );
    return pFrame && pFrame->GetFrame().IsInPlace() && pFrame->GetFrame().GetWorkWindow_Impl()->IsVisible_Impl();
}

bool SfxObjectShell::UseInteractionToHandleError(
                    const uno::Reference< task::XInteractionHandler >& xHandler,
                    ErrCode nError )
{
    bool bResult = false;

    if ( xHandler.is() )
    {
        try
        {
            uno::Any aInteraction;
            uno::Sequence< uno::Reference< task::XInteractionContinuation > > lContinuations(2);
            ::comphelper::OInteractionAbort* pAbort = new ::comphelper::OInteractionAbort();
            ::comphelper::OInteractionApprove* pApprove = new ::comphelper::OInteractionApprove();
            lContinuations[0].set( static_cast< task::XInteractionContinuation* >( pAbort ), uno::UNO_QUERY );
            lContinuations[1].set( static_cast< task::XInteractionContinuation* >( pApprove ), uno::UNO_QUERY );

            task::ErrorCodeRequest aErrorCode;
            aErrorCode.ErrCode = sal_uInt32(nError);
            aInteraction <<= aErrorCode;
            xHandler->handle(::framework::InteractionRequest::CreateRequest (aInteraction,lContinuations));
            bResult = pAbort->wasSelected();
        }
        catch( uno::Exception& )
        {}
    }

    return bResult;
}

sal_Int16 SfxObjectShell_Impl::getCurrentMacroExecMode() const
{
    sal_Int16 nImposedExecMode( MacroExecMode::NEVER_EXECUTE );

    const SfxMedium* pMedium( rDocShell.GetMedium() );
    OSL_PRECOND( pMedium, "SfxObjectShell_Impl::getCurrentMacroExecMode: no medium!" );
    if ( pMedium )
    {
        const SfxUInt16Item* pMacroModeItem = SfxItemSet::GetItem<SfxUInt16Item>(pMedium->GetItemSet(), SID_MACROEXECMODE, false);
        if ( pMacroModeItem )
            nImposedExecMode = pMacroModeItem->GetValue();
    }
    return nImposedExecMode;
}

void SfxObjectShell_Impl::setCurrentMacroExecMode( sal_uInt16 nMacroMode )
{
    const SfxMedium* pMedium( rDocShell.GetMedium() );
    OSL_PRECOND( pMedium, "SfxObjectShell_Impl::getCurrentMacroExecMode: no medium!" );
    if ( pMedium )
    {
        pMedium->GetItemSet()->Put( SfxUInt16Item( SID_MACROEXECMODE, nMacroMode ) );
    }
}

OUString SfxObjectShell_Impl::getDocumentLocation() const
{
    OUString sLocation;

    const SfxMedium* pMedium( rDocShell.GetMedium() );
    OSL_PRECOND( pMedium, "SfxObjectShell_Impl::getDocumentLocation: no medium!" );
    if ( pMedium )
    {
        sLocation = pMedium->GetName();
        if ( sLocation.isEmpty() )
        {
            // for documents made from a template: get the name of the template
            sLocation = rDocShell.getDocProperties()->getTemplateURL();
        }
    }
    return sLocation;
}

bool SfxObjectShell_Impl::documentStorageHasMacros() const
{
    return ::sfx2::DocumentMacroMode::storageHasMacros( m_xDocStorage );
}

bool SfxObjectShell_Impl::macroCallsSeenWhileLoading() const
{
    return rDocShell.GetMacroCallsSeenWhileLoading();
}

Reference< XEmbeddedScripts > SfxObjectShell_Impl::getEmbeddedDocumentScripts() const
{
    return Reference< XEmbeddedScripts >( rDocShell.GetModel(), UNO_QUERY );
}

SignatureState SfxObjectShell_Impl::getScriptingSignatureState()
{
    SignatureState nSignatureState( rDocShell.GetScriptingSignatureState() );

    if ( nSignatureState != SignatureState::NOSIGNATURES && m_bMacroSignBroken )
    {
        // if there is a macro signature it must be handled as broken
        nSignatureState = SignatureState::BROKEN;
    }

    return nSignatureState;
}

bool SfxObjectShell_Impl::hasTrustedScriptingSignature( bool bAllowUIToAddAuthor )
{
    bool bResult = false;

    try
    {
        OUString aVersion;
        try
        {
            uno::Reference < beans::XPropertySet > xPropSet( rDocShell.GetStorage(), uno::UNO_QUERY_THROW );
            xPropSet->getPropertyValue("Version") >>= aVersion;
        }
        catch( uno::Exception& )
        {
        }

        uno::Reference< security::XDocumentDigitalSignatures > xSigner( security::DocumentDigitalSignatures::createWithVersion(comphelper::getProcessComponentContext(), aVersion) );

        if ( nScriptingSignatureState == SignatureState::UNKNOWN
          || nScriptingSignatureState == SignatureState::OK
          || nScriptingSignatureState == SignatureState::NOTVALIDATED )
        {
            uno::Sequence< security::DocumentSignatureInformation > aInfo = rDocShell.GetDocumentSignatureInformation( true, xSigner );

            if ( aInfo.hasElements() )
            {
                if ( nScriptingSignatureState == SignatureState::UNKNOWN )
                    nScriptingSignatureState = DocumentSignatures::getSignatureState(aInfo);

                if ( nScriptingSignatureState == SignatureState::OK
                  || nScriptingSignatureState == SignatureState::NOTVALIDATED )
                {
                    bResult = std::any_of(aInfo.begin(), aInfo.end(),
                        [&xSigner](const security::DocumentSignatureInformation& rInfo) {
                            return xSigner->isAuthorTrusted( rInfo.Signer ); });

                    if ( !bResult && bAllowUIToAddAuthor )
                    {
                        uno::Reference< task::XInteractionHandler > xInteraction;
                        if ( rDocShell.GetMedium() )
                            xInteraction = rDocShell.GetMedium()->GetInteractionHandler();

                        if ( xInteraction.is() )
                        {
                            task::DocumentMacroConfirmationRequest aRequest;
                            aRequest.DocumentURL = getDocumentLocation();
                            aRequest.DocumentStorage = rDocShell.GetMedium()->GetZipStorageToSign_Impl();
                            aRequest.DocumentSignatureInformation = aInfo;
                            aRequest.DocumentVersion = aVersion;
                            aRequest.Classification = task::InteractionClassification_QUERY;
                            bResult = SfxMedium::CallApproveHandler( xInteraction, uno::makeAny( aRequest ), true );
                        }
                    }
                }
            }
        }
    }
    catch( uno::Exception& )
    {}

    return bResult;
}

bool SfxObjectShell::IsContinueImportOnFilterExceptions(const OUString& aErrMessage)
{
    if (mbContinueImportOnFilterExceptions == undefined)
    {
        if (Application::GetDialogCancelMode() == DialogCancelMode::Off)
        {
            // Ask the user to try to continue or abort loading
            OUString aMessage = SfxResId(STR_QMSG_ERROR_OPENING_FILE);
            if (!aErrMessage.isEmpty())
                aMessage += SfxResId(STR_QMSG_ERROR_OPENING_FILE_DETAILS) + aErrMessage;
            aMessage += SfxResId(STR_QMSG_ERROR_OPENING_FILE_CONTINUE);
            std::unique_ptr<weld::MessageDialog> xBox(Application::CreateMessageDialog(nullptr,
                                                      VclMessageType::Question, VclButtonsType::YesNo, aMessage));
            mbContinueImportOnFilterExceptions = (xBox->run() == RET_YES) ? yes : no;
        }
        else
            mbContinueImportOnFilterExceptions = no;
    }
    return mbContinueImportOnFilterExceptions == yes;
}

bool SfxObjectShell::isEditDocLocked()
{
    Reference<XModel> xModel = GetModel();
    if (!xModel.is())
        return false;
    if (!officecfg::Office::Common::Misc::AllowEditReadonlyDocs::get())
        return true;
    comphelper::NamedValueCollection aArgs(xModel->getArgs());
    return aArgs.getOrDefault("LockEditDoc", false);
}

bool SfxObjectShell::isContentExtractionLocked()
{
    Reference<XModel> xModel = GetModel();
    if (!xModel.is())
        return false;
    comphelper::NamedValueCollection aArgs(xModel->getArgs());
    return aArgs.getOrDefault("LockContentExtraction", false);
}

bool SfxObjectShell::isExportLocked()
{
    Reference<XModel> xModel = GetModel();
    if (!xModel.is())
        return false;
    comphelper::NamedValueCollection aArgs(xModel->getArgs());
    return aArgs.getOrDefault("LockExport", false);
}

bool SfxObjectShell::isPrintLocked()
{
    Reference<XModel> xModel = GetModel();
    if (!xModel.is())
        return false;
    comphelper::NamedValueCollection aArgs(xModel->getArgs());
    return aArgs.getOrDefault("LockPrint", false);
}

bool SfxObjectShell::isSaveLocked()
{
    Reference<XModel> xModel = GetModel();
    if (!xModel.is())
        return false;
    comphelper::NamedValueCollection aArgs(xModel->getArgs());
    return aArgs.getOrDefault("LockSave", false);
}

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