summaryrefslogtreecommitdiff
path: root/scripting/source/provider/MasterScriptProvider.cxx
blob: e7cc98c13d8647f1cd979f5ebf1433f35f27d48f (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
/*************************************************************************
 *
 * 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_scripting.hxx"

#include <comphelper/documentinfo.hxx>

#include <cppuhelper/implementationentry.hxx>
#include <cppuhelper/exc_hlp.hxx>
#include <cppuhelper/factory.hxx>
#include <tools/diagnose_ex.h>

#include <com/sun/star/frame/XModel.hpp>
#include <com/sun/star/lang/EventObject.hpp>
#include <com/sun/star/container/XContentEnumerationAccess.hpp>
#include <com/sun/star/document/XScriptInvocationContext.hpp>

#include <com/sun/star/uri/XUriReference.hpp>
#include <com/sun/star/uri/XUriReferenceFactory.hpp>
#include <com/sun/star/uri/XVndSunStarScriptUrl.hpp>

#include <com/sun/star/deployment/XPackage.hpp>
#include <com/sun/star/script/browse/BrowseNodeTypes.hpp>
#include <com/sun/star/script/provider/XScriptProviderFactory.hpp>
#include <com/sun/star/script/provider/ScriptFrameworkErrorType.hpp>

#include <util/scriptingconstants.hxx>
#include <util/util.hxx>
#include <util/MiscUtils.hxx>

#include "ActiveMSPList.hxx"
#include "MasterScriptProvider.hxx"
#include "URIHelper.hxx"

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::script;
using namespace ::com::sun::star::document;
using namespace ::sf_misc;

namespace func_provider
{
//*************************************************************************
//  Definitions for MasterScriptProviderFactory global methods.
//*************************************************************************

::rtl::OUString SAL_CALL mspf_getImplementationName() ;
Reference< XInterface > SAL_CALL mspf_create( Reference< XComponentContext > const & xComponentContext );
Sequence< ::rtl::OUString > SAL_CALL mspf_getSupportedServiceNames();


bool endsWith( const ::rtl::OUString& target,
    const ::rtl::OUString& item )
{
    sal_Int32 index = 0;
    if (  ( index = target.indexOf( item ) ) != -1  &&
       ( index == ( target.getLength() - item.getLength() ) ) )
    {
        return true;
    }
    return false;
}
//::rtl_StandardModuleCount s_moduleCount = MODULE_COUNT_INIT;

/* should be available in some central location. */
//*************************************************************************
// XScriptProvider implementation
//
//*************************************************************************
MasterScriptProvider::MasterScriptProvider( const Reference< XComponentContext > & xContext ) throw ( RuntimeException ):
        m_xContext( xContext ), m_bIsValid( false ), m_bInitialised( false ),
        m_bIsPkgMSP( false ), m_pPCache( 0 )
{
    ENSURE_OR_THROW( m_xContext.is(), "MasterScriptProvider::MasterScriptProvider: No context available\n" );
    m_xMgr = m_xContext->getServiceManager();
    ENSURE_OR_THROW( m_xMgr.is(), "MasterScriptProvider::MasterScriptProvider: No service manager available\n" );
    m_bIsValid = true;
}

//*************************************************************************
MasterScriptProvider::~MasterScriptProvider()
{
    //s_moduleCount.modCnt.release( &s_moduleCount.modCnt );
    if ( m_pPCache )
    {
        delete m_pPCache;
    }
    m_pPCache = 0;
}

//*************************************************************************
void SAL_CALL MasterScriptProvider::initialize( const Sequence < Any >& args )
throw ( Exception, RuntimeException )
{
    if ( m_bInitialised )
        return;

    m_bIsValid = false;

    sal_Int32 len = args.getLength();
    if ( len > 1  )
    {
        throw RuntimeException(
            OUSTR( "MasterScriptProvider::initialize: invalid number of arguments" ),
            Reference< XInterface >() );
    }

    Sequence< Any > invokeArgs( len );

    if ( len != 0 )
    {
        // check if first parameter is a string
        // if it is, this implies that this is a MSP created
        // with a user or share ctx ( used for browse functionality )
        //
        if ( args[ 0 ] >>= m_sCtxString )
        {
            invokeArgs[ 0  ] = args[ 0 ];
            if ( m_sCtxString.indexOfAsciiL( RTL_CONSTASCII_STRINGPARAM( "vnd.sun.star.tdoc" ) ) == 0 )
            {
                m_xModel =  MiscUtils::tDocUrlToModel( m_sCtxString );
            }
        }
        else if ( args[ 0 ] >>= m_xInvocationContext )
        {
            m_xModel.set( m_xInvocationContext->getScriptContainer(), UNO_QUERY_THROW );
        }
        else
        {
            args[ 0 ] >>= m_xModel;
        }

        if ( m_xModel.is() )
        {
            // from the arguments, we were able to deduce a model. That alone doesn't
            // suffice, we also need an XEmbeddedScripts which actually indicates support
            // for embeddeding scripts
            Reference< XEmbeddedScripts > xScripts( m_xModel, UNO_QUERY );
            if ( !xScripts.is() )
            {
                throw lang::IllegalArgumentException(
                    ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
                        "The given document does not support embedding scripts into it, and cannot be associated with such a document."
                    ) ),
                    *this,
                    1
                );
            }

            try
            {
                m_sCtxString =  MiscUtils::xModelToTdocUrl( m_xModel, m_xContext );
            }
            catch ( const Exception& )
            {
                Any aError( ::cppu::getCaughtException() );

                ::rtl::OUStringBuffer buf;
                buf.appendAscii( "MasterScriptProvider::initialize: caught " );
                buf.append     ( aError.getValueTypeName() );
                buf.appendAscii( ":" );

                Exception aException; aError >>= aException;
                buf.append     ( aException.Message );
                throw lang::WrappedTargetException( buf.makeStringAndClear(), *this, aError );
            }

            if ( m_xInvocationContext.is() && m_xInvocationContext != m_xModel )
                invokeArgs[ 0 ] <<= m_xInvocationContext;
            else
                invokeArgs[ 0 ] <<= m_sCtxString;
        }

        ::rtl::OUString pkgSpec = OUSTR("uno_packages");
        sal_Int32 indexOfPkgSpec = m_sCtxString.lastIndexOf( pkgSpec );

        // if contex string ends with "uno_packages"
        if ( indexOfPkgSpec > -1 && ( m_sCtxString.match( pkgSpec, indexOfPkgSpec ) == sal_True ) )
        {
            m_bIsPkgMSP = sal_True;
        }
        else
        {
            m_bIsPkgMSP = sal_False;
        }
    }
    else // no args
    {
        // use either scriping context or maybe zero args?
        invokeArgs = Sequence< Any >( 0 ); // no arguments
    }
    m_sAargs = invokeArgs;
    // don't create pkg mgr MSP for documents, not supported
    if ( m_bIsPkgMSP == sal_False && !m_xModel.is() )
    {
        createPkgProvider();
    }

    m_bInitialised = true;
    m_bIsValid = true;
}


//*************************************************************************
void MasterScriptProvider::createPkgProvider()
{
    try
    {
        ::rtl::OUString loc = m_sCtxString;
        Any location;
        ::rtl::OUString sPkgCtx =  m_sCtxString.concat( OUSTR(":uno_packages") );
        location <<= sPkgCtx;

        Reference< provider::XScriptProviderFactory > xFac(
            m_xContext->getValueByName(
                OUSTR( "/singletons/com.sun.star.script.provider.theMasterScriptProviderFactory") ), UNO_QUERY_THROW );

        m_xMSPPkg.set(
            xFac->createScriptProvider( location ), UNO_QUERY_THROW );

    }
    catch ( Exception& e )
    {
        (void)e;
        OSL_TRACE("Exception creating MasterScriptProvider for uno_packages in context %s: %s",
                ::rtl::OUStringToOString( m_sCtxString,
                    RTL_TEXTENCODING_ASCII_US ).pData->buffer,
                ::rtl::OUStringToOString( e.Message,
                    RTL_TEXTENCODING_ASCII_US ).pData->buffer );
    }
}

//*************************************************************************
Reference< provider::XScript >
MasterScriptProvider::getScript( const ::rtl::OUString& scriptURI )
throw ( provider::ScriptFrameworkErrorException,
        RuntimeException )
{
    if ( !isValid() )
    {
        throw provider::ScriptFrameworkErrorException(
            OUSTR( "MasterScriptProvider not initialised" ), Reference< XInterface >(),
            scriptURI, OUSTR(""),
            provider::ScriptFrameworkErrorType::UNKNOWN );
    }

    // need to get the language from the string

    Reference< uri::XUriReferenceFactory > xFac (
         m_xMgr->createInstanceWithContext( rtl::OUString::createFromAscii(
            "com.sun.star.uri.UriReferenceFactory"), m_xContext ) , UNO_QUERY );
    if ( !xFac.is() )
    {
        ::rtl::OUString message = ::rtl::OUString::createFromAscii("Failed to instantiate  UriReferenceFactory");
        throw provider::ScriptFrameworkErrorException(
            message, Reference< XInterface >(),
            scriptURI, ::rtl::OUString(),
            provider::ScriptFrameworkErrorType::UNKNOWN );
    }

    Reference<  uri::XUriReference > uriRef(
        xFac->parse( scriptURI ), UNO_QUERY );

    Reference < uri::XVndSunStarScriptUrl > sfUri( uriRef, UNO_QUERY );

    if ( !uriRef.is() || !sfUri.is() )
    {
        ::rtl::OUString errorMsg = OUSTR( "Incorrect format for Script URI: " );
        errorMsg = errorMsg.concat( scriptURI );
        throw provider::ScriptFrameworkErrorException(
            errorMsg, Reference< XInterface >(),
            scriptURI, OUSTR(""),
            provider::ScriptFrameworkErrorType::UNKNOWN );
    }

    ::rtl::OUString langKey = ::rtl::OUString::createFromAscii( "language" );
    ::rtl::OUString locKey = ::rtl::OUString::createFromAscii( "location" );

    if ( sfUri->hasParameter( langKey ) == sal_False ||
         sfUri->hasParameter( locKey ) == sal_False ||
         ( sfUri->getName().getLength() == 0  ) )
    {
        ::rtl::OUString errorMsg = OUSTR( "Incorrect format for Script URI: " );
        errorMsg = errorMsg.concat( scriptURI );
        throw provider::ScriptFrameworkErrorException(
            errorMsg, Reference< XInterface >(),
            scriptURI, OUSTR(""),
            provider::ScriptFrameworkErrorType::UNKNOWN );
    }

    ::rtl::OUString language = sfUri->getParameter( langKey );
    ::rtl::OUString location = sfUri->getParameter( locKey );

    // if script us located in uno pkg
    sal_Int32 index = -1;
    ::rtl::OUString pkgTag =
        ::rtl::OUString::createFromAscii( ":uno_packages" );
    // for languages other than basic,  scripts located in uno packages
    // are merged into the user/share location context.
    // For other languages the location attribute in script url has the form
    // location = [user|share]:uno_packages or location :uno_pacakges/xxxx.uno.pkg
    // we need to extract the value of location part from the
    // location attribute of the script, if the script is located in an
    // uno package then that is the location part up to and including
    // ":uno_packages", if the script is not in an uno package then the
    // normal value is used e.g. user or share.
    // The value extracted will be used to determine if the script is
    // located in the same location context as this MSP.
    // For Basic, the language script provider can handle the execution of a
    // script in any location context
    if ( ( index = location.indexOf( pkgTag ) ) > -1 )
    {
        location = location.copy( 0, index + pkgTag.getLength() );
    }

    Reference< provider::XScript > xScript;

    // If the script location is in the same location context as this
    // MSP then delate to the lanaguage provider controlled by this MSP
    // ** Special case is BASIC, all calls to getScript will be handled
    // by the language script provider in the current location context
    // even if its different
    if  (   (   location.equals( OUSTR( "document" ) )
            &&  m_xModel.is()
            )
            ||  ( endsWith( m_sCtxString, location ) )
            ||  ( language.equals( OUSTR( "Basic" ) ) )
         )
    {
        Reference< provider::XScriptProvider > xScriptProvider;
        ::rtl::OUStringBuffer buf( 80 );
        buf.appendAscii( "com.sun.star.script.provider.ScriptProviderFor");
        buf.append( language );
        ::rtl::OUString serviceName = buf.makeStringAndClear();
        if ( providerCache() )
        {
            try
            {
                xScriptProvider.set(
                    providerCache()->getProvider( serviceName ),
                    UNO_QUERY_THROW );
            }
            catch( const Exception& e )
            {
                throw provider::ScriptFrameworkErrorException(
                    e.Message, Reference< XInterface >(),
                    sfUri->getName(), language,
                    provider::ScriptFrameworkErrorType::NOTSUPPORTED );
            }
        }
        else
        {
            throw provider::ScriptFrameworkErrorException(
                OUSTR( "No LanguageProviders detected" ),
                Reference< XInterface >(),
                sfUri->getName(), language,
                provider::ScriptFrameworkErrorType::NOTSUPPORTED );
        }
        xScript=xScriptProvider->getScript( scriptURI );
    }
    else
    {
        Reference< provider::XScriptProviderFactory > xFac_(
            m_xContext->getValueByName(
                OUSTR( "/singletons/com.sun.star.script.provider.theMasterScriptProviderFactory") ), UNO_QUERY_THROW );

        Reference< provider::XScriptProvider > xSP(
            xFac_->createScriptProvider( makeAny( location ) ), UNO_QUERY_THROW );
        xScript = xSP->getScript( scriptURI );
    }

    return xScript;
}
//*************************************************************************
bool
MasterScriptProvider::isValid()
{
    return m_bIsValid;
}

//*************************************************************************
ProviderCache*
MasterScriptProvider::providerCache()
{
    if ( !m_pPCache )
    {
        ::osl::MutexGuard aGuard( m_mutex );
        if ( !m_pPCache )
        {
            ::rtl::OUString serviceName1 = OUSTR("com.sun.star.script.provider.ScriptProviderForBasic");
            Sequence< ::rtl::OUString > blacklist(1);
            blacklist[ 0 ] = serviceName1;

            if ( !m_bIsPkgMSP )
            {
                m_pPCache = new ProviderCache( m_xContext, m_sAargs );
            }
            else
            {
                m_pPCache = new ProviderCache( m_xContext, m_sAargs, blacklist );
            }
        }
    }
    return m_pPCache;
}


//*************************************************************************
::rtl::OUString SAL_CALL
MasterScriptProvider::getName()
        throw ( css::uno::RuntimeException )
{
    if ( !isPkgProvider() )
    {
        ::rtl::OUString sCtx = getContextString();
        if ( sCtx.indexOf( OUSTR( "vnd.sun.star.tdoc" ) ) == 0 )
        {
            Reference< frame::XModel > xModel = m_xModel;
            if ( !xModel.is() )
            {
                xModel = MiscUtils::tDocUrlToModel( sCtx );
            }

            m_sNodeName = ::comphelper::DocumentInfo::getDocumentTitle( xModel );
        }
        else
        {
            m_sNodeName = parseLocationName( getContextString() );
        }
    }
    else
    {
        m_sNodeName = OUSTR("uno_packages");
    }
    return m_sNodeName;
}

//*************************************************************************
Sequence< Reference< browse::XBrowseNode > > SAL_CALL
MasterScriptProvider::getChildNodes()
        throw ( css::uno::RuntimeException )
{
    Sequence< Reference< provider::XScriptProvider > > providers = getAllProviders();

    Reference< provider::XScriptProvider > pkgProv = getPkgProvider();
    sal_Int32 size = providers.getLength();
    bool hasPkgs = pkgProv.is();
    if ( hasPkgs  )
    {
        size++;
    }
    Sequence<  Reference< browse::XBrowseNode > > children( size );
    sal_Int32 provIndex = 0;
    for ( ; provIndex < providers.getLength(); provIndex++ )
    {
        children[ provIndex ] = Reference< browse::XBrowseNode >( providers[ provIndex ], UNO_QUERY );
    }

    if ( hasPkgs  )
    {
        children[ provIndex ] = Reference< browse::XBrowseNode >( pkgProv, UNO_QUERY );

    }

    return children;
}

//*************************************************************************
sal_Bool SAL_CALL
MasterScriptProvider::hasChildNodes()
        throw ( css::uno::RuntimeException )
{
    return sal_True;
}

//*************************************************************************
sal_Int16 SAL_CALL
MasterScriptProvider::getType()
        throw ( css::uno::RuntimeException )
{
    return browse::BrowseNodeTypes::CONTAINER;
}

//*************************************************************************

::rtl::OUString
MasterScriptProvider::parseLocationName( const ::rtl::OUString& location )
{
    // strip out the last leaf of location name
    // e.g. file://dir1/dir2/Blah.sxw - > Blah.sxw
    ::rtl::OUString temp = location;
    INetURLObject aURLObj( temp );
    if ( !aURLObj.HasError() )
        temp = aURLObj.getName( INetURLObject::LAST_SEGMENT, true, INetURLObject::DECODE_WITH_CHARSET );
    return temp;
}

//*************************************************************************
// Register Package
void SAL_CALL
MasterScriptProvider::insertByName( const ::rtl::OUString& aName, const Any& aElement ) throw ( lang::IllegalArgumentException, container::ElementExistException, lang::WrappedTargetException, css::uno::RuntimeException)
{
    if ( !m_bIsPkgMSP )
    {
        if ( m_xMSPPkg.is() )
        {
            Reference< container::XNameContainer > xCont( m_xMSPPkg, UNO_QUERY );
            if ( !xCont.is() )
            {
                throw RuntimeException(
                    OUSTR("PackageMasterScriptProvider doesn't implement XNameContainer"),
                    Reference< XInterface >() );
            }
            xCont->insertByName( aName, aElement );
        }
        else
        {
            throw RuntimeException( OUSTR("PackageMasterScriptProvider is unitialised"),
                                        Reference< XInterface >() );
        }

    }
    else
    {
        Reference< deployment::XPackage > xPkg( aElement, UNO_QUERY );
        if ( !xPkg.is() )
        {
            throw lang::IllegalArgumentException( OUSTR("Couldn't convert to XPackage"),
                                                      Reference < XInterface > (), 2 );
        }
        if ( !aName.getLength() )
        {
            throw lang::IllegalArgumentException( OUSTR("Name not set!!"),
                                                      Reference < XInterface > (), 1 );
        }
        // TODO for library pacakge parse the language, for the moment will try
        // to get each provider to process the new Package, the first one the succeeds
        // will terminate processing
        if ( !providerCache() )
        {
            throw RuntimeException(
                OUSTR("insertByName cannot instantiate "
                    "child script providers."),
                Reference< XInterface >() );
        }
        Sequence < Reference< provider::XScriptProvider > > xSProviders =
            providerCache()->getAllProviders();
        sal_Int32 index = 0;

        for ( ; index < xSProviders.getLength(); index++ )
        {
            Reference< container::XNameContainer > xCont( xSProviders[ index ], UNO_QUERY );
            if ( !xCont.is() )
            {
                continue;
            }
            try
            {
                xCont->insertByName( aName, aElement );
                break;
            }
            catch ( Exception& )
            {
            }

        }
        if ( index == xSProviders.getLength() )
        {
            // No script providers could process the package
            ::rtl::OUString message = OUSTR("Failed to register package for ");
            message = message.concat( aName );
            throw lang::IllegalArgumentException( message,
                Reference < XInterface > (), 2 );
        }
   }
}

//*************************************************************************
// Revoke Package
void SAL_CALL
MasterScriptProvider::removeByName( const ::rtl::OUString& Name ) throw ( container::NoSuchElementException, lang::WrappedTargetException, RuntimeException)
{
    if ( !m_bIsPkgMSP )
    {
        if ( m_xMSPPkg.is() )
        {
            Reference< container::XNameContainer > xCont( m_xMSPPkg, UNO_QUERY );
            if ( !xCont.is() )
            {
                throw RuntimeException(
                    OUSTR("PackageMasterScriptProvider doesn't implement XNameContainer"),
                    Reference< XInterface >() );
            }
            xCont->removeByName( Name );
        }
        else
        {
            throw RuntimeException( OUSTR("PackageMasterScriptProvider is unitialised"),
                                        Reference< XInterface >() );
        }

   }
   else
   {
        if ( !Name.getLength() )
        {
            throw lang::IllegalArgumentException( OUSTR("Name not set!!"),
                                                      Reference < XInterface > (), 1 );
        }
        // TODO for Script library pacakge url parse the language,
        // for the moment will just try to get each provider to process remove/revoke
        // request, the first one the succeeds will terminate processing

        if ( !providerCache() )
        {
            throw RuntimeException(
                OUSTR("removeByName() cannot instantiate "
                    "child script providers."),
                Reference< XInterface >() );
        }
        Sequence < Reference< provider::XScriptProvider > > xSProviders =
            providerCache()->getAllProviders();
        sal_Int32 index = 0;
        for ( ; index < xSProviders.getLength(); index++ )
        {
            Reference< container::XNameContainer > xCont( xSProviders[ index ], UNO_QUERY );
            if ( !xCont.is() )
            {
                continue;
            }
            try
            {
                xCont->removeByName( Name );
                break;
            }
            catch ( Exception& )
            {
            }

        }
        if ( index == xSProviders.getLength() )
        {
            // No script providers could process the package
            ::rtl::OUString message = OUSTR("Failed to revoke package for ");
            message = message.concat( Name );
            throw lang::IllegalArgumentException( message,
                                                      Reference < XInterface > (), 1 );
        }

    }
}

//*************************************************************************
void SAL_CALL
MasterScriptProvider::replaceByName( const ::rtl::OUString& aName, const Any& aElement ) throw ( lang::IllegalArgumentException, container::NoSuchElementException, lang::WrappedTargetException, RuntimeException)
{
    (void)aName;
    (void)aElement;

    // TODO needs implementing
    if ( true )
    {
        throw RuntimeException(  OUSTR("replaceByName not implemented!!!!") ,
                Reference< XInterface >() );
    }
}
//*************************************************************************
Any SAL_CALL
MasterScriptProvider::getByName( const ::rtl::OUString& aName ) throw ( container::NoSuchElementException, lang::WrappedTargetException, RuntimeException)
{
    (void)aName;

    // TODO needs to be implemented
    Any result;
    if ( true )
    {
        throw RuntimeException(  OUSTR("getByName not implemented!!!!") ,
                Reference< XInterface >() );
    }
    return result;
}
//*************************************************************************
sal_Bool SAL_CALL
MasterScriptProvider::hasByName( const ::rtl::OUString& aName ) throw (RuntimeException)
{
    sal_Bool result = sal_False;
    if ( !m_bIsPkgMSP )
    {
        if ( m_xMSPPkg.is() )
        {
            Reference< container::XNameContainer > xCont( m_xMSPPkg, UNO_QUERY );
            if ( !xCont.is() )
            {
                throw RuntimeException(
                    OUSTR("PackageMasterScriptProvider doesn't implement XNameContainer"),
                    Reference< XInterface >() );
            }

            result = xCont->hasByName( aName );
        }
        else
        {
            throw RuntimeException( OUSTR("PackageMasterScriptProvider is unitialised"),
                                        Reference< XInterface >() );
        }

   }
   else
   {
        if ( !aName.getLength() )
        {
            throw lang::IllegalArgumentException( OUSTR("Name not set!!"),
                                                      Reference < XInterface > (), 1 );
        }
        // TODO for Script library pacakge url parse the language,
        // for the moment will just try to get each provider to see if the
        // package exists in any provider, first one that succeed will
        // terminate the loop

        if ( !providerCache() )
        {
            throw RuntimeException(
                OUSTR("removeByName() cannot instantiate "
                    "child script providers."),
                Reference< XInterface >() );
        }
        Sequence < Reference< provider::XScriptProvider > > xSProviders =
            providerCache()->getAllProviders();
        for ( sal_Int32 index = 0; index < xSProviders.getLength(); index++ )
        {
            Reference< container::XNameContainer > xCont( xSProviders[ index ], UNO_QUERY );
            if ( !xCont.is() )
            {
                continue;
            }
            try
            {
                result = xCont->hasByName( aName );
                if ( result == sal_True )
                {
                    break;
                }
            }
            catch ( Exception& )
            {
            }

        }
    }
    return result;
}

//*************************************************************************
Sequence< ::rtl::OUString > SAL_CALL
MasterScriptProvider::getElementNames(  ) throw ( RuntimeException)
{
    // TODO needs implementing
    Sequence< ::rtl::OUString >  names;
    if ( true )
    {
        throw RuntimeException(  OUSTR("getElementNames not implemented!!!!") ,
                Reference< XInterface >() );
    }
    return names;
}
//*************************************************************************
Type SAL_CALL
MasterScriptProvider::getElementType(  ) throw ( RuntimeException)
{
    // TODO needs implementing
    Type t;
    return t;
}
//*************************************************************************
sal_Bool SAL_CALL MasterScriptProvider::hasElements(  ) throw ( RuntimeException)
{
    // TODO needs implementing
    if ( true )
    {
        throw RuntimeException(  OUSTR("hasElements not implemented!!!!") ,
                Reference< XInterface >() );
    }
    return false;
}

//*************************************************************************
Sequence< Reference< provider::XScriptProvider > > SAL_CALL
MasterScriptProvider::getAllProviders() throw ( css::uno::RuntimeException )
{
    if ( providerCache() )
    {
        return providerCache()->getAllProviders();
    }
    else
    {
        ::rtl::OUString errorMsg = ::rtl::OUString::createFromAscii(
            "MasterScriptProvider::getAllProviders, cache not initialised");
        throw RuntimeException( errorMsg.concat( errorMsg ),
            Reference< XInterface >() );
    }
}


//*************************************************************************
::rtl::OUString SAL_CALL MasterScriptProvider::getImplementationName( )
throw( RuntimeException )
{
    return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM (
        "com.sun.star.script.provider.MasterScriptProvider" ) );
}

//*************************************************************************
sal_Bool SAL_CALL MasterScriptProvider::supportsService( const ::rtl::OUString& serviceName )
throw( RuntimeException )
{
    Sequence< ::rtl::OUString > serviceNames( getSupportedServiceNames() );
    ::rtl::OUString const * pNames = serviceNames.getConstArray();
    for ( sal_Int32 nPos = serviceNames.getLength(); nPos--; )
    {
        if ( serviceName.equals( pNames[ nPos ] ) )
        {
            return sal_True;
        }
    }
    return sal_False;
}

//*************************************************************************
Sequence< ::rtl::OUString > SAL_CALL MasterScriptProvider::getSupportedServiceNames( )
throw( RuntimeException )
{
    ::rtl::OUString names[3];

    names[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM (
        "com.sun.star.script.provider.MasterScriptProvider" ) );
    names[1] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM (
        "com.sun.star.script.browse.BrowseNode" ) );
    names[2] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM (
        "com.sun.star.script.provider.ScriptProvider" ) );

    return Sequence< ::rtl::OUString >( names, 3 );
}

} // namespace func_provider


namespace browsenodefactory
{
::rtl::OUString SAL_CALL bnf_getImplementationName() ;
Reference< XInterface > SAL_CALL bnf_create( Reference< XComponentContext > const & xComponentContext );
Sequence< ::rtl::OUString > SAL_CALL bnf_getSupportedServiceNames();
}

namespace scripting_runtimemgr
{
//*************************************************************************
Reference< XInterface > SAL_CALL sp_create(
    const Reference< XComponentContext > & xCompC )
{
    return ( cppu::OWeakObject * ) new ::func_provider::MasterScriptProvider( xCompC );
}

//*************************************************************************
Sequence< ::rtl::OUString > sp_getSupportedServiceNames( )
    SAL_THROW( () )
{
    ::rtl::OUString names[3];

    names[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM (
        "com.sun.star.script.provider.MasterScriptProvider" ) );
    names[1] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM (
        "com.sun.star.script.browse.BrowseNode" ) );
    names[2] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM (
        "com.sun.star.script.provider.ScriptProvider" ) );

    return Sequence< ::rtl::OUString >( names, 3 );
}

//*************************************************************************
::rtl::OUString sp_getImplementationName( )
SAL_THROW( () )
{
    return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM (
        "com.sun.star.script.provider.MasterScriptProvider" ) );
}

// ***** registration or ScriptingFrameworkURIHelper
Reference< XInterface > SAL_CALL urihelper_create(
    const Reference< XComponentContext > & xCompC )
{
    return ( cppu::OWeakObject * )
        new ::func_provider::ScriptingFrameworkURIHelper( xCompC );
}

Sequence< ::rtl::OUString > urihelper_getSupportedServiceNames( )
    SAL_THROW( () )
{
    ::rtl::OUString serviceNameList[] = { 
        ::rtl::OUString::createFromAscii(
            "com.sun.star.script.provider.ScriptURIHelper" ) };

    Sequence< ::rtl::OUString > serviceNames = Sequence <
        ::rtl::OUString > ( serviceNameList, 1 );

    return serviceNames;
}

::rtl::OUString urihelper_getImplementationName( )
    SAL_THROW( () )
{
    return ::rtl::OUString::createFromAscii(
        "com.sun.star.script.provider.ScriptURIHelper");
}

static struct cppu::ImplementationEntry s_entries [] =
    {
        {
            sp_create, sp_getImplementationName,
            sp_getSupportedServiceNames, cppu::createSingleComponentFactory,
            0, 0
        },
        {
            urihelper_create,
            urihelper_getImplementationName,
            urihelper_getSupportedServiceNames,
            cppu::createSingleComponentFactory,
            0, 0
        },
        {
            func_provider::mspf_create, func_provider::mspf_getImplementationName,
            func_provider::mspf_getSupportedServiceNames, cppu::createSingleComponentFactory,
            0, 0
        },
        {
            browsenodefactory::bnf_create, browsenodefactory::bnf_getImplementationName,
            browsenodefactory::bnf_getSupportedServiceNames, cppu::createSingleComponentFactory,
            0, 0
        },
        { 0, 0, 0, 0, 0, 0 }
    };
}

//############################################################################
//#### EXPORTED ##############################################################
//############################################################################

/**
 * Gives the environment this component belongs to.
 */
extern "C"
{
    SAL_DLLPUBLIC_EXPORT void SAL_CALL component_getImplementationEnvironment(
            const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv )
    {
        (void)ppEnv;
        *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
    }

    /**
     * This function is called to get service factories for an implementation.
     *
     * @param pImplName       name of implementation
     * @param pServiceManager a service manager, need for component creation
     * @param pRegistryKey    the registry key for this component, need for persistent
     *                        data
     * @return a component factory
     */
    SAL_DLLPUBLIC_EXPORT void * SAL_CALL component_getFactory(
        const sal_Char * pImplName,
        lang::XMultiServiceFactory * pServiceManager,
        registry::XRegistryKey * pRegistryKey )
    {
        return ::cppu::component_getFactoryHelper( pImplName, pServiceManager,
            pRegistryKey, ::scripting_runtimemgr::s_entries );
    }
}