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

#include <sal/config.h>

#include <com/sun/star/datatransfer/UnsupportedFlavorException.hpp>
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#include <com/sun/star/lang/DisposedException.hpp>
#include <com/sun/star/embed/WrongStateException.hpp>
#include <com/sun/star/embed/UnreachableStateException.hpp>
#include <com/sun/star/embed/EmbedStates.hpp>
#include <com/sun/star/ucb/XSimpleFileAccess.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/io/TempFile.hpp>
#include <com/sun/star/io/XTruncate.hpp>
#include <com/sun/star/io/IOException.hpp>
#include <com/sun/star/awt/XRequestCallback.hpp>

#include "platform.h"
#include <comphelper/multicontainer2.hxx>
#include <comphelper/mimeconfighelper.hxx>
#include <comphelper/processfactory.hxx>
#include <comphelper/servicehelper.hxx>
#include <comphelper/windowserrorstring.hxx>
#include <osl/file.hxx>
#include <rtl/ref.hxx>
#include <o3tl/char16_t2wchar_t.hxx>
#include <o3tl/unit_conversion.hxx>
#include <systools/win32/comtools.hxx>
#include <vcl/svapp.hxx>
#include <vcl/threadex.hxx>

#include "graphconvert.hxx"
#include "olecomponent.hxx"
#include "olepersist.hxx"
#include "olewrapclient.hxx"
#include "advisesink.hxx"
#include <oleembobj.hxx>
#include "mtnotification.hxx"
#include <memory>
#include <string>

using namespace ::com::sun::star;
using namespace ::comphelper;
#define     MAX_ENUM_ELE     20
#define     FORMATS_NUM      3

FORMATETC const pFormatTemplates[FORMATS_NUM] = {
                    { CF_ENHMETAFILE, nullptr, 0, -1, TYMED_ENHMF },
                    { CF_METAFILEPICT, nullptr, 0, -1, TYMED_MFPICT },
                    { CF_BITMAP, nullptr, 0, -1, TYMED_GDI } };


// We have at least one single-threaded apartment (STA) in the process (the VCL Main thread, which
// is the GUI thread), and a multithreaded apartment (MTA) for most of other threads. OLE objects
// may be created in either: in interactive mode, this typically happens in the STA; when serving
// external requests, this may be either in STA (when explicit "OnMainThread" argument is passed to
// loadComponentFromURL, and the instantiation of the object happens during the load), or in MTA
// (the thread actually serving the incoming calls).
//
// The objects typically can only be used in the apartment where they were instantiated. This means
// that e.g. a call to IOleObject::Close will fail, if it is performed in a different thread, when
// it was started in the main thread. And vice versa, opening a document in a handler thread, then
// trying to interact with the OLE object in GUI would fail.
//
// To handle this, several workarounds were implemented in the past; the mentioned "OnMainThread"
// argument is one of these, allowing open document requests be processed not in the handler threads
// that received the request, but in the main thread which will then be used for interaction. Also
// OleComponent::GetExtent was changed to check if the first call to IDataObject::GetData failed
// with RPC_E_WRONG_THREAD, and then retry in the main thread.
//
// But ultimately every call to the OLE object needs such checks. E.g., failing to close the object
// keeps the server running, effectively leaking resources, until it crashes/freezes after multiple
// iterations.
//
// Currently, OleComponentNative_Impl is implemented using IGlobalInterfaceTable, which allows to
// register an object in process-global instance of the table from the thread that instantiated the
// object, and obtain a "cookie" (a number); and then use that cookie from any thread to access that
// object. The global table will do its magic to provide either the original object (when it is
// requested from the same apartment as used for its registration), or a "proxy", which will marshal
// all calls to the proper thread, transparently for the caller. This implementation should obsolete
// the previous workarounds (in theory).
//
// m_pGlobalTable is the reference to the global table.
// The storage object gets registered in the global table immediately when it's created.
// But the OLE object itself can't be registered immediately, before it is run: an attempt to call
// RegisterInterfaceInGlobal with such a newly created OLE object fails with CO_E_OBJNOTCONNECTED.
// Thus, the initial reference to the OLE object (which at this stage seems to be apartment-neutral)
// is stored to m_pObj. Only when it is run, it is registered in the global table.
//
// Indeed, the implicit change of the thread is a blocking operation, which opens a wonderful new
// opportunities for shiny deadlocks. Thus, precautions are needed to avoid them.
//
// When the OLE object is accessed by m_pObj (should be only in initialization code!), no measures
// are taken to change locking. But when it is accessed by getObj() - which may return the proxy -
// the calls are guarded by a SolarMutexReleaser, to allow the other thread do its job.
//
// There are at least two other mutexes in play here. One is in OleEmbeddedObject, that holds the
// OleComponent. The calls to OleComponent's methods are also wrapped there into unlock/lock pairs
// (see OleEmbeddedObject::changeState). The other is in OleComponent itself. For now, I see no
// deadlocks caused by that mutex, so no unlock/lock is introduced for that. It may turn out to be
// required eventually.
class OleComponentNative_Impl
{
public:
    sal::systools::COMReference< IUnknown > m_pObj;
    uno::Sequence< datatransfer::DataFlavor > m_aSupportedGraphFormats;

    // The getters may return a proxy, that redirects the calls to another thread.
    // Thus, calls to methods of returned objects must be inside solar mutex releaser.
    auto getStorage() const { return getInterface<IStorage>(m_nStorage); }
    auto getObj() const { return m_nOleObject ? getInterface<IUnknown>(m_nOleObject) : m_pObj; }
    template <typename T>
    auto get() const { return getObj().QueryInterface<T>(sal::systools::COM_QUERY); }

    void registerStorage(IStorage* pStorage) { registerInterface(pStorage, m_nStorage); }
    void registerObj() { registerInterface(m_pObj.get(), m_nOleObject); }

    bool IsStorageRegistered() const { return m_nStorage != 0; }

    OleComponentNative_Impl()
        : m_pGlobalTable(CLSID_StdGlobalInterfaceTable, nullptr, CLSCTX_INPROC_SERVER)
    {
        // TODO: Extend format list
        m_aSupportedGraphFormats = {

        datatransfer::DataFlavor(
            "application/x-openoffice-emf;windows_formatname=\"Image EMF\"",
            "Windows Enhanced Metafile",
            cppu::UnoType<uno::Sequence< sal_Int8 >>::get() ),

        datatransfer::DataFlavor(
            "application/x-openoffice-wmf;windows_formatname=\"Image WMF\"",
            "Windows Metafile",
            cppu::UnoType<uno::Sequence< sal_Int8 >>::get() ),

        datatransfer::DataFlavor(
            "application/x-openoffice-bitmap;windows_formatname=\"Bitmap\"",
            "Bitmap",
            cppu::UnoType<uno::Sequence< sal_Int8 >>::get() ),

        datatransfer::DataFlavor(
            "image/png",
            "PNG",
            cppu::UnoType<uno::Sequence< sal_Int8 >>::get() ),

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

    ~OleComponentNative_Impl()
    {
        if (m_nOleObject)
            m_pGlobalTable->RevokeInterfaceFromGlobal(m_nOleObject);
        if (m_nStorage)
            m_pGlobalTable->RevokeInterfaceFromGlobal(m_nStorage);
    }

    bool ConvertDataForFlavor( const STGMEDIUM& aMedium,
                                    const datatransfer::DataFlavor& aFlavor,
                                    uno::Any& aResult );

    bool GraphicalFlavor( const datatransfer::DataFlavor& aFlavor );

    uno::Sequence< datatransfer::DataFlavor > GetFlavorsForAspects( sal_uInt32 nSupportedAspects );

    sal::systools::COMReference<IStorage> CreateNewStorage(const OUString& url);

private:
    sal::systools::COMReference<IGlobalInterfaceTable> m_pGlobalTable;
    DWORD m_nStorage = 0;
    DWORD m_nOleObject = 0;

    template <typename T> sal::systools::COMReference<T> getInterface(DWORD cookie) const
    {
        sal::systools::COMReference<T> result;
        HRESULT hr = m_pGlobalTable->GetInterfaceFromGlobal(cookie, IID_PPV_ARGS(&result));
        SAL_WARN_IF(FAILED(hr), "embeddedobj.ole",
                    "GetInterfaceFromGlobal failed: is cookie " << cookie << " not registered?");
        return result;
    }

    template <typename T> void registerInterface(T* pInterface, DWORD& cookie)
    {
        if (cookie != 0) // E.g., on subsequent RunObject calls
            return;
        HRESULT hr = m_pGlobalTable->RegisterInterfaceInGlobal(pInterface, __uuidof(T), &cookie);
        SAL_WARN_IF(FAILED(hr), "embeddedobj.ole", "RegisterInterfaceInGlobal failed");
    }
};

static DWORD GetAspectFromFlavor( const datatransfer::DataFlavor& aFlavor )
{
    if ( aFlavor.MimeType.indexOf( ";Aspect=THUMBNAIL" ) != -1 )
        return DVASPECT_THUMBNAIL;
    else if ( aFlavor.MimeType.indexOf( ";Aspect=ICON" ) != -1 )
        return DVASPECT_ICON;
    else if ( aFlavor.MimeType.indexOf( ";Aspect=DOCPRINT" ) != -1 )
        return DVASPECT_DOCPRINT;
    else
        return DVASPECT_CONTENT;
}


static OUString GetFlavorSuffixFromAspect( DWORD nAsp )
{
    OUString aResult;

    if ( nAsp == DVASPECT_THUMBNAIL )
        aResult = ";Aspect=THUMBNAIL";
    else if ( nAsp == DVASPECT_ICON )
        aResult = ";Aspect=ICON";
    else if ( nAsp == DVASPECT_DOCPRINT )
        aResult = ";Aspect=DOCPRINT";

    // no suffix for DVASPECT_CONTENT

    return aResult;
}


bool OleComponentNative_Impl::ConvertDataForFlavor( const STGMEDIUM& aMedium,
                                                        const datatransfer::DataFlavor& aFlavor,
                                                        uno::Any& aResult )
{
    bool bAnyIsReady = false;

    // try to convert data from Medium format to specified Flavor format
    if ( aFlavor.DataType == cppu::UnoType<uno::Sequence< sal_Int8 >>::get() )
    {
        // first the GDI-metafile must be generated

        std::unique_ptr<sal_Int8[]> pBuf;
        sal_uInt32 nBufSize = 0;
        OUString aFormat;

        if ( aMedium.tymed == TYMED_MFPICT ) // Win Metafile
        {
            aFormat = "image/x-wmf";
            METAFILEPICT* pMF = static_cast<METAFILEPICT*>(GlobalLock( aMedium.hMetaFilePict ));
            if ( pMF )
            {
                nBufSize = GetMetaFileBitsEx( pMF->hMF, 0, nullptr ) + 22;
                pBuf.reset(new sal_Int8[nBufSize]);


                // TODO/LATER: the unit size must be calculated correctly
                *reinterpret_cast<long*>( pBuf.get() ) = 0x9ac6cdd7L;
                *reinterpret_cast<short*>( pBuf.get()+6 ) = SHORT(0);
                *reinterpret_cast<short*>( pBuf.get()+8 ) = SHORT(0);
                *reinterpret_cast<short*>( pBuf.get()+10 ) = static_cast<SHORT>(pMF->xExt);
                *reinterpret_cast<short*>( pBuf.get()+12 ) = static_cast<SHORT>(pMF->yExt);
                *reinterpret_cast<short*>( pBuf.get()+14 ) = USHORT(2540);


                if ( nBufSize && nBufSize == GetMetaFileBitsEx( pMF->hMF, nBufSize - 22, pBuf.get() + 22 ) )
                {
                    if ( aFlavor.MimeType.match( "application/x-openoffice-wmf;windows_formatname=\"Image WMF\"" ) )
                    {
                        aResult <<= uno::Sequence< sal_Int8 >( pBuf.get(), nBufSize );
                        bAnyIsReady = true;
                    }
                }

                GlobalUnlock( aMedium.hMetaFilePict );
            }
        }
        else if ( aMedium.tymed == TYMED_ENHMF ) // Enh Metafile
        {
            aFormat = "image/x-emf";
            nBufSize = GetEnhMetaFileBits( aMedium.hEnhMetaFile, 0, nullptr );
            pBuf.reset(new sal_Int8[nBufSize]);
            if ( nBufSize && nBufSize == GetEnhMetaFileBits( aMedium.hEnhMetaFile, nBufSize, reinterpret_cast<LPBYTE>(pBuf.get()) ) )
            {
                if ( aFlavor.MimeType.match( "application/x-openoffice-emf;windows_formatname=\"Image EMF\"" ) )
                {
                    aResult <<= uno::Sequence< sal_Int8 >( pBuf.get(), nBufSize );
                    bAnyIsReady = true;
                }
            }
        }
        else if ( aMedium.tymed == TYMED_GDI ) // Bitmap
        {
            aFormat = "image/x-MS-bmp";

            // Find out size of buffer: deprecated GetBitmapBits does not have a mode to return
            // required buffer size
            BITMAP aBmp;
            GetObjectW(aMedium.hBitmap, sizeof(aBmp), &aBmp);
            nBufSize = aBmp.bmWidthBytes * aBmp.bmHeight;

            pBuf.reset(new sal_Int8[nBufSize]);
            if ( nBufSize && nBufSize == sal::static_int_cast< ULONG >( GetBitmapBits( aMedium.hBitmap, nBufSize, pBuf.get() ) ) )
            {
                if ( aFlavor.MimeType.match( "application/x-openoffice-bitmap;windows_formatname=\"Bitmap\"" ) )
                {
                    aResult <<= uno::Sequence< sal_Int8 >( pBuf.get(), nBufSize );
                    bAnyIsReady = true;
                }
            }
        }

        if ( pBuf && !bAnyIsReady )
        {
            for (auto const& supportedFormat : m_aSupportedGraphFormats)
                if ( aFlavor.MimeType.match( supportedFormat.MimeType )
                  && aFlavor.DataType == supportedFormat.DataType
                  && aFlavor.DataType == cppu::UnoType<uno::Sequence< sal_Int8 >>::get() )
                {
                    bAnyIsReady = ConvertBufferToFormat( pBuf.get(), nBufSize, aFormat, aResult );
                    break;
                }
        }
    }

    return bAnyIsReady;
}


bool OleComponentNative_Impl::GraphicalFlavor( const datatransfer::DataFlavor& aFlavor )
{
    // Actually all the required graphical formats must be supported
    for (auto const& supportedFormat : m_aSupportedGraphFormats)
         if ( aFlavor.MimeType.match( supportedFormat.MimeType )
          && aFlavor.DataType == supportedFormat.DataType )
            return true;

    return false;
}


static bool GetClassIDFromSequence_Impl( uno::Sequence< sal_Int8 > const & aSeq, CLSID& aResult )
{
    if ( aSeq.getLength() == 16 )
    {
        aResult.Data1 = ( ( ( ( ( static_cast<sal_uInt8>(aSeq[0]) << 8 ) + static_cast<sal_uInt8>(aSeq[1]) ) << 8 ) + static_cast<sal_uInt8>(aSeq[2]) ) << 8 ) + static_cast<sal_uInt8>(aSeq[3]);
        aResult.Data2 = ( static_cast<sal_uInt8>(aSeq[4]) << 8 ) + static_cast<sal_uInt8>(aSeq[5]);
        aResult.Data3 = ( static_cast<sal_uInt8>(aSeq[6]) << 8 ) + static_cast<sal_uInt8>(aSeq[7]);
        for( int nInd = 0; nInd < 8; nInd++ )
            aResult.Data4[nInd] = static_cast<sal_uInt8>(aSeq[nInd+8]);

        return true;
    }

    return false;
}


static OUString WinAccToVcl_Impl( const sal_Unicode* pStr )
{
    OUString aResult;

    if( pStr )
    {
        while ( *pStr )
        {
            if ( *pStr == '&' )
            {
                aResult += "~";
                while( *( ++pStr ) == '&' );
            }
            else
            {
                aResult += OUStringChar( *pStr );
                pStr++;
            }
        }
    }

    return aResult;
}


OleComponent::OleComponent( const uno::Reference< uno::XComponentContext >& xContext, OleEmbeddedObject* pUnoOleObject )
: m_pInterfaceContainer( nullptr )
, m_bDisposed( false )
, m_bModified( false )
, m_pNativeImpl( std::make_unique<OleComponentNative_Impl>() )
, m_pUnoOleObject( pUnoOleObject )
, m_pOleWrapClientSite( nullptr )
, m_pImplAdviseSink( nullptr )
, m_xContext( xContext )
, m_bOleInitialized( false )
, m_bWorkaroundActive( false )
{
    OSL_ENSURE( m_pUnoOleObject, "No owner object is provided!" );

    HRESULT hr = OleInitialize( nullptr );
    if ( hr == S_OK || hr == S_FALSE )
        m_bOleInitialized = true;
    else
    {
        SAL_WARN("embeddedobj.ole", "OleComponent ctor: OleInitialize() failed with 0x"
                                        << OUString::number(static_cast<sal_uInt32>(hr), 16) << ": "
                                        << WindowsErrorStringFromHRESULT(hr));
    }

    m_pOleWrapClientSite = new OleWrapperClientSite( this );
    m_pOleWrapClientSite->AddRef();

    m_pImplAdviseSink = new OleWrapperAdviseSink( this );
    m_pImplAdviseSink->AddRef();

}


OleComponent::~OleComponent()
{
    OSL_ENSURE( !m_pOleWrapClientSite && !m_pImplAdviseSink && !m_pInterfaceContainer && !m_bOleInitialized,
                "The object was not closed successfully! DISASTER is possible!" );

    if ( m_pOleWrapClientSite || m_pImplAdviseSink || m_pInterfaceContainer || m_bOleInitialized )
    {
        osl_atomic_increment(&m_refCount);
        try {
            Dispose();
        } catch( const uno::Exception& ) {}
    }
}

void OleComponent::Dispose()
{
    if ( m_bDisposed )
        return;

    // Call CloseObject() without m_aMutex locked, since it will call
    // IOleObject::Close(), which can call event listeners, which can run on a
    // different thread.
    CloseObject();

    osl::MutexGuard aGuard(m_aMutex);
    if ( m_pOleWrapClientSite )
    {
        m_pOleWrapClientSite->disconnectOleComponent();
        m_pOleWrapClientSite->Release();
        m_pOleWrapClientSite = nullptr;
    }

    if ( m_pImplAdviseSink )
    {
        m_pImplAdviseSink->disconnectOleComponent();
        m_pImplAdviseSink->Release();
        m_pImplAdviseSink = nullptr;
    }

    if ( m_pInterfaceContainer )
    {
        lang::EventObject aEvent( static_cast< ::cppu::OWeakObject* >( this ) );
        m_pInterfaceContainer->disposeAndClear( aEvent );

        delete m_pInterfaceContainer;
        m_pInterfaceContainer = nullptr;
    }

    if ( m_bOleInitialized )
    {
        // since the disposing can happen not only from main thread but also from a clipboard
        // the deinitialization might lead to a disaster, SO7 does not deinitialize OLE at all
        // so currently the same approach is selected as workaround
        // OleUninitialize();
        m_bOleInitialized = false;
    }

    m_bDisposed = true;
}


void OleComponent::disconnectEmbeddedObject()
{
    // must not be called from destructor of UNO OLE object!!!
    osl::MutexGuard aGuard( m_aMutex );
    m_pUnoOleObject = nullptr;
}


OUString OleComponent::getTempURL() const
{
    OSL_ENSURE( m_pUnoOleObject, "Unexpected object absence!" );
    if ( m_pUnoOleObject )
        return m_pUnoOleObject->CreateTempURLEmpty_Impl();
    else
        return GetNewTempFileURL_Impl(m_xContext);
}


sal::systools::COMReference<IStorage> OleComponentNative_Impl::CreateNewStorage(const OUString& url)
{
    if (IsStorageRegistered())
        throw io::IOException(); // TODO:the object is already initialized
    // TODO: in future a global memory could be used instead of file.

    // write the stream to the temporary file
    if (url.isEmpty())
        throw uno::RuntimeException(); // TODO

    // open an IStorage based on the temporary file
    OUString aTempFilePath;
    if (osl::FileBase::getSystemPathFromFileURL(url, aTempFilePath) != osl::FileBase::E_None)
        throw uno::RuntimeException(); // TODO: something dangerous happened

    sal::systools::COMReference<IStorage> pStorage;
    HRESULT hr = StgCreateDocfile( o3tl::toW(aTempFilePath.getStr()), STGM_CREATE | STGM_READWRITE | STGM_TRANSACTED | STGM_DELETEONRELEASE, 0, &pStorage );
    if (FAILED(hr) || !pStorage)
        throw io::IOException(); // TODO: transport error code?
    registerStorage(pStorage);
    return pStorage;
}


uno::Sequence< datatransfer::DataFlavor > OleComponentNative_Impl::GetFlavorsForAspects( sal_uInt32 nSupportedAspects )
{
    uno::Sequence< datatransfer::DataFlavor > aResult;
    for ( sal_uInt32 nAsp = 1; nAsp <= 8; nAsp *= 2 )
        if ( ( nSupportedAspects & nAsp ) == nAsp )
        {
            OUString aAspectSuffix = GetFlavorSuffixFromAspect( nAsp );

            sal_Int32 nLength = aResult.getLength();
            aResult.realloc( nLength + m_aSupportedGraphFormats.getLength() );
            auto pResult = aResult.getArray();

            for ( sal_Int32 nInd = 0; nInd < m_aSupportedGraphFormats.getLength(); nInd++ )
            {
                pResult[nLength + nInd].MimeType = m_aSupportedGraphFormats[nInd].MimeType + aAspectSuffix;
                pResult[nLength + nInd].HumanPresentableName = m_aSupportedGraphFormats[nInd].HumanPresentableName;
                pResult[nLength + nInd].DataType = m_aSupportedGraphFormats[nInd].DataType;
            }
        }

    return aResult;
}


void OleComponent::RetrieveObjectDataFlavors_Impl()
{
    if (!m_pNativeImpl->m_pObj)
        throw embed::WrongStateException(); // TODO: the object is in wrong state

    if ( !m_aDataFlavors.getLength() )
    {
        if (auto pDataObject = m_pNativeImpl->get<IDataObject>())
        {
            HRESULT hr;
            sal::systools::COMReference< IEnumFORMATETC > pFormatEnum;
            {
                SolarMutexReleaser releaser;
                hr = pDataObject->EnumFormatEtc(DATADIR_GET, &pFormatEnum);
            }
            if ( SUCCEEDED( hr ) && pFormatEnum )
            {
                FORMATETC pElem[ MAX_ENUM_ELE ];
                ULONG nNum = 0;

                // if it is possible to retrieve at least one supported graphical format for an aspect
                // this format can be converted to other supported formats
                sal_uInt32 nSupportedAspects = 0;
                do
                {
                    HRESULT hr2 = pFormatEnum->Next( MAX_ENUM_ELE, pElem, &nNum );
                    if( hr2 == S_OK || hr2 == S_FALSE )
                    {
                        for( sal_uInt32 nInd = 0; nInd < FORMATS_NUM; nInd++ )
                        {
                            if ( pElem[nInd].cfFormat == pFormatTemplates[nInd].cfFormat
                              && pElem[nInd].tymed == pFormatTemplates[nInd].tymed )
                                nSupportedAspects |= pElem[nInd].dwAspect;
                        }
                    }
                    else
                        break;
                }
                while( nNum == MAX_ENUM_ELE );

                m_aDataFlavors = m_pNativeImpl->GetFlavorsForAspects( nSupportedAspects );
            }
        }

        if ( !m_aDataFlavors.getLength() )
        {
            // TODO:
            // for any reason the object could not provide this information
            // try to get access to the cached representation
        }
    }
}


void OleComponent::InitializeObject_Impl()
// There will be no static objects!
{
    if ( !m_pNativeImpl->m_pObj )
        throw embed::WrongStateException();

    // the linked object will be detected here
    OSL_ENSURE( m_pUnoOleObject, "Unexpected object absence!" );
    if ( m_pUnoOleObject )
        m_pUnoOleObject->SetObjectIsLink_Impl( m_pNativeImpl->m_pObj.QueryInterface<IOleLink>(sal::systools::COM_QUERY).is() );

    auto pViewObject2(m_pNativeImpl->m_pObj.QueryInterface<IViewObject2>(sal::systools::COM_QUERY));
    if (!pViewObject2)
        throw uno::RuntimeException(); // TODO

    // remove all the caches
    if ( sal::systools::COMReference< IOleCache > pIOleCache{ m_pNativeImpl->m_pObj, sal::systools::COM_QUERY } )
    {
        IEnumSTATDATA* pEnumSD = nullptr;
        HRESULT hr2 = pIOleCache->EnumCache( &pEnumSD );

        if ( SUCCEEDED( hr2 ) && pEnumSD )
        {
            pEnumSD->Reset();
            STATDATA aSD;
            DWORD nNum;
            while( SUCCEEDED( pEnumSD->Next( 1, &aSD, &nNum ) ) && nNum == 1 )
                hr2 = pIOleCache->Uncache( aSD.dwConnection );
        }

        // No IDataObject implementation, caching must be used instead
        DWORD nConn;
        FORMATETC aFormat = { 0, nullptr, DVASPECT_CONTENT, -1, TYMED_MFPICT };
        hr2 = pIOleCache->Cache( &aFormat, ADVFCACHE_ONSAVE, &nConn );
    }

    auto pOleObject(m_pNativeImpl->m_pObj.QueryInterface<IOleObject>(sal::systools::COM_QUERY));
    if (!pOleObject)
        throw uno::RuntimeException(); // Static objects are not supported, they should be inserted as graphics

    DWORD nOLEMiscFlags(0);
    pOleObject->GetMiscStatus(DVASPECT_CONTENT, reinterpret_cast<DWORD*>(&nOLEMiscFlags));
    // TODO: use other misc flags also
    // the object should have drawable aspect even in case it supports only iconic representation
    // if ( nOLEMiscFlags & OLEMISC_ONLYICONIC )

    pOleObject->SetClientSite(m_pOleWrapClientSite);

    // the only need in this registration is workaround for close notification
    DWORD nAdvConn(0);
    pOleObject->Advise(m_pImplAdviseSink, reinterpret_cast<DWORD*>(&nAdvConn));
    pViewObject2->SetAdvise(DVASPECT_CONTENT, 0, m_pImplAdviseSink);

    OleSetContainedObject(pOleObject, TRUE);
}

namespace
{
    HRESULT OleLoadSeh(LPSTORAGE pIStorage, IUnknown** ppObj)
    {
        HRESULT hr = E_FAIL;
        // tdf#119039: there is a nasty bug in OleLoad, that may call an unpaired
        // IUnknown::Release on pIStorage on STG_E_FILENOTFOUND: see
        // https://developercommunity.visualstudio.com/t/10144795
        // Workaround it here to avoid crash in smart COM pointer destructor that
        // would try to release already released object. Since we don't know if
        // the bug appears each time STG_E_FILENOTFOUND is returned, this might
        // potentially leak the storage object.
        if (pIStorage)
            pIStorage->AddRef();

        __try {
            hr = OleLoad(pIStorage, IID_IUnknown, nullptr, IID_PPV_ARGS_Helper(ppObj));
        } __except( EXCEPTION_EXECUTE_HANDLER ) {
            hr = E_FAIL;
        }
        if (pIStorage && hr != STG_E_FILENOTFOUND)
            pIStorage->Release();

        return hr;
    }
}

void OleComponent::LoadEmbeddedObject( const OUString& aTempURL )
{
    if ( !aTempURL.getLength() )
        throw lang::IllegalArgumentException(); // TODO

    if (m_pNativeImpl->IsStorageRegistered())
        throw io::IOException(); // TODO the object is already initialized or wrong initialization is done

    // open an IStorage based on the temporary file
    OUString aFilePath;
    if (osl::FileBase::getSystemPathFromFileURL(aTempURL, aFilePath) != ::osl::FileBase::E_None)
        throw uno::RuntimeException(); // TODO: something dangerous happened

    sal::systools::COMReference<IStorage> pStorage;
    HRESULT hr = StgOpenStorage(o3tl::toW(aFilePath.getStr()), nullptr,
                                STGM_READWRITE | STGM_TRANSACTED, // | STGM_DELETEONRELEASE,
                                nullptr, 0, &pStorage);
    if (FAILED(hr) || !pStorage)
        throw io::IOException(); // TODO: transport error code?

    m_pNativeImpl->registerStorage(pStorage);

    hr = OleLoadSeh(pStorage, &m_pNativeImpl->m_pObj);
    if (FAILED(hr))
        throw uno::RuntimeException();

    InitializeObject_Impl();
}


void OleComponent::CreateObjectFromClipboard()
{
    auto pStorage(m_pNativeImpl->CreateNewStorage(getTempURL()));
    if (!pStorage)
        throw uno::RuntimeException(); // TODO

    IDataObject * pDO = nullptr;
    HRESULT hr = OleGetClipboard( &pDO );
    if (FAILED(hr))
        throw uno::RuntimeException();

    hr = OleQueryCreateFromData(pDO);
    if (S_OK == hr)
    {
        hr = OleCreateFromData( pDO,
                                IID_IUnknown,
                                OLERENDER_DRAW, // OLERENDER_FORMAT
                                nullptr,        // &aFormat,
                                nullptr,
                                pStorage,
                                IID_PPV_ARGS_Helper(&m_pNativeImpl->m_pObj) );
        if (FAILED(hr))
            throw uno::RuntimeException();
    }
    else
    {
        // Static objects are not supported
        pDO->Release();
    }

    InitializeObject_Impl();
}


void OleComponent::CreateNewEmbeddedObject( const uno::Sequence< sal_Int8 >& aSeqCLSID )
{
    CLSID aClsID;

    if ( !GetClassIDFromSequence_Impl( aSeqCLSID, aClsID ) )
        throw lang::IllegalArgumentException(); // TODO

    auto pStorage(m_pNativeImpl->CreateNewStorage(getTempURL()));
    if (!pStorage)
        throw uno::RuntimeException(); // TODO

    // FORMATETC aFormat = { CF_METAFILEPICT, NULL, nAspect, -1, TYMED_MFPICT }; // for OLE..._DRAW should be NULL

    HRESULT hr = OleCreate( aClsID,
                            IID_IUnknown,
                            OLERENDER_DRAW, // OLERENDER_FORMAT
                            nullptr,        // &aFormat,
                            nullptr,
                            pStorage,
                            IID_PPV_ARGS_Helper(&m_pNativeImpl->m_pObj) );
    if (FAILED(hr))
        throw uno::RuntimeException(); // TODO

    InitializeObject_Impl();

    // TODO: getExtent???
}


void OleComponent::CreateObjectFromData( const uno::Reference< datatransfer::XTransferable >& )
// Static objects are not supported, they should be inserted as graphics
{
    // TODO: May be this call is useless since there are no static objects
    //       and nonstatic objects will be created based on OLEstorage ( stream ).
    //       ???

    // OleQueryCreateFromData...
}


void OleComponent::CreateObjectFromFile( const OUString& aFileURL )
{
    auto pStorage(m_pNativeImpl->CreateNewStorage(getTempURL()));
    if (!pStorage)
        throw uno::RuntimeException(); // TODO:

    OUString aFilePath;
    if ( ::osl::FileBase::getSystemPathFromFileURL( aFileURL, aFilePath ) != ::osl::FileBase::E_None )
        throw uno::RuntimeException(); // TODO: something dangerous happened

    HRESULT hr = OleCreateFromFile( CLSID_NULL,
                                    o3tl::toW(aFilePath.getStr()),
                                    IID_IUnknown,
                                    OLERENDER_DRAW, // OLERENDER_FORMAT
                                    nullptr,
                                    nullptr,
                                    pStorage,
                                    IID_PPV_ARGS_Helper(&m_pNativeImpl->m_pObj) );
    if (FAILED(hr))
        throw uno::RuntimeException(); // TODO

    InitializeObject_Impl();
}


void OleComponent::CreateLinkFromFile( const OUString& aFileURL )
{
    auto pStorage(m_pNativeImpl->CreateNewStorage(getTempURL()));
    if (!pStorage)
        throw uno::RuntimeException(); // TODO:

    OUString aFilePath;
    if ( ::osl::FileBase::getSystemPathFromFileURL( aFileURL, aFilePath ) != ::osl::FileBase::E_None )
        throw uno::RuntimeException(); // TODO: something dangerous happened

    HRESULT hr = OleCreateLinkToFile( o3tl::toW(aFilePath.getStr()),
                                        IID_IUnknown,
                                        OLERENDER_DRAW, // OLERENDER_FORMAT
                                        nullptr,
                                        nullptr,
                                        pStorage,
                                        IID_PPV_ARGS_Helper(&m_pNativeImpl->m_pObj) );
    if (FAILED(hr))
        throw uno::RuntimeException(); // TODO

    InitializeObject_Impl();
}


void OleComponent::InitEmbeddedCopyOfLink( rtl::Reference<OleComponent> const & pOleLinkComponent )
{
    if (!pOleLinkComponent)
        throw lang::IllegalArgumentException(); // TODO

    auto pOleLinkComponentObj(pOleLinkComponent->m_pNativeImpl->getObj());
    if (!pOleLinkComponentObj)
        throw lang::IllegalArgumentException();

    // the object must be already disconnected from the temporary URL
    auto pStorage(m_pNativeImpl->CreateNewStorage(getTempURL()));

    SolarMutexReleaser releaser;

    auto pDataObject(pOleLinkComponentObj.QueryInterface<IDataObject>(sal::systools::COM_QUERY));
    if ( pDataObject && SUCCEEDED( OleQueryCreateFromData( pDataObject ) ) )
    {
        if (!pStorage)
            throw uno::RuntimeException(); // TODO:

        OleCreateFromData( pDataObject,
                                IID_IUnknown,
                                OLERENDER_DRAW,
                                nullptr,
                                nullptr,
                                pStorage,
                                IID_PPV_ARGS_Helper(&m_pNativeImpl->m_pObj) );
    }

    if ( !m_pNativeImpl->m_pObj )
    {
        auto pOleLink(pOleLinkComponentObj.QueryInterface<IOleLink>(sal::systools::COM_QUERY));
        if ( !pOleLink )
            throw io::IOException(); // TODO: the object doesn't support IOleLink

        sal::systools::COMReference< IMoniker > pMoniker;
        HRESULT hr = pOleLink->GetSourceMoniker( &pMoniker );
        if ( FAILED( hr ) || !pMoniker )
            throw io::IOException(); // TODO: can not retrieve moniker

        // In case of file moniker life is easy : )
        DWORD aMonType = 0;
        hr = pMoniker->IsSystemMoniker( &aMonType );
        if ( SUCCEEDED( hr ) && aMonType == MKSYS_FILEMONIKER )
        {
            sal::systools::COMReference< IMalloc > pMalloc;
            hr = CoGetMalloc( 1, &pMalloc ); // if fails there will be a memory leak
            OSL_ENSURE(SUCCEEDED(hr) && pMalloc, "CoGetMalloc() failed!");

            LPOLESTR pOleStr = nullptr;
            hr = pOleLink->GetSourceDisplayName( &pOleStr );
            if ( SUCCEEDED( hr ) && pOleStr )
            {
                std::wstring aFilePath( pOleStr );
                if ( pMalloc )
                    pMalloc->Free( pOleStr );

                hr = OleCreateFromFile( CLSID_NULL,
                                        aFilePath.c_str(),
                                        IID_IUnknown,
                                        OLERENDER_DRAW, // OLERENDER_FORMAT
                                        nullptr,
                                        nullptr,
                                        pStorage,
                                        IID_PPV_ARGS_Helper(&m_pNativeImpl->m_pObj) );
            }
        }

        // in case of other moniker types the only way is to get storage
        if ( !m_pNativeImpl->m_pObj )
        {
            sal::systools::COMReference< IBindCtx > pBindCtx;
            hr = CreateBindCtx( 0, &pBindCtx );
            if ( SUCCEEDED( hr ) && pBindCtx )
            {
                sal::systools::COMReference< IStorage > pObjectStorage;
                hr = pMoniker->BindToStorage(pBindCtx, nullptr, IID_PPV_ARGS(&pObjectStorage));
                if ( SUCCEEDED( hr ) && pObjectStorage )
                {
                    hr = pObjectStorage->CopyTo(0, nullptr, nullptr, pStorage);
                    if ( SUCCEEDED( hr ) )
                        hr = OleLoadSeh(pStorage, &m_pNativeImpl->m_pObj);
                }
            }
        }
    }

    InitializeObject_Impl();
}


void OleComponent::RunObject()
{
    auto pOleObject(m_pNativeImpl->get<IOleObject>());
    OSL_ENSURE(pOleObject, "The pointer can not be set to NULL here!");
    if (!pOleObject)
        throw embed::WrongStateException(); // TODO: the object is in wrong state

    if (!OleIsRunning(pOleObject))
    {
        HRESULT hr = OleRun( m_pNativeImpl->m_pObj );

        if ( FAILED( hr ) )
        {
            OUString error = WindowsErrorStringFromHRESULT(hr);
            if ( hr == REGDB_E_CLASSNOTREG )
            {
                if (auto pOleObj
                    = m_pNativeImpl->m_pObj.QueryInterface<IOleObject>(sal::systools::COM_QUERY))
                {
                    LPOLESTR lpUserType = nullptr;
                    if (SUCCEEDED(pOleObj->GetUserType(USERCLASSTYPE_FULL, &lpUserType)))
                    {
                        error += OUString::Concat("\n") + o3tl::toU(lpUserType);
                        sal::systools::COMReference<IMalloc> pMalloc;
                        hr = CoGetMalloc(1, &pMalloc); // if fails there will be a memory leak
                        SAL_WARN_IF(FAILED(hr) || !pMalloc, "embeddedobj.ole", "CoGetMalloc() failed");
                        if (pMalloc)
                            pMalloc->Free(lpUserType);
                    }
                }
                throw embed::UnreachableStateException(
                    error, getXWeak(), -1,
                    css::embed::EmbedStates::RUNNING); // the object server is not installed
            }
            else
                throw io::IOException(error, getXWeak());
        }
        // Only now, when the object is activated, it can be registered in the global table;
        // before this point, RegisterInterfaceInGlobal would return CO_E_OBJNOTCONNECTED
        m_pNativeImpl->registerObj();
    }
}


awt::Size OleComponent::CalculateWithFactor( const awt::Size& aSize,
                                            const awt::Size& aMultiplier,
                                            const awt::Size& aDivisor )
{
    awt::Size aResult;

    sal_Int64 nWidth = static_cast<sal_Int64>(aSize.Width) * static_cast<sal_Int64>(aMultiplier.Width) / static_cast<sal_Int64>(aDivisor.Width);
    sal_Int64 nHeight = static_cast<sal_Int64>(aSize.Height) * static_cast<sal_Int64>(aMultiplier.Height) / static_cast<sal_Int64>(aDivisor.Height);
    OSL_ENSURE( nWidth < SAL_MAX_INT32 && nWidth > SAL_MIN_INT32
             && nHeight < SAL_MAX_INT32 && nHeight > SAL_MIN_INT32,
             "Unacceptable result size!" );

    aResult.Width = static_cast<sal_Int32>(nWidth);
    aResult.Height = static_cast<sal_Int32>(nHeight);

    return aResult;
}


void OleComponent::CloseObject()
{
    auto pOleObject(m_pNativeImpl->get<IOleObject>());
    if (pOleObject && OleIsRunning(pOleObject))
    {
        SolarMutexReleaser releaser;
        HRESULT hr = pOleObject->Close(OLECLOSE_NOSAVE); // must be saved before
        SAL_WARN_IF(FAILED(hr), "embeddedobj.ole", "IOleObject::Close failed");
    }
}


uno::Sequence< embed::VerbDescriptor > OleComponent::GetVerbList()
{
    auto pOleObject(m_pNativeImpl->get<IOleObject>());
    if (!pOleObject)
        throw embed::WrongStateException(); // TODO: the object is in wrong state

    if( !m_aVerbList.getLength() )
    {
        sal::systools::COMReference< IEnumOLEVERB > pEnum;
        HRESULT hr;
        {
            SolarMutexReleaser releaser;
            hr = pOleObject->EnumVerbs(&pEnum);
        }
        if (SUCCEEDED(hr))
        {
            OLEVERB     szEle[ MAX_ENUM_ELE ];
            ULONG       nNum = 0;
            sal_Int32   nSeqSize = 0;

            do
            {
                hr = pEnum->Next(MAX_ENUM_ELE, szEle, &nNum);
                if( hr == S_OK || hr == S_FALSE )
                {
                    m_aVerbList.realloc( nSeqSize += nNum );
                    auto pVerbList = m_aVerbList.getArray();
                    for( sal_uInt32 nInd = 0; nInd < nNum; nInd++ )
                    {
                        pVerbList[nSeqSize-nNum+nInd].VerbID = szEle[ nInd ].lVerb;
                        pVerbList[nSeqSize-nNum+nInd].VerbName = WinAccToVcl_Impl( o3tl::toU(szEle[ nInd ].lpszVerbName) );
                        pVerbList[nSeqSize-nNum+nInd].VerbFlags = szEle[ nInd ].fuFlags;
                        pVerbList[nSeqSize-nNum+nInd].VerbAttributes = szEle[ nInd ].grfAttribs;
                    }
                }
                else
                    break;
            }
            while( nNum == MAX_ENUM_ELE );
        }
    }

    return m_aVerbList;
}


void OleComponent::ExecuteVerb( sal_Int32 nVerbID )
{
    RunObject();

    auto pOleObject(m_pNativeImpl->get<IOleObject>());
    if (!pOleObject)
        throw embed::WrongStateException(); // TODO

    SolarMutexReleaser releaser;

    // TODO: probably extents should be set here and stored in aRect
    // TODO: probably the parent window also should be set
    HRESULT hr = pOleObject->DoVerb(nVerbID, nullptr, m_pOleWrapClientSite, 0, nullptr, nullptr);

    if ( FAILED( hr ) )
        throw io::IOException(); // TODO
}


void OleComponent::SetHostName( const OUString& aEmbDocName )
{
    auto pOleObject(m_pNativeImpl->get<IOleObject>());
    if (!pOleObject)
        throw embed::WrongStateException(); // TODO: the object is in wrong state

    SolarMutexReleaser releaser;
    pOleObject->SetHostNames(L"app name", o3tl::toW(aEmbDocName.getStr()));
}


void OleComponent::SetExtent( const awt::Size& aVisAreaSize, sal_Int64 nAspect )
{
    auto pOleObject(m_pNativeImpl->get<IOleObject>());
    if (!pOleObject)
        throw embed::WrongStateException(); // TODO: the object is in wrong state

    DWORD nMSAspect = static_cast<DWORD>(nAspect); // first 32 bits are for MS aspects

    SIZEL aSize = { aVisAreaSize.Width, aVisAreaSize.Height };
    HRESULT hr;
    {
        SolarMutexReleaser releaser;
        hr = pOleObject->SetExtent(nMSAspect, &aSize);
    }

    if ( FAILED( hr ) )
    {
        // TODO/LATER: is it correct? In future user code probably should be ready for the exception.
        // if the object is running but not activated, RPC_E_SERVER_DIED error code is returned by OLE package
        // in this case just do nothing
        // Also Visio returns E_FAIL on resize if it is in running state
        // if ( hr != RPC_E_SERVER_DIED )
        throw io::IOException(); // TODO
    }
}


awt::Size OleComponent::GetExtent( sal_Int64 nAspect )
{
    if (!m_pNativeImpl->m_pObj)
        throw embed::WrongStateException(); // TODO: the object is in wrong state

    DWORD nMSAspect = static_cast<DWORD>(nAspect); // first 32 bits are for MS aspects
    awt::Size aSize;
    bool bGotSize = false;

    if ( nMSAspect == DVASPECT_CONTENT )
    {
        // Try to get the size from the replacement image first
        if (auto pDataObject = m_pNativeImpl->get<IDataObject>())
        {
            STGMEDIUM aMedium;
            FORMATETC aFormat = pFormatTemplates[1]; // use windows metafile format
            aFormat.dwAspect = nMSAspect;

            HRESULT hr;
            {
                SolarMutexReleaser releaser;
                hr = pDataObject->GetData(&aFormat, &aMedium);
            }

            if (hr == RPC_E_WRONG_THREAD)
            {
                // Assume that the OLE object was loaded on the main thread.
                vcl::solarthread::syncExecute([this, &hr, &pDataObject, &aFormat, &aMedium]() {
                    // Make sure that the current state is embed::EmbedStates::RUNNING.
                    RunObject();
                    // Now try again on the correct thread.
                    hr = pDataObject->GetData(&aFormat, &aMedium);
                });
            }

            if ( SUCCEEDED( hr ) && aMedium.tymed == TYMED_MFPICT ) // Win Metafile
            {
                METAFILEPICT* pMF = static_cast<METAFILEPICT*>(GlobalLock( aMedium.hMetaFilePict ));
                if ( pMF )
                {
                    // the object uses 0.01 mm as unit, so the metafile size should be converted to object unit
                    o3tl::Length eFrom = o3tl::Length::mm100;
                    switch( pMF->mm )
                    {
                        case MM_HIENGLISH:
                            eFrom = o3tl::Length::in1000;
                            break;

                        case MM_LOENGLISH:
                            eFrom = o3tl::Length::in100;
                            break;

                        case MM_LOMETRIC:
                            eFrom = o3tl::Length::mm10;
                            break;

                        case MM_TWIPS:
                            eFrom = o3tl::Length::twip;
                            break;

                        case MM_ISOTROPIC:
                        case MM_ANISOTROPIC:
                        case MM_HIMETRIC:
                            // do nothing
                            break;
                    }

                    sal_Int64 nX = o3tl::convert(abs( pMF->xExt ), eFrom, o3tl::Length::mm100);
                    sal_Int64 nY = o3tl::convert(abs( pMF->yExt ), eFrom, o3tl::Length::mm100);
                    if (  nX < SAL_MAX_INT32 && nY < SAL_MAX_INT32 )
                    {
                        aSize.Width = static_cast<sal_Int32>(nX);
                        aSize.Height = static_cast<sal_Int32>(nY);
                        bGotSize = true;
                    }
                    else
                        OSL_FAIL( "Unexpected size is provided!" );
                }
            }
            else if (!SUCCEEDED(hr))
            {
                SAL_WARN("embeddedobj.ole", " OleComponent::GetExtent: GetData() failed");
            }
            // i113605, to release storage medium
            if ( SUCCEEDED( hr ) )
                ::ReleaseStgMedium(&aMedium);
        }
    }

    if ( !bGotSize )
        throw lang::IllegalArgumentException();

    return aSize;
}


awt::Size OleComponent::GetCachedExtent( sal_Int64 nAspect )
{
    auto pViewObject2(m_pNativeImpl->get<IViewObject2>());
    if (!pViewObject2)
        throw embed::WrongStateException(); // TODO: the object is in wrong state

    DWORD nMSAspect = static_cast<DWORD>(nAspect); // first 32 bits are for MS aspects
    SIZEL aSize;

    HRESULT hr;
    {
        SolarMutexReleaser releaser;
        hr = pViewObject2->GetExtent(nMSAspect, -1, nullptr, &aSize);
    }

    if ( FAILED( hr ) )
    {
        // TODO/LATER: is it correct?
        // if there is no appropriate cache for the aspect, OLE_E_BLANK error code is returned
        // if ( hr == OLE_E_BLANK )
        //  throw lang::IllegalArgumentException();
        //else
        //  throw io::IOException(); // TODO

        SAL_WARN("embeddedobj.ole", " OleComponent::GetCachedExtent: GetExtent() failed");
        throw lang::IllegalArgumentException();
    }

    return awt::Size( aSize.cx, aSize.cy );
}


awt::Size OleComponent::GetRecommendedExtent( sal_Int64 nAspect )
{
    auto pOleObject(m_pNativeImpl->get<IOleObject>());
    if (!pOleObject)
        throw embed::WrongStateException(); // TODO: the object is in wrong state

    DWORD nMSAspect = static_cast<DWORD>(nAspect); // first 32 bits are for MS aspects
    SIZEL aSize;
    HRESULT hr;
    {
        SolarMutexReleaser releaser;
        hr = pOleObject->GetExtent(nMSAspect, &aSize);
    }
    if ( FAILED( hr ) )
    {
        SAL_WARN("embeddedobj.ole", " OleComponent::GetRecommendedExtent: GetExtent() failed");
        throw lang::IllegalArgumentException();
    }

    return awt::Size( aSize.cx, aSize.cy );
}


sal_Int64 OleComponent::GetMiscStatus( sal_Int64 nAspect )
{
    auto pOleObject(m_pNativeImpl->get<IOleObject>());
    if (!pOleObject)
        throw embed::WrongStateException(); // TODO: the object is in wrong state

    DWORD nResult = 0;
    {
        SolarMutexReleaser releaser;
        pOleObject->GetMiscStatus(static_cast<DWORD>(nAspect), &nResult);
    }
    return static_cast<sal_Int64>(nResult); // first 32 bits are for MS flags
}


uno::Sequence< sal_Int8 > OleComponent::GetCLSID()
{
    auto pOleObject(m_pNativeImpl->get<IOleObject>());
    if (!pOleObject)
        throw embed::WrongStateException(); // TODO: the object is in wrong state

    GUID aCLSID;
    HRESULT hr;
    {
        SolarMutexReleaser releaser;
        hr = pOleObject->GetUserClassID(&aCLSID);
    }
    if ( FAILED( hr ) )
        throw io::IOException(); // TODO:

    return  MimeConfigurationHelper::GetSequenceClassID( aCLSID.Data1, aCLSID.Data2, aCLSID.Data3,
                                aCLSID.Data4[0], aCLSID.Data4[1],
                                aCLSID.Data4[2], aCLSID.Data4[3],
                                aCLSID.Data4[4], aCLSID.Data4[5],
                                aCLSID.Data4[6], aCLSID.Data4[7] );
}


bool OleComponent::IsDirty()
{
    if ( IsWorkaroundActive() )
        return true;

    auto pPersistStorage(m_pNativeImpl->get<IPersistStorage>());
    if ( !pPersistStorage )
        throw io::IOException(); // TODO

    SolarMutexReleaser releaser;
    HRESULT hr = pPersistStorage->IsDirty();
    return ( hr != S_FALSE );
}


void OleComponent::StoreOwnTmpIfNecessary()
{
    auto pOleObject(m_pNativeImpl->get<IOleObject>());
    if (!pOleObject)
        throw embed::WrongStateException(); // TODO: the object is in wrong state

    auto pPersistStorage(m_pNativeImpl->get<IPersistStorage>());
    if ( !pPersistStorage )
        throw io::IOException(); // TODO

    SolarMutexReleaser releaser;

    if ( m_bWorkaroundActive || pPersistStorage->IsDirty() != S_FALSE )
    {
        auto pStorage(m_pNativeImpl->getStorage());
        HRESULT hr = OleSave(pPersistStorage, pStorage, TRUE);
        if ( FAILED( hr ) )
        {
            // Till now was required only for AcrobatReader7.0.8
            GUID aCLSID;
            hr = pOleObject->GetUserClassID(&aCLSID);
            if ( FAILED( hr ) )
            {
                SAL_WARN("embeddedobj.ole", "OleComponent::StoreOwnTmpIfNecessary: GetUserClassID() failed");
                throw io::IOException(); // TODO
            }

            hr = WriteClassStg(pStorage, aCLSID);
            if ( FAILED( hr ) )
                throw io::IOException(); // TODO

            // the result of the following call is not checked because some objects, for example AcrobatReader7.0.8
            // return error even in case the saving was done correctly
            hr = pPersistStorage->Save(pStorage, TRUE);

            // another workaround for AcrobatReader7.0.8 object, this object might think that it is not changed
            // when it has been created from file, although it must be saved
            m_bWorkaroundActive = true;
        }

        hr = pStorage->Commit(STGC_DEFAULT);
        if ( FAILED( hr ) )
            throw io::IOException(); // TODO

        hr = pPersistStorage->SaveCompleted( nullptr );
        if ( FAILED( hr ) && hr != E_UNEXPECTED )
            throw io::IOException(); // TODO

    }
}


bool OleComponent::SaveObject_Impl()
{
    bool bResult = false;
    OleEmbeddedObject* pLockObject = nullptr;

    {
        osl::MutexGuard aGuard( m_aMutex );
        if ( m_pUnoOleObject )
        {
            pLockObject = m_pUnoOleObject;
            pLockObject->acquire();
        }
    }

    if ( pLockObject )
    {
        bResult = pLockObject->SaveObject_Impl();
        pLockObject->release();
    }

    return bResult;
}


bool OleComponent::OnShowWindow_Impl( bool bShow )
{
    bool bResult = false;
    OleEmbeddedObject* pLockObject = nullptr;

    {
        osl::MutexGuard aGuard( m_aMutex );

        if ( m_pUnoOleObject )
        {
            pLockObject = m_pUnoOleObject;
            pLockObject->acquire();
        }
    }

    if ( pLockObject )
    {
        bResult = pLockObject->OnShowWindow_Impl( bShow );
        pLockObject->release();
    }

    return bResult;
}


void OleComponent::OnViewChange_Impl( sal_uInt32 dwAspect )
{
    // TODO: check if it is enough or may be saving notifications are required for Visio2000
    ::rtl::Reference< OleEmbeddedObject > xLockObject;

    {
        osl::MutexGuard aGuard( m_aMutex );
        if ( m_pUnoOleObject )
            xLockObject = m_pUnoOleObject;
    }

    if ( xLockObject.is() )
    {
        uno::Reference < awt::XRequestCallback > xRequestCallback(
            m_xContext->getServiceManager()->createInstanceWithContext("com.sun.star.awt.AsyncCallback", m_xContext),
             uno::UNO_QUERY );
        xRequestCallback->addCallback( new MainThreadNotificationRequest( xLockObject, OLECOMP_ONVIEWCHANGE, dwAspect ), uno::Any() );
    }
}


void OleComponent::OnClose_Impl()
{
    ::rtl::Reference< OleEmbeddedObject > xLockObject;

    {
        osl::MutexGuard aGuard( m_aMutex );
        if ( m_pUnoOleObject )
            xLockObject = m_pUnoOleObject;
    }

    if ( xLockObject.is() )
    {
        uno::Reference < awt::XRequestCallback > xRequestCallback(
            m_xContext->getServiceManager()->createInstanceWithContext("com.sun.star.awt.AsyncCallback", m_xContext),
             uno::UNO_QUERY );
        xRequestCallback->addCallback( new MainThreadNotificationRequest( xLockObject, OLECOMP_ONCLOSE ), uno::Any() );
    }
}

// XCloseable

void SAL_CALL OleComponent::close( sal_Bool bDeliverOwnership )
{
    uno::Reference< uno::XInterface > xSelfHold;
    {
        osl::MutexGuard aGuard(m_aMutex);
        if (m_bDisposed)
            throw lang::DisposedException(); // TODO

        xSelfHold.set(static_cast<::cppu::OWeakObject*>(this));
        lang::EventObject aSource(static_cast<::cppu::OWeakObject*>(this));

        if (m_pInterfaceContainer)
        {
            comphelper::OInterfaceContainerHelper2* pContainer
                = m_pInterfaceContainer->getContainer(cppu::UnoType<util::XCloseListener>::get());
            if (pContainer != nullptr)
            {
                comphelper::OInterfaceIteratorHelper2 pIterator(*pContainer);
                while (pIterator.hasMoreElements())
                {
                    try
                    {
                        static_cast<util::XCloseListener*>(pIterator.next())
                            ->queryClosing(aSource, bDeliverOwnership);
                    }
                    catch (const uno::RuntimeException&)
                    {
                        pIterator.remove();
                    }
                }
            }

            pContainer
                = m_pInterfaceContainer->getContainer(cppu::UnoType<util::XCloseListener>::get());
            if (pContainer != nullptr)
            {
                comphelper::OInterfaceIteratorHelper2 pCloseIterator(*pContainer);
                while (pCloseIterator.hasMoreElements())
                {
                    try
                    {
                        static_cast<util::XCloseListener*>(pCloseIterator.next())
                            ->notifyClosing(aSource);
                    }
                    catch (const uno::RuntimeException&)
                    {
                        pCloseIterator.remove();
                    }
                }
            }
        }
    }

    Dispose();
}


void SAL_CALL OleComponent::addCloseListener( const uno::Reference< util::XCloseListener >& xListener )
{
    ::osl::MutexGuard aGuard( m_aMutex );
    if ( m_bDisposed )
        throw lang::DisposedException(); // TODO

    if ( !m_pInterfaceContainer )
        m_pInterfaceContainer = new comphelper::OMultiTypeInterfaceContainerHelper2( m_aMutex );

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


void SAL_CALL OleComponent::removeCloseListener( const uno::Reference< util::XCloseListener >& xListener )
{
    ::osl::MutexGuard aGuard( m_aMutex );
    if ( m_bDisposed )
        throw lang::DisposedException(); // TODO

    if ( m_pInterfaceContainer )
        m_pInterfaceContainer->removeInterface( cppu::UnoType<util::XCloseListener>::get(),
                                                xListener );
}

// XTransferable

uno::Any SAL_CALL OleComponent::getTransferData( const datatransfer::DataFlavor& aFlavor )
{
    ::osl::MutexGuard aGuard( m_aMutex );
    if ( m_bDisposed )
        throw lang::DisposedException(); // TODO

    if (!m_pNativeImpl->m_pObj)
        throw embed::WrongStateException(); // TODO: the object is in wrong state

    uno::Any aResult;
    bool bSupportedFlavor = false;

    if ( m_pNativeImpl->GraphicalFlavor( aFlavor ) )
    {
        DWORD nRequestedAspect = GetAspectFromFlavor( aFlavor );
        // if own icon is set and icon aspect is requested the own icon can be returned directly

        auto pDataObject(m_pNativeImpl->get<IDataObject>());
        if ( !pDataObject )
            throw io::IOException(); // TODO: transport error code

        // The following optimization does not make much sense currently just because
        // only one aspect is supported, and only three formats for the aspect are supported
        // and moreover it is not guaranteed that the once returned format will be supported further
        // example - i52106
        // TODO/LATER: bring the optimization back when other aspects are supported

        // FORMATETC* pFormatEtc = m_pNativeImpl->GetSupportedFormatForAspect( nRequestedAspect );
        // if ( pFormatEtc )
        // {
        //  STGMEDIUM aMedium;
        //  hr = pDataObject->GetData( pFormatEtc, &aMedium );
        //  if ( SUCCEEDED( hr ) )
        //      bSupportedFlavor = m_pNativeImpl->ConvertDataForFlavor( aMedium, aFlavor, aResult );
        // }
        // else
        {
            // the supported format of the application is still not found, find one
            for ( sal_Int32 nInd = 0; nInd < FORMATS_NUM; nInd++ )
            {
                STGMEDIUM aMedium;
                FORMATETC aFormat = pFormatTemplates[nInd];
                aFormat.dwAspect = nRequestedAspect;

                HRESULT hr;
                {
                    SolarMutexReleaser releaser;
                    hr = pDataObject->GetData(&aFormat, &aMedium);
                }
                if ( SUCCEEDED( hr ) )
                {
                    bSupportedFlavor = m_pNativeImpl->ConvertDataForFlavor( aMedium, aFlavor, aResult );
                    ::ReleaseStgMedium(&aMedium);     // i113605, to release storage medium
                    if ( bSupportedFlavor )
                    {
                        // TODO/LATER: bring the optimization back when other aspects are supported
                        // m_pNativeImpl->AddSupportedFormat( aFormat );
                        break;
                    }
                }
            }
        }

        // If the replacement could not be retrieved, the cached representation should be used
        // currently it is not necessary to retrieve it here, so it is implemented in the object itself
    }
    // TODO: Investigate if there is already the format name
    //       and whether this format is really required
    else if ( aFlavor.DataType == cppu::UnoType<io::XInputStream>::get()
            && aFlavor.MimeType == "application/x-openoffice-contentstream" )
    {
        // allow to retrieve stream-representation of the object persistence
        bSupportedFlavor = true;
        uno::Reference < io::XStream > xTempFileStream(
            io::TempFile::create(m_xContext),
            uno::UNO_QUERY_THROW );

        uno::Reference< io::XOutputStream > xTempOutStream = xTempFileStream->getOutputStream();
        uno::Reference< io::XInputStream > xTempInStream = xTempFileStream->getInputStream();
        if ( !(xTempOutStream.is() && xTempInStream.is()) )
            throw io::IOException(); // TODO:

        OSL_ENSURE( m_pUnoOleObject, "Unexpected object absence!" );
        if ( !m_pUnoOleObject )
            throw uno::RuntimeException();

        m_pUnoOleObject->StoreObjectToStream( xTempOutStream );

        xTempOutStream->closeOutput();
        xTempOutStream.clear();

        aResult <<= xTempInStream;
    }

    if ( !bSupportedFlavor )
        throw datatransfer::UnsupportedFlavorException();

    return aResult;
}


uno::Sequence< datatransfer::DataFlavor > SAL_CALL OleComponent::getTransferDataFlavors()
{
    ::osl::MutexGuard aGuard( m_aMutex );
    if ( m_bDisposed )
        throw lang::DisposedException(); // TODO

    RetrieveObjectDataFlavors_Impl();

    return m_aDataFlavors;
}


sal_Bool SAL_CALL OleComponent::isDataFlavorSupported( const datatransfer::DataFlavor& aFlavor )
{
    ::osl::MutexGuard aGuard( m_aMutex );
    if ( m_bDisposed )
        throw lang::DisposedException(); // TODO

    RetrieveObjectDataFlavors_Impl();

    for (auto const& supportedFormat : m_aDataFlavors)
        if ( supportedFormat.MimeType.equals( aFlavor.MimeType ) && supportedFormat.DataType == aFlavor.DataType )
            return true;

    return false;
}

void SAL_CALL OleComponent::dispose()
{
    try
    {
        close( true );
    }
    catch ( const uno::Exception& )
    {
    }
}

void SAL_CALL OleComponent::addEventListener( const uno::Reference< lang::XEventListener >& xListener )
{
    ::osl::MutexGuard aGuard( m_aMutex );
    if ( m_bDisposed )
        throw lang::DisposedException(); // TODO

    if ( !m_pInterfaceContainer )
        m_pInterfaceContainer = new comphelper::OMultiTypeInterfaceContainerHelper2( m_aMutex );

    m_pInterfaceContainer->addInterface( cppu::UnoType<lang::XEventListener>::get(), xListener );
}


void SAL_CALL OleComponent::removeEventListener( const uno::Reference< lang::XEventListener >& xListener )
{
    ::osl::MutexGuard aGuard( m_aMutex );
    if ( m_bDisposed )
        throw lang::DisposedException(); // TODO

    if ( m_pInterfaceContainer )
        m_pInterfaceContainer->removeInterface( cppu::UnoType<lang::XEventListener>::get(),
                                                xListener );
}

sal_Int64 SAL_CALL OleComponent::getSomething( const css::uno::Sequence< sal_Int8 >& aIdentifier )
{
    try
    {
        uno::Sequence < sal_Int8 > aCLSID = GetCLSID();
        if ( MimeConfigurationHelper::ClassIDsEqual( aIdentifier, aCLSID ) )
            return comphelper::getSomething_cast(m_pNativeImpl->m_pObj.get());
    }
    catch ( const uno::Exception& )
    {
    }

    return 0;
}

sal_Bool SAL_CALL OleComponent::isModified()
{
    return m_bModified;
}

void SAL_CALL OleComponent::setModified( sal_Bool bModified )
{
    m_bModified = bModified;

    if ( bModified && m_pInterfaceContainer )
    {
        comphelper::OInterfaceContainerHelper2* pContainer =
            m_pInterfaceContainer->getContainer( cppu::UnoType<util::XModifyListener>::get());
        if ( pContainer != nullptr )
        {
            comphelper::OInterfaceIteratorHelper2 pIterator( *pContainer );
            while ( pIterator.hasMoreElements() )
            {
                try
                {
                    lang::EventObject aEvent( static_cast<util::XModifiable*>(this) );
                    static_cast<util::XModifyListener*>(pIterator.next())->modified( aEvent );
                }
                catch( const uno::RuntimeException& )
                {
                    pIterator.remove();
                }
            }
        }
    }
}

void SAL_CALL OleComponent::addModifyListener( const css::uno::Reference < css::util::XModifyListener >& xListener )
{
    ::osl::MutexGuard aGuard( m_aMutex );
    if ( m_bDisposed )
        throw lang::DisposedException(); // TODO

    if ( !m_pInterfaceContainer )
        m_pInterfaceContainer = new comphelper::OMultiTypeInterfaceContainerHelper2( m_aMutex );

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

void SAL_CALL OleComponent::removeModifyListener( const css::uno::Reference < css::util::XModifyListener >& xListener)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    if ( m_bDisposed )
        throw lang::DisposedException(); // TODO

    if ( m_pInterfaceContainer )
        m_pInterfaceContainer->removeInterface( cppu::UnoType<util::XModifyListener>::get(),
                                                xListener );
}

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