summaryrefslogtreecommitdiff
path: root/embeddedobj/source/msole/olecomponent.cxx
blob: d1116b35bf5159c9cc7afacd9edbf285e0cf0ac8 (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
/*************************************************************************
 *
 *  $RCSfile: olecomponent.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: mav $ $Date: 2003-11-17 16:19:24 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_DOUBLEINITIALIZATIONEXCEPTION_HPP_
#include <com/sun/star/frame/DoubleInitializationException.hpp>
#endif

#ifndef _COM_SUN_STAR_EMBED_WRONGSTATEEXCEPTION_HPP_
#include <com/sun/star/embed/WrongStateException.hpp>
#endif

#ifndef _COM_SUN_STAR_UCB_XSIMPLEFILEACCESS_HPP_
#include <com/sun/star/ucb/XSimpleFileAccess.hpp>
#endif

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


#include <platform.h>

#include <cppuhelper/interfacecontainer.h>
#include <osl/file.hxx>

#include "olecomponent.hxx"
#include "olewrapclient.hxx"
#include "advisesink.hxx"
#include "oleembobj.hxx"


using namespace ::com::sun::star;

#define     MAX_ENUM_ELE     20
const sal_Int32 n_ConstBufferSize = 32000;

STDAPI StarObject_SwitchDisplayAspect(IUnknown *pObj, LPDWORD pdwCurAspect
    , DWORD dwNewAspect, HGLOBAL hMetaPict, BOOL fDeleteOld
    , BOOL fViewAdvise, IAdviseSink *pSink, BOOL *pfMustUpdate)
{
    // TODO: implement the switching
    return S_OK;
}


sal_Bool ConvertDataForFlavor( const STGMEDIUM& aMedium, const datatransfer::DataFlavor& aFlavor, uno::Any& aResult )
{
    // TODO: try to convert data from Medium format to specified Flavor format
    return sal_False;
}

//----------------------------------------------
sal_Bool GraphicalFlavor( const datatransfer::DataFlavor& aFlavor )
{
    // TODO: just check that the requested flavour is one of supported graphical flavours
    return sal_False;
}

//-----------------------------------------------
// TODO: probably later such a common function can be moved
//       to a separate helper library.
void copyInputToOutput_Impl( const uno::Reference< io::XInputStream >& aIn,
                             const uno::Reference< io::XOutputStream >& aOut )
{
    sal_Int32 nRead;
    uno::Sequence < sal_Int8 > aSequence ( n_ConstBufferSize );

    do
    {
        nRead = aIn->readBytes ( aSequence, n_ConstBufferSize );
        if ( nRead < n_ConstBufferSize )
        {
            uno::Sequence < sal_Int8 > aTempBuf ( aSequence.getConstArray(), nRead );
            aOut->writeBytes ( aTempBuf );
        }
        else
            aOut->writeBytes ( aSequence );
    }
    while ( nRead == n_ConstBufferSize );
}

//-----------------------------------------------
sal_Bool KillFile( const ::rtl::OUString& aURL, const uno::Reference< lang::XMultiServiceFactory >& xFactory )
{
    if ( !xFactory.is() )
        return sal_False;

    sal_Bool bRet = sal_False;

    try
    {
        uno::Reference < ucb::XSimpleFileAccess > xAccess(
                xFactory->createInstance (
                        ::rtl::OUString::createFromAscii( "com.sun.star.ucb.SimpleFileAccess" ) ),
                uno::UNO_QUERY );

        if ( xAccess.is() )
        {
            xAccess->kill( aURL );
            bRet = sal_True;
        }
    }
    catch( uno::Exception& )
    {
    }

    return bRet;
}

//----------------------------------------------
::rtl::OUString GetNewTempFileURL( const uno::Reference< lang::XMultiServiceFactory >& xFactory )
{
    OSL_ENSURE( xFactory.is(), "No factory is provided!\n" );

    ::rtl::OUString aResult;

    uno::Reference < beans::XPropertySet > xTempFile(
            xFactory->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.io.TempFile" ) ),
            uno::UNO_QUERY );

    if ( !xTempFile.is() )
        throw uno::RuntimeException(); // TODO

    try {
        xTempFile->setPropertyValue( ::rtl::OUString::createFromAscii( "RemoveFile" ), uno::makeAny( sal_False ) );
        uno::Any aUrl = xTempFile->getPropertyValue( ::rtl::OUString::createFromAscii( "Uri" ) );
        aUrl >>= aResult;
    }
    catch ( uno::Exception& )
    {
    }

    if ( !aResult.getLength() )
        throw uno::RuntimeException(); // TODO: can not create tempfile

    return aResult;
}

//-----------------------------------------------
::rtl::OUString GetNewFilledTempFile( const uno::Reference< io::XInputStream >& xInStream,
                                      const uno::Reference< lang::XMultiServiceFactory >& xFactory )
        throw( io::IOException )
{
    OSL_ENSURE( xInStream.is() && xFactory.is(), "Wrong parameters are provided!\n" );

    ::rtl::OUString aResult = GetNewTempFileURL( xFactory );

    if ( aResult )
    {
        try {
            uno::Reference < ucb::XSimpleFileAccess > xTempAccess(
                            xFactory->createInstance (
                                    ::rtl::OUString::createFromAscii( "com.sun.star.ucb.SimpleFileAccess" ) ),
                            uno::UNO_QUERY );

            if ( !xTempAccess.is() )
                throw uno::RuntimeException(); // TODO:

            uno::Reference< io::XOutputStream > xTempOutStream = xTempAccess->openFileWrite( aResult );
            if ( xTempOutStream.is() )
            {
                // copy stream contents to the file
                copyInputToOutput_Impl( xInStream, xTempOutStream );
                xTempOutStream->closeOutput();
                xTempOutStream = uno::Reference< io::XOutputStream >();
            }
            else
                throw io::IOException(); // TODO:
        }
        catch( packages::WrongPasswordException& )
        {
               KillFile( aResult, xFactory );
            throw io::IOException(); //TODO:
        }
        catch( io::IOException& )
        {
               KillFile( aResult, xFactory );
            throw;
        }
        catch( uno::RuntimeException& )
        {
               KillFile( aResult, xFactory );
            throw;
        }
        catch( uno::Exception& )
        {
               KillFile( aResult, xFactory );
            aResult = ::rtl::OUString();
        }
    }

    return aResult;
}

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

        return sal_True;
    }

    return sal_False;
}

//----------------------------------------------
::rtl::OUString WinAccToVcl( const sal_Unicode* pStr )
{
    ::rtl::OUString aResult;

    if( pStr )
    {
        while ( *pStr )
        {
            if ( *pStr == '&' )
            {
                aResult += ::rtl::OUString::createFromAscii( "~" );
                while( *(++pStr) == '&' );
            }
            else
            {
                aResult += ::rtl::OUString( pStr, 1 );
                pStr++;
            }
        }
    }

    return aResult;
}

//----------------------------------------------
OleComponent::OleComponent( const uno::Reference< lang::XMultiServiceFactory >& xFactory, OleEmbeddedObject* pUnoOleObject )
: m_pInterfaceContainer( NULL )
, m_bDisposed( sal_False )
, m_xFactory( xFactory )
, m_pOleWrapClientSite( NULL )
, m_pImplAdviseSink( NULL )
, m_pUnoOleObject( pUnoOleObject )
, m_nMSAspect( 0 )
, m_nOLEMiscFlags( 0 )
, m_nAdvConn( 0 )
, m_nSupportedFormat( 0 )
, m_nSupportedMedium( 0 )
, m_bOleInitialized( sal_False )
{
    OSL_ENSURE( m_pUnoOleObject, "No owner object is provided!" );

    HRESULT hr = OleInitialize( NULL );
    OSL_ENSURE( hr == S_OK || hr == S_FALSE, "The ole can not be successfuly initialized\n" );
    if ( hr == S_OK || hr == S_FALSE )
        m_bOleInitialized = sal_True;

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

    m_pImplAdviseSink = new OleWrapperAdviseSink( (OleComponent*)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 )
    {
        m_refCount++;
        try {
            Dispose();
        } catch( uno::Exception& ) {}
    }
}

//----------------------------------------------
void OleComponent::Dispose()
{
    if ( m_pOleWrapClientSite )
    {
        m_pOleWrapClientSite->disconnectOleComponent();
        m_pOleWrapClientSite->Release();
        m_pOleWrapClientSite = NULL;
    }

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

    if ( m_pInterfaceContainer )
    {
        lang::EventObject aEvent( (embed::XEmbeddedObject*)this );
        m_pInterfaceContainer->disposeAndClear( aEvent );

        delete m_pInterfaceContainer;
        m_pInterfaceContainer = NULL;
    }

    if ( m_bOleInitialized )
    {
        OleUninitialize();
        m_bOleInitialized = sal_False;
    }

    m_bDisposed = sal_True;
}

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

//----------------------------------------------
CComPtr< IStorage > OleComponent::CreateIStorageOnXInputStream_Impl( const uno::Reference< io::XInputStream >& xInStream )
{
    // TODO: in future a global memory should be used instead of file.

    OSL_ENSURE( !m_aTempURL.getLength(), "The object already has temporary representation!\n" );

    // write the stream to the temporary file
    m_aTempURL = GetNewFilledTempFile( xInStream, m_xFactory );
    if ( !m_aTempURL.getLength() )
        throw uno::RuntimeException(); // TODO

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

    HRESULT hr = StgCreateDocfile( aTempFilePath, STGM_READWRITE | STGM_DELETEONRELEASE, 0, &m_pIStorage );
    if ( FAILED( hr ) || !m_pIStorage )
        throw io::IOException(); // TODO: transport error code?

    return m_pIStorage;
}

//----------------------------------------------
CComPtr< IStorage > OleComponent::CreateNewIStorage_Impl()
{
    // TODO: in future a global memory should be used instead of file.

    OSL_ENSURE( !m_aTempURL.getLength(), "The object already has temporary representation!\n" );

    // write the stream to the temporary file
    m_aTempURL = GetNewTempFileURL( m_xFactory );
    if ( !m_aTempURL.getLength() )
        throw uno::RuntimeException(); // TODO

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

    HRESULT hr = StgCreateDocfile( aTempFilePath, STGM_CREATE | STGM_READWRITE | STGM_TRANSACTED | STGM_DELETEONRELEASE, 0, &m_pIStorage );
    if ( FAILED( hr ) || !m_pIStorage )
        throw io::IOException(); // TODO: transport error code?

    return m_pIStorage;
}

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

    if ( !m_aDataFlavors.getLength() )
    {
        CComPtr< IDataObject > pDataObject;
        HRESULT hr = m_pObj->QueryInterface( IID_IDataObject, (void**)&pDataObject );
        if ( FAILED( hr ) || !pDataObject )
            throw io::IOException(); // TODO: transport error code

        CComPtr< IEnumFORMATETC > pFormatEnum;
        hr = pDataObject->EnumFormatEtc( DATADIR_GET, &pFormatEnum );
        if ( FAILED( hr ) || !pFormatEnum )
            throw io::IOException(); // TODO: transport error code

        FORMATETC pElem[ MAX_ENUM_ELE ];
        ULONG nNum = 0;

        do
        {
            HRESULT hr = pFormatEnum->Next( MAX_ENUM_ELE, pElem, &nNum );
            if( hr == S_OK || hr == S_FALSE )
            {
                for( sal_uInt32 nInd = 0; nInd < nNum; nInd++ )
                {
                    //TODO: add OOo format reachable from specified OLE format to the list
                }
            }
            else
                break;
        }
        while( nNum == MAX_ENUM_ELE );
    }
}

//----------------------------------------------
sal_Bool OleComponent::InitializeObject_Impl( sal_uInt32 nIconHandle )
// There will be no static objects!
{
    if ( !m_pObj )
        return sal_False;

    // the linked object will be detected here
    CComPtr< IOleLink > pOleLink;
    HRESULT hr = m_pObj->QueryInterface( IID_IOleLink, (void**)&pOleLink );
    m_pUnoOleObject->SetObjectIsLink_Impl( pOleLink != NULL );


    hr = m_pObj->QueryInterface( IID_IViewObject2, (void**)&m_pViewObject2 );
    if ( FAILED( hr ) || !m_pViewObject2 )
        return sal_False;

    m_pViewObject2->SetAdvise( m_nMSAspect, 0, m_pImplAdviseSink );

    // register cache in case there is no ( Visio 2000 workaround )
    IOleCache* pIOleCache = NULL;
    if ( SUCCEEDED( m_pObj->QueryInterface( IID_IOleCache, (void**)&pIOleCache ) ) && pIOleCache )
    {
        IEnumSTATDATA* pEnumSD = NULL;
        HRESULT hr = pIOleCache->EnumCache( &pEnumSD );

        sal_Bool bRegister = sal_True;
        if ( SUCCEEDED( hr ) && pEnumSD )
        {
            pEnumSD->Reset();
            STATDATA aSD;
            DWORD nNum;
            while( SUCCEEDED( pEnumSD->Next( 1, &aSD, &nNum ) ) && nNum == 1 )
            {
                if ( aSD.formatetc.cfFormat == 0 )
                {
                    bRegister = sal_False;
                    break;
                }
            }
        }

        if ( bRegister )
        {
            DWORD nConn;
            FORMATETC aFormat = { 0, 0, DVASPECT_CONTENT, -1, TYMED_MFPICT };
            hr = pIOleCache->Cache( &aFormat, ADVFCACHE_ONSAVE, &nConn );
        }

        pIOleCache->Release();
        pIOleCache = NULL;
    }

    hr = m_pObj->QueryInterface( IID_IOleObject, (void**)&m_pOleObject );
    if ( FAILED( hr ) || !m_pOleObject )
        return sal_False; // Static objects are not supported, they should be inserted as graphics

    m_pOleObject->GetMiscStatus( m_nMSAspect, (DWORD*)&m_nOLEMiscFlags );
    // TODO: use other misc flags also
    // the object should have drawable aspect even in case it supports only iconic representation
    // if ( m_nOLEMiscFlags & OLEMISC_ONLYICONIC )
    //  m_nMSAspect = DVASPECT_ICON;

    m_pOleObject->SetClientSite( m_pOleWrapClientSite );
    m_pOleObject->Advise( m_pImplAdviseSink, (DWORD*)&m_nAdvConn );

    OleSetContainedObject( m_pOleObject, TRUE );

    if ( m_nMSAspect & DVASPECT_ICON )
    {
        // TODO: the icon provided from dialog must be stored
        //       if there is no icon, it should be retrieved
        DWORD nOldAspect = DVASPECT_CONTENT;
        IAdviseSink *pSink;

        pSink = ( nIconHandle == NULL ) ? NULL : m_pImplAdviseSink;

        StarObject_SwitchDisplayAspect( m_pOleObject,
                                        &nOldAspect,
                                        DVASPECT_ICON,
                                        (HGLOBAL)(UINT)nIconHandle,
                                        FALSE,
                                        nIconHandle != NULL,
                                        pSink,
                                        NULL );
    }

    return sal_True;
}

//----------------------------------------------
void OleComponent::LoadEmbeddedObject( const uno::Reference< io::XInputStream >& xInStream, sal_Int64 nAspect )
{
    if ( !xInStream.is() )
        throw lang::IllegalArgumentException(); // TODO

    if ( m_pIStorage || m_aTempURL.getLength() )
        throw frame::DoubleInitializationException(); // TODO the object is already initialized

    m_nMSAspect = (DWORD)nAspect; // first 32 bits are for MS aspects

    m_pIStorage = CreateIStorageOnXInputStream_Impl( xInStream );
    if ( !m_pIStorage )
        throw uno::RuntimeException(); // TODO:

    HRESULT hr = OleLoad( m_pIStorage, IID_IUnknown, NULL, (void**)&m_pObj );
    if ( FAILED( hr ) || !m_pObj )
        throw uno::RuntimeException();

    if ( !InitializeObject_Impl( NULL ) )
        throw uno::RuntimeException(); // TODO
}

//----------------------------------------------
void OleComponent::CreateNewEmbeddedObject( const uno::Sequence< sal_Int8 >& aSeqCLSID,
                                            sal_Int64 nAspect,
                                            sal_uInt32 nIconHandle )
{
    CLSID aClsID;

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

    if ( m_pIStorage || m_aTempURL.getLength() )
        throw frame::DoubleInitializationException(); // the object is already initialized

    m_pIStorage = CreateNewIStorage_Impl();
    if ( !m_pIStorage )
        throw uno::RuntimeException(); // TODO

    // FORMATETC aFormat = { CF_METAFILEPICT, NULL, nAspect, -1, TYMED_MFPICT }; // for OLE..._DRAW should be NULL
    m_nMSAspect = (DWORD)nAspect; // first 32 bits are for MS aspects

    HRESULT hr = OleCreate( aClsID,
                            IID_IUnknown,
                            OLERENDER_DRAW, // OLERENDER_FORMAT
                            NULL,           // &aFormat,
                            NULL,
                            m_pIStorage,
                            (void**)&m_pObj );

    if ( FAILED( hr ) || !m_pObj )
        throw uno::RuntimeException(); // TODO

    if ( !InitializeObject_Impl( nIconHandle ) )
        throw uno::RuntimeException(); // TODO

    // TODO: getExtent???
}

//----------------------------------------------
void OleComponent::CreateObjectFromData( const uno::Reference< datatransfer::XTransferable >& xTransfer,
                                         sal_Int64 nAspect )
// 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 ::rtl::OUString& aFileName, sal_Int64 nAspect, sal_uInt32 nIconHandle )
{
    // TODO:
}

//----------------------------------------------
void OleComponent::CreateLinkFromFile( const ::rtl::OUString& aFileName, sal_Int64 nAspect, sal_uInt32 nIconHandle )
{
    // TODO:
}

//----------------------------------------------
void OleComponent::RunObject()
{
    if ( !m_pOleObject )
        throw embed::WrongStateException(); // TODO: the object is in wrong state

    if ( !OleIsRunning( m_pOleObject ) )
    {
        HRESULT hr = OleRun( m_pObj );
        if ( FAILED( hr ) )
            throw io::IOException();
    }
}

//----------------------------------------------
void OleComponent::CloseObject()
{
    if ( !m_pOleObject )
        throw embed::WrongStateException(); // TODO: the object is in wrong state

    if ( OleIsRunning( m_pOleObject ) )
        m_pOleObject->Close( OLECLOSE_NOSAVE ); // must be saved before
}

//----------------------------------------------
uno::Sequence< embed::VerbDescr > OleComponent::GetVerbList()
{
    if ( !m_pOleObject )
        throw embed::WrongStateException(); // TODO: the object is in wrong state

    if( !m_aVerbList.getLength() )
    {
        CComPtr< IEnumOLEVERB > pEnum;
        if( SUCCEEDED( m_pOleObject->EnumVerbs( &pEnum ) ) )
        {
            OLEVERB     szEle[ MAX_ENUM_ELE ];
            ULONG       nNum = 0;
            sal_Int32   nSeqSize = 0;

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

    return m_aVerbList;
}

//----------------------------------------------
void OleComponent::ExecuteVerb( sal_Int32 nVerbID )
{
    if ( !m_pOleObject )
        throw embed::WrongStateException(); // TODO

    HRESULT hr = OleRun( m_pOleObject );
    if ( FAILED( hr ) )
        throw io::IOException(); // TODO: a specific exception that transport error code can be thrown here

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

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

//----------------------------------------------
void OleComponent::SetHostName( const ::rtl::OUString& aContName,
                                const ::rtl::OUString& aEmbDocName )
{
    if ( !m_pOleObject )
        throw embed::WrongStateException(); // TODO: the object is in wrong state

    // TODO: use aContName and aEmbDocName in m_pOleObject->SetHostNames()
}

//----------------------------------------------
void OleComponent::SetExtent( const awt::Size& aVisAreaSize, sal_Int64 nAspect )
{
    if ( !m_pOleObject )
        throw embed::WrongStateException(); // TODO: the object is in wrong state

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

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

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

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

    DWORD nMSAspect = (DWORD)nAspect; // first 32 bits are for MS aspects
    SIZEL aSize;
    HRESULT hr = m_pOleObject->GetExtent( nMSAspect, &aSize );

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

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

//----------------------------------------------
sal_Int64 OleComponent::GetMiscStatus()
{
    if ( !m_pOleObject )
        throw embed::WrongStateException(); // TODO: the object is in wrong state

    return (sal_Int64)m_nOLEMiscFlags; // first 32 bits are for MS flags
}

//----------------------------------------------
sal_Int64 OleComponent::GetViewAspect()
{
    if ( !m_pOleObject )
        throw embed::WrongStateException(); // TODO: the object is in wrong state

    return (sal_Int64)m_nMSAspect; // first 32 bits are for MS aspects
}

//----------------------------------------------
void OleComponent::StoreObjectToStream( uno::Reference< io::XOutputStream > xOutStream, sal_Bool bStoreVisReplace )
{
    if ( !m_pOleObject )
        throw embed::WrongStateException(); // TODO: the object is in wrong state

    CComPtr< IPersistStorage > pPersistStorage;
    HRESULT hr = m_pObj->QueryInterface(IID_IPersistStorage, (void**)&pPersistStorage);
    if ( FAILED( hr ) || !pPersistStorage )
        throw io::IOException(); // TODO

    hr = OleSave(pPersistStorage, m_pIStorage, TRUE);
    if ( FAILED( hr ) )
        throw io::IOException(); // TODO

    pPersistStorage->SaveCompleted(NULL);
    m_pIStorage->Commit( STGC_DEFAULT );

    // now all the changes should be in temporary location

    // open temporary file for reading
    uno::Reference < ucb::XSimpleFileAccess > xTempAccess(
                    m_xFactory->createInstance (
                            ::rtl::OUString::createFromAscii( "com.sun.star.ucb.SimpleFileAccess" ) ),
                    uno::UNO_QUERY );

    if ( !xTempAccess.is() )
        throw uno::RuntimeException(); // TODO:

    uno::Reference< io::XInputStream > xTempInStream = xTempAccess->openFileRead( m_aTempURL );
    OSL_ENSURE( xTempInStream.is(), "The object's temporary file can not be reopened for reading!\n" );

    // TODO: use bStoreVisReplace

    if ( xTempInStream.is() )
    {
        // write all the contents to XOutStream
        copyInputToOutput_Impl( xTempInStream, xOutStream );
    }
    else
        throw io::IOException(); // TODO:

    // TODO: should the view replacement be in the stream ???
    //       probably it must be specified on storing
}

//----------------------------------------------
sal_Bool OleComponent::SaveObject_Impl()
{
    sal_Bool bResult = sal_False;
    OleEmbeddedObject* pLockObject = NULL;

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

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

    return bResult;
}

//----------------------------------------------
sal_Bool OleComponent::OnShowWindow_Impl( sal_Bool bShow )
{
    sal_Bool bResult = sal_False;
    OleEmbeddedObject* pLockObject = NULL;

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

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

    return bResult;
}

//----------------------------------------------
void OleComponent::OnViewChange_Impl( DWORD dwAspect )
{
    // TODO: make a notification ?
    // TODO: check if it is enough or may be saving notifications are required for Visio2000
}

//----------------------------------------------
sal_Bool OleComponent::GetGraphicalCache_Impl( const datatransfer::DataFlavor& aFlavor, uno::Any& aResult )
{
    sal_Bool bOk = sal_False;
    if ( m_pIStorage )
    {
        // try to retrieve cached representation
        // TODO: in future it must be converted to requested format
        for ( sal_uInt8 nInd = 0; nInd < 10; nInd++ )
        {
            CComPtr< IStream > pGrStream;
            ::rtl::OUString aStreamName = ::rtl::OUString::createFromAscii( "\002OlePres00" );
            aStreamName += ::rtl::OUString::valueOf( nInd );
            HRESULT hr = m_pIStorage->OpenStream( aStreamName.getStr(),
                                                    NULL,
                                                    STGM_READ,
                                                    NULL,
                                                    &pGrStream );
            if ( FAILED( hr ) || !pGrStream )
                break;

            // TODO: check that the format is acceptable
            //       if so - break

            // create XInputStream ( for now SvStream ) with graphical representation
            // try to generate a Metafile or Bitmap from it
            // convert the result representation to requested format
            // if ( succeeded ) (bOk = sal_True), break;
        }
    }

    return bOk;
}

// XCloseable
//----------------------------------------------
void SAL_CALL OleComponent::close( sal_Bool bDeliverOwnership )
    throw ( util::CloseVetoException,
            uno::RuntimeException )
{
    ::osl::MutexGuard aGuard( m_aMutex );
    if ( m_bDisposed )
        throw lang::DisposedException(); // TODO

    uno::Reference< uno::XInterface > xSelfHold( static_cast< ::cppu::OWeakObject* >( this ) );
    lang::EventObject aSource( static_cast< ::cppu::OWeakObject* >( this ) );

    if ( m_pInterfaceContainer )
    {
        ::cppu::OInterfaceContainerHelper* pContainer =
            m_pInterfaceContainer->getContainer( ::getCppuType( ( const uno::Reference< util::XCloseListener >*) NULL ) );
        if ( pContainer != NULL )
        {
            ::cppu::OInterfaceIteratorHelper pIterator(*pContainer);
            while (pIterator.hasMoreElements())
            {
                try
                {
                    ((util::XCloseListener*)pIterator.next())->queryClosing( aSource, bDeliverOwnership );
                }
                catch( uno::RuntimeException& )
                {
                    pIterator.remove();
                }
            }
        }

        pContainer = m_pInterfaceContainer->getContainer(
                                    ::getCppuType( ( const uno::Reference< util::XCloseListener >*) NULL ) );
        if ( pContainer != NULL )
        {
            ::cppu::OInterfaceIteratorHelper pCloseIterator(*pContainer);
            while (pCloseIterator.hasMoreElements())
            {
                try
                {
                    ((util::XCloseListener*)pCloseIterator.next())->notifyClosing( aSource );
                }
                catch( uno::RuntimeException& )
                {
                    pCloseIterator.remove();
                }
            }
        }
    }

    Dispose();
}

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

    if ( !m_pInterfaceContainer )
        m_pInterfaceContainer = new ::cppu::OMultiTypeInterfaceContainerHelper( m_aMutex );

    m_pInterfaceContainer->addInterface( ::getCppuType( (const uno::Reference< util::XCloseListener >*)0 ), xListener );
}

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

    if ( m_pInterfaceContainer )
        m_pInterfaceContainer->removeInterface( ::getCppuType( (const uno::Reference< util::XCloseListener >*)0 ),
                                                xListener );
}

// XTransferable
//----------------------------------------------
uno::Any SAL_CALL OleComponent::getTransferData( const datatransfer::DataFlavor& aFlavor )
    throw ( datatransfer::UnsupportedFlavorException,
            io::IOException,
            uno::RuntimeException )
{
    ::osl::MutexGuard aGuard( m_aMutex );
    if ( m_bDisposed )
        throw lang::DisposedException(); // TODO

    if ( !m_pOleObject )
        throw embed::WrongStateException(); // TODO: the object is in wrong state

    uno::Any aResult;
    sal_Bool bSupportedFlavor = sal_False;

    if ( GraphicalFlavor( aFlavor ) )
    {
        // first check if there is a cached representation
        if ( m_pIStorage )
        {
            // try to retrieve cached representation
            bSupportedFlavor = GetGraphicalCache_Impl( aFlavor, aResult );
        }

        if ( !bSupportedFlavor )
        {
            // TODO: retrieve MS METAFILE or bitmap and try to convert it to required format
            CComPtr< IDataObject > pDataObject;
            HRESULT hr = m_pObj->QueryInterface( IID_IDataObject, (void**)&pDataObject );
            if ( FAILED( hr ) || !pDataObject )
                throw io::IOException(); // TODO: transport error code

            if ( m_nSupportedFormat )
            {
                FORMATETC aFormatEtc = { m_nSupportedFormat, NULL, m_nMSAspect, -1, m_nSupportedMedium };
                STGMEDIUM aMedium;
                hr = pDataObject->GetData( &aFormatEtc, &aMedium );
                if ( SUCCEEDED( hr ) )
                    bSupportedFlavor = ConvertDataForFlavor( aMedium, aFlavor, aResult );
            }
            else
            {
                // the supported format of the application is still not found, find one
                sal_Int16 nFormats[3] = { CF_ENHMETAFILE, CF_METAFILEPICT, CF_BITMAP };
                sal_Int32 nMediums[3] = { TYMED_ENHMF, TYMED_MFPICT, TYMED_GDI };

                for ( sal_Int32 nInd = 0; nInd < 3; nInd++ )
                {
                    FORMATETC aFormatEtc = { nFormats[nInd], NULL, m_nMSAspect, -1, nMediums[nInd] };
                    STGMEDIUM aMedium;
                    hr = pDataObject->GetData( &aFormatEtc, &aMedium );
                    if ( SUCCEEDED( hr ) )
                    {
                        m_nSupportedFormat = nFormats[nInd];
                        m_nSupportedMedium = nMediums[nInd];

                        bSupportedFlavor = ConvertDataForFlavor( aMedium, aFlavor, aResult );
                        break;
                    }
                }
            }

            if ( !bSupportedFlavor )
            {
                // TODO: implement workaround for stampit
            }
        }
    }
    else
    {
        // TODO: allow to retrieve stream-representation of the object persistence
    }

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

    return aResult;
}

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

    if ( !m_pOleObject )
        throw embed::WrongStateException(); // TODO: the object is in wrong state

    RetrieveObjectDataFlavors_Impl();

    return m_aDataFlavors;
}

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

    if ( !m_pOleObject )
        throw embed::WrongStateException(); // TODO: the object is in wrong state

    if ( !m_aDataFlavors.getLength() )
    {
        // TODO: detect format, the object writes representation in, and return reachable from it formats
        RetrieveObjectDataFlavors_Impl();
    }

    for ( sal_Int32 nInd = 0; nInd < m_aDataFlavors.getLength(); nInd++ )
        if ( m_aDataFlavors[nInd].MimeType.equals( aFlavor.MimeType ) && m_aDataFlavors[nInd].DataType == aFlavor.DataType )
            return sal_True;

    return sal_False;
}