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
  
     | 
    
      /* -*- 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 "sb.hxx"
#include <tools/rcid.h>
#include <tools/stream.hxx>
#include <tools/errinf.hxx>
#include <comphelper/solarmutex.hxx>
#include <basic/sbx.hxx>
#include <tools/rc.hxx>
#include <vcl/svapp.hxx>
#include <comphelper/processfactory.hxx>
#include "image.hxx"
#include "sbunoobj.hxx"
#include "sbjsmeth.hxx"
#include "sbjsmod.hxx"
#include "sbintern.hxx"
#include "runtime.hxx"
#include <basic/sbuno.hxx>
#include "sbobjmod.hxx"
#include "stdobj.hxx"
#include "filefmt.hxx"
#include "sb.hrc"
#include <basrid.hxx>
#include <osl/mutex.hxx>
#include <cppuhelper/implbase.hxx>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/util/XCloseBroadcaster.hpp>
#include <com/sun/star/util/XCloseListener.hpp>
#include "errobject.hxx"
#include <memory>
#include <unordered_map>
#include <com/sun/star/script/ModuleType.hpp>
#include <com/sun/star/script/ModuleInfo.hpp>
#include <svtools/miscopt.hxx>
using namespace ::com::sun::star::script;
#define RTLNAME "@SBRTL"
//  i#i68894#
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using com::sun::star::uno::Reference;
using com::sun::star::uno::Any;
using com::sun::star::uno::UNO_QUERY;
using com::sun::star::lang::XMultiServiceFactory;
class DocBasicItem : public ::cppu::WeakImplHelper< util::XCloseListener >
{
public:
    explicit DocBasicItem( StarBASIC& rDocBasic );
    virtual ~DocBasicItem();
    inline const SbxObjectRef& getClassModules() const { return mxClassModules; }
    inline bool isDocClosed() const { return mbDocClosed; }
    void clearDependingVarsOnDelete( StarBASIC& rDeletedBasic );
    void startListening();
    void stopListening();
    void setDisposed( bool bDisposed )
    {
        mbDisposed = bDisposed;
    }
    virtual void SAL_CALL queryClosing( const lang::EventObject& rSource, sal_Bool bGetsOwnership ) throw (util::CloseVetoException, uno::RuntimeException, std::exception) override;
    virtual void SAL_CALL notifyClosing( const lang::EventObject& rSource ) throw (uno::RuntimeException, std::exception) override;
    virtual void SAL_CALL disposing( const lang::EventObject& rSource ) throw (uno::RuntimeException, std::exception) override;
private:
    StarBASIC&      mrDocBasic;
    SbxObjectRef    mxClassModules;
    bool            mbDocClosed;
    bool            mbDisposed;
};
DocBasicItem::DocBasicItem( StarBASIC& rDocBasic ) :
    mrDocBasic( rDocBasic ),
    mxClassModules( new SbxObject( OUString() ) ),
    mbDocClosed( false ),
    mbDisposed( false )
{
}
DocBasicItem::~DocBasicItem()
{
    // tdf#90969 HACK: don't use SolarMutexGuard - there is a horrible global
    // map GaDocBasicItems holding instances, and these get deleted from exit
    // handlers, when the SolarMutex is already dead
    comphelper::SolarMutex *pSolarMutex = comphelper::SolarMutex::get();
    if ( pSolarMutex )
        pSolarMutex->acquire();
    try
    {
        stopListening();
        mxClassModules.Clear(); // release with SolarMutex locked
    }
    catch (...)
    {
        assert(false);
    }
    pSolarMutex = comphelper::SolarMutex::get();
    if ( pSolarMutex )
        pSolarMutex->release();
}
void DocBasicItem::clearDependingVarsOnDelete( StarBASIC& rDeletedBasic )
{
    mrDocBasic.implClearDependingVarsOnDelete( &rDeletedBasic );
}
void DocBasicItem::startListening()
{
    Any aThisComp;
    mrDocBasic.GetUNOConstant( "ThisComponent", aThisComp );
    Reference< util::XCloseBroadcaster > xCloseBC( aThisComp, UNO_QUERY );
    mbDisposed = !xCloseBC.is();
    if( xCloseBC.is() )
    {
        try { xCloseBC->addCloseListener( this ); } catch(const uno::Exception& ) {}
    }
}
void DocBasicItem::stopListening()
{
    if( mbDisposed ) return;
    mbDisposed = true;
    Any aThisComp;
    if (!mrDocBasic.GetUNOConstant("ThisComponent", aThisComp))
        return;
    Reference< util::XCloseBroadcaster > xCloseBC( aThisComp, UNO_QUERY );
    if( xCloseBC.is() )
    {
        try { xCloseBC->removeCloseListener( this ); } catch(const uno::Exception& ) {}
    }
}
void SAL_CALL DocBasicItem::queryClosing( const lang::EventObject& /*rSource*/, sal_Bool /*bGetsOwnership*/ ) throw (util::CloseVetoException, uno::RuntimeException, std::exception)
{
}
void SAL_CALL DocBasicItem::notifyClosing( const lang::EventObject& /*rEvent*/ ) throw (uno::RuntimeException, std::exception)
{
    stopListening();
    mbDocClosed = true;
}
void SAL_CALL DocBasicItem::disposing( const lang::EventObject& /*rEvent*/ ) throw (uno::RuntimeException, std::exception)
{
    stopListening();
}
namespace {
typedef ::rtl::Reference< DocBasicItem > DocBasicItemRef;
typedef std::unordered_map< const StarBASIC *, DocBasicItemRef > DocBasicItemMap;
class GaDocBasicItems : public rtl::Static<DocBasicItemMap,GaDocBasicItems> {};
const DocBasicItem* lclFindDocBasicItem( const StarBASIC* pDocBasic )
{
    DocBasicItemMap::iterator it = GaDocBasicItems::get().find( pDocBasic );
    DocBasicItemMap::iterator end = GaDocBasicItems::get().end();
    return (it != end) ? it->second.get() : nullptr;
}
void lclInsertDocBasicItem( StarBASIC& rDocBasic )
{
    DocBasicItemRef& rxDocBasicItem = GaDocBasicItems::get()[ &rDocBasic ];
    rxDocBasicItem.set( new DocBasicItem( rDocBasic ) );
    rxDocBasicItem->startListening();
}
void lclRemoveDocBasicItem( StarBASIC& rDocBasic )
{
    DocBasicItemMap::iterator it = GaDocBasicItems::get().find( &rDocBasic );
    if( it != GaDocBasicItems::get().end() )
    {
        it->second->stopListening();
        GaDocBasicItems::get().erase( it );
    }
    DocBasicItemMap::iterator it_end = GaDocBasicItems::get().end();
    for( it = GaDocBasicItems::get().begin(); it != it_end; ++it )
    {
        it->second->clearDependingVarsOnDelete( rDocBasic );
    }
}
StarBASIC* lclGetDocBasicForModule( SbModule* pModule )
{
    StarBASIC* pRetBasic = nullptr;
    SbxObject* pCurParent = pModule;
    while( pCurParent->GetParent() != nullptr )
    {
        pCurParent = pCurParent->GetParent();
        StarBASIC* pDocBasic = dynamic_cast<StarBASIC*>( pCurParent  );
        if( pDocBasic != nullptr && pDocBasic->IsDocBasic() )
        {
            pRetBasic = pDocBasic;
            break;
        }
    }
    return pRetBasic;
}
} // namespace
SbxObject* StarBASIC::getVBAGlobals( )
{
    if ( !pVBAGlobals )
    {
        Any aThisDoc;
        if ( GetUNOConstant("ThisComponent", aThisDoc) )
        {
            Reference< XMultiServiceFactory > xDocFac( aThisDoc, UNO_QUERY );
            if ( xDocFac.is() )
            {
                try
                {
                    xDocFac->createInstance("ooo.vba.VBAGlobals");
                }
                catch(const Exception& )
                {
                    // Ignore
                }
            }
        }
        const OUString aVBAHook("VBAGlobals");
        pVBAGlobals = static_cast<SbUnoObject*>(Find( aVBAHook , SbxClassType::DontCare ));
    }
    return pVBAGlobals;
}
//  i#i68894#
SbxVariable* StarBASIC::VBAFind( const OUString& rName, SbxClassType t )
{
    if( rName == "ThisComponent" )
    {
        return nullptr;
    }
    // rename to init globals
    if ( getVBAGlobals( ) )
    {
        return pVBAGlobals->Find( rName, t );
    }
    return nullptr;
}
// Create array for conversion SFX <-> VB error code
struct SFX_VB_ErrorItem
{
    sal_uInt16  nErrorVB;
    SbError nErrorSFX;
};
const SFX_VB_ErrorItem SFX_VB_ErrorTab[] =
{
    { 1, ERRCODE_BASIC_EXCEPTION },  // #87844 Map exception to error code 1
    { 2, ERRCODE_BASIC_SYNTAX },
    { 3, ERRCODE_BASIC_NO_GOSUB },
    { 4, ERRCODE_BASIC_REDO_FROM_START },
    { 5, ERRCODE_BASIC_BAD_ARGUMENT },
    { 6, ERRCODE_BASIC_MATH_OVERFLOW },
    { 7, ERRCODE_BASIC_NO_MEMORY },
    { 8, ERRCODE_BASIC_ALREADY_DIM },
    { 9, ERRCODE_BASIC_OUT_OF_RANGE },
    { 10, ERRCODE_BASIC_DUPLICATE_DEF },
    { 11, ERRCODE_BASIC_ZERODIV },
    { 12, ERRCODE_BASIC_VAR_UNDEFINED },
    { 13, ERRCODE_BASIC_CONVERSION },
    { 14, ERRCODE_BASIC_BAD_PARAMETER },
    { 18, ERRCODE_BASIC_USER_ABORT },
    { 20, ERRCODE_BASIC_BAD_RESUME },
    { 28, ERRCODE_BASIC_STACK_OVERFLOW },
    { 35, ERRCODE_BASIC_PROC_UNDEFINED },
    { 48, ERRCODE_BASIC_BAD_DLL_LOAD },
    { 49, ERRCODE_BASIC_BAD_DLL_CALL },
    { 51, ERRCODE_BASIC_INTERNAL_ERROR },
    { 52, ERRCODE_BASIC_BAD_CHANNEL },
    { 53, ERRCODE_BASIC_FILE_NOT_FOUND },
    { 54, ERRCODE_BASIC_BAD_FILE_MODE },
    { 55, ERRCODE_BASIC_FILE_ALREADY_OPEN },
    { 57, ERRCODE_BASIC_IO_ERROR },
    { 58, ERRCODE_BASIC_FILE_EXISTS },
    { 59, ERRCODE_BASIC_BAD_RECORD_LENGTH },
    { 61, ERRCODE_BASIC_DISK_FULL },
    { 62, ERRCODE_BASIC_READ_PAST_EOF },
    { 63, ERRCODE_BASIC_BAD_RECORD_NUMBER },
    { 67, ERRCODE_BASIC_TOO_MANY_FILES },
    { 68, ERRCODE_BASIC_NO_DEVICE },
    { 70, ERRCODE_BASIC_ACCESS_DENIED },
    { 71, ERRCODE_BASIC_NOT_READY },
    { 73, ERRCODE_BASIC_NOT_IMPLEMENTED },
    { 74, ERRCODE_BASIC_DIFFERENT_DRIVE },
    { 75, ERRCODE_BASIC_ACCESS_ERROR },
    { 76, ERRCODE_BASIC_PATH_NOT_FOUND },
    { 91, ERRCODE_BASIC_NO_OBJECT },
    { 93, ERRCODE_BASIC_BAD_PATTERN },
    { 94, ERRCODE_BASIC_IS_NULL },
    { 250, ERRCODE_BASIC_DDE_ERROR },
    { 280, ERRCODE_BASIC_DDE_WAITINGACK },
    { 281, ERRCODE_BASIC_DDE_OUTOFCHANNELS },
    { 282, ERRCODE_BASIC_DDE_NO_RESPONSE },
    { 283, ERRCODE_BASIC_DDE_MULT_RESPONSES },
    { 284, ERRCODE_BASIC_DDE_CHANNEL_LOCKED },
    { 285, ERRCODE_BASIC_DDE_NOTPROCESSED },
    { 286, ERRCODE_BASIC_DDE_TIMEOUT },
    { 287, ERRCODE_BASIC_DDE_USER_INTERRUPT },
    { 288, ERRCODE_BASIC_DDE_BUSY },
    { 289, ERRCODE_BASIC_DDE_NO_DATA },
    { 290, ERRCODE_BASIC_DDE_WRONG_DATA_FORMAT },
    { 291, ERRCODE_BASIC_DDE_PARTNER_QUIT },
    { 292, ERRCODE_BASIC_DDE_CONV_CLOSED },
    { 293, ERRCODE_BASIC_DDE_NO_CHANNEL },
    { 294, ERRCODE_BASIC_DDE_INVALID_LINK },
    { 295, ERRCODE_BASIC_DDE_QUEUE_OVERFLOW },
    { 296, ERRCODE_BASIC_DDE_LINK_ALREADY_EST },
    { 297, ERRCODE_BASIC_DDE_LINK_INV_TOPIC },
    { 298, ERRCODE_BASIC_DDE_DLL_NOT_FOUND },
    { 323, ERRCODE_BASIC_CANNOT_LOAD },
    { 341, ERRCODE_BASIC_BAD_INDEX },
    { 366, ERRCODE_BASIC_NO_ACTIVE_OBJECT },
    { 380, ERRCODE_BASIC_BAD_PROP_VALUE },
    { 382, ERRCODE_BASIC_PROP_READONLY },
    { 394, ERRCODE_BASIC_PROP_WRITEONLY },
    { 420, ERRCODE_BASIC_INVALID_OBJECT },
    { 423, ERRCODE_BASIC_NO_METHOD },
    { 424, ERRCODE_BASIC_NEEDS_OBJECT },
    { 425, ERRCODE_BASIC_INVALID_USAGE_OBJECT },
    { 430, ERRCODE_BASIC_NO_OLE },
    { 438, ERRCODE_BASIC_BAD_METHOD },
    { 440, ERRCODE_BASIC_OLE_ERROR },
    { 445, ERRCODE_BASIC_BAD_ACTION },
    { 446, ERRCODE_BASIC_NO_NAMED_ARGS },
    { 447, ERRCODE_BASIC_BAD_LOCALE },
    { 448, ERRCODE_BASIC_NAMED_NOT_FOUND },
    { 449, ERRCODE_BASIC_NOT_OPTIONAL },
    { 450, ERRCODE_BASIC_WRONG_ARGS },
    { 451, ERRCODE_BASIC_NOT_A_COLL },
    { 452, ERRCODE_BASIC_BAD_ORDINAL },
    { 453, ERRCODE_BASIC_DLLPROC_NOT_FOUND },
    { 460, ERRCODE_BASIC_BAD_CLIPBD_FORMAT },
    { 951, ERRCODE_BASIC_UNEXPECTED },
    { 952, ERRCODE_BASIC_EXPECTED },
    { 953, ERRCODE_BASIC_SYMBOL_EXPECTED },
    { 954, ERRCODE_BASIC_VAR_EXPECTED },
    { 955, ERRCODE_BASIC_LABEL_EXPECTED },
    { 956, ERRCODE_BASIC_LVALUE_EXPECTED },
    { 957, ERRCODE_BASIC_VAR_DEFINED },
    { 958, ERRCODE_BASIC_PROC_DEFINED },
    { 959, ERRCODE_BASIC_LABEL_DEFINED },
    { 960, ERRCODE_BASIC_UNDEF_VAR },
    { 961, ERRCODE_BASIC_UNDEF_ARRAY },
    { 962, ERRCODE_BASIC_UNDEF_PROC },
    { 963, ERRCODE_BASIC_UNDEF_LABEL },
    { 964, ERRCODE_BASIC_UNDEF_TYPE },
    { 965, ERRCODE_BASIC_BAD_EXIT },
    { 966, ERRCODE_BASIC_BAD_BLOCK },
    { 967, ERRCODE_BASIC_BAD_BRACKETS },
    { 968, ERRCODE_BASIC_BAD_DECLARATION },
    { 969, ERRCODE_BASIC_BAD_PARAMETERS },
    { 970, ERRCODE_BASIC_BAD_CHAR_IN_NUMBER },
    { 971, ERRCODE_BASIC_MUST_HAVE_DIMS },
    { 972, ERRCODE_BASIC_NO_IF },
    { 973, ERRCODE_BASIC_NOT_IN_SUBR },
    { 974, ERRCODE_BASIC_NOT_IN_MAIN },
    { 975, ERRCODE_BASIC_WRONG_DIMS },
    { 976, ERRCODE_BASIC_BAD_OPTION },
    { 977, ERRCODE_BASIC_CONSTANT_REDECLARED },
    { 978, ERRCODE_BASIC_PROG_TOO_LARGE },
    { 979, ERRCODE_BASIC_NO_STRINGS_ARRAYS },
    { 1000, ERRCODE_BASIC_PROPERTY_NOT_FOUND },
    { 1001, ERRCODE_BASIC_METHOD_NOT_FOUND },
    { 1002, ERRCODE_BASIC_ARG_MISSING },
    { 1003, ERRCODE_BASIC_BAD_NUMBER_OF_ARGS },
    { 1004, ERRCODE_BASIC_METHOD_FAILED },
    { 1005, ERRCODE_BASIC_SETPROP_FAILED },
    { 1006, ERRCODE_BASIC_GETPROP_FAILED },
    { 1007, ERRCODE_BASIC_COMPAT },
    { 0xFFFF, 0xFFFFFFFFL }     // End mark
};
// The StarBASIC factory is a hack. When a SbModule is created, its pointer
// is saved and given to the following SbProperties/SbMethods. This restores
// the Modul-relationshop. But it works only when a modul is loaded.
// Can cause troubles with separately loaded properties!
SbxBase* SbiFactory::Create( sal_uInt16 nSbxId, sal_uInt32 nCreator )
{
    if( nCreator ==  SBXCR_SBX )
    {
        switch( nSbxId )
        {
        case SBXID_BASIC:
            return new StarBASIC( nullptr );
        case SBXID_BASICMOD:
            return new SbModule( "" );
        case SBXID_BASICPROP:
            return new SbProperty( "", SbxVARIANT, nullptr );
        case SBXID_BASICMETHOD:
            return new SbMethod( "", SbxVARIANT, nullptr );
        case SBXID_JSCRIPTMOD:
            return new SbJScriptModule( "" );
        case SBXID_JSCRIPTMETH:
            return new SbJScriptMethod( "", SbxVARIANT, nullptr );
        }
    }
    return nullptr;
}
SbxObject* SbiFactory::CreateObject( const OUString& rClass )
{
    if( rClass.equalsIgnoreAsciiCase( "StarBASIC" ) )
    {
        return new StarBASIC( nullptr );
    }
    else if( rClass.equalsIgnoreAsciiCase( "StarBASICModule" ) )
    {
        return new SbModule( OUString() );
    }
    else if( rClass.equalsIgnoreAsciiCase( "Collection" ) )
    {
        return new BasicCollection( OUString("Collection"));
    }
    else if( rClass.equalsIgnoreAsciiCase( "FileSystemObject" ) )
    {
        try
        {
            Reference< XMultiServiceFactory > xFactory( comphelper::getProcessServiceFactory(), UNO_SET_THROW );
            OUString aServiceName("ooo.vba.FileSystemObject");
            Reference< XInterface > xInterface( xFactory->createInstance( aServiceName ), UNO_SET_THROW );
            return new SbUnoObject( aServiceName, uno::makeAny( xInterface ) );
        }
        catch(const Exception& )
        {
        }
    }
    return nullptr;
}
// Factory class to create OLE objects
class SbOLEFactory : public SbxFactory
{
public:
    virtual SbxBase* Create( sal_uInt16 nSbxId, sal_uInt32 = SBXCR_SBX ) override;
    virtual SbxObject* CreateObject( const OUString& ) override;
};
SbxBase* SbOLEFactory::Create( sal_uInt16, sal_uInt32 )
{
    // Not supported
    return nullptr;
}
SbxObject* SbOLEFactory::CreateObject( const OUString& rClassName )
{
    SbxObject* pRet = createOLEObject_Impl( rClassName );
    return pRet;
}
// SbFormFactory, show user forms by: dim as new <user form name>
class SbFormFactory : public SbxFactory
{
public:
    virtual SbxBase* Create( sal_uInt16 nSbxId, sal_uInt32 = SBXCR_SBX ) override;
    virtual SbxObject* CreateObject( const OUString& ) override;
};
SbxBase* SbFormFactory::Create( sal_uInt16, sal_uInt32 )
{
    // Not supported
    return nullptr;
}
SbxObject* SbFormFactory::CreateObject( const OUString& rClassName )
{
    if( SbModule* pMod = GetSbData()->pMod )
    {
        if( SbxVariable* pVar = pMod->Find( rClassName, SbxClassType::Object ) )
        {
            if( SbUserFormModule* pFormModule = dynamic_cast<SbUserFormModule*>( pVar->GetObject() )  )
            {
                bool bInitState = pFormModule->getInitState();
                if( bInitState )
                {
                    // Not the first instantiate, reset
                    bool bTriggerTerminateEvent = false;
                    pFormModule->ResetApiObj( bTriggerTerminateEvent );
                    pFormModule->setInitState( false );
                }
                else
                {
                    pFormModule->Load();
                }
                return pFormModule->CreateInstance();
            }
        }
    }
    return nullptr;
}
// SbTypeFactory
SbxObject* cloneTypeObjectImpl( const SbxObject& rTypeObj )
{
    SbxObject* pRet = new SbxObject( rTypeObj );
    pRet->PutObject( pRet );
    // Copy the properties, not only the reference to them
    SbxArray* pProps = pRet->GetProperties();
    sal_uInt32 nCount = pProps->Count32();
    for( sal_uInt32 i = 0 ; i < nCount ; i++ )
    {
        SbxVariable* pVar = pProps->Get32( i );
        SbxProperty* pProp = dynamic_cast<SbxProperty*>( pVar  );
        if( pProp )
        {
            SbxProperty* pNewProp = new SbxProperty( *pProp );
            SbxDataType eVarType = pVar->GetType();
            if( eVarType & SbxARRAY )
            {
                SbxBase* pParObj = pVar->GetObject();
                SbxDimArray* pSource = dynamic_cast<SbxDimArray*>( pParObj );
                SbxDimArray* pDest = new SbxDimArray( pVar->GetType() );
                pDest->setHasFixedSize( pSource && pSource->hasFixedSize() );
                if ( pSource && pSource->GetDims() && pSource->hasFixedSize() )
                {
                    sal_Int32 lb = 0;
                    sal_Int32 ub = 0;
                    for ( sal_Int32 j = 1 ; j <= pSource->GetDims(); ++j )
                    {
                        pSource->GetDim32( (sal_Int32)j, lb, ub );
                        pDest->AddDim32( lb, ub );
                    }
                }
                else
                {
                    pDest->unoAddDim( 0, -1 ); // variant array
                }
                SbxFlagBits nSavFlags = pVar->GetFlags();
                pNewProp->ResetFlag( SbxFlagBits::Fixed );
                // need to reset the FIXED flag
                // when calling PutObject ( because the type will not match Object )
                pNewProp->PutObject( pDest );
                pNewProp->SetFlags( nSavFlags );
            }
            if( eVarType == SbxOBJECT )
            {
                SbxBase* pObjBase = pVar->GetObject();
                SbxObject* pSrcObj = dynamic_cast<SbxObject*>( pObjBase );
                SbxObject* pDestObj = nullptr;
                if( pSrcObj != nullptr )
                    pDestObj = cloneTypeObjectImpl( *pSrcObj );
                pNewProp->PutObject( pDestObj );
            }
            pProps->PutDirect( pNewProp, i );
        }
    }
    return pRet;
}
// Factory class to create user defined objects (type command)
class SbTypeFactory : public SbxFactory
{
public:
    virtual SbxBase* Create( sal_uInt16 nSbxId, sal_uInt32 = SBXCR_SBX ) override;
    virtual SbxObject* CreateObject( const OUString& ) override;
};
SbxBase* SbTypeFactory::Create( sal_uInt16, sal_uInt32 )
{
    // Not supported
    return nullptr;
}
SbxObject* SbTypeFactory::CreateObject( const OUString& rClassName )
{
    SbxObject* pRet = nullptr;
    SbModule* pMod = GetSbData()->pMod;
    if( pMod )
    {
        const SbxObject* pObj = pMod->FindType( rClassName );
        if( pObj )
        {
            pRet = cloneTypeObjectImpl( *pObj );
        }
    }
    return pRet;
}
SbxObject* createUserTypeImpl( const OUString& rClassName )
{
    SbxObject* pRetObj = GetSbData()->pTypeFac->CreateObject( rClassName );
    return pRetObj;
}
SbClassModuleObject::SbClassModuleObject( SbModule* pClassModule )
    : SbModule( pClassModule->GetName() )
    , mpClassModule( pClassModule )
    , mbInitializeEventDone( false )
{
    aOUSource = pClassModule->aOUSource;
    aComment = pClassModule->aComment;
    pImage = pClassModule->pImage;
    pBreaks = pClassModule->pBreaks;
    SetClassName( pClassModule->GetName() );
    // Allow search only internally
    ResetFlag( SbxFlagBits::GlobalSearch );
    // Copy the methods from original class module
    SbxArray* pClassMethods = pClassModule->GetMethods();
    sal_uInt32 nMethodCount = pClassMethods->Count32();
    sal_uInt32 i;
    for( i = 0 ; i < nMethodCount ; i++ )
    {
        SbxVariable* pVar = pClassMethods->Get32( i );
        // Exclude SbIfaceMapperMethod to copy them in a second step
        SbIfaceMapperMethod* pIfaceMethod = dynamic_cast<SbIfaceMapperMethod*>( pVar  );
        if( !pIfaceMethod )
        {
            SbMethod* pMethod = dynamic_cast<SbMethod*>( pVar  );
            if( pMethod )
            {
                SbxFlagBits nFlags_ = pMethod->GetFlags();
                pMethod->SetFlag( SbxFlagBits::NoBroadcast );
                SbMethod* pNewMethod = new SbMethod( *pMethod );
                pNewMethod->ResetFlag( SbxFlagBits::NoBroadcast );
                pMethod->SetFlags( nFlags_ );
                pNewMethod->pMod = this;
                pNewMethod->SetParent( this );
                pMethods->PutDirect( pNewMethod, i );
                StartListening( pNewMethod->GetBroadcaster(), true );
            }
        }
    }
    // Copy SbIfaceMapperMethod in a second step to ensure that
    // the corresponding base methods have already been copied
    for( i = 0 ; i < nMethodCount ; i++ )
    {
        SbxVariable* pVar = pClassMethods->Get32( i );
        SbIfaceMapperMethod* pIfaceMethod = dynamic_cast<SbIfaceMapperMethod*>( pVar  );
        if( pIfaceMethod )
        {
            SbMethod* pImplMethod = pIfaceMethod->getImplMethod();
            if( !pImplMethod )
            {
                OSL_FAIL( "No ImplMethod" );
                continue;
            }
            // Search for own copy of ImplMethod
            SbxVariable* p = pMethods->Find( pImplMethod->GetName(), SbxClassType::Method );
            SbMethod* pImplMethodCopy = p ? dynamic_cast<SbMethod*>( p ) : nullptr;
            if( !pImplMethodCopy )
            {
                OSL_FAIL( "Found no ImplMethod copy" );
                continue;
            }
            SbIfaceMapperMethod* pNewIfaceMethod =
                new SbIfaceMapperMethod( pIfaceMethod->GetName(), pImplMethodCopy );
            pMethods->PutDirect( pNewIfaceMethod, i );
        }
    }
    // Copy the properties from original class module
    SbxArray* pClassProps = pClassModule->GetProperties();
    sal_uInt32 nPropertyCount = pClassProps->Count32();
    for( i = 0 ; i < nPropertyCount ; i++ )
    {
        SbxVariable* pVar = pClassProps->Get32( i );
        SbProcedureProperty* pProcedureProp = dynamic_cast<SbProcedureProperty*>( pVar  );
        if( pProcedureProp )
        {
            SbxFlagBits nFlags_ = pProcedureProp->GetFlags();
            pProcedureProp->SetFlag( SbxFlagBits::NoBroadcast );
            SbProcedureProperty* pNewProp = new SbProcedureProperty
                ( pProcedureProp->GetName(), pProcedureProp->GetType() );
            pNewProp->SetFlags( nFlags_ ); // Copy flags
            pNewProp->ResetFlag( SbxFlagBits::NoBroadcast ); // except the Broadcast if it was set
            pProcedureProp->SetFlags( nFlags_ );
            pProps->PutDirect( pNewProp, i );
            StartListening( pNewProp->GetBroadcaster(), true );
        }
        else
        {
            SbxProperty* pProp = dynamic_cast<SbxProperty*>( pVar  );
            if( pProp )
            {
                SbxFlagBits nFlags_ = pProp->GetFlags();
                pProp->SetFlag( SbxFlagBits::NoBroadcast );
                SbxProperty* pNewProp = new SbxProperty( *pProp );
                // Special handling for modules instances and collections, they need
                // to be instantiated, otherwise all refer to the same base object
                SbxDataType eVarType = pProp->GetType();
                if( eVarType == SbxOBJECT )
                {
                    SbxBase* pObjBase = pProp->GetObject();
                    SbxObject* pObj = dynamic_cast<SbxObject*>( pObjBase );
                    if( pObj != nullptr )
                    {
                        OUString aObjClass = pObj->GetClassName();
                        SbClassModuleObject* pClassModuleObj = dynamic_cast<SbClassModuleObject*>( pObjBase );
                        if( pClassModuleObj != nullptr )
                        {
                            SbModule* pLclClassModule = pClassModuleObj->getClassModule();
                            SbClassModuleObject* pNewObj = new SbClassModuleObject( pLclClassModule );
                            pNewObj->SetName( pProp->GetName() );
                            pNewObj->SetParent( pLclClassModule->pParent );
                            pNewProp->PutObject( pNewObj );
                        }
                        else if( aObjClass.equalsIgnoreAsciiCase( "Collection" ) )
                        {
                            OUString aCollectionName("Collection");
                            BasicCollection* pNewCollection = new BasicCollection( aCollectionName );
                            pNewCollection->SetName( pProp->GetName() );
                            pNewCollection->SetParent( pClassModule->pParent );
                            pNewProp->PutObject( pNewCollection );
                        }
                    }
                }
                pNewProp->ResetFlag( SbxFlagBits::NoBroadcast );
                pNewProp->SetParent( this );
                pProps->PutDirect( pNewProp, i );
                pProp->SetFlags( nFlags_ );
            }
        }
    }
    SetModuleType( ModuleType::CLASS );
    mbVBACompat = pClassModule->mbVBACompat;
}
SbClassModuleObject::~SbClassModuleObject()
{
    // do not trigger termination event when document is already closed
    if( StarBASIC::IsRunning() )
        if( StarBASIC* pDocBasic = lclGetDocBasicForModule( this ) )
            if( const DocBasicItem* pDocBasicItem = lclFindDocBasicItem( pDocBasic ) )
                if( !pDocBasicItem->isDocClosed() )
                    triggerTerminateEvent();
    // Must be deleted by base class dtor because this data
    // is not owned by the SbClassModuleObject object
    pImage = nullptr;
    pBreaks = nullptr;
}
void SbClassModuleObject::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )
{
    handleProcedureProperties( rBC, rHint );
}
SbxVariable* SbClassModuleObject::Find( const OUString& rName, SbxClassType t )
{
    SbxVariable* pRes = SbxObject::Find( rName, t );
    if( pRes )
    {
        triggerInitializeEvent();
        SbIfaceMapperMethod* pIfaceMapperMethod = dynamic_cast<SbIfaceMapperMethod*>( pRes );
        if( pIfaceMapperMethod )
        {
            pRes = pIfaceMapperMethod->getImplMethod();
            pRes->SetFlag( SbxFlagBits::ExtFound );
        }
    }
    return pRes;
}
void SbClassModuleObject::triggerInitializeEvent()
{
    if( mbInitializeEventDone )
    {
        return;
    }
    mbInitializeEventDone = true;
    // Search method
    SbxVariable* pMeth = SbxObject::Find("Class_Initialize", SbxClassType::Method);
    if( pMeth )
    {
        SbxValues aVals;
        pMeth->Get( aVals );
    }
}
void SbClassModuleObject::triggerTerminateEvent()
{
    if( !mbInitializeEventDone || GetSbData()->bRunInit )
    {
        return;
    }
    // Search method
    SbxVariable* pMeth = SbxObject::Find("Class_Terminate", SbxClassType::Method );
    if( pMeth )
    {
        SbxValues aVals;
        pMeth->Get( aVals );
    }
}
SbClassData::SbClassData()
{
    mxIfaces = new SbxArray();
}
void SbClassData::clear()
{
    mxIfaces->Clear();
    maRequiredTypes.clear();
}
SbClassFactory::SbClassFactory()
{
    OUString aDummyName;
    xClassModules = new SbxObject( aDummyName );
}
SbClassFactory::~SbClassFactory()
{}
void SbClassFactory::AddClassModule( SbModule* pClassModule )
{
    SbxObjectRef xToUseClassModules = xClassModules;
    if( StarBASIC* pDocBasic = lclGetDocBasicForModule( pClassModule ) )
        if( const DocBasicItem* pDocBasicItem = lclFindDocBasicItem( pDocBasic ) )
            xToUseClassModules = pDocBasicItem->getClassModules();
    SbxObject* pParent = pClassModule->GetParent();
    xToUseClassModules->Insert( pClassModule );
    pClassModule->SetParent( pParent );
}
void SbClassFactory::RemoveClassModule( SbModule* pClassModule )
{
    xClassModules->Remove( pClassModule );
}
SbxBase* SbClassFactory::Create( sal_uInt16, sal_uInt32 )
{
    // Not supported
    return nullptr;
}
SbxObject* SbClassFactory::CreateObject( const OUString& rClassName )
{
    SbxObjectRef xToUseClassModules = xClassModules;
    if( SbModule* pMod = GetSbData()->pMod )
    {
        if( StarBASIC* pDocBasic = lclGetDocBasicForModule( pMod ) )
        {
            if( const DocBasicItem* pDocBasicItem = lclFindDocBasicItem( pDocBasic ) )
            {
                xToUseClassModules = pDocBasicItem->getClassModules();
            }
        }
    }
    SbxVariable* pVar = xToUseClassModules->Find( rClassName, SbxClassType::Object );
    SbxObject* pRet = nullptr;
    if( pVar )
    {
        SbModule* pVarMod = static_cast<SbModule*>(pVar);
        pRet = new SbClassModuleObject( pVarMod );
    }
    return pRet;
}
SbModule* SbClassFactory::FindClass( const OUString& rClassName )
{
    SbxVariable* pVar = xClassModules->Find( rClassName, SbxClassType::DontCare );
    SbModule* pMod = pVar ? static_cast<SbModule*>(pVar) : nullptr;
    return pMod;
}
StarBASIC::StarBASIC( StarBASIC* p, bool bIsDocBasic  )
    : SbxObject( OUString("StarBASIC") ), bDocBasic( bIsDocBasic )
{
    SetParent( p );
    pLibInfo = nullptr;
    bNoRtl = bBreak = false;
    bVBAEnabled = false;
    if( !GetSbData()->nInst++ )
    {
        GetSbData()->pSbFac = new SbiFactory;
        AddFactory( GetSbData()->pSbFac );
        GetSbData()->pTypeFac = new SbTypeFactory;
        AddFactory( GetSbData()->pTypeFac );
        GetSbData()->pClassFac = new SbClassFactory;
        AddFactory( GetSbData()->pClassFac );
        GetSbData()->pOLEFac = new SbOLEFactory;
        AddFactory( GetSbData()->pOLEFac );
        GetSbData()->pFormFac = new SbFormFactory;
        AddFactory( GetSbData()->pFormFac );
        GetSbData()->pUnoFac = new SbUnoFactory;
        AddFactory( GetSbData()->pUnoFac );
    }
    pRtl = new SbiStdObject(OUString(RTLNAME), this );
    // Search via StarBasic is always global
    SetFlag( SbxFlagBits::GlobalSearch );
    pVBAGlobals = nullptr;
    bQuit = false;
    if( bDocBasic )
    {
        lclInsertDocBasicItem( *this );
    }
}
// #51727 Override SetModified so that the modified state
// is not given to the parent
void StarBASIC::SetModified( bool b )
{
    SbxBase::SetModified( b );
}
StarBASIC::~StarBASIC()
{
    // Needs to be first action as it can trigger events
    disposeComVariablesForBasic( this );
    if( !--GetSbData()->nInst )
    {
        RemoveFactory( GetSbData()->pSbFac );
        delete GetSbData()->pSbFac; GetSbData()->pSbFac = nullptr;
        RemoveFactory( GetSbData()->pUnoFac );
        delete GetSbData()->pUnoFac; GetSbData()->pUnoFac = nullptr;
        RemoveFactory( GetSbData()->pTypeFac );
        delete GetSbData()->pTypeFac; GetSbData()->pTypeFac = nullptr;
        RemoveFactory( GetSbData()->pClassFac );
        delete GetSbData()->pClassFac; GetSbData()->pClassFac = nullptr;
        RemoveFactory( GetSbData()->pOLEFac );
        delete GetSbData()->pOLEFac; GetSbData()->pOLEFac = nullptr;
        RemoveFactory( GetSbData()->pFormFac );
        delete GetSbData()->pFormFac; GetSbData()->pFormFac = nullptr;
        if( SbiGlobals::pGlobals )
        {
            delete SbiGlobals::pGlobals;
            SbiGlobals::pGlobals = nullptr;
        }
    }
    else if( bDocBasic )
    {
        SbxError eOld = SbxBase::GetError();
        lclRemoveDocBasicItem( *this );
        SbxBase::ResetError();
        if( eOld != ERRCODE_SBX_OK )
        {
            SbxBase::SetError( eOld );
        }
    }
    // #100326 Set Parent NULL in registered listeners
    if( xUnoListeners.Is() )
    {
        sal_uInt16 uCount = xUnoListeners->Count();
        for( sal_uInt16 i = 0 ; i < uCount ; i++ )
        {
            SbxVariable* pListenerObj = xUnoListeners->Get( i );
            pListenerObj->SetParent( nullptr );
        }
        xUnoListeners = nullptr;
    }
    clearUnoMethodsForBasic( this );
}
void StarBASIC::implClearDependingVarsOnDelete( StarBASIC* pDeletedBasic )
{
    if( this != pDeletedBasic )
    {
        for( const auto& pModule: pModules)
        {
            pModule->ClearVarsDependingOnDeletedBasic( pDeletedBasic );
        }
    }
    for( sal_uInt16 nObj = 0; nObj < pObjs->Count(); nObj++ )
    {
        SbxVariable* pVar = pObjs->Get( nObj );
        StarBASIC* pBasic = dynamic_cast<StarBASIC*>( pVar );
        if( pBasic && pBasic != pDeletedBasic )
        {
            pBasic->implClearDependingVarsOnDelete( pDeletedBasic );
        }
    }
}
/**************************************************************************
*
*    Creation/Management of modules
*
**************************************************************************/
SbModule* StarBASIC::MakeModule( const OUString& rName, const OUString& rSrc )
{
    ModuleInfo aInfo;
    aInfo.ModuleType = ModuleType::NORMAL;
    return MakeModule(  rName, aInfo, rSrc );
}
SbModule* StarBASIC::MakeModule( const OUString& rName, const ModuleInfo& mInfo, const OUString& rSrc )
{
    SAL_INFO(
        "basic",
        "create module " << rName  << " type mInfo " << mInfo.ModuleType);
    SbModule* p = nullptr;
    switch ( mInfo.ModuleType )
    {
    case ModuleType::DOCUMENT:
        // In theory we should be able to create Object modules
        // in ordinary basic ( in vba mode thought these are create
        // by the application/basic and not by the user )
        p = new SbObjModule( rName, mInfo, isVBAEnabled() );
        break;
    case ModuleType::CLASS:
        p = new SbModule( rName, isVBAEnabled() );
        p->SetModuleType( ModuleType::CLASS );
        break;
    case ModuleType::FORM:
        p = new SbUserFormModule( rName, mInfo, isVBAEnabled() );
        break;
    default:
        p = new SbModule( rName, isVBAEnabled() );
        break;
    }
    p->SetSource32( rSrc );
    p->SetParent( this );
    pModules.push_back(p);
    SetModified( true );
    return p;
}
void StarBASIC::Insert( SbxVariable* pVar )
{
    if( dynamic_cast<const SbModule*>(pVar) != nullptr)
    {
        pModules.push_back(static_cast<SbModule*>(pVar));
        pVar->SetParent( this );
        StartListening( pVar->GetBroadcaster(), true );
    }
    else
    {
        bool bWasModified = IsModified();
        SbxObject::Insert( pVar );
        if( !bWasModified && pVar->IsSet( SbxFlagBits::DontStore ) )
        {
            SetModified( false );
        }
    }
}
void StarBASIC::Remove( SbxVariable* pVar )
{
    if( dynamic_cast<const SbModule*>(pVar) != nullptr)
    {
        // #87540 Can be last reference!
        SbxVariableRef xVar = pVar;
        pModules.erase(std::remove(pModules.begin(), pModules.end(), pVar));
        pVar->SetParent( nullptr );
        EndListening( pVar->GetBroadcaster() );
    }
    else
    {
        SbxObject::Remove( pVar );
    }
}
void StarBASIC::Clear()
{
    pModules.clear();
}
SbModule* StarBASIC::FindModule( const OUString& rName )
{
    for (const auto& pModule: pModules)
    {
        if( pModule->GetName().equalsIgnoreAsciiCase( rName ) )
        {
            return pModule.get();
        }
    }
    return nullptr;
}
struct ClassModuleRunInitItem
{
    SbModule*       m_pModule;
    bool            m_bProcessing;
    bool            m_bRunInitDone;
    ClassModuleRunInitItem()
        : m_pModule( nullptr )
        , m_bProcessing( false )
        , m_bRunInitDone( false )
    {}
    explicit ClassModuleRunInitItem( SbModule* pModule )
        : m_pModule( pModule )
        , m_bProcessing( false )
        , m_bRunInitDone( false )
    {}
};
// Derive from unordered_map type instead of typedef
// to allow forward declaration in sbmod.hxx
class ModuleInitDependencyMap : public
    std::unordered_map< OUString, ClassModuleRunInitItem,
                          OUStringHash >
{};
void SbModule::implProcessModuleRunInit( ModuleInitDependencyMap& rMap, ClassModuleRunInitItem& rItem )
{
    rItem.m_bProcessing = true;
    SbModule* pModule = rItem.m_pModule;
    if( pModule->pClassData != nullptr )
    {
        StringVector& rReqTypes = pModule->pClassData->maRequiredTypes;
        if( rReqTypes.size() > 0 )
        {
            for( const auto& rStr : rReqTypes )
            {
                // Is required type a class module?
                ModuleInitDependencyMap::iterator itFind = rMap.find( rStr );
                if( itFind != rMap.end() )
                {
                    ClassModuleRunInitItem& rParentItem = itFind->second;
                    if( rParentItem.m_bProcessing )
                    {
                        // TODO: raise error?
                        OSL_FAIL( "Cyclic module dependency detected" );
                        continue;
                    }
                    if( !rParentItem.m_bRunInitDone )
                    {
                        implProcessModuleRunInit( rMap, rParentItem );
                    }
                }
            }
        }
    }
    pModule->RunInit();
    rItem.m_bRunInitDone = true;
    rItem.m_bProcessing = false;
}
// Run Init-Code of all modules (including inserted libraries)
void StarBASIC::InitAllModules( StarBASIC* pBasicNotToInit )
{
    SolarMutexGuard guard;
    // Init own modules
    for (const auto& pModule: pModules)
    {
        pModule->Compile();
    }
    // compile modules first then RunInit ( otherwise there is
    // can be order dependency, e.g. classmodule A has a member
    // of type classmodule B and classmodule B hasn't been compiled yet )
    // Consider required types to init in right order. Class modules
    // that are required by other modules have to be initialized first.
    ModuleInitDependencyMap aMIDMap;
    for (const auto& pModule: pModules)
    {
        OUString aModuleName = pModule->GetName();
        if( pModule->isProxyModule() )
        {
            aMIDMap[aModuleName] = ClassModuleRunInitItem( pModule.get() );
        }
    }
    ModuleInitDependencyMap::iterator it;
    for( it = aMIDMap.begin() ; it != aMIDMap.end(); ++it )
    {
        ClassModuleRunInitItem& rItem = it->second;
        SbModule::implProcessModuleRunInit( aMIDMap, rItem );
    }
    // Call RunInit on standard modules
    for (const auto& pModule: pModules)
    {
        if( !pModule->isProxyModule() )
        {
            pModule->RunInit();
        }
    }
    // Check all objects if they are BASIC,
    // if yes initialize
    for ( sal_uInt16 nObj = 0; nObj < pObjs->Count(); nObj++ )
    {
        SbxVariable* pVar = pObjs->Get( nObj );
        StarBASIC* pBasic = dynamic_cast<StarBASIC*>( pVar );
        if( pBasic && pBasic != pBasicNotToInit )
        {
            pBasic->InitAllModules();
        }
    }
}
// #88329 Put modules back to not initialised state to
// force reinitialisation at next start
void StarBASIC::DeInitAllModules()
{
    // Deinit own modules
    for (const auto& pModule: pModules)
    {
        if( pModule->pImage && !pModule->isProxyModule() && nullptr == dynamic_cast<SbObjModule*>( pModule.get()) )
        {
            pModule->pImage->bInit = false;
        }
    }
    for ( sal_uInt16 nObj = 0; nObj < pObjs->Count(); nObj++ )
    {
        SbxVariable* pVar = pObjs->Get( nObj );
        StarBASIC* pBasic = dynamic_cast<StarBASIC*>( pVar );
        if( pBasic )
        {
            pBasic->DeInitAllModules();
        }
    }
}
// This implementation at first searches within the runtime library,
// then it looks for an element within one module. This module can be
// a public var or an entrypoint. If it is not found and we look for a
// method and a module with the given name is found the search continues
// for entrypoint "Main".
// If this fails again a conventional search over objects is performend.
SbxVariable* StarBASIC::Find( const OUString& rName, SbxClassType t )
{
    SbxVariable* pRes = nullptr;
    SbModule* pNamed = nullptr;
    // "Extended" search in Runtime Lib
    // but only if SbiRuntime has not set the flag
    if( !bNoRtl )
    {
        if( t == SbxClassType::DontCare || t == SbxClassType::Object )
        {
            if( rName.equalsIgnoreAsciiCase( RTLNAME ) )
            {
                pRes = pRtl;
            }
        }
        if( !pRes )
        {
            pRes = static_cast<SbiStdObject*>(static_cast<SbxObject*>(pRtl))->Find( rName, t );
        }
        if( pRes )
        {
            pRes->SetFlag( SbxFlagBits::ExtFound );
        }
    }
    // Search module
    if( !pRes )
    {
        for (const auto& pModule: pModules)
        {
            if( pModule->IsVisible() )
            {
                // Remember modul fpr Main() call
                // or is the name equal?!?
                if( pModule->GetName().equalsIgnoreAsciiCase( rName ) )
                {
                    if( t == SbxClassType::Object || t == SbxClassType::DontCare )
                    {
                        pRes = pModule.get(); break;
                    }
                    pNamed = pModule.get();
                }
                // Only variables qualified by the Module Name e.g. Sheet1.foo
                // should work for Document && Class type Modules
                sal_Int32 nType = pModule->GetModuleType();
                if ( nType == ModuleType::DOCUMENT || nType == ModuleType::FORM )
                {
                    continue;
                }
                // otherwise check if the element is available
                // unset GBLSEARCH-Flag (due to Rekursion)
                SbxFlagBits nGblFlag = pModule->GetFlags() & SbxFlagBits::GlobalSearch;
                pModule->ResetFlag( SbxFlagBits::GlobalSearch );
                pRes = pModule->Find( rName, t );
                pModule->SetFlag( nGblFlag );
                if( pRes )
                {
                    break;
                }
            }
        }
    }
    OUString aMainStr("Main");
    if( !pRes && pNamed && ( t == SbxClassType::Method || t == SbxClassType::DontCare ) &&
        !pNamed->GetName().equalsIgnoreAsciiCase( aMainStr ) )
    {
        pRes = pNamed->Find( aMainStr, SbxClassType::Method );
    }
    if( !pRes )
    {
        pRes = SbxObject::Find( rName, t );
    }
    return pRes;
}
bool StarBASIC::Call( const OUString& rName, SbxArray* pParam )
{
    bool bRes = SbxObject::Call( rName, pParam );
    if( !bRes )
    {
        SbxError eErr = SbxBase::GetError();
        SbxBase::ResetError();
        if( eErr != ERRCODE_SBX_OK )
        {
            RTError( (SbError)eErr, 0, 0, 0 );
        }
    }
    return bRes;
}
// Find method via name (e.g. query via BASIC IDE)
SbxBase* StarBASIC::FindSBXInCurrentScope( const OUString& rName )
{
    if( !GetSbData()->pInst )
    {
        return nullptr;
    }
    if( !GetSbData()->pInst->pRun )
    {
        return nullptr;
    }
    return GetSbData()->pInst->pRun->FindElementExtern( rName );
}
void StarBASIC::QuitAndExitApplication()
{
    Stop();
    bQuit = true;
}
void StarBASIC::Stop()
{
    SbiInstance* p = GetSbData()->pInst;
    while( p )
    {
        p->Stop();
        p = p->pNext;
    }
}
bool StarBASIC::IsRunning()
{
    return GetSbData()->pInst != nullptr;
}
/**************************************************************************
*
*    Debugging and error handling
*
**************************************************************************/
SbMethod* StarBASIC::GetActiveMethod( sal_uInt16 nLevel )
{
    if( GetSbData()->pInst )
    {
        return GetSbData()->pInst->GetCaller( nLevel );
    }
    else
    {
        return nullptr;
    }
}
SbModule* StarBASIC::GetActiveModule()
{
    if( GetSbData()->pInst && !IsCompilerError() )
    {
        return GetSbData()->pInst->GetActiveModule();
    }
    else
    {
        return GetSbData()->pCompMod;
    }
}
sal_uInt16 StarBASIC::BreakPoint( sal_Int32 l, sal_Int32 c1, sal_Int32 c2 )
{
    SetErrorData( 0, l, c1, c2 );
    bBreak = true;
    if( GetSbData()->aBreakHdl.IsSet() )
    {
        return GetSbData()->aBreakHdl.Call( this );
    }
    else
    {
        return BreakHdl();
    }
}
sal_uInt16 StarBASIC::StepPoint( sal_Int32 l, sal_Int32 c1, sal_Int32 c2 )
{
    SetErrorData( 0, l, c1, c2 );
    bBreak = false;
    if( GetSbData()->aBreakHdl.IsSet() )
    {
        return GetSbData()->aBreakHdl.Call( this );
    }
    else
    {
        return BreakHdl();
    }
}
sal_uInt16 StarBASIC::BreakHdl()
{
    return aBreakHdl.IsSet() ? aBreakHdl.Call( this ) : SbDEBUG_CONTINUE;
}
// Calls for error handler and break handler
sal_uInt16 StarBASIC::GetLine()     { return GetSbData()->nLine; }
sal_uInt16 StarBASIC::GetCol1()     { return GetSbData()->nCol1; }
sal_uInt16 StarBASIC::GetCol2()     { return GetSbData()->nCol2; }
// Specific to error handler
SbError StarBASIC::GetErrorCode()       { return GetSbData()->nCode; }
const OUString& StarBASIC::GetErrorText() { return GetSbData()->aErrMsg; }
bool StarBASIC::IsCompilerError()       { return GetSbData()->bCompiler; }
// From 1996-03-29:
// The mapping between the old and the new error codes take place by searching
// through the table SFX_VB_ErrorTab[]. This is indeed not with good performance,
// but it consumes much less memory than corresponding switch blocs.
// Because the conversion of error codes has not to be fast. there is no
// binary search by VB Error -> Error SFX.
// Map back new error codes to old, Sbx-compatible
sal_uInt16 StarBASIC::GetVBErrorCode( SbError nError )
{
    sal_uInt16 nRet = 0;
    if( SbiRuntime::isVBAEnabled() )
    {
        switch( nError )
        {
        case ERRCODE_BASIC_ARRAY_FIX:
            return 10;
        case ERRCODE_BASIC_STRING_OVERFLOW:
            return 14;
        case ERRCODE_BASIC_EXPR_TOO_COMPLEX:
            return 16;
        case ERRCODE_BASIC_OPER_NOT_PERFORM:
            return 17;
        case ERRCODE_BASIC_TOO_MANY_DLL:
            return 47;
        case ERRCODE_BASIC_LOOP_NOT_INIT:
            return 92;
        default:
            nRet = 0;
        }
    }
    // search loop
    const SFX_VB_ErrorItem* pErrItem;
    sal_uInt16 nIndex = 0;
    do
    {
        pErrItem = SFX_VB_ErrorTab + nIndex;
        if( pErrItem->nErrorSFX == nError )
        {
            nRet = pErrItem->nErrorVB;
            break;
        }
        nIndex++;
    }
    while( pErrItem->nErrorVB != 0xFFFF );      // up to end mark
    return nRet;
}
SbError StarBASIC::GetSfxFromVBError( sal_uInt16 nError )
{
    SbError nRet = 0L;
    if( SbiRuntime::isVBAEnabled() )
    {
        switch( nError )
        {
        case 1:
        case 2:
        case 4:
        case 8:
        case 12:
        case 73:
            return 0L;
        case 10:
            return ERRCODE_BASIC_ARRAY_FIX;
        case 14:
            return ERRCODE_BASIC_STRING_OVERFLOW;
        case 16:
            return ERRCODE_BASIC_EXPR_TOO_COMPLEX;
        case 17:
            return ERRCODE_BASIC_OPER_NOT_PERFORM;
        case 47:
            return ERRCODE_BASIC_TOO_MANY_DLL;
        case 92:
            return ERRCODE_BASIC_LOOP_NOT_INIT;
        default:
            nRet = 0L;
        }
    }
    const SFX_VB_ErrorItem* pErrItem;
    sal_uInt16 nIndex = 0;
    do
    {
        pErrItem = SFX_VB_ErrorTab + nIndex;
        if( pErrItem->nErrorVB == nError )
        {
            nRet = pErrItem->nErrorSFX;
            break;
        }
        else if( pErrItem->nErrorVB > nError )
        {
            break;              // couldn't found anymore
        }
        nIndex++;
    }
    while( pErrItem->nErrorVB != 0xFFFF );      // up to end mark
    return nRet;
}
// set Error- / Break-data
void StarBASIC::SetErrorData( SbError nCode, sal_uInt16 nLine,
                              sal_uInt16 nCol1, sal_uInt16 nCol2 )
{
    SbiGlobals& aGlobals = *GetSbData();
    aGlobals.nCode = nCode;
    aGlobals.nLine = nLine;
    aGlobals.nCol1 = nCol1;
    aGlobals.nCol2 = nCol2;
}
// help class for access to string SubResource of a Resource.
// Source: sfx2\source\doc\docfile.cxx (TLX)
struct BasicStringList_Impl : private Resource
{
    ResId aResId;
    BasicStringList_Impl( ResId& rErrIdP,  sal_uInt16 nId)
        : Resource( rErrIdP ),aResId(nId, *rErrIdP.GetResMgr() ){}
    ~BasicStringList_Impl() { FreeResource(); }
    OUString GetString(){ return aResId.toString(); }
    bool IsErrorTextAvailable()
        { return IsAvailableRes(aResId.SetRT(RSC_STRING)); }
};
void StarBASIC::MakeErrorText( SbError nId, const OUString& aMsg )
{
    SolarMutexGuard aSolarGuard;
    sal_uInt16 nOldID = GetVBErrorCode( nId );
    // instantiate the help class
    BasResId aId( RID_BASIC_START );
    BasicStringList_Impl aMyStringList( aId, sal_uInt16(nId & ERRCODE_RES_MASK) );
    if( aMyStringList.IsErrorTextAvailable() )
    {
        // merge message with additional text
        OUStringBuffer aMsg1(aMyStringList.GetString());
        // replace argument placeholder with %s
        OUString aSrgStr( "$(ARG1)" );
        sal_Int32 nResult = aMyStringList.GetString().indexOf( aSrgStr );
        if( nResult >= 0 )
        {
            aMsg1.remove(nResult, aSrgStr.getLength());
            aMsg1.insert(nResult, aMsg);
        }
        GetSbData()->aErrMsg = aMsg1.makeStringAndClear();
    }
    else if( nOldID != 0 )
    {
        OUString aStdMsg = "Fehler " + OUString::number(nOldID) +
                           ": Kein Fehlertext verfuegbar!";
        GetSbData()->aErrMsg = aStdMsg;
    }
    else
    {
        GetSbData()->aErrMsg.clear();
    }
}
bool StarBASIC::CError( SbError code, const OUString& rMsg,
                            sal_Int32 l, sal_Int32 c1, sal_Int32 c2 )
{
    SolarMutexGuard aSolarGuard;
    // compiler error during runtime -> stop programm
    if( IsRunning() )
    {
        // #109018 Check if running Basic is affected
        StarBASIC* pStartedBasic = GetSbData()->pInst->GetBasic();
        if( pStartedBasic != this )
        {
            return false;
        }
        Stop();
    }
    // set flag, so that GlobalRunInit notice the error
    GetSbData()->bGlobalInitErr = true;
    // tinker the error message
    MakeErrorText( code, rMsg );
    // Implementation of the code for the string transport to SFX-Error
    if( !rMsg.isEmpty() )
    {
        code = (SbError)*new StringErrorInfo( code, rMsg );
    }
    SetErrorData( code, l, c1, c2 );
    GetSbData()->bCompiler = true;
    bool bRet;
    if( GetSbData()->aErrHdl.IsSet() )
    {
        bRet = GetSbData()->aErrHdl.Call( this );
    }
    else
    {
        bRet = ErrorHdl();
    }
    GetSbData()->bCompiler = false;     // only true for error handler
    return bRet;
}
void StarBASIC::RTError( SbError code, sal_Int32 l, sal_Int32 c1, sal_Int32 c2 )
{
    RTError( code, OUString(), l, c1, c2 );
}
bool StarBASIC::RTError( SbError code, const OUString& rMsg, sal_Int32 l, sal_Int32 c1, sal_Int32 c2 )
{
    SolarMutexGuard aSolarGuard;
    SbError c = code;
    if( (c & ERRCODE_CLASS_MASK) == ERRCODE_CLASS_COMPILER )
    {
        c = 0;
    }
    MakeErrorText( c, rMsg );
    // Implementation of the code for the string transport to SFX-Error
    if( !rMsg.isEmpty() )
    {
        // very confusing, even though MakeErrorText sets up the error text
        // seems that this is not used ( if rMsg already has content )
        // In the case of VBA MakeErrorText also formats the error to be a little more
        // like vba ( adds an error number etc )
        if ( SbiRuntime::isVBAEnabled() && ( code == ERRCODE_BASIC_COMPAT ) )
        {
            OUString aTmp = "\'" + OUString::number(SbxErrObject::getUnoErrObject()->getNumber()) +
                            "\'\n" + OUString(!GetSbData()->aErrMsg.isEmpty() ? GetSbData()->aErrMsg : rMsg);
            code = (SbError)*new StringErrorInfo( code, aTmp );
        }
        else
        {
            code = (SbError)*new StringErrorInfo( code, rMsg );
        }
    }
    SetErrorData( code, l, c1, c2 );
    if( GetSbData()->aErrHdl.IsSet() )
    {
        return GetSbData()->aErrHdl.Call( this );
    }
    else
    {
        return ErrorHdl();
    }
}
void StarBASIC::Error( SbError n )
{
    Error( n, OUString() );
}
void StarBASIC::Error( SbError n, const OUString& rMsg )
{
    if( GetSbData()->pInst )
    {
        GetSbData()->pInst->Error( n, rMsg );
    }
}
void StarBASIC::FatalError( SbError n )
{
    if( GetSbData()->pInst )
    {
        GetSbData()->pInst->FatalError( n );
    }
}
void StarBASIC::FatalError( SbError _errCode, const OUString& _details )
{
    if( GetSbData()->pInst )
    {
        GetSbData()->pInst->FatalError( _errCode, _details );
    }
}
SbError StarBASIC::GetErrBasic()
{
    if( GetSbData()->pInst )
    {
        return GetSbData()->pInst->GetErr();
    }
    else
    {
        return 0;
    }
}
// make the additional message for the RTL function error accessible
OUString StarBASIC::GetErrorMsg()
{
    if( GetSbData()->pInst )
    {
        return GetSbData()->pInst->GetErrorMsg();
    }
    else
    {
        return OUString();
    }
}
sal_Int32 StarBASIC::GetErl()
{
    if( GetSbData()->pInst )
    {
        return GetSbData()->pInst->GetErl();
    }
    else
    {
        return 0;
    }
}
bool StarBASIC::ErrorHdl()
{
    return aErrorHdl.Call( this );
}
Link<StarBASIC*,bool> StarBASIC::GetGlobalErrorHdl()
{
    return GetSbData()->aErrHdl;
}
void StarBASIC::SetGlobalErrorHdl( const Link<StarBASIC*,bool>& rLink )
{
    GetSbData()->aErrHdl = rLink;
}
void StarBASIC::SetGlobalBreakHdl( const Link<StarBASIC*,sal_uInt16>& rLink )
{
    GetSbData()->aBreakHdl = rLink;
}
SbxArrayRef StarBASIC::getUnoListeners()
{
    if( !xUnoListeners.Is() )
    {
        xUnoListeners = new SbxArray();
    }
    return xUnoListeners;
}
/**************************************************************************
*
*   load and save
*
**************************************************************************/
bool StarBASIC::LoadData( SvStream& r, sal_uInt16 nVer )
{
    if( !SbxObject::LoadData( r, nVer ) )
    {
        return false;
    }
    // #95459 Delete dialogs, otherwise endless recursion
    // in SbxVarable::GetType() if dialogs are accessed
    sal_uInt16 nObjCount = pObjs->Count();
    std::unique_ptr<SbxVariable*[]> ppDeleteTab(new SbxVariable*[ nObjCount ]);
    sal_uInt16 nObj;
    for( nObj = 0 ; nObj < nObjCount ; nObj++ )
    {
        SbxVariable* pVar = pObjs->Get( nObj );
        StarBASIC* pBasic = dynamic_cast<StarBASIC*>( pVar  );
        ppDeleteTab[nObj] = pBasic ? nullptr : pVar;
    }
    for( nObj = 0 ; nObj < nObjCount ; nObj++ )
    {
        SbxVariable* pVar = ppDeleteTab[nObj];
        if( pVar )
        {
            pObjs->Remove( pVar );
        }
    }
    ppDeleteTab.reset();
    sal_uInt16 nMod(0);
    pModules.clear();
    r.ReadUInt16( nMod );
    const size_t nMinSbxSize(14);
    const size_t nMaxPossibleEntries = r.remainingSize() / nMinSbxSize;
    if (nMod > nMaxPossibleEntries)
    {
        nMod = nMaxPossibleEntries;
        SAL_WARN("basic", "Parsing error: " << nMaxPossibleEntries <<
                 " max possible entries, but " << nMod << " claimed, truncating");
    }
    for (sal_uInt16 i = 0; i < nMod; ++i)
    {
        SbxBase* pBase = SbxBase::Load( r );
        SbModule* pMod = dynamic_cast<SbModule*>(pBase);
        if( !pMod )
        {
            return false;
        }
        else if( nullptr != dynamic_cast<const SbJScriptModule*>( pMod) )
        {
            // assign Ref, so that pMod will be deleted
            SbModuleRef xRef = pMod;
        }
        else
        {
            pMod->SetParent( this );
            pModules.push_back( pMod );
        }
    }
    // HACK for SFX-Bullshit!
    SbxVariable* p = Find( "FALSE", SbxClassType::Property );
    if( p )
    {
        Remove( p );
    }
    p = Find( "TRUE", SbxClassType::Property );
    if( p )
    {
        Remove( p );
    }
    // End of the hacks!
    // Search via StarBASIC is at all times global
    DBG_ASSERT( IsSet( SbxFlagBits::GlobalSearch ), "Basic loaded without GBLSEARCH" );
    SetFlag( SbxFlagBits::GlobalSearch );
    return true;
}
bool StarBASIC::StoreData( SvStream& r ) const
{
    if( !SbxObject::StoreData( r ) )
    {
        return false;
    }
    assert(pModules.size() < SAL_MAX_UINT16);
    r.WriteUInt16( static_cast<sal_uInt16>(pModules.size()));
    for( const auto& rpModule: pModules )
    {
        if( !rpModule->Store( r ) )
        {
            return false;
        }
    }
    return true;
}
bool StarBASIC::GetUNOConstant( const OUString& rName, css::uno::Any& aOut )
{
    bool bRes = false;
    SbUnoObject* pGlobs = dynamic_cast<SbUnoObject*>( Find( rName, SbxClassType::DontCare ) );
    if ( pGlobs )
    {
        aOut = pGlobs->getUnoAny();
        bRes = true;
    }
    return bRes;
}
Reference< frame::XModel > StarBASIC::GetModelFromBasic( SbxObject* pBasic )
{
    OSL_PRECOND( pBasic != nullptr, "getModelFromBasic: illegal call!" );
    if ( !pBasic )
    {
        return nullptr;
    }
    // look for the ThisComponent variable, first in the parent (which
    // might be the document's Basic), then in the parent's parent (which might be
    // the application Basic)
    const OUString sThisComponent( "ThisComponent");
    SbxVariable* pThisComponent = nullptr;
    SbxObject* pLookup = pBasic->GetParent();
    while ( pLookup && !pThisComponent )
    {
        pThisComponent = pLookup->Find( sThisComponent, SbxClassType::Object );
        pLookup = pLookup->GetParent();
    }
    if ( !pThisComponent )
    {
        OSL_TRACE("Failed to get ThisComponent");
            // the application Basic, at the latest, should have this variable
        return nullptr;
    }
    Any aThisComponentAny( sbxToUnoValue( pThisComponent ) );
    Reference< frame::XModel > xModel( aThisComponentAny, UNO_QUERY );
    if ( !xModel.is() )
    {
        // it's no XModel. Okay, ThisComponent nowadays is allowed to be a controller.
        Reference< frame::XController > xController( aThisComponentAny, UNO_QUERY );
        if ( xController.is() )
        {
            xModel = xController->getModel();
        }
    }
    if ( !xModel.is() )
    {
        return nullptr;
    }
#if OSL_DEBUG_LEVEL > 0
    OSL_TRACE("Have model ThisComponent points to url %s",
              OUStringToOString( xModel->getURL(),
                                 RTL_TEXTENCODING_ASCII_US ).pData->buffer );
#endif
    return xModel;
}
void StarBASIC::DetachAllDocBasicItems()
{
    DocBasicItemMap& rItems = GaDocBasicItems::get();
    DocBasicItemMap::iterator it = rItems.begin(), itEnd = rItems.end();
    for (; it != itEnd; ++it)
    {
        DocBasicItemRef xItem = it->second;
        xItem->setDisposed(true);
    }
}
// #118116 Implementation Collection object
static const char pCountStr[]   = "Count";
static const char pAddStr[]     = "Add";
static const char pItemStr[]    = "Item";
static const char pRemoveStr[]  = "Remove";
static sal_uInt16 nCountHash = 0, nAddHash, nItemHash, nRemoveHash;
SbxInfoRef BasicCollection::xAddInfo = nullptr;
SbxInfoRef BasicCollection::xItemInfo = nullptr;
BasicCollection::BasicCollection( const OUString& rClass )
             : SbxObject( rClass )
{
    if( !nCountHash )
    {
        nCountHash  = MakeHashCode( pCountStr );
        nAddHash    = MakeHashCode( pAddStr );
        nItemHash   = MakeHashCode( pItemStr );
        nRemoveHash = MakeHashCode( pRemoveStr );
    }
    Initialize();
}
BasicCollection::~BasicCollection()
{}
void BasicCollection::Clear()
{
    SbxObject::Clear();
    Initialize();
}
void BasicCollection::Initialize()
{
    xItemArray = new SbxArray();
    SetType( SbxOBJECT );
    SetFlag( SbxFlagBits::Fixed );
    ResetFlag( SbxFlagBits::Write );
    SbxVariable* p;
    p = Make( pCountStr, SbxClassType::Property, SbxINTEGER );
    p->ResetFlag( SbxFlagBits::Write );
    p->SetFlag( SbxFlagBits::DontStore );
    p = Make( pAddStr, SbxClassType::Method, SbxEMPTY );
    p->SetFlag( SbxFlagBits::DontStore );
    p = Make( pItemStr, SbxClassType::Method, SbxVARIANT );
    p->SetFlag( SbxFlagBits::DontStore );
    p = Make( pRemoveStr, SbxClassType::Method, SbxEMPTY );
    p->SetFlag( SbxFlagBits::DontStore );
    if ( !xAddInfo.Is() )
    {
        xAddInfo = new SbxInfo;
        xAddInfo->AddParam(  "Item", SbxVARIANT );
        xAddInfo->AddParam(  "Key", SbxVARIANT, SbxFlagBits::Read | SbxFlagBits::Optional );
        xAddInfo->AddParam(  "Before", SbxVARIANT, SbxFlagBits::Read | SbxFlagBits::Optional );
        xAddInfo->AddParam(  "After", SbxVARIANT, SbxFlagBits::Read | SbxFlagBits::Optional );
    }
    if ( !xItemInfo.Is() )
    {
        xItemInfo = new SbxInfo;
        xItemInfo->AddParam(  "Index", SbxVARIANT, SbxFlagBits::Read | SbxFlagBits::Optional);
    }
}
void BasicCollection::Notify( SfxBroadcaster& rCst, const SfxHint& rHint )
{
    const SbxHint* p = dynamic_cast<const SbxHint*>(&rHint);
    if( p )
    {
        const sal_uInt32 nId = p->GetId();
        bool bRead  = nId == SBX_HINT_DATAWANTED;
        bool bWrite = nId == SBX_HINT_DATACHANGED;
        bool bRequestInfo = nId == SBX_HINT_INFOWANTED;
        SbxVariable* pVar = p->GetVar();
        SbxArray* pArg = pVar->GetParameters();
        OUString aVarName( pVar->GetName() );
        if( bRead || bWrite )
        {
            if( pVar->GetHashCode() == nCountHash
                  && aVarName.equalsIgnoreAsciiCase( pCountStr ) )
            {
                pVar->PutLong( xItemArray->Count32() );
            }
            else if( pVar->GetHashCode() == nAddHash
                  && aVarName.equalsIgnoreAsciiCase( pAddStr ) )
            {
                CollAdd( pArg );
            }
            else if( pVar->GetHashCode() == nItemHash
                  && aVarName.equalsIgnoreAsciiCase( pItemStr ) )
            {
                CollItem( pArg );
            }
            else if( pVar->GetHashCode() == nRemoveHash
                  && aVarName.equalsIgnoreAsciiCase( pRemoveStr ) )
            {
                CollRemove( pArg );
            }
            else
            {
                SbxObject::Notify( rCst, rHint );
            }
            return;
        }
        else if ( bRequestInfo )
        {
            if( pVar->GetHashCode() == nAddHash
                  && aVarName.equalsIgnoreAsciiCase( pAddStr ) )
            {
                pVar->SetInfo( xAddInfo );
            }
            else if( pVar->GetHashCode() == nItemHash
                  && aVarName.equalsIgnoreAsciiCase( pItemStr ) )
            {
                pVar->SetInfo( xItemInfo );
            }
        }
    }
    SbxObject::Notify( rCst, rHint );
}
sal_Int32 BasicCollection::implGetIndex( SbxVariable* pIndexVar )
{
    sal_Int32 nIndex = -1;
    if( pIndexVar->GetType() == SbxSTRING )
    {
        nIndex = implGetIndexForName( pIndexVar->GetOUString() );
    }
    else
    {
        nIndex = pIndexVar->GetLong() - 1;
    }
    return nIndex;
}
sal_Int32 BasicCollection::implGetIndexForName( const OUString& rName )
{
    sal_Int32 nIndex = -1;
    sal_Int32 nCount = xItemArray->Count32();
    sal_Int32 nNameHash = MakeHashCode( rName );
    for( sal_Int32 i = 0 ; i < nCount ; i++ )
    {
        SbxVariable* pVar = xItemArray->Get32( i );
        if( pVar->GetHashCode() == nNameHash &&
            pVar->GetName().equalsIgnoreAsciiCase( rName ) )
        {
            nIndex = i;
            break;
        }
    }
    return nIndex;
}
void BasicCollection::CollAdd( SbxArray* pPar_ )
{
    sal_uInt16 nCount = pPar_->Count();
    if( nCount < 2 || nCount > 5 )
    {
        SetError( ERRCODE_SBX_WRONG_ARGS );
        return;
    }
    SbxVariable* pItem = pPar_->Get(1);
    if( pItem )
    {
        int nNextIndex;
        if( nCount < 4 )
        {
            nNextIndex = xItemArray->Count();
        }
        else
        {
            SbxVariable* pBefore = pPar_->Get(3);
            if( nCount == 5 )
            {
                if( !( pBefore->IsErr() || ( pBefore->GetType() == SbxEMPTY ) ) )
                {
                    SetError( ERRCODE_BASIC_BAD_ARGUMENT );
                    return;
                }
                SbxVariable* pAfter = pPar_->Get(4);
                sal_Int32 nAfterIndex = implGetIndex( pAfter );
                if( nAfterIndex == -1 )
                {
                    SetError( ERRCODE_BASIC_BAD_ARGUMENT );
                    return;
                }
                nNextIndex = nAfterIndex + 1;
            }
            else // if( nCount == 4 )
            {
                sal_Int32 nBeforeIndex = implGetIndex( pBefore );
                if( nBeforeIndex == -1 )
                {
                    SetError( ERRCODE_BASIC_BAD_ARGUMENT );
                    return;
                }
                nNextIndex = nBeforeIndex;
            }
        }
        auto pNewItem = tools::make_ref<SbxVariable>( *pItem );
        if( nCount >= 3 )
        {
            SbxVariable* pKey = pPar_->Get(2);
            if( !( pKey->IsErr() || ( pKey->GetType() == SbxEMPTY ) ) )
            {
                if( pKey->GetType() != SbxSTRING )
                {
                    SetError( ERRCODE_BASIC_BAD_ARGUMENT );
                    return;
                }
                OUString aKey = pKey->GetOUString();
                if( implGetIndexForName( aKey ) != -1 )
                {
                    SetError( ERRCODE_BASIC_BAD_ARGUMENT );
                    return;
                }
                pNewItem->SetName( aKey );
            }
        }
        pNewItem->SetFlag( SbxFlagBits::ReadWrite );
        xItemArray->Insert32( pNewItem, nNextIndex );
    }
    else
    {
        SetError( ERRCODE_BASIC_BAD_ARGUMENT );
        return;
    }
}
void BasicCollection::CollItem( SbxArray* pPar_ )
{
    if( pPar_->Count() != 2 )
    {
        SetError( ERRCODE_SBX_WRONG_ARGS );
        return;
    }
    SbxVariable* pRes = nullptr;
    SbxVariable* p = pPar_->Get( 1 );
    sal_Int32 nIndex = implGetIndex( p );
    if( nIndex >= 0 && nIndex < (sal_Int32)xItemArray->Count32() )
    {
        pRes = xItemArray->Get32( nIndex );
    }
    if( !pRes )
    {
        SetError( ERRCODE_BASIC_BAD_ARGUMENT );
    }
    else
    {
        *(pPar_->Get(0)) = *pRes;
    }
}
void BasicCollection::CollRemove( SbxArray* pPar_ )
{
    if( pPar_ == nullptr || pPar_->Count() != 2 )
    {
        SetError( ERRCODE_SBX_WRONG_ARGS );
        return;
    }
    SbxVariable* p = pPar_->Get( 1 );
    sal_Int32 nIndex = implGetIndex( p );
    if( nIndex >= 0 && nIndex < (sal_Int32)xItemArray->Count32() )
    {
        xItemArray->Remove32( nIndex );
        // Correct for stack if necessary
        SbiInstance* pInst = GetSbData()->pInst;
        SbiRuntime* pRT = pInst ? pInst->pRun : nullptr;
        if( pRT )
        {
            SbiForStack* pStack = pRT->FindForStackItemForCollection( this );
            if( pStack != nullptr )
            {
                if( pStack->nCurCollectionIndex >= nIndex )
                {
                    --pStack->nCurCollectionIndex;
                }
            }
        }
    }
    else
    {
        SetError( ERRCODE_BASIC_BAD_ARGUMENT );
    }
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
 
     |