summaryrefslogtreecommitdiff
path: root/cui/source/dialogs/scriptdlg.cxx
blob: 999ffacfedeeeb6f4a1e00ab4843829cbe828511 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <memory>
#include <utility>

#include <sfx2/objsh.hxx>
#include <vcl/svapp.hxx>
#include <vcl/layout.hxx>
#include <vcl/builderfactory.hxx>
#include <o3tl/make_unique.hxx>

#include <strings.hrc>
#include <bitmaps.hlst>
#include "scriptdlg.hxx"
#include <dialmgr.hxx>
#include "cfgutil.hxx"

#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/script/provider/ScriptFrameworkErrorException.hpp>
#include <com/sun/star/script/provider/XScriptProviderSupplier.hpp>
#include <com/sun/star/script/provider/XScriptProvider.hpp>
#include <com/sun/star/script/browse/BrowseNodeTypes.hpp>
#include <com/sun/star/script/browse/XBrowseNodeFactory.hpp>
#include <com/sun/star/script/browse/BrowseNodeFactoryViewTypes.hpp>
#include <com/sun/star/script/browse/theBrowseNodeFactory.hpp>
#include <com/sun/star/script/provider/ScriptErrorRaisedException.hpp>
#include <com/sun/star/script/provider/ScriptExceptionRaisedException.hpp>
#include <com/sun/star/script/provider/ScriptFrameworkErrorType.hpp>
#include <com/sun/star/frame/Desktop.hpp>
#include <com/sun/star/frame/ModuleManager.hpp>
#include <com/sun/star/script/XInvocation.hpp>
#include <com/sun/star/document/XEmbeddedScripts.hpp>

#include <comphelper/documentinfo.hxx>
#include <comphelper/uno3.hxx>
#include <comphelper/processfactory.hxx>
#include <comphelper/broadcasthelper.hxx>
#include <comphelper/propertycontainer.hxx>
#include <comphelper/proparrhlp.hxx>

#include <basic/sbx.hxx>
#include <svtools/imagemgr.hxx>
#include "svtools/treelistentry.hxx"
#include <tools/urlobj.hxx>
#include <vector>
#include <algorithm>

using namespace ::com::sun::star;
using namespace css::uno;
using namespace css::script;
using namespace css::frame;
using namespace css::document;

void ShowErrorDialog( const Any& aException )
{
    ScopedVclPtrInstance<SvxScriptErrorDialog> pDlg( aException );
    pDlg->Execute();
}

SFTreeListBox::SFTreeListBox(vcl::Window* pParent)
    : SvTreeListBox(pParent)
    , m_hdImage(BitmapEx(RID_CUIBMP_HARDDISK))
    , m_libImage(BitmapEx(RID_CUIBMP_LIB))
    , m_macImage(BitmapEx(RID_CUIBMP_MACRO))
    , m_docImage(BitmapEx(RID_CUIBMP_DOC))
    , m_sMyMacros(CuiResId(RID_SVXSTR_MYMACROS))
    , m_sProdMacros(CuiResId(RID_SVXSTR_PRODMACROS))
{
    SetSelectionMode( SelectionMode::Single );

    SetStyle( GetStyle() | WB_CLIPCHILDREN | WB_HSCROLL |
                   WB_HASBUTTONS | WB_HASBUTTONSATROOT | WB_HIDESELECTION |
                   WB_HASLINES | WB_HASLINESATROOT | WB_TABSTOP );
    SetNodeDefaultImages();
}

VCL_BUILDER_FACTORY(SFTreeListBox)

SFTreeListBox::~SFTreeListBox()
{
    disposeOnce();
}

void SFTreeListBox::dispose()
{
    deleteAllTree();
    SvTreeListBox::dispose();
}

void SFTreeListBox::delUserData( SvTreeListEntry* pEntry )
{
    if ( pEntry )
    {
        SFEntry* pUserData = static_cast<SFEntry*>(pEntry->GetUserData());
        if ( pUserData )
        {
            delete pUserData;
            // TBD seem to get a Select event on node that is remove ( below )
            // so need to be able to detect that this node is not to be
            // processed in order to do this, setting userData to NULL ( must
            // be a better way to do this )
            pUserData = nullptr;
            pEntry->SetUserData( pUserData );
        }
    }
}

void SFTreeListBox::deleteTree( SvTreeListEntry* pEntry )
{

    delUserData( pEntry );
    pEntry = FirstChild( pEntry );
    while ( pEntry )
    {
        SvTreeListEntry* pNextEntry = NextSibling( pEntry );
        deleteTree( pEntry );
        GetModel()->Remove( pEntry );
        pEntry = pNextEntry;
    }
}

void SFTreeListBox::deleteAllTree()
{
    SvTreeListEntry* pEntry =  GetEntry( 0 );

    // TBD - below is a candidate for a destroyAllTrees method
    if ( pEntry )
    {
        while ( pEntry )
        {
            SvTreeListEntry* pNextEntry = NextSibling( pEntry ) ;
            deleteTree( pEntry );
            GetModel()->Remove( pEntry );
            pEntry = pNextEntry;
        }
    }
}

void SFTreeListBox::Init( const OUString& language  )
{
    SetUpdateMode( false );

    deleteAllTree();

    Reference< browse::XBrowseNode > rootNode;
    Reference< XComponentContext > xCtx(
        comphelper::getProcessComponentContext() );

    Sequence< Reference< browse::XBrowseNode > > children;

    OUString userStr("user");
    OUString const shareStr("share");

    try
    {
        Reference< browse::XBrowseNodeFactory > xFac = browse::theBrowseNodeFactory::get(xCtx);

        rootNode.set( xFac->createView(
            browse::BrowseNodeFactoryViewTypes::MACROORGANIZER ) );

        if (  rootNode.is() && rootNode->hasChildNodes() )
        {
            children = rootNode->getChildNodes();
        }
    }
    catch( Exception& e )
    {
        SAL_WARN("cui.dialogs", "Exception getting root browse node from factory: " << e.Message );
        // TODO exception handling
    }

    Reference<XModel> xDocumentModel;
    for ( sal_Int32 n = 0; n < children.getLength(); n++ )
    {
        bool app = false;
        OUString uiName = children[ n ]->getName();
        OUString factoryURL;
        if ( uiName == userStr || uiName == shareStr )
        {
            app = true;
            if ( uiName == userStr )
            {
                uiName = m_sMyMacros;
            }
            else
            {
                uiName = m_sProdMacros;
            }
        }
        else
        {
            xDocumentModel.set(getDocumentModel(xCtx, uiName ), UNO_QUERY);

            if ( xDocumentModel.is() )
            {
                Reference< frame::XModuleManager2 > xModuleManager( frame::ModuleManager::create(xCtx) );

                // get the long name of the document:
                Sequence<beans::PropertyValue> moduleDescr;
                try{
                    OUString appModule = xModuleManager->identify( xDocumentModel );
                    xModuleManager->getByName(appModule) >>= moduleDescr;
                } catch(const uno::Exception&)
                    {}

                beans::PropertyValue const * pmoduleDescr =
                    moduleDescr.getConstArray();
                for ( sal_Int32 pos = moduleDescr.getLength(); pos--; )
                {
                    if ( pmoduleDescr[ pos ].Name == "ooSetupFactoryEmptyDocumentURL" )
                    {
                        pmoduleDescr[ pos ].Value >>= factoryURL;
                        break;
                    }
                }
            }
        }

        OUString lang( language );
        Reference< browse::XBrowseNode > langEntries =
            getLangNodeFromRootNode( children[ n ], lang );

        insertEntry( uiName, app ? OUStringLiteral(RID_CUIBMP_HARDDISK) : OUStringLiteral(RID_CUIBMP_DOC),
            nullptr, true, o3tl::make_unique< SFEntry >( langEntries, xDocumentModel ), factoryURL );
    }

    SetUpdateMode( true );
}

Reference< XInterface  >
SFTreeListBox::getDocumentModel( Reference< XComponentContext >& xCtx, OUString& docName )
{
    Reference< XInterface > xModel;
    Reference< frame::XDesktop2 > desktop  = frame::Desktop::create(xCtx);

    Reference< container::XEnumerationAccess > componentsAccess =
        desktop->getComponents();
    Reference< container::XEnumeration > components =
        componentsAccess->createEnumeration();
    while (components->hasMoreElements())
    {
        Reference< frame::XModel > model(
            components->nextElement(), UNO_QUERY );
        if ( model.is() )
        {
            OUString sTdocUrl = ::comphelper::DocumentInfo::getDocumentTitle( model );
            if( sTdocUrl == docName )
            {
                xModel = model;
                break;
            }
        }
    }
    return xModel;
}

Reference< browse::XBrowseNode >
SFTreeListBox::getLangNodeFromRootNode( Reference< browse::XBrowseNode >& rootNode, OUString& language )
{
    Reference< browse::XBrowseNode > langNode;

    try
    {
        Sequence < Reference< browse::XBrowseNode > > children = rootNode->getChildNodes();
        for ( sal_Int32 n = 0; n < children.getLength(); n++ )
        {
            if ( children[ n ]->getName() == language )
            {
                langNode = children[ n ];
                break;
            }
        }
    }
    catch ( Exception& )
    {
        // if getChildNodes() throws an exception we just return
        // the empty Reference
    }
    return langNode;
}

void SFTreeListBox:: RequestSubEntries( SvTreeListEntry* pRootEntry, Reference< css::script::browse::XBrowseNode >& node,
                                       Reference< XModel >& model )
{
    if (! node.is() )
    {
        return;
    }

    Sequence< Reference< browse::XBrowseNode > > children;
    try
    {
        children = node->getChildNodes();
    }
    catch ( Exception& )
    {
        // if we catch an exception in getChildNodes then no entries are added
    }

    for ( sal_Int32 n = 0; n < children.getLength(); n++ )
    {
        OUString name( children[ n ]->getName() );
        if (  children[ n ]->getType() !=  browse::BrowseNodeTypes::SCRIPT)
        {
            insertEntry(name, RID_CUIBMP_LIB, pRootEntry, true, o3tl::make_unique< SFEntry >( children[ n ],model));
        }
        else
        {
            insertEntry(name, RID_CUIBMP_MACRO, pRootEntry, false, o3tl::make_unique< SFEntry >( children[ n ],model));
        }
    }
}

bool SFTreeListBox::ExpandingHdl()
{
    return true;
}

SvTreeListEntry * SFTreeListBox::insertEntry(
    OUString const & rText, OUString const & rBitmap, SvTreeListEntry * pParent,
    bool bChildrenOnDemand, std::unique_ptr< SFEntry > && aUserData, const OUString& factoryURL )
{
    SvTreeListEntry * p;
    if (rBitmap == RID_CUIBMP_DOC && !factoryURL.isEmpty())
    {
        Image aImage = SvFileInformationManager::GetFileImage( INetURLObject(factoryURL) );
        p = InsertEntry(
            rText, aImage, aImage, pParent, bChildrenOnDemand, TREELIST_APPEND,
            aUserData.release()); // XXX possible leak
    }
    else
    {
        p = insertEntry(rText, rBitmap, pParent, bChildrenOnDemand, std::move(aUserData));
    }
    return p;
}

SvTreeListEntry * SFTreeListBox::insertEntry(
    OUString const & rText, const OUString &rBitmap, SvTreeListEntry * pParent,
    bool bChildrenOnDemand, std::unique_ptr< SFEntry > && aUserData )
{
    Image aImage;
    if (rBitmap == RID_CUIBMP_HARDDISK)
    {
        aImage = m_hdImage;
    }
    else if (rBitmap == RID_CUIBMP_LIB)
    {
        aImage = m_libImage;
    }
    else if (rBitmap == RID_CUIBMP_MACRO)
    {
        aImage = m_macImage;
    }
    else if (rBitmap == RID_CUIBMP_DOC)
    {
        aImage = m_docImage;
    }
    SvTreeListEntry * p = InsertEntry(
        rText, aImage, aImage, pParent, bChildrenOnDemand, TREELIST_APPEND,
        aUserData.release()); // XXX possible leak
   return p;
}

void SFTreeListBox::RequestingChildren( SvTreeListEntry* pEntry )
{
    SFEntry* userData = nullptr;
    if ( !pEntry )
    {
        return;
    }
    userData = static_cast<SFEntry*>(pEntry->GetUserData());

    Reference< browse::XBrowseNode > node;
    Reference< XModel > model;
    if ( userData && !userData->isLoaded() )
    {
        node = userData->GetNode();
        model = userData->GetModel();
        RequestSubEntries( pEntry, node, model );
        userData->setLoaded();
    }
}

void SFTreeListBox::ExpandedHdl()
{
}


// CuiInputDialog ------------------------------------------------------------

CuiInputDialog::CuiInputDialog(vcl::Window * pParent, InputDialogMode nMode )
    : ModalDialog(pParent, "NewLibDialog",
        "cui/ui/newlibdialog.ui")
{
    get(m_pEdit, "entry");
    m_pEdit->GrabFocus();

    FixedText *pNewLibFT = get<FixedText>("newlibft");

    if ( nMode == InputDialogMode::NEWMACRO )
    {
        pNewLibFT->Hide();
        FixedText *pNewMacroFT = get<FixedText>("newmacroft");
        pNewMacroFT->Show();
        SetText(get<FixedText>("altmacrotitle")->GetText());
    }
    else if ( nMode == InputDialogMode::RENAME )
    {
        pNewLibFT->Hide();
        FixedText *pRenameFT = get<FixedText>("renameft");
        pRenameFT->Show();
        SetText(get<FixedText>("altrenametitle")->GetText());
    }
}

CuiInputDialog::~CuiInputDialog()
{
    disposeOnce();
}

void CuiInputDialog::dispose()
{
    m_pEdit.clear();
    ModalDialog::dispose();
}


// ScriptOrgDialog ------------------------------------------------------------

SvxScriptOrgDialog::SvxScriptOrgDialog( vcl::Window* pParent, const OUString& language )
    : SfxModalDialog(pParent, "ScriptOrganizerDialog",
        "cui/ui/scriptorganizer.ui")
    , m_sLanguage(language)
    , m_delErrStr(CuiResId(RID_SVXSTR_DELFAILED))
    , m_delErrTitleStr(CuiResId(RID_SVXSTR_DELFAILED_TITLE))
    , m_delQueryStr(CuiResId(RID_SVXSTR_DELQUERY))
    , m_delQueryTitleStr(CuiResId(RID_SVXSTR_DELQUERY_TITLE))
    , m_createErrStr(CuiResId(RID_SVXSTR_CREATEFAILED))
    , m_createDupStr(CuiResId(RID_SVXSTR_CREATEFAILEDDUP))
    , m_createErrTitleStr(CuiResId(RID_SVXSTR_CREATEFAILED_TITLE))
    , m_renameErrStr(CuiResId(RID_SVXSTR_RENAMEFAILED))
    , m_renameErrTitleStr(CuiResId(RID_SVXSTR_RENAMEFAILED_TITLE))
{
    get(m_pScriptsBox, "scripts");
    get(m_pRunButton, "run");
    get(m_pCloseButton, "close");
    get(m_pCreateButton, "create");
    get(m_pEditButton, "edit");
    get(m_pRenameButton, "rename");
    get(m_pDelButton, "delete");
    // must be a neater way to deal with the strings than as above
    // append the language to the dialog title
    OUString winTitle( GetText() );
    winTitle = winTitle.replaceFirst( "%MACROLANG", m_sLanguage );
    SetText( winTitle );

    m_pScriptsBox->SetSelectHdl( LINK( this, SvxScriptOrgDialog, ScriptSelectHdl ) );
    m_pRunButton->SetClickHdl( LINK( this, SvxScriptOrgDialog, ButtonHdl ) );
    m_pCloseButton->SetClickHdl( LINK( this, SvxScriptOrgDialog, ButtonHdl ) );
    m_pRenameButton->SetClickHdl( LINK( this, SvxScriptOrgDialog, ButtonHdl ) );
    m_pEditButton->SetClickHdl( LINK( this, SvxScriptOrgDialog, ButtonHdl ) );
    m_pDelButton->SetClickHdl( LINK( this, SvxScriptOrgDialog, ButtonHdl ) );
    m_pCreateButton->SetClickHdl( LINK( this, SvxScriptOrgDialog, ButtonHdl ) );

    m_pRunButton->Disable();
    m_pRenameButton->Disable();
    m_pEditButton->Disable();
    m_pDelButton->Disable();
    m_pCreateButton->Disable();

    m_pScriptsBox->Init( m_sLanguage );
    RestorePreviousSelection();
}

SvxScriptOrgDialog::~SvxScriptOrgDialog()
{
    disposeOnce();
}

void SvxScriptOrgDialog::dispose()
{
    // clear the SelectHdl so that it isn't called during the dtor
    m_pScriptsBox->SetSelectHdl( Link<SvTreeListBox*,void>() );
    m_pScriptsBox.clear();
    m_pRunButton.clear();
    m_pCloseButton.clear();
    m_pCreateButton.clear();
    m_pEditButton.clear();
    m_pRenameButton.clear();
    m_pDelButton.clear();
    SfxModalDialog::dispose();
};

short SvxScriptOrgDialog::Execute()
{

    SfxObjectShell *pDoc = SfxObjectShell::GetFirst();

    // force load of MSPs for all documents
    while ( pDoc )
    {
        Reference< provider::XScriptProviderSupplier > xSPS =
            Reference< provider::XScriptProviderSupplier >
                                        ( pDoc->GetModel(), UNO_QUERY );
        if ( xSPS.is() )
        {
            xSPS->getScriptProvider();
        }

        pDoc = SfxObjectShell::GetNext(*pDoc);
    }

    return ModalDialog::Execute();
}

void SvxScriptOrgDialog::CheckButtons( Reference< browse::XBrowseNode >& node )
{
    if ( node.is() )
    {
        if ( node->getType() == browse::BrowseNodeTypes::SCRIPT)
        {
            m_pRunButton->Enable();
        }
        else
        {
            m_pRunButton->Disable();
        }
        Reference< beans::XPropertySet > xProps( node, UNO_QUERY );

        if ( !xProps.is() )
        {
            m_pEditButton->Disable();
            m_pDelButton->Disable();
            m_pCreateButton->Disable();
            m_pRunButton->Disable();
            return;
        }

        OUString sName("Editable");

        if ( getBoolProperty( xProps, sName ) )
        {
            m_pEditButton->Enable();
        }
        else
        {
            m_pEditButton->Disable();
        }

        sName = "Deletable";

        if ( getBoolProperty( xProps, sName ) )
        {
            m_pDelButton->Enable();
        }
        else
        {
            m_pDelButton->Disable();
        }

        sName = "Creatable";

        if ( getBoolProperty( xProps, sName ) )
        {
            m_pCreateButton->Enable();
        }
        else
        {
            m_pCreateButton->Disable();
        }

        sName = "Renamable";

        if ( getBoolProperty( xProps, sName ) )
        {
            m_pRenameButton->Enable();
        }
        else
        {
            m_pRenameButton->Disable();
        }
    }
    else
    {
        // no node info available, disable all configurable actions
        m_pDelButton->Disable();
        m_pCreateButton->Disable();
        m_pEditButton->Disable();
        m_pRunButton->Disable();
        m_pRenameButton->Disable();
    }
}

IMPL_LINK( SvxScriptOrgDialog, ScriptSelectHdl, SvTreeListBox *, pBox, void )
{
    if ( !pBox->IsSelected( pBox->GetHdlEntry() ) )
    {
        return;
    }

    SvTreeListEntry* pEntry = pBox->GetHdlEntry();

    SFEntry* userData = nullptr;
    if ( !pEntry )
    {
        return;
    }
    userData = static_cast<SFEntry*>(pEntry->GetUserData());

    Reference< browse::XBrowseNode > node;
    if ( userData )
    {
              node = userData->GetNode();
        CheckButtons( node );
    }
}

IMPL_LINK( SvxScriptOrgDialog, ButtonHdl, Button *, pButton, void )
{
    if ( pButton == m_pCloseButton )
    {
        StoreCurrentSelection();
        EndDialog();
    }
    if ( pButton == m_pEditButton ||
            pButton == m_pCreateButton ||
            pButton == m_pDelButton ||
            pButton == m_pRunButton ||
            pButton == m_pRenameButton )

    {
        if ( m_pScriptsBox->IsSelected( m_pScriptsBox->GetHdlEntry() ) )
        {
            SvTreeListEntry* pEntry = m_pScriptsBox->GetHdlEntry();
            SFEntry* userData = nullptr;
            if ( !pEntry )
            {
                return;
            }
            userData = static_cast<SFEntry*>(pEntry->GetUserData());
            if ( userData )
            {
                Reference< browse::XBrowseNode > node;
                Reference< XModel > xModel;

                node = userData->GetNode();
                xModel = userData->GetModel();

                if ( !node.is() )
                {
                    return;
                }

                if ( pButton == m_pRunButton )
                {
                    OUString tmpString;
                    Reference< beans::XPropertySet > xProp( node, UNO_QUERY );
                    Reference< provider::XScriptProvider > mspNode;
                    if( !xProp.is() )
                    {
                        return;
                    }

                    if ( xModel.is() )
                    {
                        Reference< XEmbeddedScripts >  xEmbeddedScripts( xModel, UNO_QUERY);
                        if( !xEmbeddedScripts.is() )
                        {
                            return;
                        }

                        if (!xEmbeddedScripts->getAllowMacroExecution())
                        {
                            // Please FIXME: Show a message box if AllowMacroExecution is false
                            return;
                        }
                    }


                    SvTreeListEntry* pParent = m_pScriptsBox->GetParent( pEntry );
                    while ( pParent && !mspNode.is() )
                    {
                        SFEntry* mspUserData = static_cast<SFEntry*>(pParent->GetUserData());
                        mspNode.set( mspUserData->GetNode() , UNO_QUERY );
                        pParent = m_pScriptsBox->GetParent( pParent );
                    }
                    xProp->getPropertyValue("URI") >>= tmpString;
                    const OUString scriptURL( tmpString );

                    if ( mspNode.is() )
                    {
                        try
                        {
                            Reference< provider::XScript > xScript(
                            mspNode->getScript( scriptURL ), UNO_QUERY_THROW );

                            const Sequence< Any > args(0);
                            Any aRet;
                            Sequence< sal_Int16 > outIndex;
                            Sequence< Any > outArgs( 0 );
                            aRet = xScript->invoke( args, outIndex, outArgs );
                        }
                        catch ( reflection::InvocationTargetException& ite )
                        {
                            ShowErrorDialog(css::uno::Any(ite));
                        }
                        catch ( provider::ScriptFrameworkErrorException& ite )
                        {
                            ShowErrorDialog(css::uno::Any(ite));
                        }
                        catch ( RuntimeException& re )
                        {
                            ShowErrorDialog(css::uno::Any(re));
                        }
                        catch ( Exception& e )
                        {
                            ShowErrorDialog(css::uno::Any(e));
                        }
                    }
                    StoreCurrentSelection();
                    EndDialog();
                }
                else if ( pButton == m_pEditButton )
                {
                    Reference< script::XInvocation > xInv( node, UNO_QUERY );
                    if ( xInv.is() )
                    {
                        StoreCurrentSelection();
                        EndDialog();
                        Sequence< Any > args(0);
                        Sequence< Any > outArgs( 0 );
                        Sequence< sal_Int16 > outIndex;
                        try
                        {
                            // ISSUE need code to run script here
                            xInv->invoke( "Editable", args, outIndex, outArgs );
                        }
                        catch( Exception& e )
                        {
                            SAL_WARN("cui.dialogs", "Caught exception trying to invoke " << e.Message );
                        }
                    }
                }
                else if ( pButton == m_pCreateButton )
                {
                    createEntry( pEntry );
                }
                else if ( pButton == m_pDelButton )
                {
                    deleteEntry( pEntry );
                }
                else if ( pButton == m_pRenameButton )
                {
                    renameEntry( pEntry );
                }
            }
        }
    }
}

Reference< browse::XBrowseNode > SvxScriptOrgDialog::getBrowseNode( SvTreeListEntry* pEntry )
{
    Reference< browse::XBrowseNode > node;
    if ( pEntry )
    {
        SFEntry* userData = static_cast<SFEntry*>(pEntry->GetUserData());
        if ( userData )
        {
            node = userData->GetNode();
        }
    }

    return node;
}

Reference< XModel > SvxScriptOrgDialog::getModel( SvTreeListEntry* pEntry )
{
    Reference< XModel > model;
    if ( pEntry )
    {
        SFEntry* userData = static_cast<SFEntry*>(pEntry->GetUserData());
        if ( userData )
        {
            model = userData->GetModel();
        }
    }

    return model;
}

void SvxScriptOrgDialog::createEntry( SvTreeListEntry* pEntry )
{

    Reference< browse::XBrowseNode >  aChildNode;
    Reference< browse::XBrowseNode > node = getBrowseNode( pEntry );
    Reference< script::XInvocation > xInv( node, UNO_QUERY );

    if ( xInv.is() )
    {
        OUString aNewName;
        OUString aNewStdName;
        InputDialogMode nMode = InputDialogMode::NEWLIB;
        if( m_pScriptsBox->GetModel()->GetDepth( pEntry ) == 0 )
        {
            aNewStdName = "Library" ;
        }
        else
        {
            aNewStdName = "Macro" ;
            nMode = InputDialogMode::NEWMACRO;
        }
        //do we need L10N for this? ie something like:
        //String aNewStdName( ResId( STR_STDMODULENAME ) );
        bool bValid = false;
        sal_Int32 i = 1;

        Sequence< Reference< browse::XBrowseNode > > childNodes;
        // no children => ok to create Parcel1 or Script1 without checking
        try
        {
            if( !node->hasChildNodes() )
            {
                aNewName = aNewStdName + OUString::number(i);
                bValid = true;
            }
            else
            {
                childNodes = node->getChildNodes();
            }
        }
        catch ( Exception& )
        {
            // ignore, will continue on with empty sequence
        }

        OUString extn;
        while ( !bValid )
        {
            aNewName = aNewStdName + OUString::number(i);
            bool bFound = false;
            if(childNodes.getLength() > 0 )
            {
                OUString nodeName = childNodes[0]->getName();
                sal_Int32 extnPos = nodeName.lastIndexOf( '.' );
                if(extnPos>0)
                    extn = nodeName.copy(extnPos);
            }
            for( sal_Int32 index = 0; index < childNodes.getLength(); index++ )
            {
                if (aNewName+extn == childNodes[index]->getName())
                {
                    bFound = true;
                    break;
                }
            }
            if( bFound )
            {
                i++;
            }
            else
            {
                bValid = true;
            }
        }

        ScopedVclPtrInstance< CuiInputDialog > xNewDlg( static_cast<vcl::Window*>(this), nMode );
        xNewDlg->SetObjectName( aNewName );

        do
        {
            if ( xNewDlg->Execute() && !xNewDlg->GetObjectName().isEmpty() )
            {
                OUString aUserSuppliedName = xNewDlg->GetObjectName();
                bValid = true;
                for( sal_Int32 index = 0; index < childNodes.getLength(); index++ )
                {
                    if (aUserSuppliedName+extn == childNodes[index]->getName())
                    {
                        bValid = false;
                        OUString aError = m_createErrStr + m_createDupStr;
                        ScopedVclPtrInstance< MessageDialog > aErrorBox(static_cast<vcl::Window*>(this), aError);
                        aErrorBox->SetText( m_createErrTitleStr );
                        aErrorBox->Execute();
                        xNewDlg->SetObjectName( aNewName );
                        break;
                    }
                }
                if( bValid )
                    aNewName = aUserSuppliedName;
            }
            else
            {
                // user hit cancel or hit OK with nothing in the editbox

                return;
            }
        }
        while ( !bValid );

        // open up parent node (which ensures it's loaded)
        m_pScriptsBox->RequestingChildren( pEntry );

        Sequence< Any > args( 1 );
        args[ 0 ] <<= aNewName;
        Sequence< Any > outArgs( 0 );
        Sequence< sal_Int16 > outIndex;
        try
        {
            Any aResult;
            aResult = xInv->invoke( "Creatable", args, outIndex, outArgs );
            Reference< browse::XBrowseNode > newNode( aResult, UNO_QUERY );
            aChildNode = newNode;

        }
        catch( Exception& e )
        {
            SAL_WARN("cui.dialogs", "Caught exception trying to Create " << e.Message );
        }
    }
    if ( aChildNode.is() )
    {
        OUString aChildName = aChildNode->getName();
        SvTreeListEntry* pNewEntry = nullptr;

        Reference<XModel> xDocumentModel = getModel( pEntry );

        // ISSUE do we need to remove all entries for parent
        // to achieve sort? Just need to determine position
        // SvTreeListBox::InsertEntry can take position arg
        // -- Basic doesn't do this on create.
        // Suppose we could avoid this too. -> created nodes are
        // not in alphabetical order
        if ( aChildNode->getType() == browse::BrowseNodeTypes::SCRIPT )
        {
            pNewEntry = m_pScriptsBox->insertEntry( aChildName,
                    RID_CUIBMP_MACRO, pEntry, false, o3tl::make_unique< SFEntry >( aChildNode,xDocumentModel ) );
        }
        else
        {
            pNewEntry = m_pScriptsBox->insertEntry( aChildName,
                RID_CUIBMP_LIB, pEntry, false, o3tl::make_unique< SFEntry >( aChildNode,xDocumentModel ) );

            // If the Parent is not loaded then set to
            // loaded, this will prevent RequestingChildren ( called
            // from vcl via RequestingChildren ) from
            // creating new ( duplicate ) children
            SFEntry* userData = static_cast<SFEntry*>(pEntry->GetUserData());
            if ( userData &&  !userData->isLoaded() )
            {
                userData->setLoaded();
            }
        }
        m_pScriptsBox->SetCurEntry( pNewEntry );
        m_pScriptsBox->Select( m_pScriptsBox->GetCurEntry() );

    }
    else
    {
        //ISSUE L10N & message from exception?
        OUString aError( m_createErrStr );
        ScopedVclPtrInstance< MessageDialog > aErrorBox(static_cast<vcl::Window*>(this), aError);
        aErrorBox->SetText( m_createErrTitleStr );
        aErrorBox->Execute();
    }
}

void SvxScriptOrgDialog::renameEntry( SvTreeListEntry* pEntry )
{

    Reference< browse::XBrowseNode >  aChildNode;
    Reference< browse::XBrowseNode > node = getBrowseNode( pEntry );
    Reference< script::XInvocation > xInv( node, UNO_QUERY );

    if ( xInv.is() )
    {
        OUString aNewName = node->getName();
        sal_Int32 extnPos = aNewName.lastIndexOf( '.' );
        OUString extn;
        if(extnPos>0)
        {
            extn = aNewName.copy(extnPos);
            aNewName = aNewName.copy(0,extnPos);
        }
        ScopedVclPtrInstance< CuiInputDialog > xNewDlg( static_cast<vcl::Window*>(this), InputDialogMode::RENAME );
        xNewDlg->SetObjectName( aNewName );

        bool bValid;
        do
        {
            if ( xNewDlg->Execute() && !xNewDlg->GetObjectName().isEmpty() )
            {
                OUString aUserSuppliedName = xNewDlg->GetObjectName();
                bValid = true;
                if( bValid )
                    aNewName = aUserSuppliedName;
            }
            else
            {
                // user hit cancel or hit OK with nothing in the editbox
                return;
            }
        }
        while ( !bValid );

        Sequence< Any > args( 1 );
        args[ 0 ] <<= aNewName;
        Sequence< Any > outArgs( 0 );
        Sequence< sal_Int16 > outIndex;
        try
        {
            Any aResult;
            aResult = xInv->invoke( "Renamable", args, outIndex, outArgs );
            Reference< browse::XBrowseNode > newNode( aResult, UNO_QUERY );
            aChildNode = newNode;

        }
        catch( Exception& e )
        {
            SAL_WARN("cui.dialogs", "Caught exception trying to Rename " << e.Message );
        }
    }
    if ( aChildNode.is() )
    {
        m_pScriptsBox->SetEntryText( pEntry, aChildNode->getName() );
        m_pScriptsBox->SetCurEntry( pEntry );
        m_pScriptsBox->Select( m_pScriptsBox->GetCurEntry() );

    }
    else
    {
        //ISSUE L10N & message from exception?
        OUString aError( m_renameErrStr );
        ScopedVclPtrInstance< MessageDialog > aErrorBox(static_cast<vcl::Window*>(this), aError);
        aErrorBox->SetText( m_renameErrTitleStr );
        aErrorBox->Execute();
    }
}
void SvxScriptOrgDialog::deleteEntry( SvTreeListEntry* pEntry )
{
    bool result = false;
    Reference< browse::XBrowseNode > node = getBrowseNode( pEntry );
    // ISSUE L10N string & can we centre list?
    OUString aQuery = m_delQueryStr + getListOfChildren( node, 0 );
    VclPtrInstance< MessageDialog > aQueryBox(static_cast<vcl::Window*>(this), aQuery, VclMessageType::Question, VclButtonsType::YesNo);
    aQueryBox->SetText( m_delQueryTitleStr );
    if ( aQueryBox->Execute() == RET_NO )
    {
        return;
    }

    Reference< script::XInvocation > xInv( node, UNO_QUERY );
    if ( xInv.is() )
    {
        Sequence< Any > args( 0 );
        Sequence< Any > outArgs( 0 );
        Sequence< sal_Int16 > outIndex;
        try
        {
            Any aResult;
            aResult = xInv->invoke( "Deletable", args, outIndex, outArgs );
            aResult >>= result; // or do we just assume true if no exception ?
        }
        catch( Exception& e )
        {
            SAL_WARN("cui.dialogs", "Caught exception trying to delete " << e.Message );
        }
    }

    if ( result )
    {
        m_pScriptsBox->deleteTree( pEntry );
        m_pScriptsBox->GetModel()->Remove( pEntry );
    }
    else
    {
        //ISSUE L10N & message from exception?
        ScopedVclPtrInstance< MessageDialog > aErrorBox(static_cast<vcl::Window*>(this), m_delErrStr);
        aErrorBox->SetText( m_delErrTitleStr );
        aErrorBox->Execute();
    }

}

bool SvxScriptOrgDialog::getBoolProperty( Reference< beans::XPropertySet >& xProps,
                OUString& propName )
{
    bool result = false;
    try
    {
        xProps->getPropertyValue( propName ) >>= result;
    }
    catch ( Exception& )
    {
        return result;
    }
    return result;
}

OUString SvxScriptOrgDialog::getListOfChildren( const Reference< browse::XBrowseNode >& node, int depth )
{
    OUString result = "\n";
    for( int i=0;i<=depth;i++ )
    {
        result += "\t";
    }
    result += node->getName();

    try
    {
        if ( node->hasChildNodes() )
        {
            Sequence< Reference< browse::XBrowseNode > > children
                = node->getChildNodes();
            for ( sal_Int32 n = 0; n < children.getLength(); n++ )
            {
                result += getListOfChildren( children[ n ] , depth+1 );
            }
        }
    }
    catch ( Exception& )
    {
        // ignore, will return an empty string
    }

    return result;
}

Selection_hash SvxScriptOrgDialog::m_lastSelection;

void SvxScriptOrgDialog::StoreCurrentSelection()
{
    OUString aDescription;
    if ( m_pScriptsBox->IsSelected( m_pScriptsBox->GetHdlEntry() ) )
    {
        SvTreeListEntry* pEntry = m_pScriptsBox->GetHdlEntry();
        while( pEntry )
        {
            aDescription = m_pScriptsBox->GetEntryText( pEntry ) + aDescription;
            pEntry = m_pScriptsBox->GetParent( pEntry );
            if ( pEntry )
                aDescription = ";" + aDescription;
        }
        OUString sDesc( aDescription );
        m_lastSelection[ m_sLanguage ] = sDesc;
    }
}

void SvxScriptOrgDialog::RestorePreviousSelection()
{
    OUString aStoredEntry = m_lastSelection[ m_sLanguage ];
    if( aStoredEntry.isEmpty() )
        return;
    SvTreeListEntry* pEntry = nullptr;
    sal_Int32 nIndex = 0;
    while ( nIndex != -1 )
    {
        OUString aTmp( aStoredEntry.getToken( 0, ';', nIndex ) );
        SvTreeListEntry* pTmpEntry = m_pScriptsBox->FirstChild( pEntry );
        while ( pTmpEntry )
        {
            if ( m_pScriptsBox->GetEntryText( pTmpEntry ) == aTmp )
            {
                pEntry = pTmpEntry;
                break;
            }
            pTmpEntry = SvTreeListBox::NextSibling( pTmpEntry );
        }
        if ( !pTmpEntry )
            break;
        m_pScriptsBox->RequestingChildren( pEntry );
    }
    m_pScriptsBox->SetCurEntry( pEntry );
}

namespace {

OUString ReplaceString(
    const OUString& source,
    const OUString& token,
    const OUString& value )
{
    sal_Int32 pos = source.indexOf( token );

    if ( pos != -1 && !value.isEmpty() )
    {
        return source.replaceAt( pos, token.getLength(), value );
    }
    else
    {
        return source;
    }
}

OUString FormatErrorString(
    const OUString& unformatted,
    const OUString& language,
    const OUString& script,
    const OUString& line,
    const OUString& type,
    const OUString& message )
{
    OUString result = unformatted.copy( 0 );

    result = ReplaceString(result, "%LANGUAGENAME", language );
    result = ReplaceString(result, "%SCRIPTNAME", script );
    result = ReplaceString(result, "%LINENUMBER", line );

    if ( !type.isEmpty() )
    {
        result += "\n\n" + CuiResId(RID_SVXSTR_ERROR_TYPE_LABEL) + " " + type;
    }

    if ( !message.isEmpty() )
    {
        result += "\n\n" + CuiResId(RID_SVXSTR_ERROR_MESSAGE_LABEL) + " " + message;
    }

    return result;
}

OUString GetErrorMessage(
    const provider::ScriptErrorRaisedException& eScriptError )
{
    OUString unformatted = CuiResId( RID_SVXSTR_ERROR_AT_LINE );

    OUString unknown("UNKNOWN");
    OUString language = unknown;
    OUString script = unknown;
    OUString line = unknown;
    OUString type = "";
    OUString message = eScriptError.Message;

        if ( !eScriptError.language.isEmpty() )
        {
            language = eScriptError.language;
        }

        if ( !eScriptError.scriptName.isEmpty() )
        {
            script = eScriptError.scriptName;
        }

        if ( !eScriptError.Message.isEmpty() )
        {
            message = eScriptError.Message;
        }
        if ( eScriptError.lineNum != -1 )
        {
            line = OUString::number( eScriptError.lineNum );
            unformatted = CuiResId( RID_SVXSTR_ERROR_AT_LINE );
        }
        else
        {
            unformatted = CuiResId( RID_SVXSTR_ERROR_RUNNING );
        }

    return FormatErrorString(
        unformatted, language, script, line, type, message );
}

OUString GetErrorMessage(
    const provider::ScriptExceptionRaisedException& eScriptException )
{
    OUString unformatted = CuiResId( RID_SVXSTR_EXCEPTION_AT_LINE );

    OUString unknown("UNKNOWN");
    OUString language = unknown;
    OUString script = unknown;
    OUString line = unknown;
    OUString type = unknown;
    OUString message = eScriptException.Message;

    if ( !eScriptException.language.isEmpty() )
    {
        language = eScriptException.language;
    }
    if ( !eScriptException.scriptName.isEmpty() )
    {
        script = eScriptException.scriptName;
    }

    if ( !eScriptException.Message.isEmpty() )
    {
        message = eScriptException.Message;
    }

    if ( eScriptException.lineNum != -1 )
    {
        line = OUString::number( eScriptException.lineNum );
        unformatted = CuiResId( RID_SVXSTR_EXCEPTION_AT_LINE );
    }
    else
    {
        unformatted = CuiResId( RID_SVXSTR_EXCEPTION_RUNNING );
    }

    if ( !eScriptException.exceptionType.isEmpty() )
    {
        type = eScriptException.exceptionType;
    }

    return FormatErrorString(
        unformatted, language, script, line, type, message );

}
OUString GetErrorMessage(
    const provider::ScriptFrameworkErrorException& sError )
{
    OUString unformatted = CuiResId( RID_SVXSTR_FRAMEWORK_ERROR_RUNNING );

    OUString language("UNKNOWN");

    OUString script("UNKNOWN");

    OUString message;

    if ( !sError.scriptName.isEmpty() )
    {
        script = sError.scriptName;
    }
    if ( !sError.language.isEmpty() )
    {
        language = sError.language;
    }
    if ( sError.errorType == provider::ScriptFrameworkErrorType::NOTSUPPORTED )
    {
        message =
            CuiResId(  RID_SVXSTR_ERROR_LANG_NOT_SUPPORTED );
        message = ReplaceString(message, "%LANGUAGENAME", language );

    }
    else
    {
        message = sError.Message;
    }
    return FormatErrorString(
        unformatted, language, script, OUString(), OUString(), message );
}

OUString GetErrorMessage( const css::uno::Any& aException )
{
    if ( aException.getValueType() ==
         cppu::UnoType<reflection::InvocationTargetException>::get())
    {
        reflection::InvocationTargetException ite;
        aException >>= ite;
        if ( ite.TargetException.getValueType() == cppu::UnoType<provider::ScriptErrorRaisedException>::get())
        {
            // Error raised by script
            provider::ScriptErrorRaisedException scriptError;
            ite.TargetException >>= scriptError;
            return GetErrorMessage( scriptError );
        }
        else if ( ite.TargetException.getValueType() == cppu::UnoType<provider::ScriptExceptionRaisedException>::get())
        {
            // Exception raised by script
            provider::ScriptExceptionRaisedException scriptException;
            ite.TargetException >>= scriptException;
            return GetErrorMessage( scriptException );
        }
        else
        {
            // Unknown error, shouldn't happen
            // OSL_ASSERT(...)
        }

    }
    else if ( aException.getValueType() == cppu::UnoType<provider::ScriptFrameworkErrorException>::get())
    {
        // A Script Framework error has occurred
        provider::ScriptFrameworkErrorException sfe;
        aException >>= sfe;
        return GetErrorMessage( sfe );

    }
    // unknown exception
    auto msg = aException.getValueTypeName();
    Exception e;
    if ( (aException >>= e) && !e.Message.isEmpty() )
    {
        msg += ": " + e.Message;
    }
    return msg;
}

}

SvxScriptErrorDialog::SvxScriptErrorDialog( css::uno::Any const & aException )
    : m_sMessage()
{
    SolarMutexGuard aGuard;
    m_sMessage = GetErrorMessage( aException );
}

SvxScriptErrorDialog::~SvxScriptErrorDialog()
{
}

short SvxScriptErrorDialog::Execute()
{
    // Show Error dialog asynchronously

    // Pass a copy of the message to the ShowDialog method as the
    // SvxScriptErrorDialog may be deleted before ShowDialog is called
    Application::PostUserEvent(
        LINK( this, SvxScriptErrorDialog, ShowDialog ),
        new OUString( m_sMessage ) );

    return 0;
}

IMPL_STATIC_LINK( SvxScriptErrorDialog, ShowDialog, void*, p, void )
{
    OUString* pMessage = static_cast<OUString*>(p);
    OUString message;

    if ( pMessage && !pMessage->isEmpty() )
    {
        message = *pMessage;
    }
    else
    {
        message = CuiResId( RID_SVXSTR_ERROR_TITLE );
    }

    ScopedVclPtrInstance<MessageDialog> pBox( nullptr, message, VclMessageType::Warning );
    pBox->SetText( CuiResId( RID_SVXSTR_ERROR_TITLE ) );
    pBox->Execute();

    delete pMessage;
}

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