summaryrefslogtreecommitdiff
path: root/extensions/source/plugin/base/xplugin.cxx
blob: 5afcbbf45f0735a1f390d734dc4d117d99b36e53 (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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_extensions.hxx"
#ifdef AIX
#define _LINUX_SOURCE_COMPAT
#include <sys/timer.h>
#undef _LINUX_SOURCE_COMPAT
#endif

#ifdef WNT
#include <prewin.h>
#include <postwin.h>
#undef OPTIONAL
#endif

#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#include <com/sun/star/loader/XImplementationLoader.hpp>
#include <com/sun/star/loader/CannotActivateFactoryException.hpp>

#include <plugin/impl.hxx>
#include <tools/fsys.hxx>
#include <ucbhelper/content.hxx>
#include <tools/urlobj.hxx>
#include <tools/string.hxx>
#include <vcl/svapp.hxx>
#include <salhelper/timer.hxx>
#include <osl/file.hxx>

#ifdef UNX
#include <sys/types.h>
#include <sys/socket.h>
#endif

#if OSL_DEBUG_LEVEL > 1
#include <stdio.h>
#endif

using namespace com::sun::star;
using namespace com::sun::star::io;
using namespace com::sun::star::beans;
using namespace com::sun::star::plugin;
using namespace osl;

using ::rtl::OUString;
using ::rtl::OString;

class PluginDisposer : public salhelper::Timer
{
private:
    XPlugin_Impl*       m_pPlugin;

    virtual void SAL_CALL onShot();
public:
    PluginDisposer( XPlugin_Impl* pPlugin ) :
        salhelper::Timer( salhelper::TTimeValue( 2, 0 ),
                          salhelper::TTimeValue( 2, 0 ) ),
        m_pPlugin( pPlugin )
        { start(); }
    ~PluginDisposer() {}
};

void PluginDisposer::onShot()
{
    if( m_pPlugin )
    {
        if( m_pPlugin->isDisposable() )
        {
            sal_uLong nEvent;
            Application::PostUserEvent( nEvent, LINK( m_pPlugin, XPlugin_Impl, secondLevelDispose ), (void*)m_pPlugin );
        }
    }
    else
        release();
}

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

Any XPlugin_Impl::queryInterface( const Type& type ) throw( RuntimeException )
{
    return OWeakAggObject::queryInterface( type );
}

Any XPlugin_Impl::queryAggregation( const Type& type ) throw( RuntimeException )
{
    Any aRet( cppu::queryInterface( type, static_cast< XPlugin* >(this) ) );
    if( ! aRet.hasValue() )
        aRet = PluginControl_Impl::queryAggregation( type );
    return aRet;
}


XPlugin_Impl::XPlugin_Impl( const uno::Reference< com::sun::star::lang::XMultiServiceFactory >  & rSMgr) :
        PluginControl_Impl(),
        m_xSMgr( rSMgr ),
        m_pPluginComm( NULL ),
        m_aEncoding( gsl_getSystemTextEncoding() ),
        m_pArgv( NULL ),
        m_pArgn( NULL ),
        m_nArgs( 0 ),
        m_aPluginMode( NP_FULL ),
        m_nProvidingState( PROVIDING_NONE ),
        m_nCalledFromPlugin( 0 ),
        m_pDisposer( NULL ),
        m_bIsDisposed( sal_False )
{
    memset( &m_aInstance, 0, sizeof( m_aInstance ) );
    memset( &m_aNPWindow, 0, sizeof( m_aNPWindow ) );
    memset( &m_aSysPlugData, 0, sizeof( m_aSysPlugData ) );

    m_xModel = new PluginModel();
    uno::Reference< com::sun::star::beans::XPropertySet >  xPS( m_xModel, UNO_QUERY );
    xPS->addPropertyChangeListener( OUString(), this );

    Guard< Mutex > aGuard( PluginManager::get().getPluginMutex() );
    PluginManager::get().getPlugins().push_back( this );
}

void XPlugin_Impl::destroyInstance()
{
    Guard< Mutex > aGuard( m_aMutex );

    NPSavedData* pSavedData = NULL;

    destroyStreams();
    if( getPluginComm() )
    {
        getPluginComm()->NPP_Destroy( this, &pSavedData );
        getPluginComm()->decRef();
        m_pPluginComm = NULL;
    }

    freeArgs();

    while( m_aPEventListeners.size() )
    {
        delete *m_aPEventListeners.begin();
        m_aPEventListeners.pop_front();
    }
}

XPlugin_Impl::~XPlugin_Impl()
{
    destroyInstance();
}

void XPlugin_Impl::checkListeners( const char* normalizedURL )
{
    if( ! normalizedURL )
        return;

    Guard< Mutex > aGuard( m_aMutex );

    std::list<PluginEventListener*>::iterator iter;
    for( iter = m_aPEventListeners.begin();
         iter != m_aPEventListeners.end();
         ++iter )
    {
        if( ! strcmp( normalizedURL, (*iter)->getURL() ) ||
            ! strcmp( normalizedURL, (*iter)->getNormalizedURL() ) )
        {
            (*iter)->disposing( com::sun::star::lang::EventObject() );
            delete *iter;
            m_aPEventListeners.remove( *iter );
            return;
        }
    }
}

IMPL_LINK( XPlugin_Impl, secondLevelDispose, XPlugin_Impl*, /*pThis*/ )
{
    Guard< Mutex > aGuard( m_aMutex );

    // may have become undisposable between PostUserEvent and here
    // or may have disposed and receive a second UserEvent
    std::list<XPlugin_Impl*>& rList = PluginManager::get().getPlugins();
    std::list<XPlugin_Impl*>::iterator iter;

    {
        Guard< Mutex > aPluginGuard( PluginManager::get().getPluginMutex() );
        for( iter = rList.begin(); iter != rList.end(); ++iter )
        {
            if( *iter == this )
                break;
        }
        if( iter == rList.end() || ! isDisposable() )
            return 0;
    }

    if (m_pDisposer)
    {
        m_pDisposer->release();
        m_pDisposer = NULL;
    }

    uno::Reference< XPlugin >  xProtection( this );
    uno::Reference< com::sun::star::beans::XPropertySet >  xPS( m_xModel, UNO_QUERY );
    xPS->removePropertyChangeListener( OUString(), this );
    {
        Guard< Mutex > aPluginGuard( PluginManager::get().getPluginMutex() );
        rList.remove( this );
    }
    m_aNPWindow.window = NULL;
#ifndef UNX
    // acrobat does an unconditional XtParent on the windows widget
    getPluginComm()->NPP_SetWindow( this );
#endif
    destroyInstance();
    PluginControl_Impl::dispose();
    return 0;
}

void XPlugin_Impl::dispose() throw()
{
    Guard< Mutex > aGuard( m_aMutex );

    if (m_bIsDisposed || !getPluginComm())
        return;
    m_bIsDisposed = sal_True;

    if( isDisposable() )
        secondLevelDispose( this );
    else
    {
        m_pDisposer = new PluginDisposer( this );
        m_pDisposer->acquire();
    }
}

void XPlugin_Impl::initArgs( const Sequence< OUString >& argn,
                             const Sequence< OUString >& argv,
                             sal_Int16 mode )
{
    m_aPluginMode = mode;

    m_nArgs = argn.getLength();
    m_pArgn = new const char*[m_nArgs];
    m_pArgv = new const char*[m_nArgs];
    const OUString* pUArgn = argn.getConstArray();
    const OUString* pUArgv = argv.getConstArray();
    for( int i = 0; i < m_nArgs; i++ )
    {
        m_pArgn[i] = strdup(
            OUStringToOString( pUArgn[i], m_aEncoding ).getStr()
            );
        m_pArgv[i] = strdup(
            OUStringToOString( pUArgv[i], m_aEncoding ).getStr()
            );
    }
}

void XPlugin_Impl::freeArgs()
{
    if( m_nArgs > 0 )
    {
        for( ; m_nArgs--; )
        {
            free( (void*)m_pArgn[m_nArgs] );
            free( (void*)m_pArgv[m_nArgs] );
        }
        delete [] m_pArgn;
        delete [] m_pArgv;
    }
}

void XPlugin_Impl::prependArg( const char* pName, const char* pValue )
{
    const char** pNewNames      = new const char*[m_nArgs+1];
    const char** pNewValues = new const char*[m_nArgs+1];

    pNewNames[0]        = strdup( pName );
    pNewValues[0]       = strdup( pValue );
    for( int nIndex = 0; nIndex < m_nArgs; ++nIndex )
    {
        pNewNames[nIndex+1] = m_pArgn[nIndex];
        pNewValues[nIndex+1]= m_pArgv[nIndex];
    }
    // free old arrays
    delete [] m_pArgn;
    delete [] m_pArgv;
    // set new arrays
    m_pArgn = pNewNames;
    m_pArgv = pNewValues;
    // set new number of arguments
    m_nArgs++;
#if OSL_DEBUG_LEVEL > 1
    fprintf( stderr, "inserted %s=%s\n", pNewNames[0], pNewValues[0] );
#endif
}

void XPlugin_Impl::handleSpecialArgs()
{
    // special handling for real audio which needs a lot of parameters
    // or won't function at all
    if( ! m_aDescription.Mimetype.compareToAscii( "audio/x-pn-realaudio-plugin" ) && m_nArgs < 1 )
    {
        OUString aURL;
        if( m_xModel.is() )
        {
            try
            {
                uno::Reference< XPropertySet > xProp( m_xModel, UNO_QUERY );
                Any aProp = xProp->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "URL" ) ) );
                aProp >>= aURL;
            }
            catch( UnknownPropertyException )
            {
            }
        }

        if( aURL.getLength() )
        {
            // set new args, old args need not be freed as there were none set
            m_nArgs = 6;
            m_pArgn = new const char*[m_nArgs];
            m_pArgv = new const char*[m_nArgs];

            // SRC
            m_pArgn[0]      = strdup( "SRC" );
            m_pArgv[0]      = strdup( OUStringToOString( aURL, m_aEncoding ).getStr() );
            // WIDTH
            m_pArgn[1]      = strdup( "WIDTH" );
            m_pArgv[1]      = strdup( "200" );
            // HEIGHT
            m_pArgn[2]      = strdup( "HEIGHT" );
            m_pArgv[2]      = strdup( "200" );
            // CONTROLS
            m_pArgn[3]      = strdup( "CONTROLS" );
            m_pArgv[3]      = strdup( "PlayButton,StopButton,ImageWindow" );
            // AUTOSTART
            m_pArgn[4]      = strdup( "AUTOSTART" );
            m_pArgv[4]      = strdup( "TRUE" );
            // NOJAVA
            m_pArgn[5]      = strdup( "NOJAVA" );
            m_pArgv[5]      = strdup( "TRUE" );
        }
    }
    // #69333# special for pdf
    else if( ! m_aDescription.Mimetype.compareToAscii( "application/pdf" ) )
        m_aPluginMode = PluginMode::FULL;

    // see if we have a TYPE tag
    int nIndex;
    for( nIndex = 0; nIndex < m_nArgs; ++nIndex )
        if( m_pArgn[nIndex][0] == 'T' &&
            m_pArgn[nIndex][1] == 'Y' &&
            m_pArgn[nIndex][2] == 'P' &&
            m_pArgn[nIndex][3] == 'E' &&
            m_pArgn[nIndex][4] == 0 )
            break;
    if( nIndex >= m_nArgs )
    {
        // TYPE
        prependArg( "TYPE", OUStringToOString( m_aDescription.Mimetype, m_aEncoding ).getStr() );
    }

    // see if we have a SRC tag
    for( nIndex = 0; nIndex < m_nArgs; ++nIndex )
        if( m_pArgn[nIndex][0] == 'S' &&
            m_pArgn[nIndex][1] == 'R' &&
            m_pArgn[nIndex][2] == 'C' &&
            m_pArgn[nIndex][3] == 0 )
            break;
    if( nIndex >= m_nArgs )
    {
        // need a SRC parameter (as all browser set one on the plugin
        OUString aURL;
        if( m_xModel.is() )
        {
            try
            {
                uno::Reference< XPropertySet > xProp( m_xModel, UNO_QUERY );
                Any aProp = xProp->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "URL" ) ) );
                aProp >>= aURL;
            }
            catch( UnknownPropertyException )
            {
            }
        }

        if( aURL.getLength() )
        {
            // SRC
            prependArg( "SRC", OUStringToOString( aURL, m_aEncoding ).getStr() );
        }
    }
}

void XPlugin_Impl::initInstance( const PluginDescription& rDescription,
                                 const Sequence< OUString >& argn,
                                 const Sequence< OUString >& argv,
                                 sal_Int16 mode )
{
    Guard< Mutex > aGuard( m_aMutex );

    m_aDescription = rDescription;
    initArgs( argn, argv, mode );
    handleSpecialArgs();
}

void XPlugin_Impl::initInstance( const OUString& rURL,
                                 const Sequence< OUString >& argn,
                                 const Sequence< OUString >& argv,
                                 sal_Int16 mode )
{
    Guard< Mutex > aGuard( m_aMutex );

    initArgs( argn, argv, mode );
    m_aDescription = fitDescription( rURL );

    m_xModel = new PluginModel( rURL, m_aDescription.Mimetype );
    handleSpecialArgs();
}

void XPlugin_Impl::modelChanged()
{
    Guard< Mutex > aGuard( m_aMutex );

    m_nProvidingState = PROVIDING_MODEL_UPDATE;

    destroyInstance();

    m_aDescription = fitDescription( getCreationURL() );
    if( !m_aDescription.Mimetype.getLength() )
    {
        m_nProvidingState = PROVIDING_NONE;
        return;
    }

    OUString aURL = getCreationURL();
    provideNewStream( m_aDescription.Mimetype,
                      uno::Reference< XActiveDataSource >(),
                      aURL,
                      0, 0, (sal_Bool)(aURL.compareToAscii( "file:", 5 ) == 0) );
    m_nProvidingState = PROVIDING_NONE;
}

OUString XPlugin_Impl::getCreationURL()
{
    Guard< Mutex > aGuard( m_aMutex );

    OUString aRet;
    uno::Reference< com::sun::star::beans::XPropertySet >  xPS( m_xModel, UNO_QUERY );
    if( xPS.is() )
    {
        Any aValue = xPS->getPropertyValue( OUString(RTL_CONSTASCII_USTRINGPARAM("URL")) );
        aValue >>= aRet;
    }
    return aRet;
}


sal_Bool XPlugin_Impl::setModel( const uno::Reference< com::sun::star::awt::XControlModel > & Model )
    throw( RuntimeException )
{
    Guard< Mutex > aGuard( m_aMutex );

    uno::Reference< com::sun::star::beans::XPropertySet >  xPS( Model, UNO_QUERY );
    if( ! xPS.is() )
        return sal_False;

    if( getCreationURL().getLength() )
    {
        m_xModel = Model;
        modelChanged();
        xPS->addPropertyChangeListener( OUString(), this );
        return sal_True;
    }
    return sal_False;
}

void XPlugin_Impl::createPeer( const uno::Reference< com::sun::star::awt::XToolkit > & xToolkit, const uno::Reference< com::sun::star::awt::XWindowPeer > & Parent )
    throw( RuntimeException )
{
    Guard< Mutex > aGuard( m_aMutex );

    if( ! _xPeer.is() )
    {
        if( ! Parent.is() )
            throw  RuntimeException();
        PluginControl_Impl::createPeer( xToolkit, Parent );
    }
}

void XPlugin_Impl::loadPlugin()
{
    Guard< Mutex > aGuard( m_aMutex );

    std::list<PluginComm*>::iterator iter;
    for( iter = PluginManager::get().getPluginComms().begin();
         iter != PluginManager::get().getPluginComms().end(); ++iter )
    {
        if( OStringToOUString( (*iter)->getLibName(), m_aEncoding ) == m_aDescription.PluginName )
        {
            setPluginComm( *iter );
            break;
        }
    }
    const SystemEnvData* pEnvData = getSysChildSysData();
#if defined( UNX ) && !(defined(QUARTZ))
    XSync( (Display*)pEnvData->pDisplay, False );
#endif
    if( ! getPluginComm() )
    {
        if( m_aDescription.PluginName.getLength() )
        {
#if defined QUARTZ
            PluginComm* pComm = new MacPluginComm( m_aDescription.Mimetype,
                                                   m_aDescription.PluginName,
                                                   pEnvData->pView );
#elif defined UNX
            // need a new PluginComm
            PluginComm* pComm = NULL;
            int sv[2];
            if( !socketpair( AF_UNIX, SOCK_STREAM, 0, sv ) )
                pComm = new UnxPluginComm( m_aDescription.Mimetype,
                                           m_aDescription.PluginName,
                                           (XLIB_Window)pEnvData->aWindow,
                                           sv[0],
                                           sv[1]
                                           );
#elif (defined WNT || defined OS2)
            PluginComm* pComm = new PluginComm_Impl( m_aDescription.Mimetype,
                                                     m_aDescription.PluginName,
                                                     (HWND)pEnvData->hWnd );
#endif
            setPluginComm( pComm );
        }
        else
            return;
    }

    getPluginComm()->
        NPP_New( (char*)OUStringToOString( m_aDescription.Mimetype,
                                                  m_aEncoding).getStr(),
                 getNPPInstance(),
                 m_aPluginMode == PluginMode::FULL ? NP_FULL : NP_EMBED,
                 ::sal::static_int_cast< int16, int >( m_nArgs ),
                 (char**)(m_nArgs ? m_pArgn : NULL),
                 (char**)(m_nArgs ? m_pArgv : NULL),
                 NULL );
#ifdef QUARTZ
    // m_aNPWindow is set up in the MacPluginComm from the view
    m_aSysPlugData.m_pParentView = pEnvData->pView;
#elif defined( UNX )
    XSync( (Display*)pEnvData->pDisplay, False );
    m_aNPWindow.window      = (void*)pEnvData->aWindow;
    m_aNPWindow.ws_info     = NULL;
#else
    m_aNPWindow.window = (void*)pEnvData->hWnd;
#endif
    com::sun::star::awt::Rectangle aPosSize = getPosSize();

    for( int i = 0; i < m_nArgs; i++ )
    {
        OString aName( m_pArgn[i] );
        if( aName.equalsIgnoreAsciiCase( "width" ) )
        {
            OString aValue( m_pArgv[i] );
            aPosSize.Width = aValue.toInt32();
        }
        else if( aName.equalsIgnoreAsciiCase( "height" ) )
        {
            OString aValue( m_pArgv[i] );
            aPosSize.Height = aValue.toInt32();
        }
    }

    m_aNPWindow.clipRect.top        = 0;
    m_aNPWindow.clipRect.left       = 0;
    m_aNPWindow.clipRect.bottom     = ::sal::static_int_cast< uint16, sal_Int32 >( aPosSize.Height );
    m_aNPWindow.clipRect.right      = ::sal::static_int_cast< uint16, sal_Int32 >( aPosSize.Width );
    m_aNPWindow.type = NPWindowTypeWindow;

    m_aNPWindow.x       = 0;
    m_aNPWindow.y       = 0;
    m_aNPWindow.width   = aPosSize.Width ? aPosSize.Width : 600;
    m_aNPWindow.height  = aPosSize.Height ? aPosSize.Height : 600;

    getPluginComm()->NPP_SetWindow( this );
}

void XPlugin_Impl::destroyStreams()
{
    Guard< Mutex > aGuard( m_aMutex );

    // streams remove themselves from this list when deleted
    while( m_aOutputStreams.size() )
        delete *m_aOutputStreams.begin();

    // input streams are XOutputStreams, they cannot be simply deleted
    std::list<PluginInputStream*> aLocalList( m_aInputStreams );
    for( std::list<PluginInputStream*>::iterator it = aLocalList.begin();
         it != aLocalList.end(); ++it )
        (*it)->setMode( -1 );
}

PluginStream* XPlugin_Impl::getStreamFromNPStream( NPStream* stream )
{
    Guard< Mutex > aGuard( m_aMutex );

    std::list<PluginInputStream*>::iterator iter;
    for( iter = m_aInputStreams.begin(); iter != m_aInputStreams.end(); ++iter )
        if( (*iter)->getStream() == stream )
            return *iter;

    std::list<PluginOutputStream*>::iterator iter2;
    for( iter2 = m_aOutputStreams.begin(); iter2 != m_aOutputStreams.end(); ++iter2 )
        if( (*iter2)->getStream() == stream )
            return *iter2;

    return NULL;
}

sal_Bool XPlugin_Impl::provideNewStream(const OUString& mimetype,
                                        const uno::Reference< com::sun::star::io::XActiveDataSource > & stream,
                                        const OUString& url, sal_Int32 length,
                                        sal_Int32 lastmodified, sal_Bool isfile) throw()

{
    Guard< Mutex > aGuard( m_aMutex );
    sal_Bool bRet = sal_False;

    if( m_nProvidingState != PROVIDING_NONE )
    {
        m_nProvidingState = PROVIDING_NOW;
        Any aAny;
        aAny <<= url;
        uno::Reference< com::sun::star::beans::XPropertySet >  xPS( m_xModel, UNO_QUERY );
        if( xPS.is() )
        {
            try
            {
                xPS->setPropertyValue( OUString(RTL_CONSTASCII_USTRINGPARAM("URL")), aAny );
                aAny <<= mimetype;
                xPS->setPropertyValue( OUString(RTL_CONSTASCII_USTRINGPARAM("TYPE")), aAny );
            }
            catch(...)
            {
            }
        }
    }
    m_nProvidingState = PROVIDING_NOW;

    OString aMIME;
    if( mimetype.getLength() )
        aMIME = OUStringToOString( mimetype, m_aEncoding );
    else
        aMIME = OUStringToOString( m_aDescription.Mimetype, m_aEncoding );

    OString aURL  = OUStringToOString( url, m_aEncoding );

    // check wether there is a notifylistener for this stream
    // this means that the strema is created from the plugin
    // via NPN_GetURLNotify or NPN_PostURLNotify
    std::list<PluginEventListener*>::iterator iter;
    for( iter = m_aPEventListeners.begin();
         iter != m_aPEventListeners.end();
         ++iter )
    {
        if( (*iter)->getNormalizedURL() == aURL )
        {
            aURL = (*iter)->getURL();
            break;
        }
    }

    if( ! m_pPluginComm )
    {
        loadPlugin();
        if( m_aLastGetUrl.getLength() && m_aLastGetUrl == aURL )
        {
            // plugin is pulling data, don't push the same stream;
            // this complicated method could have been avoided if
            // all plugins respected the SRC parameter; but e.g.
            // acrobat reader plugin does not
            m_nProvidingState = PROVIDING_NONE;
            return sal_True;
        }
    }
     if( ! m_pPluginComm )
        return sal_False;

     if( ! url.getLength() )
         // this is valid if the plugin is supposed to
         // pull data (via e.g. NPN_GetURL)
         return sal_True;

     // set mimetype on model
     {
         uno::Reference< com::sun::star::beans::XPropertySet >  xPS( m_xModel, UNO_QUERY );
         if( xPS.is() )
         {
             try
             {
                 Any aAny;
                 aAny <<= m_aDescription.Mimetype;
                 xPS->setPropertyValue( OUString(RTL_CONSTASCII_USTRINGPARAM("TYPE")), aAny );
             }
             catch(...)
             {
             }
         }
     }

     // there may be plugins that can use the file length information,
     // but currently none are known. Since this file opening/seeking/closing
     // is rather costly, it is not implemented. If there are plugins known to
     // make use of the file length, simply put it in

     PluginInputStream* pStream = new PluginInputStream( this, aURL.getStr(),
                                                        length, lastmodified );
     uno::Reference< com::sun::star::io::XOutputStream > xNewStream( pStream );

     if( iter != m_aPEventListeners.end() )
         pStream->getStream()->notifyData = (*iter)->getNotifyData();

    uint16 stype = 0;

    // special handling acrobat reader
    // presenting a seekable stream to it does not seem to work correctly
    if( aMIME.equals( "application/pdf" ) )
        isfile = sal_False;

#if OSL_DEBUG_LEVEL > 1
    fprintf( stderr,
             "new stream \"%s\" of MIMEType \"%s\"\n"
             "for plugin \"%s\"\n"
             "seekable = %s, length = %"SAL_PRIdINT32"\n",
             aURL.getStr(), aMIME.getStr(), getPluginComm()->getLibName().getStr(),
             isfile ? "true" : "false", length );

#endif
    if( ! m_pPluginComm->NPP_NewStream( &m_aInstance,
                                        (char*)aMIME.getStr(),
                                        pStream->getStream(), isfile,
                                        &stype ) )
    {
#if OSL_DEBUG_LEVEL > 1
        const char* pType;
        switch( stype )
        {
            case NP_NORMAL:     pType = "NP_NORMAL";break;
            case NP_SEEK:       pType = "NP_SEEK";break;
            case NP_ASFILE:     pType = "NP_ASFILE";break;
            case NP_ASFILEONLY: pType = "NP_ASFILEONLY";break;
            default:            pType = "unknown!!!";
        }
        fprintf( stderr, "Plugin wants it in Mode %s\n", pType );
#endif
        if( isfile && stype == NP_ASFILEONLY )
        {
            OString aFileName;
            if( url.compareToAscii( "file:", 5 ) == 0 )
            {
                OUString aSysName;
                osl_getSystemPathFromFileURL( url.pData, &aSysName.pData );
                aFileName = OUStringToOString( aSysName, m_aEncoding );
            }
            else
                aFileName = OUStringToOString( url, m_aEncoding );
            m_pPluginComm->
                NPP_StreamAsFile( &m_aInstance,
                                  pStream->getStream(),
                                  aFileName.getStr() );
        }
        else
        {
            pStream->setMode( stype );

            if( ! stream.is() )
            {
                // stream has to be loaded by PluginStream itself via UCB
                pStream->load();
            }
            else
            {
                uno::Reference< com::sun::star::io::XConnectable > xConnectable( stream, UNO_QUERY );
                pStream->setPredecessor( xConnectable );
                if( xConnectable.is() )
                {
                    xConnectable->setSuccessor( static_cast< com::sun::star::io::XConnectable* >(pStream) );
                    while( xConnectable->getPredecessor().is() )
                        xConnectable = xConnectable->getPredecessor();
                }
                stream->setOutputStream( xNewStream );
                pStream->setSource( stream );
                uno::Reference< com::sun::star::io::XActiveDataControl > xController;
                if( xConnectable.is() )
                    xController = uno::Reference< com::sun::star::io::XActiveDataControl >( xConnectable, UNO_QUERY );
                else
                    xController = uno::Reference< com::sun::star::io::XActiveDataControl >( stream, UNO_QUERY );

                if( xController.is() )
                    xController->start();
            }
        }
        bRet = sal_True;
    }

    m_nProvidingState = PROVIDING_NONE;

    return bRet;
}

void XPlugin_Impl::disposing( const com::sun::star::lang::EventObject& /*rSource*/ ) throw()
{
}

void XPlugin_Impl::propertyChange( const com::sun::star::beans::PropertyChangeEvent& rEvent ) throw()
{
    Guard< Mutex > aGuard( m_aMutex );

    if( ! rEvent.PropertyName.compareToAscii( "URL" ) )
    {
        OUString aStr;
        rEvent.NewValue >>= aStr;
        if( m_nProvidingState == PROVIDING_NONE )
        {
            if( aStr != m_aURL )
            {
                m_aURL = aStr;
                modelChanged();
            }
        }
    }
}

void XPlugin_Impl::setPluginContext( const uno::Reference< XPluginContext > & rContext )
{
    m_rBrowserContext = rContext;
}

void XPlugin_Impl::setPosSize( sal_Int32 nX_, sal_Int32 nY_, sal_Int32 nWidth_, sal_Int32 nHeight_, sal_Int16 nFlags )
        throw( RuntimeException )
{
    Guard< Mutex > aGuard( m_aMutex );

#if OSL_DEBUG_LEVEL > 1
    fprintf( stderr, "XPlugin_Impl::setPosSize( %"SAL_PRIdINT32", %"SAL_PRIdINT32", %"SAL_PRIdINT32", %"SAL_PRIdINT32", %d )\n",
             nX_, nY_, nWidth_, nHeight_, nFlags );
#endif

    PluginControl_Impl::setPosSize(nX_, nY_, nWidth_, nHeight_, nFlags);

    m_aNPWindow.x                   = 0;
    m_aNPWindow.y                   = 0;
    m_aNPWindow.width               = nWidth_;
    m_aNPWindow.height              = nHeight_;
    m_aNPWindow.clipRect.top        = 0;
    m_aNPWindow.clipRect.left       = 0;
    m_aNPWindow.clipRect.right      = ::sal::static_int_cast< uint16, sal_Int32 >( nWidth_ );
    m_aNPWindow.clipRect.bottom     = ::sal::static_int_cast< uint16, sal_Int32 >( nHeight_ );

    if( getPluginComm() )
        getPluginComm()->NPP_SetWindow( this );
}

PluginDescription XPlugin_Impl::fitDescription( const OUString& rURL )
{
    uno::Reference< XPluginManager >  xPMgr( m_xSMgr->createInstance( OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.plugin.PluginManager")) ), UNO_QUERY );
    if( !xPMgr.is() )
    {
        m_nProvidingState = PROVIDING_NONE;
        return PluginDescription();
    }

    Sequence< PluginDescription > aDescrs = xPMgr->getPluginDescriptions();
    const PluginDescription* pDescrs = aDescrs.getConstArray();

    for( int nArg = 0; nArg < m_nArgs; nArg++ )
    {
        if( strncmp( m_pArgn[nArg], "TYPE", 4 ) == 0 &&
            m_pArgn[nArg][4] == 0 )
        {
            for( int i = 0; i < aDescrs.getLength(); i++ )
            {
                if( pDescrs[i].Mimetype.compareToAscii( m_pArgv[nArg] ) == 0 )
                    return pDescrs[i];
            }
        }
    }

    int nPos = rURL.lastIndexOf( (sal_Unicode)'.' );
    OUString aExt = rURL.copy( nPos ).toAsciiLowerCase();
    if( nPos != -1 )
    {
        for( int i = 0; i < aDescrs.getLength(); i++ )
        {
            OUString aThisExt = pDescrs[ i ].Extension.toAsciiLowerCase();
            if( aThisExt.indexOf( aExt ) != -1 )
            {
                return pDescrs[i];
            }
        }
    }
    return PluginDescription();
}


PluginStream::PluginStream( XPlugin_Impl* pPlugin,
                            const char* url, sal_uInt32 len, sal_uInt32 lastmod ) :
        m_pPlugin( pPlugin )
{
    memset( &m_aNPStream, 0, sizeof( m_aNPStream ) );
    m_aNPStream.url             = strdup( url );
    m_aNPStream.end             = len;
    m_aNPStream.lastmodified    = lastmod;
}

PluginStream::~PluginStream()
{
    Guard< Mutex > aGuard( m_pPlugin->getMutex() );

    if( m_pPlugin && m_pPlugin->getPluginComm() )
    {
        m_pPlugin->getPluginComm()->NPP_DestroyStream( m_pPlugin->getNPPInstance(),
                                                       &m_aNPStream, NPRES_DONE );
        m_pPlugin->checkListeners( m_aNPStream.url );
        m_pPlugin->getPluginComm()->NPP_SetWindow( m_pPlugin );
    }
    ::free( (void*)m_aNPStream.url );
}

PluginInputStream::PluginInputStream( XPlugin_Impl* pPlugin,
                                      const char* url,
                                      sal_uInt32 len,
                                      sal_uInt32 lastmod ) :
        PluginStream( pPlugin, url, len, lastmod ),
        m_pContent( NULL ),
        m_nMode( NP_NORMAL ),
        m_nWritePos( 0 )
{
    Guard< Mutex > aGuard( m_pPlugin->getMutex() );

    m_pPlugin->getInputStreams().push_back( this );
    DirEntry aEntry;
    aEntry = aEntry.TempName();

    // set correct extension, some plugins need that
    DirEntry aName( String( m_aNPStream.url, m_pPlugin->getTextEncoding() ) );
    String aExtension = aName.GetExtension();
    if( aExtension.Len() )
        aEntry.SetExtension( aExtension );
    m_aFileStream.Open( aEntry.GetFull(), STREAM_READ | STREAM_WRITE );
    if( ! m_aFileStream.IsOpen() )
    {
        // #74808# might be that the extension scrambled the whole filename
        aEntry = aEntry.TempName();
        m_aFileStream.Open( aEntry.GetFull(), STREAM_READ | STREAM_WRITE );
    }
}

PluginInputStream::~PluginInputStream()
{
    Guard< Mutex > aGuard( m_pPlugin->getMutex() );

    m_pPlugin->getInputStreams().remove( this );

    String aFile( m_aFileStream.GetFileName() );

    m_aFileStream.Close();
    if( m_pPlugin )
    {
        ByteString aFileName( aFile, m_pPlugin->getTextEncoding() );
        if( m_pPlugin->getPluginComm() && m_nMode != -1 )
            // mode -1 means either an error occurred,
            // or the plugin is already disposing
        {
            m_pPlugin->getPluginComm()->addFileToDelete( aFile );
            if( m_nMode == NP_ASFILE )
            {
                m_pPlugin->getPluginComm()->
                    NPP_StreamAsFile( m_pPlugin->getNPPInstance(),
                                      &m_aNPStream,
                                      aFileName.GetBuffer() );
            }
            m_pPlugin->getPluginComm()->NPP_SetWindow( m_pPlugin );
            m_pPlugin->getInputStreams().remove( this );
        }
        else
            DirEntry( m_aFileStream.GetFileName() ).Kill();
    }
    else
        DirEntry( m_aFileStream.GetFileName() ).Kill();
    if( m_pContent )
        delete m_pContent;
}

PluginStreamType PluginInputStream::getStreamType()
{
    return InputStream;
}

void PluginInputStream::load()
{
    Guard< Mutex > aGuard( m_pPlugin->getMutex() );

    INetURLObject aUrl;
    aUrl.SetSmartProtocol( INET_PROT_FILE );
    aUrl.SetSmartURL(
        String( getStream()->url,
                ::sal::static_int_cast< sal_uInt16, size_t >( strlen( getStream()->url ) ),
                RTL_TEXTENCODING_MS_1252
            ) );
    try
    {
        m_pContent =
            new ::ucbhelper::Content(
                               aUrl.GetMainURL(INetURLObject::DECODE_TO_IURI),
                               uno::Reference< com::sun::star::ucb::XCommandEnvironment >()
                               );
        m_pContent->openStream( static_cast< XOutputStream* >( this ) );
    }
    catch( com::sun::star::uno::Exception )
    {
    }
}

void PluginInputStream::setMode( sal_Int32 nMode )
{
    Guard< Mutex > aGuard( m_pPlugin->getMutex() );

    m_nMode = nMode;

    // invalidation by plugin
    if( m_nMode == -1 && m_pPlugin )
    {
        m_pPlugin->getInputStreams().remove( this );
        m_pPlugin = NULL;
    }
}

void PluginInputStream::writeBytes( const Sequence<sal_Int8>& Buffer ) throw()
{
    Guard< Mutex > aGuard( m_pPlugin->getMutex() );

    m_aFileStream.Seek( STREAM_SEEK_TO_END );
    m_aFileStream.Write( Buffer.getConstArray(), Buffer.getLength() );

    if( m_nMode == NP_SEEK )
        // hold reference, streem gets destroyed in NPN_DestroyStream
        m_xSelf = this;

    if( m_nMode == -1 || !m_pPlugin->getPluginComm() )
        return;

    sal_uInt32 nPos = m_aFileStream.Tell();
    sal_uInt32 nBytes = 0;
    while( m_nMode != NP_ASFILEONLY &&
           m_nWritePos < nPos &&
           (nBytes = m_pPlugin->getPluginComm()-> NPP_WriteReady(
               m_pPlugin->getNPPInstance(), &m_aNPStream )) > 0 )
    {
        nBytes = (nBytes > nPos - m_nWritePos) ? nPos - m_nWritePos : nBytes;

        char* pBuffer = new char[ nBytes ];
        m_aFileStream.Seek( m_nWritePos );
        nBytes = m_aFileStream.Read( pBuffer, nBytes );

        int32 nBytesRead = 0;
        try
        {
            nBytesRead = m_pPlugin->getPluginComm()->NPP_Write(
                m_pPlugin->getNPPInstance(), &m_aNPStream, m_nWritePos, nBytes, pBuffer );
        }
        catch( ... )
        {
            nBytesRead = 0;
        }
        delete [] pBuffer;

        if( nBytesRead < 0 )
        {
            m_nMode = -1;
            return;
        }

        m_nWritePos += nBytesRead;
    }
}

void PluginInputStream::closeOutput() throw()
{
    Guard< Mutex > aGuard( m_pPlugin->getMutex() );

    flush();
    m_xSource = uno::Reference< com::sun::star::io::XActiveDataSource >();
}

sal_uInt32 PluginInputStream::read( sal_uInt32 offset, sal_Int8* buffer, sal_uInt32 size )
{
    Guard< Mutex > aGuard( m_pPlugin->getMutex() );

    if( m_nMode != NP_SEEK )
        return 0;

    m_aFileStream.Seek( offset );
    return m_aFileStream.Read( buffer, size );
}

void PluginInputStream::flush(void) throw()
{
}

PluginOutputStream::PluginOutputStream( XPlugin_Impl* pPlugin,
                                        const char* url,
                                        sal_uInt32 len,
                                        sal_uInt32 lastmod ) :
        PluginStream( pPlugin, url, len, lastmod ),
        m_xStream( pPlugin->getServiceManager()->createInstance( OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.io.DataOutputStream")) ), UNO_QUERY )
{
    Guard< Mutex > aGuard( m_pPlugin->getMutex() );

    m_pPlugin->getOutputStreams().push_back( this );
}

PluginOutputStream::~PluginOutputStream()
{
    Guard< Mutex > aGuard( m_pPlugin->getMutex() );

    m_pPlugin->getOutputStreams().remove( this );
}

PluginStreamType PluginOutputStream::getStreamType()
{
    return OutputStream;
}

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