1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
/* -*- 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 <vcl/svapp.hxx>
#include <tools/stream.hxx>
#include <tools/diagnose_ex.h>
#include <svl/SfxBroadcaster.hxx>
#include <basic/codecompletecache.hxx>
#include <basic/sbx.hxx>
#include <basic/sbuno.hxx>
#include <sbjsmeth.hxx>
#include <sbjsmod.hxx>
#include <sbintern.hxx>
#include <sbprop.hxx>
#include <image.hxx>
#include <opcodes.hxx>
#include <runtime.hxx>
#include <token.hxx>
#include <sbunoobj.hxx>

#include <sal/log.hxx>

#include <basic/sberrors.hxx>
#include <sbobjmod.hxx>
#include <basic/vbahelper.hxx>
#include <comphelper/sequence.hxx>
#include <cppuhelper/implbase.hxx>
#include <unotools/eventcfg.hxx>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/script/ModuleType.hpp>
#include <com/sun/star/script/vba/XVBACompatibility.hpp>
#include <com/sun/star/script/vba/VBAScriptEventId.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/document/XDocumentEventBroadcaster.hpp>
#include <com/sun/star/document/XDocumentEventListener.hpp>

#ifdef UNX
#include <sys/resource.h>
#endif

#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <comphelper/processfactory.hxx>
#include <comphelper/asyncquithandler.hxx>
#include <map>
#include <com/sun/star/reflection/ProxyFactory.hpp>
#include <com/sun/star/uno/XAggregation.hpp>
#include <com/sun/star/script/XInvocation.hpp>

#include <com/sun/star/awt/DialogProvider.hpp>
#include <com/sun/star/awt/XTopWindow.hpp>
#include <com/sun/star/awt/XWindow.hpp>
#include <ooo/vba/VbQueryClose.hpp>
#include <memory>
#include <sbxmod.hxx>
#include <parser.hxx>

#include <limits>

using namespace com::sun::star;
using namespace com::sun::star::lang;
using namespace com::sun::star::reflection;
using namespace com::sun::star::beans;
using namespace com::sun::star::script;
using namespace com::sun::star::uno;

typedef ::cppu::WeakImplHelper< XInvocation > DocObjectWrapper_BASE;
typedef std::map< sal_Int16, Any > OutParamMap;

namespace {

class DocObjectWrapper : public DocObjectWrapper_BASE
{
    Reference< XAggregation >  m_xAggProxy;
    Reference< XInvocation >  m_xAggInv;
    Reference< XTypeProvider > m_xAggregateTypeProv;
    Sequence< Type >           m_Types;
    SbModule*                m_pMod;
    /// @throws css::uno::RuntimeException
    SbMethodRef getMethod( const OUString& aName );
    /// @throws css::uno::RuntimeException
    SbPropertyRef getProperty( const OUString& aName );

public:
    explicit DocObjectWrapper( SbModule* pMod );

    virtual Sequence< sal_Int8 > SAL_CALL getImplementationId() override
    {
        return css::uno::Sequence<sal_Int8>();
    }

    virtual Reference< XIntrospectionAccess > SAL_CALL getIntrospection(  ) override;

    virtual Any SAL_CALL invoke( const OUString& aFunctionName, const Sequence< Any >& aParams, Sequence< ::sal_Int16 >& aOutParamIndex, Sequence< Any >& aOutParam ) override;
    virtual void SAL_CALL setValue( const OUString& aPropertyName, const Any& aValue ) override;
    virtual Any SAL_CALL getValue( const OUString& aPropertyName ) override;
    virtual sal_Bool SAL_CALL hasMethod( const OUString& aName ) override;
    virtual sal_Bool SAL_CALL hasProperty( const OUString& aName ) override;
    virtual  Any SAL_CALL queryInterface( const Type& aType ) override;

    virtual Sequence< Type > SAL_CALL getTypes() override;
};

}

DocObjectWrapper::DocObjectWrapper( SbModule* pVar ) : m_pMod( pVar )
{
    SbObjModule* pMod = dynamic_cast<SbObjModule*>( pVar );
    if ( !pMod )
        return;

    if ( pMod->GetModuleType() != ModuleType::DOCUMENT )
        return;

    // Use proxy factory service to create aggregatable proxy.
    SbUnoObject* pUnoObj = dynamic_cast<SbUnoObject*>( pMod->GetObject()  );
    Reference< XInterface > xIf;
    if ( pUnoObj )
    {
           Any aObj = pUnoObj->getUnoAny();
           aObj >>= xIf;
           if ( xIf.is() )
           {
               m_xAggregateTypeProv.set( xIf, UNO_QUERY );
               m_xAggInv.set( xIf, UNO_QUERY );
           }
    }
    if ( xIf.is() )
    {
        try
        {
            Reference< XProxyFactory > xProxyFac = ProxyFactory::create( comphelper::getProcessComponentContext() );
            m_xAggProxy = xProxyFac->createProxy( xIf );
        }
        catch(const Exception& )
        {
            TOOLS_WARN_EXCEPTION( "basic", "DocObjectWrapper::DocObjectWrapper" );
        }
    }

    if ( !m_xAggProxy.is() )
        return;

    osl_atomic_increment( &m_refCount );

    /* i35609 - Fix crash on Solaris. The setDelegator call needs
        to be in its own block to ensure that all temporary Reference
        instances that are acquired during the call are released
        before m_refCount is decremented again */
    {
        m_xAggProxy->setDelegator( static_cast< cppu::OWeakObject * >( this ) );
    }

    osl_atomic_decrement( &m_refCount );
}

Sequence< Type > SAL_CALL DocObjectWrapper::getTypes()
{
    if ( !m_Types.hasElements() )
    {
        Sequence< Type > sTypes;
        if ( m_xAggregateTypeProv.is() )
        {
            sTypes = m_xAggregateTypeProv->getTypes();
        }
        m_Types = comphelper::concatSequences(sTypes,
            Sequence { cppu::UnoType<XInvocation>::get() });
    }
    return m_Types;
}

Reference< XIntrospectionAccess > SAL_CALL
DocObjectWrapper::getIntrospection(  )
{
    return nullptr;
}

Any SAL_CALL
DocObjectWrapper::invoke( const OUString& aFunctionName, const Sequence< Any >& aParams, Sequence< ::sal_Int16 >& aOutParamIndex, Sequence< Any >& aOutParam )
{
    if ( m_xAggInv.is() &&  m_xAggInv->hasMethod( aFunctionName ) )
            return m_xAggInv->invoke( aFunctionName, aParams, aOutParamIndex, aOutParam );
    SbMethodRef pMethod = getMethod( aFunctionName );
    if ( !pMethod.is() )
        throw RuntimeException();
    // check number of parameters
    sal_Int32 nParamsCount = aParams.getLength();
    SbxInfo* pInfo = pMethod->GetInfo();
    if ( pInfo )
    {
        sal_Int32 nSbxOptional = 0;
        sal_uInt16 n = 1;
        for ( const SbxParamInfo* pParamInfo = pInfo->GetParam( n ); pParamInfo; pParamInfo = pInfo->GetParam( ++n ) )
        {
            if ( pParamInfo->nFlags & SbxFlagBits::Optional )
                ++nSbxOptional;
            else
                nSbxOptional = 0;
        }
        sal_Int32 nSbxCount = n - 1;
        if ( nParamsCount < nSbxCount - nSbxOptional )
        {
            throw RuntimeException( "wrong number of parameters!" );
        }
    }
    // set parameters
    SbxArrayRef xSbxParams;
    if ( nParamsCount > 0 )
    {
        xSbxParams = new SbxArray;
        const Any* pParams = aParams.getConstArray();
        for ( sal_Int32 i = 0; i < nParamsCount; ++i )
        {
            SbxVariableRef xSbxVar = new SbxVariable( SbxVARIANT );
            unoToSbxValue( xSbxVar.get(), pParams[i] );
            xSbxParams->Put32( xSbxVar.get(), static_cast< sal_uInt32 >( i ) + 1 );

            // Enable passing by ref
            if ( xSbxVar->GetType() != SbxVARIANT )
                xSbxVar->SetFlag( SbxFlagBits::Fixed );
        }
    }
    if ( xSbxParams.is() )
        pMethod->SetParameters( xSbxParams.get() );

    // call method
    SbxVariableRef xReturn = new SbxVariable;

    pMethod->Call( xReturn.get() );
    Any aReturn;
    // get output parameters
    if ( xSbxParams.is() )
    {
        SbxInfo* pInfo_ = pMethod->GetInfo();
        if ( pInfo_ )
        {
            OutParamMap aOutParamMap;
            for ( sal_uInt32 n = 1, nCount = xSbxParams->Count32(); n < nCount; ++n )
            {
                assert(n <= std::numeric_limits<sal_uInt16>::max());
                const SbxParamInfo* pParamInfo = pInfo_->GetParam( sal::static_int_cast<sal_uInt16>(n) );
                if ( pParamInfo && ( pParamInfo->eType & SbxBYREF ) != 0 )
                {
                    SbxVariable* pVar = xSbxParams->Get32( n );
                    if ( pVar )
                    {
                        SbxVariableRef xVar = pVar;
                        aOutParamMap.emplace( n - 1, sbxToUnoValue( xVar.get() ) );
                    }
                }
            }
            sal_Int32 nOutParamCount = aOutParamMap.size();
            aOutParamIndex.realloc( nOutParamCount );
            aOutParam.realloc( nOutParamCount );
            sal_Int16* pOutParamIndex = aOutParamIndex.getArray();
            Any* pOutParam = aOutParam.getArray();
            for (auto const& outParam : aOutParamMap)
            {
                *pOutParamIndex = outParam.first;
                *pOutParam = outParam.second;
                ++pOutParamIndex;
                ++pOutParam;
            }
        }
    }

    // get return value
    aReturn = sbxToUnoValue( xReturn.get() );

    pMethod->SetParameters( nullptr );

    return aReturn;
}

void SAL_CALL
DocObjectWrapper::setValue( const OUString& aPropertyName, const Any& aValue )
{
    if ( m_xAggInv.is() &&  m_xAggInv->hasProperty( aPropertyName ) )
            return m_xAggInv->setValue( aPropertyName, aValue );

    SbPropertyRef pProperty = getProperty( aPropertyName );
    if ( !pProperty.is() )
       throw UnknownPropertyException(aPropertyName);
    unoToSbxValue( pProperty.get(), aValue );
}

Any SAL_CALL
DocObjectWrapper::getValue( const OUString& aPropertyName )
{
    if ( m_xAggInv.is() &&  m_xAggInv->hasProperty( aPropertyName ) )
            return m_xAggInv->getValue( aPropertyName );

    SbPropertyRef pProperty = getProperty( aPropertyName );
    if ( !pProperty.is() )
       throw UnknownPropertyException(aPropertyName);

    SbxVariable* pProp = pProperty.get();
    if ( pProp->GetType() == SbxEMPTY )
        pProperty->Broadcast( SfxHintId::BasicDataWanted );

    Any aRet = sbxToUnoValue( pProp );
    return aRet;
}

sal_Bool SAL_CALL
DocObjectWrapper::hasMethod( const OUString& aName )
{
    if ( m_xAggInv.is() && m_xAggInv->hasMethod( aName ) )
        return true;
    return getMethod( aName ).is();
}

sal_Bool SAL_CALL
DocObjectWrapper::hasProperty( const OUString& aName )
{
    bool bRes = false;
    if ( m_xAggInv.is() && m_xAggInv->hasProperty( aName ) )
        bRes = true;
    else bRes = getProperty( aName ).is();
    return bRes;
}

Any SAL_CALL DocObjectWrapper::queryInterface( const Type& aType )
{
    Any aRet = DocObjectWrapper_BASE::queryInterface( aType );
    if ( aRet.hasValue() )
        return aRet;
    else if ( m_xAggProxy.is() )
        aRet = m_xAggProxy->queryAggregation( aType );
    return aRet;
}

SbMethodRef DocObjectWrapper::getMethod( const OUString& aName )
{
    SbMethodRef pMethod;
    if ( m_pMod )
    {
        SbxFlagBits nSaveFlgs = m_pMod->GetFlags();
        // Limit search to this module
        m_pMod->ResetFlag( SbxFlagBits::GlobalSearch );
        pMethod = dynamic_cast<SbMethod*>(m_pMod->SbModule::Find(aName,  SbxClassType::Method));
        m_pMod->SetFlags( nSaveFlgs );
    }

    return pMethod;
}

SbPropertyRef DocObjectWrapper::getProperty( const OUString& aName )
{
    SbPropertyRef pProperty;
    if ( m_pMod )
    {
        SbxFlagBits nSaveFlgs = m_pMod->GetFlags();
        // Limit search to this module.
        m_pMod->ResetFlag( SbxFlagBits::GlobalSearch );
        pProperty = dynamic_cast<SbProperty*>(m_pMod->SbModule::Find(aName,  SbxClassType::Property));
        m_pMod->SetFlag( nSaveFlgs );
    }

    return pProperty;
}


uno::Reference< frame::XModel > getDocumentModel( StarBASIC* pb )
{
    uno::Reference< frame::XModel > xModel;
    if( pb && pb->IsDocBasic() )
    {
        uno::Any aDoc;
        if( pb->GetUNOConstant( "ThisComponent", aDoc ) )
            xModel.set( aDoc, uno::UNO_QUERY );
    }
    return xModel;
}

static uno::Reference< vba::XVBACompatibility > getVBACompatibility( const uno::Reference< frame::XModel >& rxModel )
{
    uno::Reference< vba::XVBACompatibility > xVBACompat;
    try
    {
        uno::Reference< beans::XPropertySet > xModelProps( rxModel, uno::UNO_QUERY_THROW );
        xVBACompat.set( xModelProps->getPropertyValue( "BasicLibraries" ), uno::UNO_QUERY );
    }
    catch(const uno::Exception& )
    {
    }
    return xVBACompat;
}

static bool getDefaultVBAMode( StarBASIC* pb )
{
    uno::Reference< frame::XModel > xModel( getDocumentModel( pb ) );
    if (!xModel.is())
        return false;
    uno::Reference< vba::XVBACompatibility > xVBACompat = getVBACompatibility( xModel );
    return xVBACompat.is() && xVBACompat->getVBACompatibilityMode();
}

// A Basic module has set EXTSEARCH, so that the elements, that the module contains,
// could be found from other module.

SbModule::SbModule( const OUString& rName, bool bVBACompat )
         : SbxObject( "StarBASICModule" ),
           pImage(nullptr), pBreaks(nullptr), mbVBACompat( bVBACompat ), bIsProxyModule( false )
{
    SetName( rName );
    SetFlag( SbxFlagBits::ExtSearch | SbxFlagBits::GlobalSearch );
    SetModuleType( script::ModuleType::NORMAL );

    // #i92642: Set name property to initial name
    SbxVariable* pNameProp = pProps->Find( "Name", SbxClassType::Property );
    if( pNameProp != nullptr )
    {
        pNameProp->PutString( GetName() );
    }
}

SbModule::~SbModule()
{
    SAL_INFO("basic","Module named " << GetName() << " is destructing");
    delete pImage;
    delete pBreaks;
    pClassData.reset();
    mxWrapper = nullptr;
}

uno::Reference< script::XInvocation > const &
SbModule::GetUnoModule()
{
    if ( !mxWrapper.is() )
        mxWrapper = new DocObjectWrapper( this );

    SAL_INFO("basic","Module named " << GetName() << " returning wrapper mxWrapper (0x" << mxWrapper.get() <<")" );
    return mxWrapper;
}

bool SbModule::IsCompiled() const
{
    return pImage != nullptr;
}

const SbxObject* SbModule::FindType( const OUString& aTypeName ) const
{
    return pImage ? pImage->FindType( aTypeName ) : nullptr;
}


// From the code generator: deletion of images and the opposite of validation for entries

void SbModule::StartDefinitions()
{
    delete pImage; pImage = nullptr;
    if( pClassData )
        pClassData->clear();

    // methods and properties persist, but they are invalid;
    // at least are the information under certain conditions clogged
    sal_uInt32 i;
    for( i = 0; i < pMethods->Count32(); i++ )
    {
        SbMethod* p = dynamic_cast<SbMethod*>( pMethods->Get32( i )  );
        if( p )
            p->bInvalid = true;
    }
    for( i = 0; i < pProps->Count32(); )
    {
        SbProperty* p = dynamic_cast<SbProperty*>( pProps->Get32( i )  );
        if( p )
            pProps->Remove( i );
        else
            i++;
    }
}

// request/create method

SbMethod* SbModule::GetMethod( const OUString& rName, SbxDataType t )
{
    SbxVariable* p = pMethods->Find( rName, SbxClassType::Method );
    SbMethod* pMeth = dynamic_cast<SbMethod*>( p );
    if( p && !pMeth )
    {
        pMethods->Remove( p );
    }
    if( !pMeth )
    {
        pMeth = new SbMethod( rName, t, this );
        pMeth->SetParent( this );
        pMeth->SetFlags( SbxFlagBits::Read );
        pMethods->Put32( pMeth, pMethods->Count32() );
        StartListening(pMeth->GetBroadcaster(), DuplicateHandling::Prevent);
    }
    // The method is per default valid, because it could be
    // created from the compiler (code generator) as well.
    pMeth->bInvalid = false;
    pMeth->ResetFlag( SbxFlagBits::Fixed );
    pMeth->SetFlag( SbxFlagBits::Write );
    pMeth->SetType( t );
    pMeth->ResetFlag( SbxFlagBits::Write );
    if( t != SbxVARIANT )
    {
        pMeth->SetFlag( SbxFlagBits::Fixed );
    }
    return pMeth;
}

SbMethod* SbModule::FindMethod( const OUString& rName, SbxClassType t )
{
    return dynamic_cast<SbMethod*> (pMethods->Find( rName, t ));
}


// request/create property

SbProperty* SbModule::GetProperty( const OUString& rName, SbxDataType t )
{
    SbxVariable* p = pProps->Find( rName, SbxClassType::Property );
    SbProperty* pProp = dynamic_cast<SbProperty*>( p );
    if( p && !pProp )
    {
        pProps->Remove( p );
    }
    if( !pProp )
    {
        pProp = new SbProperty( rName, t, this );
        pProp->SetFlag( SbxFlagBits::ReadWrite );
        pProp->SetParent( this );
        pProps->Put32( pProp, pProps->Count32() );
        StartListening(pProp->GetBroadcaster(), DuplicateHandling::Prevent);
    }
    return pProp;
}

void SbModule::GetProcedureProperty( const OUString& rName, SbxDataType t )
{
    SbxVariable* p = pProps->Find( rName, SbxClassType::Property );
    SbProcedureProperty* pProp = dynamic_cast<SbProcedureProperty*>( p );
    if( p && !pProp )
    {
        pProps->Remove( p );
    }
    if( !pProp )
    {
        pProp = new SbProcedureProperty( rName, t );
        pProp->SetFlag( SbxFlagBits::ReadWrite );
        pProp->SetParent( this );
        pProps->Put32( pProp, pProps->Count32() );
        StartListening(pProp->GetBroadcaster(), DuplicateHandling::Prevent);
    }
}

void SbModule::GetIfaceMapperMethod( const OUString& rName, SbMethod* pImplMeth )
{
    SbxVariable* p = pMethods->Find( rName, SbxClassType::Method );
    SbIfaceMapperMethod* pMapperMethod = dynamic_cast<SbIfaceMapperMethod*>( p );
    if( p && !pMapperMethod )
    {
        pMethods->Remove( p );
    }
    if( !pMapperMethod )
    {
        pMapperMethod = new SbIfaceMapperMethod( rName, pImplMeth );
        pMapperMethod->SetParent( this );
        pMapperMethod->SetFlags( SbxFlagBits::Read );
        pMethods->Put32( pMapperMethod, pMethods->Count32() );
    }
    pMapperMethod->bInvalid = false;
}

SbIfaceMapperMethod::~SbIfaceMapperMethod()
{
}


// From the code generator: remove invalid entries

void SbModule::EndDefinitions( bool bNewState )
{
    for( sal_uInt32 i = 0; i < pMethods->Count32(); )
    {
        SbMethod* p = dynamic_cast<SbMethod*>( pMethods->Get32( i )  );
        if( p )
        {
            if( p->bInvalid )
            {
                pMethods->Remove( p );
            }
            else
            {
                p->bInvalid = bNewState;
                i++;
            }
        }
        else
            i++;
    }
    SetModified( true );
}

void SbModule::Clear()
{
    delete pImage; pImage = nullptr;
    if( pClassData )
        pClassData->clear();
    SbxObject::Clear();
}


SbxVariable* SbModule::Find( const OUString& rName, SbxClassType t )
{
    // make sure a search in an uninstantiated class module will fail
    SbxVariable* pRes = SbxObject::Find( rName, t );
    if ( bIsProxyModule && !GetSbData()->bRunInit )
    {
        return nullptr;
    }
    if( !pRes && pImage )
    {
        SbiInstance* pInst = GetSbData()->pInst;
        if( pInst && pInst->IsCompatibility() )
        {
            // Put enum types as objects into module,
            // allows MyEnum.First notation
            SbxArrayRef xArray = pImage->GetEnums();
            if( xArray.is() )
            {
                SbxVariable* pEnumVar = xArray->Find( rName, SbxClassType::DontCare );
                SbxObject* pEnumObject = dynamic_cast<SbxObject*>( pEnumVar  );
                if( pEnumObject )
                {
                    bool bPrivate = pEnumObject->IsSet( SbxFlagBits::Private );
                    OUString aEnumName = pEnumObject->GetName();

                    pRes = new SbxVariable( SbxOBJECT );
                    pRes->SetName( aEnumName );
                    pRes->SetParent( this );
                    pRes->SetFlag( SbxFlagBits::Read );
                    if( bPrivate )
                    {
                        pRes->SetFlag( SbxFlagBits::Private );
                    }
                    pRes->PutObject( pEnumObject );
                }
            }
        }
    }
    return pRes;
}

// Parent and BASIC are one!

void SbModule::SetParent( SbxObject* p )
{
    pParent = p;
}

void SbModule::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )
{
    const SbxHint* pHint = dynamic_cast<const SbxHint*>(&rHint);
    if( !pHint )
        return;

    SbxVariable* pVar = pHint->GetVar();
    SbProperty* pProp = dynamic_cast<SbProperty*>( pVar );
    SbMethod* pMeth = dynamic_cast<SbMethod*>( pVar );
    SbProcedureProperty* pProcProperty = dynamic_cast<SbProcedureProperty*>( pVar  );
    if( pProcProperty )
    {

        if( pHint->GetId() == SfxHintId::BasicDataWanted )
        {
            OUString aProcName = "Property Get "
                               + pProcProperty->GetName();

            SbxVariable* pMethVar = Find( aProcName, SbxClassType::Method );
            if( pMethVar )
            {
                SbxValues aVals;
                aVals.eType = SbxVARIANT;

                SbxArray* pArg = pVar->GetParameters();
                sal_uInt32 nVarParCount = (pArg != nullptr) ? pArg->Count32() : 0;
                if( nVarParCount > 1 )
                {
                    auto xMethParameters = tools::make_ref<SbxArray>();
                    xMethParameters->Put32( pMethVar, 0 );    // Method as parameter 0
                    for( sal_uInt32 i = 1 ; i < nVarParCount ; ++i )
                    {
                        SbxVariable* pPar = pArg->Get32( i );
                        xMethParameters->Put32( pPar, i );
                    }

                    pMethVar->SetParameters( xMethParameters.get() );
                    pMethVar->Get( aVals );
                    pMethVar->SetParameters( nullptr );
                }
                else
                {
                    pMethVar->Get( aVals );
                }

                pVar->Put( aVals );
            }
        }
        else if( pHint->GetId() == SfxHintId::BasicDataChanged )
        {
            SbxVariable* pMethVar = nullptr;

            bool bSet = pProcProperty->isSet();
            if( bSet )
            {
                pProcProperty->setSet( false );

                OUString aProcName = "Property Set "
                                   + pProcProperty->GetName();
                pMethVar = Find( aProcName, SbxClassType::Method );
            }
            if( !pMethVar ) // Let
            {
                OUString aProcName = "Property Let "
                                   + pProcProperty->GetName();
                pMethVar = Find( aProcName, SbxClassType::Method );
            }

            if( pMethVar )
            {
                // Setup parameters
                SbxArrayRef xArray = new SbxArray;
                xArray->Put32( pMethVar, 0 ); // Method as parameter 0
                xArray->Put32( pVar, 1 );
                pMethVar->SetParameters( xArray.get() );

                SbxValues aVals;
                pMethVar->Get( aVals );
                pMethVar->SetParameters( nullptr );
            }
        }
    }
    if( pProp )
    {
        if( pProp->GetModule() != this )
            SetError( ERRCODE_BASIC_BAD_ACTION );
    }
    else if( pMeth )
    {
        if( pHint->GetId() == SfxHintId::BasicDataWanted )
        {
            if( pMeth->bInvalid && !Compile() )
            {
                // auto compile has not worked!
                StarBASIC::Error( ERRCODE_BASIC_BAD_PROP_VALUE );
            }
            else
            {
                // Call of a subprogram
                SbModule* pOld = GetSbData()->pMod;
                GetSbData()->pMod = this;
                Run( static_cast<SbMethod*>(pVar) );
                GetSbData()->pMod = pOld;
            }
        }
    }
    else
    {
        // #i92642: Special handling for name property to avoid
        // side effects when using name as variable implicitly
        bool bForwardToSbxObject = true;

        const SfxHintId nId = pHint->GetId();
        if( (nId == SfxHintId::BasicDataWanted || nId == SfxHintId::BasicDataChanged) &&
            pVar->GetName().equalsIgnoreAsciiCase( "name" ) )
        {
                bForwardToSbxObject = false;
        }
        if( bForwardToSbxObject )
        {
            SbxObject::Notify( rBC, rHint );
        }
    }
}

// The setting of the source makes the image invalid
// and scans the method definitions newly in

void SbModule::SetSource32( const OUString& r )
{
    // Default basic mode to library container mode, but... allow Option VBASupport 0/1 override
    SetVBACompat( getDefaultVBAMode( static_cast< StarBASIC*>( GetParent() ) ) );
    aOUSource = r;
    StartDefinitions();
    SbiTokenizer aTok( r );
    aTok.SetCompatible( IsVBACompat() );

    while( !aTok.IsEof() )
    {
        SbiToken eEndTok = NIL;

        // Searching for SUB or FUNCTION
        SbiToken eLastTok = NIL;
        while( !aTok.IsEof() )
        {
            // #32385: not by declare
            SbiToken eCurTok = aTok.Next();
            if( eLastTok != DECLARE )
            {
                if( eCurTok == SUB )
                {
                    eEndTok = ENDSUB; break;
                }
                if( eCurTok == FUNCTION )
                {
                    eEndTok = ENDFUNC; break;
                }
                if( eCurTok == PROPERTY )
                {
                    eEndTok = ENDPROPERTY; break;
                }
                if( eCurTok == OPTION )
                {
                    eCurTok = aTok.Next();
                    if( eCurTok == COMPATIBLE )
                    {
                        aTok.SetCompatible( true );
                    }
                    else if ( ( eCurTok == VBASUPPORT ) && ( aTok.Next() == NUMBER ) )
                    {
                        bool bIsVBA = ( aTok.GetDbl()== 1 );
                        SetVBACompat( bIsVBA );
                        aTok.SetCompatible( bIsVBA );
                    }
                }
            }
            eLastTok = eCurTok;
        }
        // Definition of the method
        SbMethod* pMeth = nullptr;
        if( eEndTok != NIL )
        {
            sal_uInt16 nLine1 = aTok.GetLine();
            if( aTok.Next() == SYMBOL )
            {
                OUString aName_( aTok.GetSym() );
                SbxDataType t = aTok.GetType();
                if( t == SbxVARIANT && eEndTok == ENDSUB )
                {
                    t = SbxVOID;
                }
                pMeth = GetMethod( aName_, t );
                pMeth->nLine1 = pMeth->nLine2 = nLine1;
                // The method is for a start VALID
                pMeth->bInvalid = false;
            }
            else
            {
                eEndTok = NIL;
            }
        }
        // Skip up to END SUB/END FUNCTION
        if( eEndTok != NIL )
        {
            while( !aTok.IsEof() )
            {
                if( aTok.Next() == eEndTok )
                {
                    pMeth->nLine2 = aTok.GetLine();
                    break;
                }
            }
            if( aTok.IsEof() )
            {
                pMeth->nLine2 = aTok.GetLine();
            }
        }
    }
    EndDefinitions( true );
}

// Broadcast of a hint to all Basics

static void SendHint_( SbxObject* pObj, SfxHintId nId, SbMethod* p )
{
    // Self a BASIC?
    if( dynamic_cast<const StarBASIC *>(pObj) != nullptr && pObj->IsBroadcaster() )
        pObj->GetBroadcaster().Broadcast( SbxHint( nId, p ) );
    // Then ask for the subobjects
    SbxArray* pObjs = pObj->GetObjects();
    for( sal_uInt32 i = 0; i < pObjs->Count32(); i++ )
    {
        SbxVariable* pVar = pObjs->Get32( i );
        if( dynamic_cast<const SbxObject *>(pVar) != nullptr )
            SendHint_( dynamic_cast<SbxObject*>( pVar), nId, p  );
    }
}

static void SendHint( SbxObject* pObj, SfxHintId nId, SbMethod* p )
{
    while( pObj->GetParent() )
        pObj = pObj->GetParent();
    SendHint_( pObj, nId, p );
}

// #57841 Clear Uno-Objects, which were helt in RTL functions,
// at the end of the program, so that nothing were helt.
static void ClearUnoObjectsInRTL_Impl_Rek( StarBASIC* pBasic )
{
    // delete the return value of CreateUnoService
    SbxVariable* pVar = pBasic->GetRtl()->Find( "CreateUnoService", SbxClassType::Method );
    if( pVar )
    {
        pVar->SbxValue::Clear();
    }
    // delete the return value of CreateUnoDialog
    pVar = pBasic->GetRtl()->Find( "CreateUnoDialog", SbxClassType::Method );
    if( pVar )
    {
        pVar->SbxValue::Clear();
    }
    // delete the return value of CDec
    pVar = pBasic->GetRtl()->Find( "CDec", SbxClassType::Method );
    if( pVar )
    {
        pVar->SbxValue::Clear();
    }
    // delete return value of CreateObject
    pVar = pBasic->GetRtl()->Find( "CreateObject", SbxClassType::Method );
    if( pVar )
    {
        pVar->SbxValue::Clear();
    }
    // Go over all Sub-Basics
    SbxArray* pObjs = pBasic->GetObjects();
    sal_uInt32 nCount = pObjs->Count32();
    for( sal_uInt32 i = 0 ; i < nCount ; i++ )
    {
        SbxVariable* pObjVar = pObjs->Get32( i );
        StarBASIC* pSubBasic = dynamic_cast<StarBASIC*>( pObjVar  );
        if( pSubBasic )
        {
            ClearUnoObjectsInRTL_Impl_Rek( pSubBasic );
        }
    }
}

static void ClearUnoObjectsInRTL_Impl( StarBASIC* pBasic )
{
    // #67781 Delete return values of the Uno-methods
    clearUnoMethods();

    ClearUnoObjectsInRTL_Impl_Rek( pBasic );

    // Search for the topmost Basic
    SbxObject* p = pBasic;
    while( p->GetParent() )
        p = p->GetParent();
    if( static_cast<StarBASIC*>(p) != pBasic )
        ClearUnoObjectsInRTL_Impl_Rek( static_cast<StarBASIC*>(p) );
}


void SbModule::SetVBACompat( bool bCompat )
{
    if( mbVBACompat == bCompat )
        return;

    mbVBACompat = bCompat;
    // initialize VBA document API
    if( mbVBACompat ) try
    {
        StarBASIC* pBasic = static_cast< StarBASIC* >( GetParent() );
        uno::Reference< lang::XMultiServiceFactory > xFactory( getDocumentModel( pBasic ), uno::UNO_QUERY_THROW );
        xFactory->createInstance( "ooo.vba.VBAGlobals" );
    }
    catch( Exception& )
    {
    }
}

namespace
{
    class RunInitGuard
    {
    protected:
        std::unique_ptr<SbiRuntime> m_xRt;
        SbiGlobals* m_pSbData;
        SbModule* m_pOldMod;
    public:
        RunInitGuard(SbModule* pModule, SbMethod* pMethod, sal_uInt32 nArg, SbiGlobals* pSbData)
            : m_xRt(new SbiRuntime(pModule, pMethod, nArg))
            , m_pSbData(pSbData)
            , m_pOldMod(pSbData->pMod)
        {
            m_xRt->pNext = pSbData->pInst->pRun;
            m_pSbData->pMod = pModule;
            m_pSbData->pInst->pRun = m_xRt.get();
        }
        void run()
        {
            while (m_xRt->Step()) {}
        }
        virtual ~RunInitGuard()
        {
            m_pSbData->pInst->pRun = m_xRt->pNext;
            m_pSbData->pMod = m_pOldMod;
            m_xRt.reset();
        }
    };

    class RunGuard : public RunInitGuard
    {
    private:
        bool m_bDelInst;
    public:
        RunGuard(SbModule* pModule, SbMethod* pMethod, sal_uInt32 nArg, SbiGlobals* pSbData, bool bDelInst)
            : RunInitGuard(pModule, pMethod, nArg, pSbData)
            , m_bDelInst(bDelInst)
        {
            if (m_xRt->pNext)
                m_xRt->pNext->block();
        }
        virtual ~RunGuard() override
        {
            if (m_xRt->pNext)
                m_xRt->pNext->unblock();

            // #63710 It can happen by an another thread handling at events,
            // that the show call returns to a dialog (by closing the
            // dialog per UI), before a by an event triggered further call returned,
            // which stands in Basic more top in the stack and that had been run on
            // a  Basic-Breakpoint. Then would the instance below destroyed. And if the Basic,
            // that stand still in the call, further runs, there is a GPF.
            // Thus here had to be wait until the other call comes back.
            if (m_bDelInst)
            {
                // Compare here with 1 instead of 0, because before nCallLvl--
                while (m_pSbData->pInst->nCallLvl != 1)
                    Application::Yield();
            }

            m_pSbData->pInst->nCallLvl--;          // Call-Level down again

            // Exist an higher-ranking runtime instance?
            // Then take over BasicDebugFlags::Break, if set
            SbiRuntime* pRtNext = m_xRt->pNext;
            if (pRtNext && (m_xRt->GetDebugFlags() & BasicDebugFlags::Break))
                pRtNext->SetDebugFlags(BasicDebugFlags::Break);
        }
    };
}

// Run a Basic-subprogram
void SbModule::Run( SbMethod* pMeth )
{
    SAL_INFO("basic","About to run " << pMeth->GetName() << ", vba compatmode is " << mbVBACompat );

    static sal_uInt16 nMaxCallLevel = 0;

    SbiGlobals* pSbData = GetSbData();

    bool bDelInst = pSbData->pInst == nullptr;
    bool bQuit = false;
    StarBASICRef xBasic;
    uno::Reference< frame::XModel > xModel;
    uno::Reference< script::vba::XVBACompatibility > xVBACompat;
    if( bDelInst )
    {
        // #32779: Hold Basic during the execution
        xBasic = static_cast<StarBASIC*>( GetParent() );

        pSbData->pInst = new SbiInstance( static_cast<StarBASIC*>(GetParent()) );

        /*  If a VBA script in a document is started, get the VBA compatibility
            interface from the document Basic library container, and notify all
            VBA script listeners about the started script. */
        if( mbVBACompat )
        {
            StarBASIC* pBasic = static_cast< StarBASIC* >( GetParent() );
            if( pBasic && pBasic->IsDocBasic() ) try
            {
                xModel.set( getDocumentModel( pBasic ), uno::UNO_SET_THROW );
                xVBACompat.set( getVBACompatibility( xModel ), uno::UNO_SET_THROW );
                xVBACompat->broadcastVBAScriptEvent( script::vba::VBAScriptEventId::SCRIPT_STARTED, GetName() );
            }
            catch(const uno::Exception& )
            {
            }
        }

        // Launcher problem
        // i80726 The Find below will generate an error in Testtool so we reset it unless there was one before already
        bool bWasError = SbxBase::GetError() != ERRCODE_NONE;
        SbxVariable* pMSOMacroRuntimeLibVar = Find( "Launcher", SbxClassType::Object );
        if ( !bWasError && (SbxBase::GetError() == ERRCODE_BASIC_PROC_UNDEFINED) )
            SbxBase::ResetError();
        if( pMSOMacroRuntimeLibVar )
        {
            StarBASIC* pMSOMacroRuntimeLib = dynamic_cast<StarBASIC*>( pMSOMacroRuntimeLibVar );
            if( pMSOMacroRuntimeLib )
            {
                SbxFlagBits nGblFlag = pMSOMacroRuntimeLib->GetFlags() & SbxFlagBits::GlobalSearch;
                pMSOMacroRuntimeLib->ResetFlag( SbxFlagBits::GlobalSearch );
                SbxVariable* pAppSymbol = pMSOMacroRuntimeLib->Find( "Application", SbxClassType::Method );
                pMSOMacroRuntimeLib->SetFlag( nGblFlag );
                if( pAppSymbol )
                {
                    pMSOMacroRuntimeLib->SetFlag( SbxFlagBits::ExtSearch );      // Could have been disabled before
                    pSbData->pMSOMacroRuntimLib = pMSOMacroRuntimeLib;
                }
            }
        }

        if( nMaxCallLevel == 0 )
        {
#ifdef UNX
          struct rlimit rl;
          getrlimit ( RLIMIT_STACK, &rl );
#endif
#if defined LINUX
          // Empiric value, 900 = needed bytes/Basic call level
          // for Linux including 10% safety margin
          nMaxCallLevel = rl.rlim_cur / 900;
#elif defined __sun
          // Empiric value, 1650 = needed bytes/Basic call level
          // for Solaris including 10% safety margin
          nMaxCallLevel = rl.rlim_cur / 1650;
#elif defined _WIN32
          nMaxCallLevel = 5800;
#else
          nMaxCallLevel = MAXRECURSION;
#endif
        }
    }

    // Recursion to deep?
    if( ++pSbData->pInst->nCallLvl <= nMaxCallLevel )
    {
        // Define a globale variable in all Mods
        GlobalRunInit( /* bBasicStart = */ bDelInst );

        // Appeared a compiler error? Then we don't launch
        if( !pSbData->bGlobalInitErr )
        {
            if( bDelInst )
            {
                SendHint( GetParent(), SfxHintId::BasicStart, pMeth );

                // 1996-10-16: #31460 New concept for StepInto/Over/Out
                // For an explanation see runtime.cxx at SbiInstance::CalcBreakCallLevel()
                // Identify the BreakCallLevel
                pSbData->pInst->CalcBreakCallLevel( pMeth->GetDebugFlags() );
            }

            auto xRuntimeGuard(std::make_unique<RunGuard>(this, pMeth, pMeth->nStart, pSbData, bDelInst));

            if ( mbVBACompat )
            {
                pSbData->pInst->EnableCompatibility( true );
            }

            xRuntimeGuard->run();

            xRuntimeGuard.reset();

            if( bDelInst )
            {
                // #57841 Clear Uno-Objects, which were helt in RTL functions,
                // at the end of the program, so that nothing were helt.
                ClearUnoObjectsInRTL_Impl( xBasic.get() );

                clearNativeObjectWrapperVector();

                SAL_WARN_IF(pSbData->pInst->nCallLvl != 0,"basic","BASIC-Call-Level > 0");
                delete pSbData->pInst;
                pSbData->pInst = nullptr;
                bDelInst = false;

                // #i30690
                SolarMutexGuard aSolarGuard;
                SendHint( GetParent(), SfxHintId::BasicStop, pMeth );

                GlobalRunDeInit();

                if( xVBACompat.is() )
                {
                    // notify all VBA script listeners about the stopped script
                    try
                    {
                        xVBACompat->broadcastVBAScriptEvent( script::vba::VBAScriptEventId::SCRIPT_STOPPED, GetName() );
                    }
                    catch(const uno::Exception& )
                    {
                    }
                    // VBA always ensures screenupdating is enabled after completing
                    ::basic::vba::lockControllersOfAllDocuments( xModel, false );
                    ::basic::vba::enableContainerWindowsOfAllDocuments( xModel, true );
                }
            }
        }
        else
            pSbData->pInst->nCallLvl--;           // Call-Level down again
    }
    else
    {
        pSbData->pInst->nCallLvl--;          // Call-Level down again
        StarBASIC::FatalError( ERRCODE_BASIC_STACK_OVERFLOW );
    }

    StarBASIC* pBasic = dynamic_cast<StarBASIC*>( GetParent() );
    if( bDelInst )
    {
       // #57841 Clear Uno-Objects, which were helt in RTL functions,
       // the end of the program, so that nothing were helt.
        ClearUnoObjectsInRTL_Impl( xBasic.get() );

        delete pSbData->pInst;
        pSbData->pInst = nullptr;
    }
    if ( pBasic && pBasic->IsDocBasic() && pBasic->IsQuitApplication() && !pSbData->pInst )
            bQuit = true;
    if ( bQuit )
    {
        Application::PostUserEvent( LINK( &AsyncQuitHandler::instance(), AsyncQuitHandler, OnAsyncQuit ) );
    }
}

// Execute of the init method of a module after the loading
// or the compilation
void SbModule::RunInit()
{
    if( !(pImage
     && !pImage->bInit
     && pImage->IsFlag( SbiImageFlags::INITCODE )) )
        return;

    SbiGlobals* pSbData = GetSbData();

    // Set flag, so that RunInit get active (Testtool)
    pSbData->bRunInit = true;

    // The init code starts always here
    auto xRuntimeGuard(std::make_unique<RunInitGuard>(this, nullptr, 0, pSbData));
    xRuntimeGuard->run();
    xRuntimeGuard.reset();

    pImage->bInit = true;
    pImage->bFirstInit = false;

    // RunInit is not active anymore
    pSbData->bRunInit = false;
}

// Delete with private/dim declared variables

void SbModule::AddVarName( const OUString& aName )
{
    // see if the name is added already
    for ( const auto& rModuleVariableName: mModuleVariableNames )
    {
        if ( aName == rModuleVariableName )<--- Consider using std::any_of algorithm instead of a raw loop.
            return;
    }
    mModuleVariableNames.push_back( aName );
}

void SbModule::RemoveVars()
{
    for ( const auto& rModuleVariableName: mModuleVariableNames )
    {
    // We don't want a Find being called in a derived class ( e.g.
    // SbUserform because it could trigger say an initialise event
    // which would cause basic to be re-run in the middle of the init ( and remember RemoveVars is called from compile and we don't want code to run as part of the compile )
    SbxVariableRef p = SbModule::Find( rModuleVariableName, SbxClassType::Property );
    if( p.is() )
        Remove( p.get() );
    }
}

void SbModule::ClearPrivateVars()
{
    for( sal_uInt32 i = 0 ; i < pProps->Count32() ; i++ )
    {
        SbProperty* p = dynamic_cast<SbProperty*>( pProps->Get32( i )  );
        if( p )
        {
            // Delete not the arrays, only their content
            if( p->GetType() & SbxARRAY )
            {
                SbxArray* pArray = dynamic_cast<SbxArray*>( p->GetObject() );
                if( pArray )
                {
                    for( sal_uInt32 j = 0 ; j < pArray->Count32() ; j++ )
                    {
                        SbxVariable* pj = pArray->Get32( j );
                        pj->SbxValue::Clear();
                    }
                }
            }
            else
            {
                p->SbxValue::Clear();
            }
        }
    }
}

void SbModule::implClearIfVarDependsOnDeletedBasic( SbxVariable* pVar, StarBASIC* pDeletedBasic )
{
    if( pVar->SbxValue::GetType() != SbxOBJECT || dynamic_cast<const SbProcedureProperty*>( pVar) != nullptr )
        return;

    SbxObject* pObj = dynamic_cast<SbxObject*>( pVar->GetObject() );
    if( pObj == nullptr )
        return;

    SbxObject* p = pObj;

    SbModule* pMod = dynamic_cast<SbModule*>( p  );
    if( pMod != nullptr )
        pMod->ClearVarsDependingOnDeletedBasic( pDeletedBasic );

    while( (p = p->GetParent()) != nullptr )
    {
        StarBASIC* pBasic = dynamic_cast<StarBASIC*>( p  );
        if( pBasic != nullptr && pBasic == pDeletedBasic )
        {
            pVar->SbxValue::Clear();
            break;
        }
    }
}

void SbModule::ClearVarsDependingOnDeletedBasic( StarBASIC* pDeletedBasic )
{
    for( sal_uInt32 i = 0 ; i < pProps->Count32() ; i++ )
    {
        SbProperty* p = dynamic_cast<SbProperty*>( pProps->Get32( i )  );
        if( p )
        {
            if( p->GetType() & SbxARRAY )
            {
                SbxArray* pArray = dynamic_cast<SbxArray*>( p->GetObject() );
                if( pArray )
                {
                    for( sal_uInt32 j = 0 ; j < pArray->Count32() ; j++ )
                    {
                        SbxVariable* pVar = pArray->Get32( j );
                        implClearIfVarDependsOnDeletedBasic( pVar, pDeletedBasic );
                    }
                }
            }
            else
            {
                implClearIfVarDependsOnDeletedBasic( p, pDeletedBasic );
            }
        }
    }
}

void StarBASIC::ClearAllModuleVars()
{
    // Initialise the own module
    for (const auto& rModule: pModules)
    {
        // Initialise only, if the startcode was already executed
        if( rModule->pImage && rModule->pImage->bInit && !rModule->isProxyModule() && dynamic_cast<const SbObjModule*>( rModule.get()) == nullptr )
            rModule->ClearPrivateVars();
    }

}

// Execution of the init-code of all module
void SbModule::GlobalRunInit( bool bBasicStart )
{
    // If no Basic-Start, only initialise, if the module is not initialised
    if( !bBasicStart )
        if( !(pImage && !pImage->bInit) )
            return;

    // Initialise GlobalInitErr-Flag for Compiler-Error
    // With the help of this flags could be located in SbModule::Run() after the call of
    // GlobalRunInit, if at the initialising of the module
    // an error occurred. Then it will not be launched.
    GetSbData()->bGlobalInitErr = false;

    // Parent of the module is a Basic
    StarBASIC *pBasic = dynamic_cast<StarBASIC*>( GetParent() );
    if( !pBasic )
        return;

    pBasic->InitAllModules();

    SbxObject* pParent_ = pBasic->GetParent();
    if( !pParent_ )
        return;

    StarBASIC * pParentBasic = dynamic_cast<StarBASIC*>( pParent_ );
    if( !pParentBasic )
        return;

    pParentBasic->InitAllModules( pBasic );

    // #109018 Parent can also have a parent (library in doc)
    SbxObject* pParentParent = pParentBasic->GetParent();
    if( pParentParent )
    {
        StarBASIC * pParentParentBasic = dynamic_cast<StarBASIC*>( pParentParent );
        if( pParentParentBasic )
            pParentParentBasic->InitAllModules( pParentBasic );
    }
}

void SbModule::GlobalRunDeInit()
{
    StarBASIC *pBasic = dynamic_cast<StarBASIC*>( GetParent() );
    if( pBasic )
    {
        pBasic->DeInitAllModules();

        SbxObject* pParent_ = pBasic->GetParent();
        if( pParent_ )
            pBasic = dynamic_cast<StarBASIC*>( pParent_ );
        if( pBasic )
            pBasic->DeInitAllModules();
    }
}

// Search for the next STMNT-Command in the code. This was used from the STMNT-
// Opcode to set the endcolumn.

const sal_uInt8* SbModule::FindNextStmnt( const sal_uInt8* p, sal_uInt16& nLine, sal_uInt16& nCol ) const
{
    return FindNextStmnt( p, nLine, nCol, false );
}

const sal_uInt8* SbModule::FindNextStmnt( const sal_uInt8* p, sal_uInt16& nLine, sal_uInt16& nCol,
    bool bFollowJumps, const SbiImage* pImg ) const
{
    sal_uInt32 nPC = static_cast<sal_uInt32>( p - reinterpret_cast<const sal_uInt8*>(pImage->GetCode()) );
    while( nPC < pImage->GetCodeSize() )
    {
        SbiOpcode eOp = static_cast<SbiOpcode>( *p++ );
        nPC++;
        if( bFollowJumps && eOp == SbiOpcode::JUMP_ && pImg )
        {
            SAL_WARN_IF( !pImg, "basic", "FindNextStmnt: pImg==NULL with FollowJumps option" );
            sal_uInt32 nOp1 = *p++; nOp1 |= *p++ << 8;
            nOp1 |= *p++ << 16; nOp1 |= *p++ << 24;
            p = reinterpret_cast<const sal_uInt8*>(pImg->GetCode()) + nOp1;
        }
        else if( eOp >= SbiOpcode::SbOP1_START && eOp <= SbiOpcode::SbOP1_END )
        {
            p += 4;
            nPC += 4;
        }
        else if( eOp == SbiOpcode::STMNT_ )
        {
            sal_uInt32 nl, nc;
            nl = *p++; nl |= *p++ << 8;
            nl |= *p++ << 16 ; nl |= *p++ << 24;
            nc = *p++; nc |= *p++ << 8;
            nc |= *p++ << 16 ; nc |= *p++ << 24;
            nLine = static_cast<sal_uInt16>(nl); nCol = static_cast<sal_uInt16>(nc);
            return p;
        }
        else if( eOp >= SbiOpcode::SbOP2_START && eOp <= SbiOpcode::SbOP2_END )
        {
            p += 8;
            nPC += 8;
        }
        else if( eOp < SbiOpcode::SbOP0_START || eOp > SbiOpcode::SbOP0_END )
        {
            StarBASIC::FatalError( ERRCODE_BASIC_INTERNAL_ERROR );
            break;
        }
    }
    return nullptr;
}

// Test, if a line contains STMNT-Opcodes

bool SbModule::IsBreakable( sal_uInt16 nLine ) const
{
    if( !pImage )
        return false;
    const sal_uInt8* p = reinterpret_cast<const sal_uInt8*>(pImage->GetCode());
    sal_uInt16 nl, nc;
    while( ( p = FindNextStmnt( p, nl, nc ) ) != nullptr )
        if( nl == nLine )
            return true;
    return false;
}

bool SbModule::IsBP( sal_uInt16 nLine ) const
{
    if( pBreaks )
    {
        for( size_t i = 0; i < pBreaks->size(); i++ )
        {
            sal_uInt16 b = pBreaks->operator[]( i );
            if( b == nLine )
                return true;
            if( b < nLine )
                break;
        }
    }
    return false;
}

bool SbModule::SetBP( sal_uInt16 nLine )
{
    if( !IsBreakable( nLine ) )
        return false;
    if( !pBreaks )
        pBreaks = new SbiBreakpoints;
    auto it = std::find_if(pBreaks->begin(), pBreaks->end(),
        [&nLine](const sal_uInt16 b) { return b <= nLine; });
    if (it != pBreaks->end() && *it == nLine)
        return true;
    pBreaks->insert( it, nLine );

    // #38568: Set during runtime as well here BasicDebugFlags::Break
    if( GetSbData()->pInst && GetSbData()->pInst->pRun )
        GetSbData()->pInst->pRun->SetDebugFlags( BasicDebugFlags::Break );

    return IsBreakable( nLine );
}

bool SbModule::ClearBP( sal_uInt16 nLine )
{
    bool bRes = false;
    if( pBreaks )
    {
        auto it = std::find_if(pBreaks->begin(), pBreaks->end(),
            [&nLine](const sal_uInt16 b) { return b <= nLine; });
        bRes = (it != pBreaks->end()) && (*it == nLine);
        if (bRes)
        {
            pBreaks->erase(it);
        }
        if( pBreaks->empty() )
        {
            delete pBreaks;
            pBreaks = nullptr;
        }
    }
    return bRes;
}

void SbModule::ClearAllBP()
{
    delete pBreaks;
    pBreaks = nullptr;
}

void
SbModule::fixUpMethodStart( bool bCvtToLegacy, SbiImage* pImg ) const
{
        if ( !pImg )
            pImg = pImage;
        for( sal_uInt32 i = 0; i < pMethods->Count32(); i++ )
        {
            SbMethod* pMeth = dynamic_cast<SbMethod*>( pMethods->Get32(i)  );
            if( pMeth )
            {
                //fixup method start positions
                if ( bCvtToLegacy )
                    pMeth->nStart = pImg->CalcLegacyOffset( pMeth->nStart );
                else
                    pMeth->nStart = pImg->CalcNewOffset( static_cast<sal_uInt16>(pMeth->nStart) );
            }
        }

}

bool SbModule::LoadData( SvStream& rStrm, sal_uInt16 nVer )
{
    Clear();
    if( !SbxObject::LoadData( rStrm, 1 ) )
        return false;
    // As a precaution...
    SetFlag( SbxFlagBits::ExtSearch | SbxFlagBits::GlobalSearch );
    sal_uInt8 bImage;
    rStrm.ReadUChar( bImage );
    if( bImage )
    {
        SbiImage* p = new SbiImage;
        sal_uInt32 nImgVer = 0;

        if( !p->Load( rStrm, nImgVer ) )
        {
            delete p;
            return false;
        }
        // If the image is in old format, we fix up the method start offsets
        if ( nImgVer < B_EXT_IMG_VERSION )
        {
            fixUpMethodStart( false, p );
            p->ReleaseLegacyBuffer();
        }
        aComment = p->aComment;
        SetName( p->aName );
        if( p->GetCodeSize() )
        {
            aOUSource = p->aOUSource;
            // Old version: image away
            if( nVer == 1 )
            {
                SetSource32( p->aOUSource );
                delete p;
            }
            else
                pImage = p;
        }
        else
        {
            SetSource32( p->aOUSource );
            delete p;
        }
    }
    return true;
}

bool SbModule::StoreData( SvStream& rStrm ) const
{
    bool bFixup = ( pImage && !pImage->ExceedsLegacyLimits() );
    if ( bFixup )
        fixUpMethodStart( true );
    bool bRet = SbxObject::StoreData( rStrm );
    if ( !bRet )
        return false;

    if( pImage )
    {
        pImage->aOUSource = aOUSource;
        pImage->aComment = aComment;
        pImage->aName = GetName();
        rStrm.WriteUChar( 1 );
        // # PCode is saved only for legacy formats only
        // It should be noted that it probably isn't necessary
        // It would be better not to store the image ( more flexible with
        // formats )
        bool bRes = pImage->Save( rStrm, B_LEGACYVERSION );
        if ( bFixup )
            fixUpMethodStart( false ); // restore method starts
        return bRes;

    }
    else
    {
        SbiImage aImg;
        aImg.aOUSource = aOUSource;
        aImg.aComment = aComment;
        aImg.aName = GetName();
        rStrm.WriteUChar( 1 );
        return aImg.Save( rStrm );
    }
}

bool SbModule::ExceedsLegacyModuleSize()
{
    if ( !IsCompiled() )
        Compile();
    return pImage && pImage->ExceedsLegacyLimits();
}

namespace {

class ErrorHdlResetter
{
    Link<StarBASIC*,bool> mErrHandler;
    bool    mbError;
public:
    ErrorHdlResetter()
        : mErrHandler(StarBASIC::GetGlobalErrorHdl()) // save error handler
        , mbError( false )
    {
        // set new error handler
        StarBASIC::SetGlobalErrorHdl( LINK( this, ErrorHdlResetter, BasicErrorHdl ) );
    }
    ~ErrorHdlResetter()
    {
        // restore error handler
        StarBASIC::SetGlobalErrorHdl(mErrHandler);
    }
    DECL_LINK( BasicErrorHdl, StarBASIC *, bool );
    bool HasError() const { return mbError; }
};

}

IMPL_LINK( ErrorHdlResetter, BasicErrorHdl, StarBASIC *, /*pBasic*/, bool)
{
    mbError = true;
    return false;
}

void SbModule::GetCodeCompleteDataFromParse(CodeCompleteDataCache& aCache)
{
    ErrorHdlResetter aErrHdl;
    SbxBase::ResetError();

    std::unique_ptr<SbiParser> pParser(new SbiParser( static_cast<StarBASIC*>(GetParent()), this ));
    pParser->SetCodeCompleting(true);

    while( pParser->Parse() ) {}
    SbiSymPool* pPool = pParser->pPool;
    aCache.Clear();
    for( sal_uInt16 i = 0; i < pPool->GetSize(); ++i )
    {
        SbiSymDef* pSymDef = pPool->Get(i);
        //std::cerr << "i: " << i << ", type: " << pSymDef->GetType() << "; name:" << pSymDef->GetName() << std::endl;
        if( (pSymDef->GetType() != SbxEMPTY) && (pSymDef->GetType() != SbxNULL) )
            aCache.InsertGlobalVar( pSymDef->GetName(), pParser->aGblStrings.Find(pSymDef->GetTypeId()) );

        SbiSymPool& rChildPool = pSymDef->GetPool();
        for(sal_uInt16 j = 0; j < rChildPool.GetSize(); ++j )
        {
            SbiSymDef* pChildSymDef = rChildPool.Get(j);
            //std::cerr << "j: " << j << ", type: " << pChildSymDef->GetType() << "; name:" << pChildSymDef->GetName() << std::endl;
            if( (pChildSymDef->GetType() != SbxEMPTY) && (pChildSymDef->GetType() != SbxNULL) )
                aCache.InsertLocalVar( pSymDef->GetName(), pChildSymDef->GetName(), pParser->aGblStrings.Find(pChildSymDef->GetTypeId()) );
        }
    }
}


OUString SbModule::GetKeywordCase( const OUString& sKeyword )
{
    return SbiParser::GetKeywordCase( sKeyword );
}

bool SbModule::HasExeCode()
{
    // And empty Image always has the Global Chain set up
    static const unsigned char pEmptyImage[] = { 0x45, 0x0 , 0x0, 0x0, 0x0 };
    // lets be stricter for the moment than VBA

    if (!IsCompiled())
    {
        ErrorHdlResetter aGblErrHdl;
        Compile();
        if (aGblErrHdl.HasError()) //assume unsafe on compile error
            return true;
    }

    bool bRes = false;
    if (pImage && (pImage->GetCodeSize() != 5 || (memcmp(pImage->GetCode(), pEmptyImage, pImage->GetCodeSize()) != 0 )))
        bRes = true;

    return bRes;
}

// Store only image, no source
void SbModule::StoreBinaryData( SvStream& rStrm )
{
    if (!Compile())
        return;

    if (!SbxObject::StoreData(rStrm))
        return;

    pImage->aOUSource.clear();
    pImage->aComment = aComment;
    pImage->aName = GetName();

    rStrm.WriteUChar(1);
    pImage->Save(rStrm);

    pImage->aOUSource = aOUSource;
}

// Called for >= OO 1.0 passwd protected libraries only

void SbModule::LoadBinaryData( SvStream& rStrm )
{
    OUString aKeepSource = aOUSource;
    LoadData( rStrm, 2 );
    LoadCompleted();
    aOUSource = aKeepSource;
}

bool SbModule::LoadCompleted()
{
    SbxArray* p = GetMethods().get();
    sal_uInt32 i;
    for( i = 0; i < p->Count32(); i++ )
    {
        SbMethod* q = dynamic_cast<SbMethod*>( p->Get32( i )  );
        if( q )
            q->pMod = this;
    }
    p = GetProperties();
    for( i = 0; i < p->Count32(); i++ )
    {
        SbProperty* q = dynamic_cast<SbProperty*>( p->Get32( i )  );
        if( q )
            q->pMod = this;
    }
    return true;
}

void SbModule::handleProcedureProperties( SfxBroadcaster& rBC, const SfxHint& rHint )
{
    bool bDone = false;

    const SbxHint* pHint = dynamic_cast<const SbxHint*>(&rHint);
    if( pHint )
    {
        SbxVariable* pVar = pHint->GetVar();
        SbProcedureProperty* pProcProperty = dynamic_cast<SbProcedureProperty*>( pVar  );
        if( pProcProperty )
        {
            bDone = true;

            if( pHint->GetId() == SfxHintId::BasicDataWanted )
            {
                OUString aProcName = "Property Get "
                                   + pProcProperty->GetName();

                SbxVariable* pMeth = Find( aProcName, SbxClassType::Method );
                if( pMeth )
                {
                    SbxValues aVals;
                    aVals.eType = SbxVARIANT;

                    SbxArray* pArg = pVar->GetParameters();
                    sal_uInt32 nVarParCount = (pArg != nullptr) ? pArg->Count32() : 0;
                    if( nVarParCount > 1 )
                    {
                        SbxArrayRef xMethParameters = new SbxArray;
                        xMethParameters->Put32( pMeth, 0 );   // Method as parameter 0
                        for( sal_uInt32 i = 1 ; i < nVarParCount ; ++i )
                        {
                            SbxVariable* pPar = pArg->Get32( i );
                            xMethParameters->Put32( pPar, i );
                        }

                        pMeth->SetParameters( xMethParameters.get() );
                        pMeth->Get( aVals );
                        pMeth->SetParameters( nullptr );
                    }
                    else
                    {
                        pMeth->Get( aVals );
                    }

                    pVar->Put( aVals );
                }
            }
            else if( pHint->GetId() == SfxHintId::BasicDataChanged )
            {
                SbxVariable* pMeth = nullptr;

                bool bSet = pProcProperty->isSet();
                if( bSet )
                {
                    pProcProperty->setSet( false );

                    OUString aProcName = "Property Set "
                                       + pProcProperty->GetName();
                    pMeth = Find( aProcName, SbxClassType::Method );
                }
                if( !pMeth )    // Let
                {
                    OUString aProcName = "Property Let "
                                       + pProcProperty->GetName();
                    pMeth = Find( aProcName, SbxClassType::Method );
                }

                if( pMeth )
                {
                    // Setup parameters
                    SbxArrayRef xArray = new SbxArray;
                    xArray->Put32( pMeth, 0 );    // Method as parameter 0
                    xArray->Put32( pVar, 1 );
                    pMeth->SetParameters( xArray.get() );

                    SbxValues aVals;
                    pMeth->Get( aVals );
                    pMeth->SetParameters( nullptr );
                }
            }
        }
    }

    if( !bDone )
        SbModule::Notify( rBC, rHint );
}


// Implementation SbJScriptModule (Basic module for JavaScript source code)
SbJScriptModule::SbJScriptModule()
    :SbModule( "" )
{
}

bool SbJScriptModule::LoadData( SvStream& rStrm, sal_uInt16 )
{
    Clear();
    if( !SbxObject::LoadData( rStrm, 1 ) )
        return false;

    // Get the source string
    aOUSource = rStrm.ReadUniOrByteString( osl_getThreadTextEncoding() );
    return true;
}

bool SbJScriptModule::StoreData( SvStream& rStrm ) const
{
    if( !SbxObject::StoreData( rStrm ) )
        return false;

    // Write the source string
    OUString aTmp = aOUSource;
    rStrm.WriteUniOrByteString( aTmp, osl_getThreadTextEncoding() );
    return true;
}


SbMethod::SbMethod( const OUString& r, SbxDataType t, SbModule* p )
        : SbxMethod( r, t ), pMod( p )
{
    bInvalid     = true;
    nStart       = 0;
    nDebugFlags  = BasicDebugFlags::NONE;
    nLine1       = 0;
    nLine2       = 0;
    refStatics   = new SbxArray;
    mCaller      = nullptr;
    // HACK due to 'Reference could not be saved'
    SetFlag( SbxFlagBits::NoModify );
}

SbMethod::SbMethod( const SbMethod& r )
    : SvRefBase( r ), SbxMethod( r )
{
    pMod         = r.pMod;
    bInvalid     = r.bInvalid;
    nStart       = r.nStart;
    nDebugFlags  = r.nDebugFlags;
    nLine1       = r.nLine1;
    nLine2       = r.nLine2;
    refStatics = r.refStatics;
    mCaller          = r.mCaller;
    SetFlag( SbxFlagBits::NoModify );
}

SbMethod::~SbMethod()
{
}

void SbMethod::ClearStatics()
{
    refStatics = new SbxArray;

}
SbxArray* SbMethod::GetStatics()
{
    return refStatics.get();
}

bool SbMethod::LoadData( SvStream& rStrm, sal_uInt16 nVer )
{
    if( !SbxMethod::LoadData( rStrm, 1 ) )
        return false;

    sal_uInt16 nFlag;
    rStrm.ReadUInt16( nFlag );

    sal_Int16 nTempStart = static_cast<sal_Int16>(nStart);

    if( nVer == 2 )
    {
        rStrm.ReadUInt16( nLine1 ).ReadUInt16( nLine2 ).ReadInt16( nTempStart ).ReadCharAsBool( bInvalid );
        //tdf#94617
        if (nFlag & 0x8000)
        {
            sal_uInt16 nMult = nFlag & 0x7FFF;
            sal_Int16 const nMax = std::numeric_limits<sal_Int16>::max();
            nStart = nMult * nMax + nTempStart;
        }
        else
        {
            nStart = nTempStart;
        }
    }
    else
    {
        nStart = nTempStart;
    }

    // HACK due to 'Reference could not be saved'
    SetFlag( SbxFlagBits::NoModify );

    return true;
}

bool SbMethod::StoreData( SvStream& rStrm ) const
{
    if( !SbxMethod::StoreData( rStrm ) )
        return false;

    //tdf#94617
    sal_Int16 nMax = std::numeric_limits<sal_Int16>::max();
    sal_Int16 nStartTemp = nStart % nMax;
    sal_uInt16 nDebugFlagsTemp = nStart / nMax;
    nDebugFlagsTemp |= 0x8000;

    rStrm.WriteUInt16( nDebugFlagsTemp )
         .WriteInt16( nLine1 )
         .WriteInt16( nLine2 )
         .WriteInt16( nStartTemp )
         .WriteBool( bInvalid );

    return true;
}

void SbMethod::GetLineRange( sal_uInt16& l1, sal_uInt16& l2 )
{
    l1 = nLine1; l2 = nLine2;
}

// Could later be deleted

SbxInfo* SbMethod::GetInfo()
{
    return pInfo.get();
}

// Interface to execute a method of the applications
// With special RefCounting, so that the Basic was not fired of by CloseDocument()
// The return value will be delivered as string.
ErrCode SbMethod::Call( SbxValue* pRet, SbxVariable* pCaller )
{
    if ( pCaller )
    {
        SAL_INFO("basic", "SbMethod::Call Have been passed a caller 0x" << pCaller );
        mCaller = pCaller;
    }
    // Increment the RefCount of the module
    tools::SvRef<SbModule> pMod_ = static_cast<SbModule*>(GetParent());

    tools::SvRef<StarBASIC> xHolder = static_cast<StarBASIC*>(pMod_->GetParent());<--- Variable 'xHolder' is assigned a value that is never used.

    // Establish the values to get the return value
    SbxValues aVals;
    aVals.eType = SbxVARIANT;

    // #104083: Compile BEFORE get
    if( bInvalid && !pMod_->Compile() )
        StarBASIC::Error( ERRCODE_BASIC_BAD_PROP_VALUE );

    Get( aVals );
    if ( pRet )
        pRet->Put( aVals );

    // Was there an error
    ErrCode nErr = SbxBase::GetError();
    SbxBase::ResetError();

    mCaller = nullptr;
    return nErr;
}


// #100883 Own Broadcast for SbMethod
void SbMethod::Broadcast( SfxHintId nHintId )
{
    if( !(mpBroadcaster && !IsSet( SbxFlagBits::NoBroadcast )) )
        return;

    // Because the method could be called from outside, test here once again
    // the authorisation
    if( nHintId == SfxHintId::BasicDataWanted )
        if( !CanRead() )
            return;
    if( nHintId == SfxHintId::BasicDataChanged )
        if( !CanWrite() )
            return;

    if( pMod && !pMod->IsCompiled() )
        pMod->Compile();

    // Block broadcasts while creating new method
    std::unique_ptr<SfxBroadcaster> pSaveBroadcaster = std::move(mpBroadcaster);
    SbMethod* pThisCopy = new SbMethod( *this );
    SbMethodRef xHolder = pThisCopy;<--- Variable 'xHolder' is assigned a value that is never used.
    if( mpPar.is() )
    {
        // Enregister this as element 0, but don't reset the parent!
        if( GetType() != SbxVOID ) {
            mpPar->PutDirect( pThisCopy, 0 );
        }
        SetParameters( nullptr );
    }

    mpBroadcaster = std::move(pSaveBroadcaster);
    mpBroadcaster->Broadcast( SbxHint( nHintId, pThisCopy ) );

    SbxFlagBits nSaveFlags = GetFlags();
    SetFlag( SbxFlagBits::ReadWrite );
    pSaveBroadcaster = std::move(mpBroadcaster);
    Put( pThisCopy->GetValues_Impl() );
    mpBroadcaster = std::move(pSaveBroadcaster);
    SetFlags( nSaveFlags );
}


// Implementation of SbJScriptMethod (method class as a wrapper for JavaScript-functions)

SbJScriptMethod::SbJScriptMethod( SbxDataType t )
        : SbMethod( "", t, nullptr )
{
}

SbJScriptMethod::~SbJScriptMethod()
{}


SbObjModule::SbObjModule( const OUString& rName, const css::script::ModuleInfo& mInfo, bool bIsVbaCompatible )
    : SbModule( rName, bIsVbaCompatible )
{
    SetModuleType( mInfo.ModuleType );
    if ( mInfo.ModuleType == script::ModuleType::FORM )
    {
        SetClassName( "Form" );
    }
    else if ( mInfo.ModuleObject.is() )
    {
        SetUnoObject( uno::Any( mInfo.ModuleObject ) );
    }
}

SbObjModule::~SbObjModule()
{
}

void
SbObjModule::SetUnoObject( const uno::Any& aObj )
{
    SbUnoObject* pUnoObj = dynamic_cast<SbUnoObject*>( pDocObject.get() );
    if ( pUnoObj && pUnoObj->getUnoAny() == aObj ) // object is equal, nothing to do
        return;
    pDocObject = new SbUnoObject( GetName(), aObj );

    css::uno::Reference< css::lang::XServiceInfo > xServiceInfo( aObj, css::uno::UNO_QUERY_THROW );
    if( xServiceInfo->supportsService( "ooo.vba.excel.Worksheet" ) )
    {
        SetClassName( "Worksheet" );
    }
    else if( xServiceInfo->supportsService( "ooo.vba.excel.Workbook" ) )
    {
        SetClassName( "Workbook" );
    }
}

SbxVariable*
SbObjModule::GetObject()
{
    return pDocObject.get();
}
SbxVariable*
SbObjModule::Find( const OUString& rName, SbxClassType t )
{
    SbxVariable* pVar = nullptr;
    if ( pDocObject )
        pVar = pDocObject->Find( rName, t );
    if ( !pVar )
        pVar = SbModule::Find( rName, t );
    return pVar;
}

void SbObjModule::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )
{
    SbModule::handleProcedureProperties( rBC, rHint );
}


typedef ::cppu::WeakImplHelper<
    awt::XTopWindowListener,
    awt::XWindowListener,
    document::XDocumentEventListener > FormObjEventListener_BASE;

class FormObjEventListenerImpl:
    public FormObjEventListener_BASE
{
    SbUserFormModule* mpUserForm;
    uno::Reference< lang::XComponent > mxComponent;
    uno::Reference< frame::XModel > mxModel;
    bool mbDisposed;
    bool mbOpened;
    bool mbActivated;
    bool mbShowing;

public:
    FormObjEventListenerImpl(const FormObjEventListenerImpl&) = delete;
    const FormObjEventListenerImpl& operator=(const FormObjEventListenerImpl&) = delete;
    FormObjEventListenerImpl( SbUserFormModule* pUserForm, const uno::Reference< lang::XComponent >& xComponent, const uno::Reference< frame::XModel >& xModel ) :
        mpUserForm( pUserForm ), mxComponent( xComponent), mxModel( xModel ),
        mbDisposed( false ), mbOpened( false ), mbActivated( false ), mbShowing( false )
    {
        if ( mxComponent.is() )
        {
            try
            {
                uno::Reference< awt::XTopWindow >( mxComponent, uno::UNO_QUERY_THROW )->addTopWindowListener( this );
            }
            catch(const uno::Exception& ) {}
            try
            {
                uno::Reference< awt::XWindow >( mxComponent, uno::UNO_QUERY_THROW )->addWindowListener( this );
            }
            catch(const uno::Exception& ) {}
        }

        if ( mxModel.is() )
        {
            try
            {
                uno::Reference< document::XDocumentEventBroadcaster >( mxModel, uno::UNO_QUERY_THROW )->addDocumentEventListener( this );
            }
            catch(const uno::Exception& ) {}
        }
    }

    virtual ~FormObjEventListenerImpl() override
    {
        removeListener();
    }

    bool isShowing() const { return mbShowing; }

    void removeListener()
    {
        if ( mxComponent.is() && !mbDisposed )
        {
            try
            {
                uno::Reference< awt::XTopWindow >( mxComponent, uno::UNO_QUERY_THROW )->removeTopWindowListener( this );
            }
            catch(const uno::Exception& ) {}
            try
            {
                uno::Reference< awt::XWindow >( mxComponent, uno::UNO_QUERY_THROW )->removeWindowListener( this );
            }
            catch(const uno::Exception& ) {}
        }
        mxComponent.clear();

        if ( mxModel.is() && !mbDisposed )
        {
            try
            {
                uno::Reference< document::XDocumentEventBroadcaster >( mxModel, uno::UNO_QUERY_THROW )->removeDocumentEventListener( this );
            }
            catch(const uno::Exception& ) {}
        }
        mxModel.clear();
    }

    virtual void SAL_CALL windowOpened( const lang::EventObject& /*e*/ ) override
    {
        if ( mpUserForm )
        {
            mbOpened = true;
            mbShowing = true;
            if ( mbActivated )
            {
                mbOpened = mbActivated = false;
                mpUserForm->triggerActivateEvent();
            }
        }
    }


    virtual void SAL_CALL windowClosing( const lang::EventObject& /*e*/ ) override
    {
#ifdef IN_THE_FUTURE
        uno::Reference< awt::XDialog > xDialog( e.Source, uno::UNO_QUERY );
        if ( xDialog.is() )
        {
            uno::Reference< awt::XControl > xControl( xDialog, uno::UNO_QUERY );
            if ( xControl->getPeer().is() )
            {
                uno::Reference< document::XVbaMethodParameter > xVbaMethodParameter( xControl->getPeer(), uno::UNO_QUERY );
                if ( xVbaMethodParameter.is() )
                {
                    sal_Int8 nCancel = 0;
                    sal_Int8 nCloseMode = ::ooo::vba::VbQueryClose::vbFormControlMenu;

                    Sequence< Any > aParams;
                    aParams.realloc(2);
                    aParams[0] <<= nCancel;
                    aParams[1] <<= nCloseMode;

                    mpUserForm->triggerMethod( "Userform_QueryClose", aParams);
                    return;

                }
            }
        }

        mpUserForm->triggerMethod( "Userform_QueryClose" );
#endif
    }


    virtual void SAL_CALL windowClosed( const lang::EventObject& /*e*/ ) override
    {
        mbOpened = false;
        mbShowing = false;
    }

    virtual void SAL_CALL windowMinimized( const lang::EventObject& /*e*/ ) override
    {
    }

    virtual void SAL_CALL windowNormalized( const lang::EventObject& /*e*/ ) override
    {
    }

    virtual void SAL_CALL windowActivated( const lang::EventObject& /*e*/ ) override
    {
        if ( mpUserForm )
        {
            mbActivated = true;
            if ( mbOpened )
            {
                mbOpened = mbActivated = false;
                mpUserForm->triggerActivateEvent();
            }
        }
    }

    virtual void SAL_CALL windowDeactivated( const lang::EventObject& /*e*/ ) override
    {
        if ( mpUserForm )
            mpUserForm->triggerDeactivateEvent();
    }

    virtual void SAL_CALL windowResized( const awt::WindowEvent& /*e*/ ) override
    {
        if ( mpUserForm )
        {
            mpUserForm->triggerResizeEvent();
            mpUserForm->triggerLayoutEvent();
        }
    }

    virtual void SAL_CALL windowMoved( const awt::WindowEvent& /*e*/ ) override
    {
        if ( mpUserForm )
            mpUserForm->triggerLayoutEvent();
    }

    virtual void SAL_CALL windowShown( const lang::EventObject& /*e*/ ) override
    {
    }

    virtual void SAL_CALL windowHidden( const lang::EventObject& /*e*/ ) override
    {
    }

    virtual void SAL_CALL documentEventOccured( const document::DocumentEvent& rEvent ) override
    {
        // early disposing on document event "OnUnload", to be sure Basic still exists when calling VBA "UserForm_Terminate"
        if( rEvent.EventName == GlobalEventConfig::GetEventName( GlobalEventId::CLOSEDOC ) )
        {
            removeListener();
            mbDisposed = true;
            if ( mpUserForm )
                mpUserForm->ResetApiObj();   // will trigger "UserForm_Terminate"
        }
    }

    virtual void SAL_CALL disposing( const lang::EventObject& /*Source*/ ) override
    {
        removeListener();
        mbDisposed = true;
        if ( mpUserForm )
            mpUserForm->ResetApiObj( false );   // pass false (too late to trigger VBA events here)
    }
};

SbUserFormModule::SbUserFormModule( const OUString& rName, const css::script::ModuleInfo& mInfo, bool bIsCompat )
    : SbObjModule( rName, mInfo, bIsCompat )
    , m_mInfo( mInfo )
    , mbInit( false )
{
    m_xModel.set( mInfo.ModuleObject, uno::UNO_QUERY_THROW );
}

SbUserFormModule::~SbUserFormModule()
{
}

void SbUserFormModule::ResetApiObj(  bool bTriggerTerminateEvent )
{
    SAL_INFO("basic", " SbUserFormModule::ResetApiObj( " << (bTriggerTerminateEvent ? "true )" : "false )") );
    if ( bTriggerTerminateEvent && m_xDialog.is() ) // probably someone close the dialog window
    {
        triggerTerminateEvent();
    }
    pDocObject = nullptr;
    m_xDialog = nullptr;
}

void SbUserFormModule::triggerMethod( const OUString& aMethodToRun )
{
    Sequence< Any > aArguments;
    triggerMethod( aMethodToRun, aArguments );
}

void SbUserFormModule::triggerMethod( const OUString& aMethodToRun, Sequence< Any >& aArguments )
{
    SAL_INFO("basic", "trigger " << aMethodToRun);
    // Search method
    SbxVariable* pMeth = SbObjModule::Find( aMethodToRun, SbxClassType::Method );
    if( !pMeth )
        return;

    if ( aArguments.hasElements() )   // Setup parameters
    {
        auto xArray = tools::make_ref<SbxArray>();
        xArray->Put32( pMeth, 0 );    // Method as parameter 0

        for ( sal_Int32 i = 0; i < aArguments.getLength(); ++i )
        {
            auto xSbxVar = tools::make_ref<SbxVariable>( SbxVARIANT );
            unoToSbxValue( xSbxVar.get(), aArguments[i] );
            xArray->Put32( xSbxVar.get(), static_cast< sal_uInt32 >( i ) + 1 );

            // Enable passing by ref
            if ( xSbxVar->GetType() != SbxVARIANT )
                xSbxVar->SetFlag( SbxFlagBits::Fixed );
        }
        pMeth->SetParameters( xArray.get() );

        SbxValues aVals;
        pMeth->Get( aVals );

        for ( sal_Int32 i = 0; i < aArguments.getLength(); ++i )
        {
            aArguments[i] = sbxToUnoValue( xArray->Get32( static_cast< sal_uInt32 >(i) + 1) );
        }
        pMeth->SetParameters( nullptr );
    }
    else
    {
        SbxValues aVals;
        pMeth->Get( aVals );
    }
}

void SbUserFormModule::triggerActivateEvent()
{
    triggerMethod( "UserForm_Activate" );
}

void SbUserFormModule::triggerDeactivateEvent()
{
    triggerMethod( "Userform_Deactivate" );
}

void SbUserFormModule::triggerInitializeEvent()
{
    if ( mbInit )
        return;
    triggerMethod("Userform_Initialize");
    mbInit = true;
}

void SbUserFormModule::triggerTerminateEvent()
{
    triggerMethod("Userform_Terminate");
    mbInit=false;
}

void SbUserFormModule::triggerLayoutEvent()
{
    triggerMethod("Userform_Layout");
}

void SbUserFormModule::triggerResizeEvent()
{
    triggerMethod("Userform_Resize");
}

SbUserFormModuleInstance* SbUserFormModule::CreateInstance()
{
    SbUserFormModuleInstance* pInstance = new SbUserFormModuleInstance( this, GetName(), m_mInfo, IsVBACompat() );
    return pInstance;
}

SbUserFormModuleInstance::SbUserFormModuleInstance( SbUserFormModule* pParentModule,
    const OUString& rName, const css::script::ModuleInfo& mInfo, bool bIsVBACompat )
        : SbUserFormModule( rName, mInfo, bIsVBACompat )
        , m_pParentModule( pParentModule )
{
}

bool SbUserFormModuleInstance::IsClass( const OUString& rName ) const
{
    bool bParentNameMatches = m_pParentModule->GetName().equalsIgnoreAsciiCase( rName );
    bool bRet = bParentNameMatches || SbxObject::IsClass( rName );
    return bRet;
}

SbxVariable* SbUserFormModuleInstance::Find( const OUString& rName, SbxClassType t )
{
    SbxVariable* pVar = m_pParentModule->Find( rName, t );
    return pVar;
}


void SbUserFormModule::Load()
{
    // forces a load
    if ( !pDocObject.is() )
        InitObject();
}


void SbUserFormModule::Unload()
{
    sal_Int8 nCancel = 0;

    Sequence< Any > aParams;
    aParams.realloc(2);
    aParams[0] <<= nCancel;
    aParams[1] <<= sal_Int8(::ooo::vba::VbQueryClose::vbFormCode);

    triggerMethod( "Userform_QueryClose", aParams);

    aParams[0] >>= nCancel;
    // basic boolean ( and what the user might use ) can be ambiguous ( e.g. basic true = -1 )
    // test against 0 ( false ) and assume anything else is true
    // ( Note: ) this used to work ( something changes somewhere )
    if (nCancel != 0)
    {
        return;
    }

    if ( m_xDialog.is() )
    {
        triggerTerminateEvent();
    }
    // Search method
    SbxVariable* pMeth = SbObjModule::Find( "UnloadObject", SbxClassType::Method );
    if( !pMeth )
        return;

    SAL_INFO("basic", "Attempting to run the UnloadObjectMethod");
    m_xDialog.clear(); //release ref to the uno object
    SbxValues aVals;
    bool bWaitForDispose = true; // assume dialog is showing
    if (m_DialogListener)
    {
        bWaitForDispose = m_DialogListener->isShowing();
        SAL_INFO("basic", "Showing " << bWaitForDispose );
    }
    pMeth->Get( aVals);
    if ( !bWaitForDispose )
    {
        // we've either already got a dispose or we are never going to get one
        ResetApiObj();
    } // else wait for dispose
    SAL_INFO("basic", "UnloadObject completed (we hope)");
}


void SbUserFormModule::InitObject()
{
    try
    {
        SbUnoObject* pGlobs = static_cast<SbUnoObject*>(GetParent()->Find( "VBAGlobals", SbxClassType::DontCare ));
        if ( m_xModel.is() && pGlobs )
        {
            // broadcast INITIALIZE_USERFORM script event before the dialog is created
            Reference< script::vba::XVBACompatibility > xVBACompat( getVBACompatibility( m_xModel ), uno::UNO_SET_THROW );
            xVBACompat->broadcastVBAScriptEvent( script::vba::VBAScriptEventId::INITIALIZE_USERFORM, GetName() );
            uno::Reference< lang::XMultiServiceFactory > xVBAFactory( pGlobs->getUnoAny(), uno::UNO_QUERY_THROW );
            uno::Reference< uno::XComponentContext > xContext = comphelper::getProcessComponentContext();
            OUString sDialogUrl( "vnd.sun.star.script:"  );
            OUString sProjectName( "Standard" );

            try
            {
                Reference< beans::XPropertySet > xProps( m_xModel, UNO_QUERY_THROW );
                uno::Reference< script::vba::XVBACompatibility > xVBAMode( xProps->getPropertyValue( "BasicLibraries" ), uno::UNO_QUERY_THROW );
                sProjectName = xVBAMode->getProjectName();
            }
            catch(const Exception& ) {}

            sDialogUrl += sProjectName + "." + GetName() + "?location=document";

            uno::Reference< awt::XDialogProvider > xProvider = awt::DialogProvider::createWithModel( xContext, m_xModel  );
            m_xDialog = xProvider->createDialog( sDialogUrl );

            // create vba api object
            uno::Sequence< uno::Any > aArgs(4);
            aArgs[ 0 ] = uno::Any();
            aArgs[ 1 ] <<= m_xDialog;
            aArgs[ 2 ] <<= m_xModel;
            aArgs[ 3 ] <<= GetParent()->GetName();
            pDocObject = new SbUnoObject( GetName(), uno::Any( xVBAFactory->createInstanceWithArguments( "ooo.vba.msforms.UserForm", aArgs  ) ) );

            uno::Reference< lang::XComponent > xComponent( m_xDialog, uno::UNO_QUERY_THROW );

            // the dialog must be disposed at the end!
            StarBASIC* pParentBasic = nullptr;
            SbxObject* pCurObject = this;
            do
            {
                SbxObject* pObjParent = pCurObject->GetParent();
                pParentBasic = dynamic_cast<StarBASIC*>( pObjParent  );
                pCurObject = pObjParent;
            }
            while( pParentBasic == nullptr && pCurObject != nullptr );

            SAL_WARN_IF( pParentBasic == nullptr, "basic", "pParentBasic == NULL" );
            registerComponentToBeDisposedForBasic( xComponent, pParentBasic );

            // if old listener object exists, remove it from dialog and document model
            if( m_DialogListener.is() )
                m_DialogListener->removeListener();
            m_DialogListener.set( new FormObjEventListenerImpl( this, xComponent, m_xModel ) );

            triggerInitializeEvent();
        }
    }
    catch(const uno::Exception& )
    {
    }

}

SbxVariable*
SbUserFormModule::Find( const OUString& rName, SbxClassType t )
{
    if ( !pDocObject.is() && !GetSbData()->bRunInit && GetSbData()->pInst )
        InitObject();
    return SbObjModule::Find( rName, t );
}

SbProperty::SbProperty( const OUString& r, SbxDataType t, SbModule* p )
        : SbxProperty( r, t ), pMod( p )
{
}

SbProperty::~SbProperty()
{}


SbProcedureProperty::~SbProcedureProperty()
{}

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