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 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009
|
#!/usr/bin/env python
#----------------------------------------------------------------------------
# Name: Main.py
# Purpose: Testing lots of stuff, controls, window types, etc.
#
# Author: Robin Dunn
#
# Created: A long time ago, in a galaxy far, far away...
# RCS-ID: $Id$
# Copyright: (c) 1999 by Total Control Software
# Licence: wxWindows license
#----------------------------------------------------------------------------
# FIXME List:
# * Problems with flickering related to ERASE_BACKGROUND
# and the splitters. Might be a problem with this 2.5 beta...?
# UPDATE: can't see on 2.5.2 GTK - maybe just a faster machine :)
# * Demo Code menu?
# * Annoying switching between tabs and resulting flicker
# how to replace a page in the notebook without deleting/adding?
# Where is SetPage!? tried freeze...tried reparent of dummy panel....
# AG: It looks like this issue is fixed by Freeze()ing and Thaw()ing the
# main frame and not the notebook
# TODO List:
# * UI design more professional (is the new version more professional?)
# * save file positions (new field in demoModules) (@ LoadDemoSource)
# * Update main overview
# * Why don't we move _treeList into a separate module
# =====================
# = EXTERNAL Packages =
# =====================
# In order to let a package (like AGW) be included in the wxPython demo,
# the package owner should create a sub-directory of the wxPython demo folder
# in which all the package's demos should live. In addition, the sub-folder
# should contain a Python file called __demo__.py which, when imported, should
# contain the following methods:
#
# * GetDemoBitmap: returns the bitmap to be used in the wxPython demo tree control
# in a PyEmbeddedImage format;
# * GetRecentAdditions: returns a list of demos which will be displayed under the
# "Recent Additions/Updates" tree item. This list should be a subset (or the full
# set) of the package's demos;
# * GetDemos: returns a tuple. The first item of the tuple is the package's name
# as will be displayed in the wxPython demo tree, right after the "Custom Controls"
# item. The second element of the tuple is the list of demos for the external package.
# * GetOverview: returns a wx.html-ready representation of the package's documentation.
#
# Please see the __demo__.py file in the demo/agw/ folder for an example.
# Last updated: Andrea Gavana, 20 Oct 2008, 18.00 GMT
import sys, os, time, traceback, types
import cPickle, cStringIO, re, urllib2
import shutil
from threading import Thread
import wx
import wx.aui
import wx.html
from wx.lib.msgpanel import MessagePanel
import wx.lib.mixins.inspection
import version
# We won't import the images module yet, but we'll assign it to this
# global when we do.
images = None
# For debugging
##wx.Trap();
##print "wx.VERSION_STRING = %s (%s)" % (wx.VERSION_STRING, wx.USE_UNICODE and 'unicode' or 'ansi')
##print "pid:", os.getpid()
##raw_input("Press Enter...")
#---------------------------------------------------------------------------
USE_CUSTOMTREECTRL = False
DEFAULT_PERSPECTIVE = "Default Perspective"
#---------------------------------------------------------------------------
_demoPngs = ["overview", "recent", "frame", "dialog", "moredialog", "core",
"book", "customcontrol", "morecontrols", "layout", "process",
"clipboard", "images", "miscellaneous"]
_treeList = [
# new stuff
('Recent Additions/Updates', [
'PropertyGrid',
'SystemSettings',
'GridLabelRenderer',
'InfoBar',
'WrapSizer',
'UIActionSimulator',
'GraphicsGradient',
'PDFViewer',
'ItemsPicker',
'CommandLinkButton',
'DVC_DataViewModel',
'DVC_IndexListModel',
'DVC_ListCtrl',
'DVC_TreeCtrl',
'DVC_CustomRenderer',
'PenAndBrushStyles',
'HTML2_WebView',
]),
# managed windows == things with a (optional) caption you can close
('Frames and Dialogs', [
'AUI_DockingWindowMgr',
'AUI_MDI',
'Dialog',
'Frame',
'MDIWindows',
'MiniFrame',
'Wizard',
]),
# the common dialogs
('Common Dialogs', [
'AboutBox',
'ColourDialog',
'DirDialog',
'FileDialog',
'FindReplaceDialog',
'FontDialog',
'MessageDialog',
'MultiChoiceDialog',
'PageSetupDialog',
'PrintDialog',
'ProgressDialog',
'SingleChoiceDialog',
'TextEntryDialog',
]),
# dialogs from libraries
('More Dialogs', [
'ImageBrowser',
'ScrolledMessageDialog',
]),
# core controls
('Core Windows/Controls', [
'BitmapButton',
'Button',
'CheckBox',
'CheckListBox',
'Choice',
'ComboBox',
'CommandLinkButton',
'DVC_CustomRenderer',
'DVC_DataViewModel',
'DVC_IndexListModel',
'DVC_ListCtrl',
'DVC_TreeCtrl',
'Gauge',
'Grid',
'Grid_MegaExample',
'GridLabelRenderer',
'ListBox',
'ListCtrl',
'ListCtrl_virtual',
'ListCtrl_edit',
'Menu',
'PopupMenu',
'PopupWindow',
'RadioBox',
'RadioButton',
'SashWindow',
'ScrolledWindow',
'SearchCtrl',
'Slider',
'SpinButton',
'SpinCtrl',
'SpinCtrlDouble',
'SplitterWindow',
'StaticBitmap',
'StaticBox',
'StaticText',
'StatusBar',
'StockButtons',
'TextCtrl',
'ToggleButton',
'ToolBar',
'TreeCtrl',
'Validator',
]),
('"Book" Controls', [
'AUI_Notebook',
'Choicebook',
'FlatNotebook',
'Listbook',
'Notebook',
'Toolbook',
'Treebook',
]),
('Custom Controls', [
'AnalogClock',
'ColourSelect',
'ComboTreeBox',
'Editor',
'GenericButtons',
'GenericDirCtrl',
'ItemsPicker',
'LEDNumberCtrl',
'MultiSash',
'PlateButton',
'PopupControl',
'PyColourChooser',
'TreeListCtrl',
]),
# controls coming from other libraries
('More Windows/Controls', [
'ActiveX_FlashWindow',
'ActiveX_IEHtmlWindow',
'ActiveX_PDFWindow',
'BitmapComboBox',
'Calendar',
'CalendarCtrl',
'CheckListCtrlMixin',
'CollapsiblePane',
'ComboCtrl',
'ContextHelp',
'DatePickerCtrl',
'DynamicSashWindow',
'EditableListBox',
'ExpandoTextCtrl',
'FancyText',
'FileBrowseButton',
'FloatBar',
'FloatCanvas',
'HtmlWindow',
'HTML2_WebView',
'InfoBar',
'IntCtrl',
'MVCTree',
'MaskedEditControls',
'MaskedNumCtrl',
'MediaCtrl',
'MultiSplitterWindow',
'OwnerDrawnComboBox',
'Pickers',
'PropertyGrid',
'PyCrust',
'PyPlot',
'PyShell',
'ResizeWidget',
'RichTextCtrl',
'ScrolledPanel',
'SplitTree',
'StyledTextCtrl_1',
'StyledTextCtrl_2',
'TablePrint',
'Throbber',
'Ticker',
'TimeCtrl',
'TreeMixin',
'VListBox',
]),
# How to lay out the controls in a frame/dialog
('Window Layout', [
'GridBagSizer',
'LayoutAnchors',
'LayoutConstraints',
'Layoutf',
'RowColSizer',
'ScrolledPanel',
'SizedControls',
'Sizers',
'WrapSizer',
'XmlResource',
'XmlResourceHandler',
'XmlResourceSubclass',
]),
# ditto
('Process and Events', [
'DelayedResult',
'EventManager',
'KeyEvents',
'Process',
'PythonEvents',
'Threads',
'Timer',
##'infoframe', # needs better explanation and some fixing
]),
# Clipboard and DnD
('Clipboard and DnD', [
'CustomDragAndDrop',
'DragAndDrop',
'URLDragAndDrop',
]),
# Images
('Using Images', [
'AdjustChannels',
'AlphaDrawing',
'AnimateCtrl',
'ArtProvider',
'BitmapFromBuffer',
'Cursor',
'DragImage',
'Image',
'ImageAlpha',
'ImageFromStream',
'Img2PyArtProvider',
'Mask',
'RawBitmapAccess',
'Throbber',
]),
# Other stuff
('Miscellaneous', [
'AlphaDrawing',
'Cairo',
'Cairo_Snippets',
'ColourDB',
##'DialogUnits', # needs more explanations
'DragScroller',
'DrawXXXList',
'FileHistory',
'FontEnumerator',
'GraphicsContext',
'GraphicsGradient',
'GLCanvas',
'I18N',
'Joystick',
'MimeTypesManager',
'MouseGestures',
'OGL',
'PDFViewer',
'PenAndBrushStyles',
'PrintFramework',
'PseudoDC',
'RendererNative',
'ShapedWindow',
'Sound',
'StandardPaths',
'SystemSettings',
'UIActionSimulator',
'Unicode',
]),
('Check out the samples dir too', [] ),
]
#---------------------------------------------------------------------------
_styleTable = '<h3>Window %s</h3>\n' \
'<p>This class supports the following window %s:\n' \
'<p><table bgcolor=\"#ffffff\" border cols=1>'
_eventTable = '<h3>Events</h3>\n' \
'<p>Events emitted by this class:\n' \
'<p><table bgcolor=\"#ffffff\" border cols=1>'
_appearanceTable = '<h3>Appearance</h3>\n' \
'<p>Control appearance on various platform:\n' \
'<p><table bgcolor=\"#ffffff\" cellspacing=20>'
_styleHeaders = ["Style Name", "Description"]
_eventHeaders = ["Event Name", "Description"]
_headerTable = '<td><b>%s</b></td>'
_styleTag = '<td><tt>%s</tt></td>'
_eventTag = '<td><i>%s</i></td>'
_hexValues = '<td><font color="%s"> %s </font></td>'
_description = '<td>%s</td>'
_imageTag = '<td align=center valign=middle><a href="%s"><img src="%s" alt="%s"></a></td>'
_platformTag = '<td align=center><b>%s</b></td>'
_trunkURL = "http://docs.wxwidgets.org/trunk/"
_docsURL = _trunkURL + "classwx%s.html"
_platformNames = ["wxMSW", "wxGTK", "wxMac"]
_importList = ["wx.aui", "wx.calendar", "wx.html", "wx.media", "wx.wizard",
"wx.combo", "wx.animate", "wx.gizmos", "wx.glcanvas", "wx.grid",
"wx.richtext", "wx.stc"]
_dirWX = dir(wx)
for mod in _importList:
try:
module = __import__(mod)
except ImportError:
continue
#---------------------------------------------------------------------------
def ReplaceCapitals(string):
"""
Replaces the capital letter in a string with an underscore plus the
corresponding lowercase character.
**Parameters:**
* `string`: the string to be analyzed.
"""
newString = ""
for char in string:
if char.isupper():
newString += "_%s"%char.lower()
else:
newString += char
return newString
def RemoveHTMLTags(data):
"""
Removes all the HTML tags from a string.
**Parameters:**
* `data`: the string to be analyzed.
"""
p = re.compile(r'<[^<]*?>')
return p.sub('', data)
def FormatDocs(keyword, values, num):
names = values.keys()
names.sort()
headers = (num == 2 and [_eventHeaders] or [_styleHeaders])[0]
table = (num == 2 and [_eventTable] or [_styleTable])[0]
if num == 3:
text = "<br>" + table%(keyword.lower(), keyword.lower()) + "\n<tr>\n"
else:
text = "<br>" + table
for indx in xrange(2):
text += _headerTable%headers[indx]
text += "\n</tr>\n"
for name in names:
text += "<tr>\n"
description = values[name].strip()
pythonValue = name.replace("wx", "wx.")
if num == 3:
colour = "#ff0000"
value = "Unavailable"
cutValue = pythonValue[3:]
if cutValue in _dirWX:
try:
val = eval(pythonValue)
value = "%s"%hex(val)
colour = "#0000ff"
except AttributeError:
value = "Unavailable"
else:
for packages in _importList:
if cutValue in dir(eval(packages)):
val = eval("%s.%s"%(packages, cutValue))
value = "%s"%hex(val)
colour = "#0000ff"
pythonValue = "%s.%s"%(packages, cutValue)
break
text += _styleTag%pythonValue + "\n"
else:
text += _eventTag%pythonValue + "\n"
text += _description%FormatDescription(description) + "\n"
text += "</tr>\n"
text += "\n</table>\n\n<p>"
return text
def FormatDescription(description):
"""
Formats a wxWidgets C++ description in a more wxPython-based way.
**Parameters:**
* `description`: the string description to be formatted.
"""
description = description.replace("wx", "wx.")
description = description.replace("EVT_COMMAND", "wxEVT_COMMAND")
description = description.replace("wx.Widgets", "wxWidgets")
return description
def FormatImages(appearance):
text = "<p><br>" + _appearanceTable
for indx in xrange(2):
text += "\n<tr>\n"
for key in _platformNames:
if indx == 0:
src = appearance[key]
alt = key + "Appearance"
text += _imageTag%(src, src, alt)
else:
text += _platformTag%key
text += "</tr>\n"
text += "\n</table>\n\n<p>"
return text
def FindWindowStyles(text, originalText, widgetName):
"""
Finds the windows styles and events in the input text.
**Parameters:**
* `text`: the wxWidgets C++ docs for a particular widget/event, stripped
of all HTML tags;
* `originalText`: the wxWidgets C++ docs for a particular widget/event, with
all HTML tags.
"""
winStyles, winEvents, winExtra, winAppearance = {}, {}, {}, {}
inStyle = inExtra = inEvent = False
for line in text:
if "following styles:" in line:
inStyle = True
continue
elif "Event macros" in line:
inEvent = True
continue
if "following extra styles:" in line:
inExtra = True
continue
if "Appearance:" in line:
winAppearance = FindImages(originalText, widgetName)
continue
elif not line.strip():
inStyle = inEvent = inExtra = False
continue
if inStyle:
start = line.index(':')
windowStyle = line[0:start]
styleDescription = line[start+1:]
winStyles[windowStyle] = styleDescription
elif inEvent:
start = line.index(':')
eventName = line[0:start]
eventDescription = line[start+1:]
winEvents[eventName] = eventDescription
elif inExtra:
start = line.index(':')
styleName = line[0:start]
styleDescription = line[start+1:]
winExtra[styleName] = styleDescription
return winStyles, winEvents, winExtra, winAppearance
def FindImages(text, widgetName):
"""
When the wxWidgets docs contain athe control appearance (a screenshot of the
control), this method will try and download the images.
**Parameters:**
* `text`: the wxWidgets C++ docs for a particular widget/event, with
all HTML tags.
"""
winAppearance = {}
start = text.find("class='appearance'")
if start < 0:
return winAppearance
imagesDir = GetDocImagesDir()
end = start + text.find("</table>")
text = text[start:end]
split = text.split()
for indx, items in enumerate(split):
if "src=" in items:
possibleImage = items.replace("src=", "").strip()
possibleImage = possibleImage.replace("'", "")
f = urllib2.urlopen(_trunkURL + possibleImage)
stream = f.read()
elif "alt=" in items:
plat = items.replace("alt=", "").replace("'", "").strip()
path = os.path.join(imagesDir, plat, widgetName + ".png")
if not os.path.isfile(path):
image = wx.ImageFromStream(cStringIO.StringIO(stream))
image.SaveFile(path, wx.BITMAP_TYPE_PNG)
winAppearance[plat] = path
return winAppearance
#---------------------------------------------------------------------------
# Set up a thread that will scan the wxWidgets docs for window styles,
# events and widgets screenshots
class InternetThread(Thread):
""" Worker thread class to attempt connection to the internet. """
def __init__(self, notifyWindow, selectedClass):
Thread.__init__(self)
self.notifyWindow = notifyWindow
self.selectedClass = selectedClass
self.keepRunning = True
self.setDaemon(True)
self.start()
def run(self):
""" Run the worker thread. """
# This is the code executing in the new thread. Simulation of
# a long process as a simple urllib2 call
try:
url = _docsURL % ReplaceCapitals(self.selectedClass)
fid = urllib2.urlopen(url)
originalText = fid.read()
text = RemoveHTMLTags(originalText).split("\n")
data = FindWindowStyles(text, originalText, self.selectedClass)
if not self.keepRunning:
return
wx.CallAfter(self.notifyWindow.LoadDocumentation, data)
except (IOError, urllib2.HTTPError):
# Unable to get to the internet
t, v = sys.exc_info()[:2]
message = traceback.format_exception_only(t, v)
wx.CallAfter(self.notifyWindow.StopDownload, message)
except:
# Some other strange error...
t, v = sys.exc_info()[:2]
message = traceback.format_exception_only(t, v)
wx.CallAfter(self.notifyWindow.StopDownload, message)
#---------------------------------------------------------------------------
# Show how to derive a custom wxLog class
class MyLog(wx.PyLog):
def __init__(self, textCtrl, logTime=0):
wx.PyLog.__init__(self)
self.tc = textCtrl
self.logTime = logTime
def DoLogText(self, message):
if self.tc:
self.tc.AppendText(message + '\n')
#---------------------------------------------------------------------------
# A class to be used to display source code in the demo. Try using the
# wxSTC in the StyledTextCtrl_2 sample first, fall back to wxTextCtrl
# if there is an error, such as the stc module not being present.
#
try:
##raise ImportError # for testing the alternate implementation
from wx import stc
from StyledTextCtrl_2 import PythonSTC
class DemoCodeEditor(PythonSTC):
def __init__(self, parent, style=wx.BORDER_NONE):
PythonSTC.__init__(self, parent, -1, style=style)
self.SetUpEditor()
# Some methods to make it compatible with how the wxTextCtrl is used
def SetValue(self, value):
if wx.USE_UNICODE:
value = value.decode('iso8859_1')
val = self.GetReadOnly()
self.SetReadOnly(False)
self.SetText(value)
self.EmptyUndoBuffer()
self.SetSavePoint()
self.SetReadOnly(val)
def SetEditable(self, val):
self.SetReadOnly(not val)
def IsModified(self):
return self.GetModify()
def Clear(self):
self.ClearAll()
def SetInsertionPoint(self, pos):
self.SetCurrentPos(pos)
self.SetAnchor(pos)
def ShowPosition(self, pos):
line = self.LineFromPosition(pos)
#self.EnsureVisible(line)
self.GotoLine(line)
def GetLastPosition(self):
return self.GetLength()
def GetPositionFromLine(self, line):
return self.PositionFromLine(line)
def GetRange(self, start, end):
return self.GetTextRange(start, end)
def GetSelection(self):
return self.GetAnchor(), self.GetCurrentPos()
def SetSelection(self, start, end):
self.SetSelectionStart(start)
self.SetSelectionEnd(end)
def SelectLine(self, line):
start = self.PositionFromLine(line)
end = self.GetLineEndPosition(line)
self.SetSelection(start, end)
def SetUpEditor(self):
"""
This method carries out the work of setting up the demo editor.
It's seperate so as not to clutter up the init code.
"""
import keyword
self.SetLexer(stc.STC_LEX_PYTHON)
self.SetKeyWords(0, " ".join(keyword.kwlist))
# Enable folding
self.SetProperty("fold", "1" )
# Highlight tab/space mixing (shouldn't be any)
self.SetProperty("tab.timmy.whinge.level", "1")
# Set left and right margins
self.SetMargins(2,2)
# Set up the numbers in the margin for margin #1
self.SetMarginType(1, wx.stc.STC_MARGIN_NUMBER)
# Reasonable value for, say, 4-5 digits using a mono font (40 pix)
self.SetMarginWidth(1, 40)
# Indentation and tab stuff
self.SetIndent(4) # Proscribed indent size for wx
self.SetIndentationGuides(True) # Show indent guides
self.SetBackSpaceUnIndents(True)# Backspace unindents rather than delete 1 space
self.SetTabIndents(True) # Tab key indents
self.SetTabWidth(4) # Proscribed tab size for wx
self.SetUseTabs(False) # Use spaces rather than tabs, or
# TabTimmy will complain!
# White space
self.SetViewWhiteSpace(False) # Don't view white space
# EOL: Since we are loading/saving ourselves, and the
# strings will always have \n's in them, set the STC to
# edit them that way.
self.SetEOLMode(wx.stc.STC_EOL_LF)
self.SetViewEOL(False)
# No right-edge mode indicator
self.SetEdgeMode(stc.STC_EDGE_NONE)
# Setup a margin to hold fold markers
self.SetMarginType(2, stc.STC_MARGIN_SYMBOL)
self.SetMarginMask(2, stc.STC_MASK_FOLDERS)
self.SetMarginSensitive(2, True)
self.SetMarginWidth(2, 12)
# and now set up the fold markers
self.MarkerDefine(stc.STC_MARKNUM_FOLDEREND, stc.STC_MARK_BOXPLUSCONNECTED, "white", "black")
self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPENMID, stc.STC_MARK_BOXMINUSCONNECTED, "white", "black")
self.MarkerDefine(stc.STC_MARKNUM_FOLDERMIDTAIL, stc.STC_MARK_TCORNER, "white", "black")
self.MarkerDefine(stc.STC_MARKNUM_FOLDERTAIL, stc.STC_MARK_LCORNER, "white", "black")
self.MarkerDefine(stc.STC_MARKNUM_FOLDERSUB, stc.STC_MARK_VLINE, "white", "black")
self.MarkerDefine(stc.STC_MARKNUM_FOLDER, stc.STC_MARK_BOXPLUS, "white", "black")
self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPEN, stc.STC_MARK_BOXMINUS, "white", "black")
# Global default style
if wx.Platform == '__WXMSW__':
self.StyleSetSpec(stc.STC_STYLE_DEFAULT,
'fore:#000000,back:#FFFFFF,face:Courier New')
elif wx.Platform == '__WXMAC__':
# TODO: if this looks fine on Linux too, remove the Mac-specific case
# and use this whenever OS != MSW.
self.StyleSetSpec(stc.STC_STYLE_DEFAULT,
'fore:#000000,back:#FFFFFF,face:Monaco')
else:
defsize = wx.SystemSettings.GetFont(wx.SYS_ANSI_FIXED_FONT).GetPointSize()
self.StyleSetSpec(stc.STC_STYLE_DEFAULT,
'fore:#000000,back:#FFFFFF,face:Courier,size:%d'%defsize)
# Clear styles and revert to default.
self.StyleClearAll()
# Following style specs only indicate differences from default.
# The rest remains unchanged.
# Line numbers in margin
self.StyleSetSpec(wx.stc.STC_STYLE_LINENUMBER,'fore:#000000,back:#99A9C2')
# Highlighted brace
self.StyleSetSpec(wx.stc.STC_STYLE_BRACELIGHT,'fore:#00009D,back:#FFFF00')
# Unmatched brace
self.StyleSetSpec(wx.stc.STC_STYLE_BRACEBAD,'fore:#00009D,back:#FF0000')
# Indentation guide
self.StyleSetSpec(wx.stc.STC_STYLE_INDENTGUIDE, "fore:#CDCDCD")
# Python styles
self.StyleSetSpec(wx.stc.STC_P_DEFAULT, 'fore:#000000')
# Comments
self.StyleSetSpec(wx.stc.STC_P_COMMENTLINE, 'fore:#008000,back:#F0FFF0')
self.StyleSetSpec(wx.stc.STC_P_COMMENTBLOCK, 'fore:#008000,back:#F0FFF0')
# Numbers
self.StyleSetSpec(wx.stc.STC_P_NUMBER, 'fore:#008080')
# Strings and characters
self.StyleSetSpec(wx.stc.STC_P_STRING, 'fore:#800080')
self.StyleSetSpec(wx.stc.STC_P_CHARACTER, 'fore:#800080')
# Keywords
self.StyleSetSpec(wx.stc.STC_P_WORD, 'fore:#000080,bold')
# Triple quotes
self.StyleSetSpec(wx.stc.STC_P_TRIPLE, 'fore:#800080,back:#FFFFEA')
self.StyleSetSpec(wx.stc.STC_P_TRIPLEDOUBLE, 'fore:#800080,back:#FFFFEA')
# Class names
self.StyleSetSpec(wx.stc.STC_P_CLASSNAME, 'fore:#0000FF,bold')
# Function names
self.StyleSetSpec(wx.stc.STC_P_DEFNAME, 'fore:#008080,bold')
# Operators
self.StyleSetSpec(wx.stc.STC_P_OPERATOR, 'fore:#800000,bold')
# Identifiers. I leave this as not bold because everything seems
# to be an identifier if it doesn't match the above criterae
self.StyleSetSpec(wx.stc.STC_P_IDENTIFIER, 'fore:#000000')
# Caret color
self.SetCaretForeground("BLUE")
# Selection background
self.SetSelBackground(1, '#66CCFF')
self.SetSelBackground(True, wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT))
self.SetSelForeground(True, wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT))
def RegisterModifiedEvent(self, eventHandler):
self.Bind(wx.stc.EVT_STC_CHANGE, eventHandler)
except ImportError:
class DemoCodeEditor(wx.TextCtrl):
def __init__(self, parent):
wx.TextCtrl.__init__(self, parent, -1, style =
wx.TE_MULTILINE | wx.HSCROLL | wx.TE_RICH2 | wx.TE_NOHIDESEL)
def RegisterModifiedEvent(self, eventHandler):
self.Bind(wx.EVT_TEXT, eventHandler)
def SetReadOnly(self, flag):
self.SetEditable(not flag)
# NOTE: STC already has this method
def GetText(self):
return self.GetValue()
def GetPositionFromLine(self, line):
return self.XYToPosition(0,line)
def GotoLine(self, line):
pos = self.GetPositionFromLine(line)
self.SetInsertionPoint(pos)
self.ShowPosition(pos)
def SelectLine(self, line):
start = self.GetPositionFromLine(line)
end = start + self.GetLineLength(line)
self.SetSelection(start, end)
#---------------------------------------------------------------------------
# Constants for module versions
modOriginal = 0
modModified = 1
modDefault = modOriginal
#---------------------------------------------------------------------------
class DemoCodePanel(wx.Panel):
"""Panel for the 'Demo Code' tab"""
def __init__(self, parent, mainFrame):
wx.Panel.__init__(self, parent, size=(1,1))
if 'wxMSW' in wx.PlatformInfo:
self.Hide()
self.mainFrame = mainFrame
self.editor = DemoCodeEditor(self)
self.editor.RegisterModifiedEvent(self.OnCodeModified)
self.btnSave = wx.Button(self, -1, "Save Changes")
self.btnRestore = wx.Button(self, -1, "Delete Modified")
self.btnSave.Enable(False)
self.btnSave.Bind(wx.EVT_BUTTON, self.OnSave)
self.btnRestore.Bind(wx.EVT_BUTTON, self.OnRestore)
self.radioButtons = { modOriginal: wx.RadioButton(self, -1, "Original", style = wx.RB_GROUP),
modModified: wx.RadioButton(self, -1, "Modified") }
self.controlBox = wx.BoxSizer(wx.HORIZONTAL)
self.controlBox.Add(wx.StaticText(self, -1, "Active Version:"), 0,
wx.RIGHT | wx.LEFT | wx.ALIGN_CENTER_VERTICAL, 5)
for modID, radioButton in self.radioButtons.items():
self.controlBox.Add(radioButton, 0, wx.EXPAND | wx.RIGHT, 5)
radioButton.modID = modID # makes it easier for the event handler
radioButton.Bind(wx.EVT_RADIOBUTTON, self.OnRadioButton)
self.controlBox.Add(self.btnSave, 0, wx.RIGHT, 5)
self.controlBox.Add(self.btnRestore, 0)
self.box = wx.BoxSizer(wx.VERTICAL)
self.box.Add(self.controlBox, 0, wx.EXPAND)
self.box.Add(wx.StaticLine(self), 0, wx.EXPAND)
self.box.Add(self.editor, 1, wx.EXPAND)
self.box.Fit(self)
self.SetSizer(self.box)
# Loads a demo from a DemoModules object
def LoadDemo(self, demoModules):
self.demoModules = demoModules
if (modDefault == modModified) and demoModules.Exists(modModified):
demoModules.SetActive(modModified)
else:
demoModules.SetActive(modOriginal)
self.radioButtons[demoModules.GetActiveID()].Enable(True)
self.ActiveModuleChanged()
def ActiveModuleChanged(self):
self.LoadDemoSource(self.demoModules.GetSource())
self.UpdateControlState()
self.mainFrame.pnl.Freeze()
self.ReloadDemo()
self.mainFrame.pnl.Thaw()
def LoadDemoSource(self, source):
self.editor.Clear()
self.editor.SetValue(source)
self.JumpToLine(0)
self.btnSave.Enable(False)
def JumpToLine(self, line, highlight=False):
self.editor.GotoLine(line)
self.editor.SetFocus()
if highlight:
self.editor.SelectLine(line)
def UpdateControlState(self):
active = self.demoModules.GetActiveID()
# Update the radio/restore buttons
for moduleID in self.radioButtons:
btn = self.radioButtons[moduleID]
if moduleID == active:
btn.SetValue(True)
else:
btn.SetValue(False)
if self.demoModules.Exists(moduleID):
btn.Enable(True)
if moduleID == modModified:
self.btnRestore.Enable(True)
else:
btn.Enable(False)
if moduleID == modModified:
self.btnRestore.Enable(False)
def OnRadioButton(self, event):
radioSelected = event.GetEventObject()
modSelected = radioSelected.modID
if modSelected != self.demoModules.GetActiveID():
busy = wx.BusyInfo("Reloading demo module...")
self.demoModules.SetActive(modSelected)
self.ActiveModuleChanged()
def ReloadDemo(self):
if self.demoModules.name != __name__:
self.mainFrame.RunModule()
def OnCodeModified(self, event):
self.btnSave.Enable(self.editor.IsModified())
def OnSave(self, event):
if self.demoModules.Exists(modModified):
if self.demoModules.GetActiveID() == modOriginal:
overwriteMsg = "You are about to overwrite an already existing modified copy\n" + \
"Do you want to continue?"
dlg = wx.MessageDialog(self, overwriteMsg, "wxPython Demo",
wx.YES_NO | wx.NO_DEFAULT| wx.ICON_EXCLAMATION)
result = dlg.ShowModal()
if result == wx.ID_NO:
return
dlg.Destroy()
self.demoModules.SetActive(modModified)
modifiedFilename = GetModifiedFilename(self.demoModules.name)
# Create the demo directory if one doesn't already exist
if not os.path.exists(GetModifiedDirectory()):
try:
os.makedirs(GetModifiedDirectory())
if not os.path.exists(GetModifiedDirectory()):
wx.LogMessage("BUG: Created demo directory but it still doesn't exist")
raise AssertionError
except:
wx.LogMessage("Error creating demo directory: %s" % GetModifiedDirectory())
return
else:
wx.LogMessage("Created directory for modified demos: %s" % GetModifiedDirectory())
# Save
f = open(modifiedFilename, "wt")
source = self.editor.GetText()
try:
f.write(source)
finally:
f.close()
busy = wx.BusyInfo("Reloading demo module...")
self.demoModules.LoadFromFile(modModified, modifiedFilename)
self.ActiveModuleChanged()
self.mainFrame.SetTreeModified(True)
def OnRestore(self, event): # Handles the "Delete Modified" button
modifiedFilename = GetModifiedFilename(self.demoModules.name)
self.demoModules.Delete(modModified)
os.unlink(modifiedFilename) # Delete the modified copy
busy = wx.BusyInfo("Reloading demo module...")
self.ActiveModuleChanged()
self.mainFrame.SetTreeModified(False)
#---------------------------------------------------------------------------
def opj(path):
"""Convert paths to the platform-specific separator"""
st = apply(os.path.join, tuple(path.split('/')))
# HACK: on Linux, a leading / gets lost...
if path.startswith('/'):
st = '/' + st
return st
def GetDataDir():
"""
Return the standard location on this platform for application data
"""
sp = wx.StandardPaths.Get()
return sp.GetUserDataDir()
def GetModifiedDirectory():
"""
Returns the directory where modified versions of the demo files
are stored
"""
return os.path.join(GetDataDir(), "modified")
def GetModifiedFilename(name):
"""
Returns the filename of the modified version of the specified demo
"""
if not name.endswith(".py"):
name = name + ".py"
return os.path.join(GetModifiedDirectory(), name)
def GetOriginalFilename(name):
"""
Returns the filename of the original version of the specified demo
"""
if not name.endswith(".py"):
name = name + ".py"
if os.path.isfile(name):
return name
originalDir = os.getcwd()
listDir = os.listdir(originalDir)
# Loop over the content of the demo directory
for item in listDir:
if not os.path.isdir(item):
# Not a directory, continue
continue
dirFile = os.listdir(item)
# See if a file called "name" is there
if name in dirFile:
return os.path.join(item, name)
# We must return a string...
return ""
def DoesModifiedExist(name):
"""Returns whether the specified demo has a modified copy"""
if os.path.exists(GetModifiedFilename(name)):
return True
else:
return False
def GetConfig():
if not os.path.exists(GetDataDir()):
os.makedirs(GetDataDir())
config = wx.FileConfig(
localFilename=os.path.join(GetDataDir(), "options"))
return config
def MakeDocDirs():
docDir = os.path.join(GetDataDir(), "docs")
if not os.path.exists(docDir):
os.makedirs(docDir)
for plat in _platformNames:
imageDir = os.path.join(docDir, "images", plat)
if not os.path.exists(imageDir):
os.makedirs(imageDir)
def GetDocFile():
docFile = os.path.join(GetDataDir(), "docs", "TrunkDocs.pkl")
return docFile
def GetDocImagesDir():
MakeDocDirs()
return os.path.join(GetDataDir(), "docs", "images")
def SearchDemo(name, keyword):
""" Returns whether a demo contains the search keyword or not. """
fid = open(GetOriginalFilename(name), "rt")
fullText = fid.read()
fid.close()
fullText = fullText.decode("iso-8859-1")
if fullText.find(keyword) >= 0:
return True
return False
def HuntExternalDemos():
"""
Searches for external demos (i.e. packages like AGW) in the wxPython
demo sub-directories. In order to be found, these external packages
must have a __demo__.py file in their directory.
"""
externalDemos = {}
originalDir = os.getcwd()
listDir = os.listdir(originalDir)
# Loop over the content of the demo directory
for item in listDir:
if not os.path.isdir(item):
# Not a directory, continue
continue
dirFile = os.listdir(item)
# See if a __demo__.py file is there
if "__demo__.py" in dirFile:
# Extend sys.path and import the external demos
sys.path.append(item)
externalDemos[item] = __import__("__demo__")
if not externalDemos:
# Nothing to import...
return {}
# Modify the tree items and icons
index = 0
for category, demos in _treeList:
# We put the external packages right before the
# More Windows/Controls item
if category == "More Windows/Controls":
break
index += 1
# Sort and reverse the external demos keys so that they
# come back in alphabetical order
keys = externalDemos.keys()
keys.sort()
keys.reverse()
# Loop over all external packages
for extern in keys:
package = externalDemos[extern]
# Insert a new package in the _treeList of demos
_treeList.insert(index, package.GetDemos())
# Get the recent additions for this package
_treeList[0][1].extend(package.GetRecentAdditions())
# Extend the demo bitmaps and the catalog
_demoPngs.insert(index+1, extern)
images.catalog[extern] = package.GetDemoBitmap()
# That's all folks...
return externalDemos
def LookForExternals(externalDemos, demoName):
"""
Checks if a demo name is in any of the external packages (like AGW) or
if the user clicked on one of the external packages parent items in the
tree, in which case it returns the html overview for the package.
"""
pkg = overview = None
# Loop over all the external demos
for key, package in externalDemos.items():
# Get the tree item name for the package and its demos
treeName, treeDemos = package.GetDemos()
# Get the overview for the package
treeOverview = package.GetOverview()
if treeName == demoName:
# The user clicked on the parent tree item, return the overview
return pkg, treeOverview
elif demoName in treeDemos:
# The user clicked on a real demo, return the package
return key, overview
# No match found, return None for both
return pkg, overview
#---------------------------------------------------------------------------
class ModuleDictWrapper(object):
"""Emulates a module with a dynamically compiled __dict__"""
def __init__(self, dict):
self.dict = dict
def __getattr__(self, name):
if name in self.dict:
return self.dict[name]
else:
raise AttributeError
class DemoModules(object):
"""
Dynamically manages the original/modified versions of a demo
module
"""
def __init__(self, name):
self.modActive = -1
self.name = name
# (dict , source , filename , description , error information )
# ( 0 , 1 , 2 , 3 , 4 )
self.modules = [[dict(), "" , "" , "<original>" , None],
[dict(), "" , "" , "<modified>" , None]]
for i in [modOriginal, modModified]:
self.modules[i][0]['__file__'] = \
os.path.join(os.getcwdu(), GetOriginalFilename(name))
# load original module
self.LoadFromFile(modOriginal, GetOriginalFilename(name))
self.SetActive(modOriginal)
# load modified module (if one exists)
if DoesModifiedExist(name):
self.LoadFromFile(modModified, GetModifiedFilename(name))
def LoadFromFile(self, modID, filename):
self.modules[modID][2] = filename
file = open(filename, "rt")
self.LoadFromSource(modID, file.read())
file.close()
def LoadFromSource(self, modID, source):
self.modules[modID][1] = source
self.LoadDict(modID)
def LoadDict(self, modID):
if self.name != __name__:
source = self.modules[modID][1]
description = self.modules[modID][2]
description = description.encode(sys.getfilesystemencoding())
try:
code = compile(source, description, "exec")
exec code in self.modules[modID][0]
except:
self.modules[modID][4] = DemoError(sys.exc_info())
self.modules[modID][0] = None
else:
self.modules[modID][4] = None
def SetActive(self, modID):
if modID != modOriginal and modID != modModified:
raise LookupError
else:
self.modActive = modID
def GetActive(self):
dict = self.modules[self.modActive][0]
if dict is None:
return None
else:
return ModuleDictWrapper(dict)
def GetActiveID(self):
return self.modActive
def GetSource(self, modID = None):
if modID is None:
modID = self.modActive
return self.modules[modID][1]
def GetFilename(self, modID = None):
if modID is None:
modID = self.modActive
return self.modules[self.modActive][2]
def GetErrorInfo(self, modID = None):
if modID is None:
modID = self.modActive
return self.modules[self.modActive][4]
def Exists(self, modID):
return self.modules[modID][1] != ""
def UpdateFile(self, modID = None):
"""Updates the file from which a module was loaded
with (possibly updated) source"""
if modID is None:
modID = self.modActive
source = self.modules[modID][1]
filename = self.modules[modID][2]
try:
file = open(filename, "wt")
file.write(source)
finally:
file.close()
def Delete(self, modID):
if self.modActive == modID:
self.SetActive(0)
self.modules[modID][0] = None
self.modules[modID][1] = ""
self.modules[modID][2] = ""
#---------------------------------------------------------------------------
class DemoError(object):
"""Wraps and stores information about the current exception"""
def __init__(self, exc_info):
import copy
excType, excValue = exc_info[:2]
# traceback list entries: (filename, line number, function name, text)
self.traceback = traceback.extract_tb(exc_info[2])
# --Based on traceback.py::format_exception_only()--
if type(excType) == types.ClassType:
self.exception_type = excType.__name__
else:
self.exception_type = excType
# If it's a syntax error, extra information needs
# to be added to the traceback
if excType is SyntaxError:
try:
msg, (filename, lineno, self.offset, line) = excValue
except:
pass
else:
if not filename:
filename = "<string>"
line = line.strip()
self.traceback.append( (filename, lineno, "", line) )
excValue = msg
try:
self.exception_details = str(excValue)
except:
self.exception_details = "<unprintable %s object>" & type(excValue).__name__
del exc_info
def __str__(self):
ret = "Type %s \n \
Traceback: %s \n \
Details : %s" % ( str(self.exception_type), str(self.traceback), self.exception_details )
return ret
#---------------------------------------------------------------------------
class DemoErrorPanel(wx.Panel):
"""Panel put into the demo tab when the demo fails to run due to errors"""
def __init__(self, parent, codePanel, demoError, log):
wx.Panel.__init__(self, parent, -1)#, style=wx.NO_FULL_REPAINT_ON_RESIZE)
self.codePanel = codePanel
self.nb = parent
self.log = log
self.box = wx.BoxSizer(wx.VERTICAL)
# Main Label
self.box.Add(wx.StaticText(self, -1, "An error has occurred while trying to run the demo")
, 0, wx.ALIGN_CENTER | wx.TOP, 10)
# Exception Information
boxInfo = wx.StaticBox(self, -1, "Exception Info" )
boxInfoSizer = wx.StaticBoxSizer(boxInfo, wx.VERTICAL ) # Used to center the grid within the box
boxInfoGrid = wx.FlexGridSizer( cols=2 )
textFlags = wx.ALIGN_RIGHT | wx.LEFT | wx.RIGHT | wx.TOP
boxInfoGrid.Add(wx.StaticText(self, -1, "Type: "), 0, textFlags, 5 )
boxInfoGrid.Add(wx.StaticText(self, -1, str(demoError.exception_type)) , 0, textFlags, 5 )
boxInfoGrid.Add(wx.StaticText(self, -1, "Details: ") , 0, textFlags, 5 )
boxInfoGrid.Add(wx.StaticText(self, -1, demoError.exception_details) , 0, textFlags, 5 )
boxInfoSizer.Add(boxInfoGrid, 0, wx.ALIGN_CENTRE | wx.ALL, 5 )
self.box.Add(boxInfoSizer, 0, wx.ALIGN_CENTER | wx.ALL, 5)
# Set up the traceback list
# This one automatically resizes last column to take up remaining space
from ListCtrl import TestListCtrl
self.list = TestListCtrl(self, -1, style=wx.LC_REPORT | wx.SUNKEN_BORDER)
self.list.Bind(wx.EVT_LEFT_DCLICK, self.OnDoubleClick)
self.list.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected)
self.list.InsertColumn(0, "Filename")
self.list.InsertColumn(1, "Line", wx.LIST_FORMAT_RIGHT)
self.list.InsertColumn(2, "Function")
self.list.InsertColumn(3, "Code")
self.InsertTraceback(self.list, demoError.traceback)
self.list.SetColumnWidth(0, wx.LIST_AUTOSIZE)
self.list.SetColumnWidth(2, wx.LIST_AUTOSIZE)
self.box.Add(wx.StaticText(self, -1, "Traceback:")
, 0, wx.ALIGN_CENTER | wx.TOP, 5)
self.box.Add(self.list, 1, wx.GROW | wx.ALIGN_CENTER | wx.ALL, 5)
self.box.Add(wx.StaticText(self, -1, "Entries from the demo module are shown in blue\n"
+ "Double-click on them to go to the offending line")
, 0, wx.ALIGN_CENTER | wx.BOTTOM, 5)
self.box.Fit(self)
self.SetSizer(self.box)
def InsertTraceback(self, list, traceback):
#Add the traceback data
for x in range(len(traceback)):
data = traceback[x]
list.InsertStringItem(x, os.path.basename(data[0])) # Filename
list.SetStringItem(x, 1, str(data[1])) # Line
list.SetStringItem(x, 2, str(data[2])) # Function
list.SetStringItem(x, 3, str(data[3])) # Code
# Check whether this entry is from the demo module
if data[0] == "<original>" or data[0] == "<modified>": # FIXME: make more generalised
self.list.SetItemData(x, int(data[1])) # Store line number for easy access
# Give it a blue colour
item = self.list.GetItem(x)
item.SetTextColour(wx.BLUE)
self.list.SetItem(item)
else:
self.list.SetItemData(x, -1) # Editor can't jump into this one's code
def OnItemSelected(self, event):
# This occurs before OnDoubleClick and can be used to set the
# currentItem. OnDoubleClick doesn't get a wxListEvent....
self.currentItem = event.m_itemIndex
event.Skip()
def OnDoubleClick(self, event):
# If double-clicking on a demo's entry, jump to the line number
line = self.list.GetItemData(self.currentItem)
if line != -1:
self.nb.SetSelection(1) # Switch to the code viewer tab
wx.CallAfter(self.codePanel.JumpToLine, line-1, True)
event.Skip()
#---------------------------------------------------------------------------
class MainPanel(wx.Panel):
"""
Just a simple derived panel where we override Freeze and Thaw so they are
only used on wxMSW.
"""
def Freeze(self):
if 'wxMSW' in wx.PlatformInfo:
return super(MainPanel, self).Freeze()
def Thaw(self):
if 'wxMSW' in wx.PlatformInfo:
return super(MainPanel, self).Thaw()
#---------------------------------------------------------------------------
class DemoTaskBarIcon(wx.TaskBarIcon):
TBMENU_RESTORE = wx.NewId()
TBMENU_CLOSE = wx.NewId()
TBMENU_CHANGE = wx.NewId()
TBMENU_REMOVE = wx.NewId()
def __init__(self, frame):
wx.TaskBarIcon.__init__(self, wx.TBI_DOCK) # wx.TBI_CUSTOM_STATUSITEM
self.frame = frame
# Set the image
icon = self.MakeIcon(images.WXPdemo.GetImage())
self.SetIcon(icon, "wxPython Demo")
self.imgidx = 1
# bind some events
self.Bind(wx.EVT_TASKBAR_LEFT_DCLICK, self.OnTaskBarActivate)
self.Bind(wx.EVT_MENU, self.OnTaskBarActivate, id=self.TBMENU_RESTORE)
self.Bind(wx.EVT_MENU, self.OnTaskBarClose, id=self.TBMENU_CLOSE)
self.Bind(wx.EVT_MENU, self.OnTaskBarChange, id=self.TBMENU_CHANGE)
self.Bind(wx.EVT_MENU, self.OnTaskBarRemove, id=self.TBMENU_REMOVE)
def CreatePopupMenu(self):
"""
This method is called by the base class when it needs to popup
the menu for the default EVT_RIGHT_DOWN event. Just create
the menu how you want it and return it from this function,
the base class takes care of the rest.
"""
menu = wx.Menu()
menu.Append(self.TBMENU_RESTORE, "Restore wxPython Demo")
menu.Append(self.TBMENU_CLOSE, "Close wxPython Demo")
menu.AppendSeparator()
menu.Append(self.TBMENU_CHANGE, "Change the TB Icon")
menu.Append(self.TBMENU_REMOVE, "Remove the TB Icon")
return menu
def MakeIcon(self, img):
"""
The various platforms have different requirements for the
icon size...
"""
if "wxMSW" in wx.PlatformInfo:
img = img.Scale(16, 16)
elif "wxGTK" in wx.PlatformInfo:
img = img.Scale(22, 22)
# wxMac can be any size upto 128x128, so leave the source img alone....
icon = wx.IconFromBitmap(img.ConvertToBitmap() )
return icon
def OnTaskBarActivate(self, evt):
if self.frame.IsIconized():
self.frame.Iconize(False)
if not self.frame.IsShown():
self.frame.Show(True)
self.frame.Raise()
def OnTaskBarClose(self, evt):
wx.CallAfter(self.frame.Close)
def OnTaskBarChange(self, evt):
names = [ "WXPdemo", "Mondrian", "Pencil", "Carrot" ]
name = names[self.imgidx]
eImg = getattr(images, name)
self.imgidx += 1
if self.imgidx >= len(names):
self.imgidx = 0
icon = self.MakeIcon(eImg.Image)
self.SetIcon(icon, "This is a new icon: " + name)
def OnTaskBarRemove(self, evt):
self.RemoveIcon()
#---------------------------------------------------------------------------
class wxPythonDemo(wx.Frame):
overviewText = "wxPython Demo"
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, -1, title, size = (970, 720),
style=wx.DEFAULT_FRAME_STYLE | wx.NO_FULL_REPAINT_ON_RESIZE)
self.SetMinSize((640,480))
self.pnl = pnl = MainPanel(self)
self.mgr = wx.aui.AuiManager()
self.mgr.SetManagedWindow(pnl)
self.loaded = False
self.cwd = os.getcwd()
self.curOverview = ""
self.demoPage = None
self.codePage = None
self.shell = None
self.firstTime = True
self.finddlg = None
icon = images.WXPdemo.GetIcon()
self.SetIcon(icon)
try:
self.tbicon = DemoTaskBarIcon(self)
except:
self.tbicon = None
self.otherWin = None
self.allowDocs = False
self.downloading = False
self.internetThread = None
self.downloadImage = 2
self.sendDownloadError = True
self.downloadTimer = wx.Timer(self, wx.ID_ANY)
self.Bind(wx.EVT_IDLE, self.OnIdle)
self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
self.Bind(wx.EVT_ICONIZE, self.OnIconfiy)
self.Bind(wx.EVT_MAXIMIZE, self.OnMaximize)
self.Bind(wx.EVT_TIMER, self.OnDownloadTimer, self.downloadTimer)
self.Centre(wx.BOTH)
self.statusBar = self.CreateStatusBar(2, wx.ST_SIZEGRIP)
self.statusBar.SetStatusWidths([-2, -1])
statusText = "Welcome to wxPython %s"%version.VERSION_STRING
self.statusBar.SetStatusText(statusText, 0)
self.downloadGauge = wx.Gauge(self.statusBar, -1, 50)
self.downloadGauge.SetToolTipString("Downloading Docs...")
self.downloadGauge.Hide()
self.sizeChanged = False
self.Reposition()
self.statusBar.Bind(wx.EVT_SIZE, self.OnStatusBarSize)
self.statusBar.Bind(wx.EVT_IDLE, self.OnStatusBarIdle)
self.dying = False
self.skipLoad = False
self.allowAuiFloating = False
def EmptyHandler(evt): pass
self.ReadConfigurationFile()
self.externalDemos = HuntExternalDemos()
# Create a Notebook
self.nb = wx.Notebook(pnl, -1, style=wx.CLIP_CHILDREN)
imgList = wx.ImageList(16, 16)
for png in ["overview", "code", "demo"]:
bmp = images.catalog[png].GetBitmap()
imgList.Add(bmp)
for indx in xrange(9):
bmp = images.catalog["spinning_nb%d"%indx].GetBitmap()
imgList.Add(bmp)
self.nb.AssignImageList(imgList)
self.BuildMenuBar()
self.finddata = wx.FindReplaceData()
self.finddata.SetFlags(wx.FR_DOWN)
# Create a TreeCtrl
leftPanel = wx.Panel(pnl, style=wx.TAB_TRAVERSAL|wx.CLIP_CHILDREN)
self.treeMap = {}
self.searchItems = {}
self.tree = wxPythonDemoTree(leftPanel)
self.filter = wx.SearchCtrl(leftPanel, style=wx.TE_PROCESS_ENTER)
self.filter.ShowCancelButton(True)
self.filter.Bind(wx.EVT_TEXT, self.RecreateTree)
self.filter.Bind(wx.EVT_SEARCHCTRL_CANCEL_BTN,
lambda e: self.filter.SetValue(''))
self.filter.Bind(wx.EVT_TEXT_ENTER, self.OnSearch)
searchMenu = wx.Menu()
item = searchMenu.AppendRadioItem(-1, "Sample Name")
self.Bind(wx.EVT_MENU, self.OnSearchMenu, item)
item = searchMenu.AppendRadioItem(-1, "Sample Content")
self.Bind(wx.EVT_MENU, self.OnSearchMenu, item)
self.filter.SetMenu(searchMenu)
self.RecreateTree()
self.tree.SetExpansionState(self.expansionState)
self.tree.Bind(wx.EVT_TREE_ITEM_EXPANDED, self.OnItemExpanded)
self.tree.Bind(wx.EVT_TREE_ITEM_COLLAPSED, self.OnItemCollapsed)
self.tree.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged)
self.tree.Bind(wx.EVT_LEFT_DOWN, self.OnTreeLeftDown)
# Set up a wx.html.HtmlWindow on the Overview Notebook page
# we put it in a panel first because there seems to be a
# refresh bug of some sort (wxGTK) when it is directly in
# the notebook...
if 0: # the old way
self.ovr = wx.html.HtmlWindow(self.nb, -1, size=(400, 400))
self.nb.AddPage(self.ovr, self.overviewText, imageId=0)
else: # hopefully I can remove this hacky code soon, see SF bug #216861
panel = wx.Panel(self.nb, -1, style=wx.CLIP_CHILDREN)
self.ovr = wx.html.HtmlWindow(panel, -1, size=(400, 400))
self.nb.AddPage(panel, self.overviewText, imageId=0)
def OnOvrSize(evt, ovr=self.ovr):
ovr.SetSize(evt.GetSize())
panel.Bind(wx.EVT_SIZE, OnOvrSize)
panel.Bind(wx.EVT_ERASE_BACKGROUND, EmptyHandler)
if "gtk2" in wx.PlatformInfo or "gtk3" in wx.PlatformInfo:
self.ovr.SetStandardFonts()
self.SetOverview(self.overviewText, mainOverview)
# Set up a log window
self.log = wx.TextCtrl(pnl, -1,
style = wx.TE_MULTILINE|wx.TE_READONLY|wx.HSCROLL)
if wx.Platform == "__WXMAC__":
self.log.MacCheckSpelling(False)
# Set the wxWindows log target to be this textctrl
#wx.Log_SetActiveTarget(wx.LogTextCtrl(self.log))
# But instead of the above we want to show how to use our own wx.Log class
wx.Log_SetActiveTarget(MyLog(self.log))
# for serious debugging
#wx.Log_SetActiveTarget(wx.LogStderr())
#wx.Log_SetTraceMask(wx.TraceMessages)
self.Bind(wx.EVT_ACTIVATE, self.OnActivate)
wx.GetApp().Bind(wx.EVT_ACTIVATE_APP, self.OnAppActivate)
# add the windows to the splitter and split it.
leftBox = wx.BoxSizer(wx.VERTICAL)
leftBox.Add(self.tree, 1, wx.EXPAND)
leftBox.Add(wx.StaticText(leftPanel, label = "Filter Demos:"), 0, wx.TOP|wx.LEFT, 5)
leftBox.Add(self.filter, 0, wx.EXPAND|wx.ALL, 5)
if 'wxMac' in wx.PlatformInfo:
leftBox.Add((5,5)) # Make sure there is room for the focus ring
leftPanel.SetSizer(leftBox)
# select initial items
self.nb.SetSelection(0)
self.tree.SelectItem(self.root)
# Load 'Main' module
self.LoadDemo(self.overviewText)
self.loaded = True
# select some other initial module?
if len(sys.argv) > 1:
arg = sys.argv[1]
if arg.endswith('.py'):
arg = arg[:-3]
selectedDemo = self.treeMap.get(arg, None)
if selectedDemo:
self.tree.SelectItem(selectedDemo)
self.tree.EnsureVisible(selectedDemo)
# Use the aui manager to set up everything
self.mgr.AddPane(self.nb, wx.aui.AuiPaneInfo().CenterPane().Name("Notebook"))
self.mgr.AddPane(leftPanel,
wx.aui.AuiPaneInfo().
Left().Layer(2).BestSize((240, -1)).
MinSize((240, -1)).
Floatable(self.allowAuiFloating).FloatingSize((240, 700)).
Caption("wxPython Demos").
CloseButton(False).
Name("DemoTree"))
self.mgr.AddPane(self.log,
wx.aui.AuiPaneInfo().
Bottom().BestSize((-1, 150)).
MinSize((-1, 140)).
Floatable(self.allowAuiFloating).FloatingSize((500, 160)).
Caption("Demo Log Messages").
CloseButton(False).
Name("LogWindow"))
self.auiConfigurations[DEFAULT_PERSPECTIVE] = self.mgr.SavePerspective()
self.mgr.Update()
self.mgr.SetFlags(self.mgr.GetFlags() ^ wx.aui.AUI_MGR_TRANSPARENT_DRAG)
def ReadConfigurationFile(self):
self.auiConfigurations = {}
self.expansionState = [0, 1]
config = GetConfig()
val = config.Read('ExpansionState')
if val:
self.expansionState = eval(val)
val = config.Read('AUIPerspectives')
if val:
self.auiConfigurations = eval(val)
val = config.Read('AllowDownloads')
if val:
self.allowDocs = eval(val)
val = config.Read('AllowAUIFloating')
if val:
self.allowAuiFloating = eval(val)
MakeDocDirs()
pickledFile = GetDocFile()
if not os.path.isfile(pickledFile):
self.pickledData = {}
return
fid = open(pickledFile, "rb")
try:
self.pickledData = cPickle.load(fid)
except:
self.pickledData = {}
fid.close()
def BuildMenuBar(self):
# Make a File menu
self.mainmenu = wx.MenuBar()
menu = wx.Menu()
item = menu.Append(-1, '&Redirect Output',
'Redirect print statements to a window',
wx.ITEM_CHECK)
self.Bind(wx.EVT_MENU, self.OnToggleRedirect, item)
wx.App.SetMacExitMenuItemId(9123)
exitItem = wx.MenuItem(menu, 9123, 'E&xit\tCtrl-Q', 'Get the heck outta here!')
exitItem.SetBitmap(images.catalog['exit'].GetBitmap())
menu.AppendItem(exitItem)
self.Bind(wx.EVT_MENU, self.OnFileExit, exitItem)
self.mainmenu.Append(menu, '&File')
# Make a Demo menu
menu = wx.Menu()
for indx, item in enumerate(_treeList[:-1]):
menuItem = wx.MenuItem(menu, -1, item[0])
submenu = wx.Menu()
for childItem in item[1]:
mi = submenu.Append(-1, childItem)
self.Bind(wx.EVT_MENU, self.OnDemoMenu, mi)
menuItem.SetBitmap(images.catalog[_demoPngs[indx+1]].GetBitmap())
menuItem.SetSubMenu(submenu)
menu.AppendItem(menuItem)
self.mainmenu.Append(menu, '&Demo')
# Make an Option menu
menu = wx.Menu()
item = wx.MenuItem(menu, -1, 'Allow download of docs', 'Docs for window styles and events from the web', wx.ITEM_CHECK)
menu.AppendItem(item)
item.Check(self.allowDocs)
self.Bind(wx.EVT_MENU, self.OnAllowDownload, item)
item = wx.MenuItem(menu, -1, 'Delete saved docs', 'Deletes the cPickle file where docs are stored')
item.SetBitmap(images.catalog['deletedocs'].GetBitmap())
menu.AppendItem(item)
self.Bind(wx.EVT_MENU, self.OnDeleteDocs, item)
menu.AppendSeparator()
item = wx.MenuItem(menu, -1, 'Allow floating panes', 'Allows the demo panes to be floated using wxAUI', wx.ITEM_CHECK)
menu.AppendItem(item)
item.Check(self.allowAuiFloating)
self.Bind(wx.EVT_MENU, self.OnAllowAuiFloating, item)
auiPerspectives = self.auiConfigurations.keys()
auiPerspectives.sort()
perspectivesMenu = wx.Menu()
item = wx.MenuItem(perspectivesMenu, -1, DEFAULT_PERSPECTIVE, "Load startup default perspective", wx.ITEM_RADIO)
self.Bind(wx.EVT_MENU, self.OnAUIPerspectives, item)
perspectivesMenu.AppendItem(item)
for indx, key in enumerate(auiPerspectives):
if key == DEFAULT_PERSPECTIVE:
continue
item = wx.MenuItem(perspectivesMenu, -1, key, "Load user perspective %d"%indx, wx.ITEM_RADIO)
perspectivesMenu.AppendItem(item)
self.Bind(wx.EVT_MENU, self.OnAUIPerspectives, item)
menu.AppendMenu(wx.ID_ANY, "&AUI Perspectives", perspectivesMenu)
self.perspectives_menu = perspectivesMenu
item = wx.MenuItem(menu, -1, 'Save Perspective', 'Save AUI perspective')
item.SetBitmap(images.catalog['saveperspective'].GetBitmap())
menu.AppendItem(item)
self.Bind(wx.EVT_MENU, self.OnSavePerspective, item)
item = wx.MenuItem(menu, -1, 'Delete Perspective', 'Delete AUI perspective')
item.SetBitmap(images.catalog['deleteperspective'].GetBitmap())
menu.AppendItem(item)
self.Bind(wx.EVT_MENU, self.OnDeletePerspective, item)
menu.AppendSeparator()
item = wx.MenuItem(menu, -1, 'Restore Tree Expansion', 'Restore the initial tree expansion state')
item.SetBitmap(images.catalog['expansion'].GetBitmap())
menu.AppendItem(item)
self.Bind(wx.EVT_MENU, self.OnTreeExpansion, item)
self.mainmenu.Append(menu, '&Options')
self.options_menu = menu
# Make a Help menu
menu = wx.Menu()
findItem = wx.MenuItem(menu, -1, '&Find\tCtrl-F', 'Find in the Demo Code')
findItem.SetBitmap(images.catalog['find'].GetBitmap())
if 'wxMac' not in wx.PlatformInfo:
findNextItem = wx.MenuItem(menu, -1, 'Find &Next\tF3', 'Find Next')
else:
findNextItem = wx.MenuItem(menu, -1, 'Find &Next\tCtrl-G', 'Find Next')
findNextItem.SetBitmap(images.catalog['findnext'].GetBitmap())
menu.AppendItem(findItem)
menu.AppendItem(findNextItem)
menu.AppendSeparator()
shellItem = wx.MenuItem(menu, -1, 'Open Py&Shell Window\tF5',
'An interactive interpreter window with the demo app and frame objects in the namesapce')
shellItem.SetBitmap(images.catalog['pyshell'].GetBitmap())
menu.AppendItem(shellItem)
inspToolItem = wx.MenuItem(menu, -1, 'Open &Widget Inspector\tF6',
'A tool that lets you browse the live widgets and sizers in an application')
inspToolItem.SetBitmap(images.catalog['inspect'].GetBitmap())
menu.AppendItem(inspToolItem)
if 'wxMac' not in wx.PlatformInfo:
menu.AppendSeparator()
helpItem = menu.Append(wx.ID_ABOUT, '&About wxPython Demo', 'wxPython RULES!!!')
self.Bind(wx.EVT_MENU, self.OnOpenShellWindow, shellItem)
self.Bind(wx.EVT_MENU, self.OnOpenWidgetInspector, inspToolItem)
self.Bind(wx.EVT_MENU, self.OnHelpAbout, helpItem)
self.Bind(wx.EVT_MENU, self.OnHelpFind, findItem)
self.Bind(wx.EVT_MENU, self.OnFindNext, findNextItem)
self.Bind(wx.EVT_FIND, self.OnFind)
self.Bind(wx.EVT_FIND_NEXT, self.OnFind)
self.Bind(wx.EVT_FIND_CLOSE, self.OnFindClose)
self.Bind(wx.EVT_UPDATE_UI, self.OnUpdateFindItems, findItem)
self.Bind(wx.EVT_UPDATE_UI, self.OnUpdateFindItems, findNextItem)
self.mainmenu.Append(menu, '&Help')
self.SetMenuBar(self.mainmenu)
self.EnableAUIMenu()
if False:
# This is another way to set Accelerators, in addition to
# using the '\t<key>' syntax in the menu items.
aTable = wx.AcceleratorTable([(wx.ACCEL_ALT, ord('X'), exitItem.GetId()),
(wx.ACCEL_CTRL, ord('H'), helpItem.GetId()),
(wx.ACCEL_CTRL, ord('F'), findItem.GetId()),
(wx.ACCEL_NORMAL, wx.WXK_F3, findNextItem.GetId()),
(wx.ACCEL_NORMAL, wx.WXK_F9, shellItem.GetId()),
])
self.SetAcceleratorTable(aTable)
#---------------------------------------------
def RecreateTree(self, evt=None):
# Catch the search type (name or content)
searchMenu = self.filter.GetMenu().GetMenuItems()
fullSearch = searchMenu[1].IsChecked()
if evt:
if fullSearch:
# Do not`scan all the demo files for every char
# the user input, use wx.EVT_TEXT_ENTER instead
return
expansionState = self.tree.GetExpansionState()
current = None
item = self.tree.GetSelection()
if item:
prnt = self.tree.GetItemParent(item)
if prnt:
current = (self.tree.GetItemText(item),
self.tree.GetItemText(prnt))
self.tree.Freeze()
self.tree.DeleteAllItems()
self.root = self.tree.AddRoot("wxPython Overview")
self.tree.SetItemImage(self.root, 0)
self.tree.SetItemPyData(self.root, 0)
treeFont = self.tree.GetFont()
catFont = self.tree.GetFont()
# The native treectrl on MSW has a bug where it doesn't draw
# all of the text for an item if the font is larger than the
# default. It seems to be clipping the item's label as if it
# was the size of the same label in the default font.
if USE_CUSTOMTREECTRL or 'wxMSW' not in wx.PlatformInfo:
treeFont.SetPointSize(treeFont.GetPointSize()+2)
treeFont.SetWeight(wx.BOLD)
catFont.SetWeight(wx.BOLD)
self.tree.SetItemFont(self.root, treeFont)
firstChild = None
selectItem = None
filter = self.filter.GetValue()
count = 0
for category, items in _treeList:
count += 1
if filter:
if fullSearch:
items = self.searchItems[category]
else:
items = [item for item in items if filter.lower() in item.lower()]
if items:
child = self.tree.AppendItem(self.root, category, image=count)
self.tree.SetItemFont(child, catFont)
self.tree.SetItemPyData(child, count)
if not firstChild: firstChild = child
for childItem in items:
image = count
if DoesModifiedExist(childItem):
image = len(_demoPngs)
theDemo = self.tree.AppendItem(child, childItem, image=image)
self.tree.SetItemPyData(theDemo, count)
self.treeMap[childItem] = theDemo
if current and (childItem, category) == current:
selectItem = theDemo
self.tree.Expand(self.root)
if firstChild:
self.tree.Expand(firstChild)
if filter:
self.tree.ExpandAll()
elif expansionState:
self.tree.SetExpansionState(expansionState)
if selectItem:
self.skipLoad = True
self.tree.SelectItem(selectItem)
self.skipLoad = False
self.tree.Thaw()
self.searchItems = {}
def OnStatusBarSize(self, evt):
self.Reposition() # for normal size events
# Set a flag so the idle time handler will also do the repositioning.
# It is done this way to get around a buglet where GetFieldRect is not
# accurate during the EVT_SIZE resulting from a frame maximize.
self.sizeChanged = True
def OnStatusBarIdle(self, evt):
if self.sizeChanged:
self.Reposition()
# reposition the download gauge
def Reposition(self):
rect = self.statusBar.GetFieldRect(1)
self.downloadGauge.SetPosition((rect.x+2, rect.y+2))
self.downloadGauge.SetSize((rect.width-4, rect.height-4))
self.sizeChanged = False
def OnSearchMenu(self, event):
# Catch the search type (name or content)
searchMenu = self.filter.GetMenu().GetMenuItems()
fullSearch = searchMenu[1].IsChecked()
if fullSearch:
self.OnSearch()
else:
self.RecreateTree()
def OnSearch(self, event=None):
value = self.filter.GetValue()
if not value:
self.RecreateTree()
return
wx.BeginBusyCursor()
for category, items in _treeList:
self.searchItems[category] = []
for childItem in items:
if SearchDemo(childItem, value):
self.searchItems[category].append(childItem)
wx.EndBusyCursor()
self.RecreateTree()
def SetTreeModified(self, modified):
item = self.tree.GetSelection()
if modified:
image = len(_demoPngs)
else:
image = self.tree.GetItemPyData(item)
self.tree.SetItemImage(item, image)
def WriteText(self, text):
if text[-1:] == '\n':
text = text[:-1]
wx.LogMessage(text)
def write(self, txt):
self.WriteText(txt)
#---------------------------------------------
def OnItemExpanded(self, event):
item = event.GetItem()
wx.LogMessage("OnItemExpanded: %s" % self.tree.GetItemText(item))
event.Skip()
#---------------------------------------------
def OnItemCollapsed(self, event):
item = event.GetItem()
wx.LogMessage("OnItemCollapsed: %s" % self.tree.GetItemText(item))
event.Skip()
#---------------------------------------------
def OnTreeLeftDown(self, event):
# reset the overview text if the tree item is clicked on again
pt = event.GetPosition();
item, flags = self.tree.HitTest(pt)
if item == self.tree.GetSelection():
self.SetOverview(self.tree.GetItemText(item)+" Overview", self.curOverview)
event.Skip()
#---------------------------------------------
def OnSelChanged(self, event):
if self.dying or not self.loaded or self.skipLoad:
return
self.StopDownload()
item = event.GetItem()
itemText = self.tree.GetItemText(item)
self.LoadDemo(itemText)
self.StartDownload()
#---------------------------------------------
def LoadDemo(self, demoName):
try:
wx.BeginBusyCursor()
self.pnl.Freeze()
os.chdir(self.cwd)
self.ShutdownDemoModule()
if demoName == self.overviewText:
# User selected the "wxPython Overview" node
# ie: _this_ module
# Changing the main window at runtime not yet supported...
self.demoModules = DemoModules(__name__)
self.SetOverview(self.overviewText, mainOverview)
self.LoadDemoSource()
self.UpdateNotebook(0)
else:
if os.path.exists(GetOriginalFilename(demoName)):
wx.LogMessage("Loading demo %s.py..." % demoName)
self.demoModules = DemoModules(demoName)
self.LoadDemoSource()
else:
package, overview = LookForExternals(self.externalDemos, demoName)
if package:
wx.LogMessage("Loading demo %s.py..." % ("%s/%s"%(package, demoName)))
self.demoModules = DemoModules("%s/%s"%(package, demoName))
self.LoadDemoSource()
elif overview:
self.SetOverview(demoName, overview)
self.codePage = None
self.UpdateNotebook(0)
else:
self.SetOverview("wxPython", mainOverview)
self.codePage = None
self.UpdateNotebook(0)
finally:
wx.EndBusyCursor()
self.pnl.Thaw()
#---------------------------------------------
def LoadDemoSource(self):
self.codePage = None
self.codePage = DemoCodePanel(self.nb, self)
self.codePage.LoadDemo(self.demoModules)
#---------------------------------------------
def RunModule(self):
"""Runs the active module"""
module = self.demoModules.GetActive()
self.ShutdownDemoModule()
overviewText = ""
# o The RunTest() for all samples must now return a window that can
# be palced in a tab in the main notebook.
# o If an error occurs (or has occurred before) an error tab is created.
if module is not None:
wx.LogMessage("Running demo module...")
if hasattr(module, "overview"):
overviewText = module.overview
try:
self.demoPage = module.runTest(self, self.nb, self)
except:
self.demoPage = DemoErrorPanel(self.nb, self.codePage,
DemoError(sys.exc_info()), self)
bg = self.nb.GetThemeBackgroundColour()
if bg:
self.demoPage.SetBackgroundColour(bg)
assert self.demoPage is not None, "runTest must return a window!"
else:
# There was a previous error in compiling or exec-ing
self.demoPage = DemoErrorPanel(self.nb, self.codePage,
self.demoModules.GetErrorInfo(), self)
self.SetOverview(self.demoModules.name + " Overview", overviewText)
if self.firstTime:
# change to the demo page the first time a module is run
self.UpdateNotebook(2)
self.firstTime = False
else:
# otherwise just stay on the same tab in case the user has changed to another one
self.UpdateNotebook()
#---------------------------------------------
def ShutdownDemoModule(self):
if self.demoPage:
# inform the window that it's time to quit if it cares
if hasattr(self.demoPage, "ShutdownDemo"):
self.demoPage.ShutdownDemo()
## wx.YieldIfNeeded() # in case the page has pending events
self.demoPage = None
#---------------------------------------------
def UpdateNotebook(self, select = -1):
nb = self.nb
debug = False
self.pnl.Freeze()
def UpdatePage(page, pageText):
pageExists = False
pagePos = -1
for i in range(nb.GetPageCount()):
if nb.GetPageText(i) == pageText:
pageExists = True
pagePos = i
break
if page:
if not pageExists:
# Add a new page
nb.AddPage(page, pageText, imageId=nb.GetPageCount())
if debug: wx.LogMessage("DBG: ADDED %s" % pageText)
else:
if nb.GetPage(pagePos) != page:
# Reload an existing page
nb.DeletePage(pagePos)
nb.InsertPage(pagePos, page, pageText, imageId=pagePos)
if debug: wx.LogMessage("DBG: RELOADED %s" % pageText)
else:
# Excellent! No redraw/flicker
if debug: wx.LogMessage("DBG: SAVED from reloading %s" % pageText)
elif pageExists:
# Delete a page
nb.DeletePage(pagePos)
if debug: wx.LogMessage("DBG: DELETED %s" % pageText)
else:
if debug: wx.LogMessage("DBG: STILL GONE - %s" % pageText)
if select == -1:
select = nb.GetSelection()
UpdatePage(self.codePage, "Demo Code")
UpdatePage(self.demoPage, "Demo")
if select >= 0 and select < nb.GetPageCount():
nb.SetSelection(select)
self.pnl.Thaw()
#---------------------------------------------
def SetOverview(self, name, text):
self.curOverview = text
lead = text[:6]
if lead != '<html>' and lead != '<HTML>':
text = '<br>'.join(text.split('\n'))
if wx.USE_UNICODE:
text = text.decode('iso8859_1')
self.ovr.SetPage(text)
self.nb.SetPageText(0, os.path.split(name)[1])
#---------------------------------------------
def StartDownload(self):
if self.downloading or not self.allowDocs:
return
item = self.tree.GetSelection()
if self.tree.ItemHasChildren(item):
return
itemText = self.tree.GetItemText(item)
if itemText in self.pickledData:
self.LoadDocumentation(self.pickledData[itemText])
return
text = self.curOverview
text += "<br><p><b>Checking for documentation on the wxWidgets website, please stand by...</b><br>"
lead = text[:6]
if lead != '<html>' and lead != '<HTML>':
text = '<br>'.join(text.split('\n'))
self.ovr.SetPage(text)
self.downloadTimer.Start(100)
self.downloadGauge.Show()
self.Reposition()
self.downloading = True
self.internetThread = InternetThread(self, itemText)
#---------------------------------------------
def StopDownload(self, error=None):
self.downloadTimer.Stop()
if not self.downloading:
return
if error:
if self.sendDownloadError:
self.log.write("Warning: problems in downloading documentation from the wxWidgets website.\n")
self.log.write("Error message from the documentation downloader was:\n")
self.log.write("\n".join(error))
self.sendDownloadError = False
self.nb.SetPageImage(0, 0)
self.internetThread.keepRunning = False
self.internetThread = None
self.downloading = False
self.downloadGauge.Hide()
self.Reposition()
text = self.curOverview
lead = text[:6]
if lead != '<html>' and lead != '<HTML>':
text = '<br>'.join(text.split('\n'))
self.ovr.SetPage(text)
#---------------------------------------------
def LoadDocumentation(self, data):
text = self.curOverview
addHtml = False
if '<html>' not in text and '<HTML>' not in text:
text = '<br>'.join(text.split('\n'))
styles, events, extra, appearance = data
if appearance:
text += FormatImages(appearance)
for names, values in zip(["Styles", "Extra Styles", "Events"], [styles, extra, events]):
if not values:
continue
headers = (names == "Events" and [2] or [3])[0]
text += "<p>" + FormatDocs(names, values, headers)
item = self.tree.GetSelection()
itemText = self.tree.GetItemText(item)
self.pickledData[itemText] = data
if wx.USE_UNICODE:
text = text.decode('iso8859_1')
self.StopDownload()
self.ovr.SetPage(text)
#print "load time: ", time.time() - start
# Menu methods
def OnFileExit(self, *event):
self.Close()
def OnToggleRedirect(self, event):
app = wx.GetApp()
if event.Checked():
app.RedirectStdio()
print "Print statements and other standard output will now be directed to this window."
else:
app.RestoreStdio()
print "Print statements and other standard output will now be sent to the usual location."
def OnAllowDownload(self, event):
self.allowDocs = event.Checked()
if self.allowDocs:
self.StartDownload()
else:
self.StopDownload()
def OnDeleteDocs(self, event):
deleteMsg = "You are about to delete the downloaded documentation.\n" + \
"Do you want to continue?"
dlg = wx.MessageDialog(self, deleteMsg, "wxPython Demo",
wx.YES_NO | wx.NO_DEFAULT| wx.ICON_QUESTION)
result = dlg.ShowModal()
if result == wx.ID_NO:
dlg.Destroy()
return
dlg.Destroy()
busy = wx.BusyInfo("Deleting downloaded data...")
wx.SafeYield()
pickledFile = GetDocFile()
docDir = os.path.split(pickledFile)[0]
if os.path.exists(docDir):
shutil.rmtree(docDir, ignore_errors=True)
self.pickledData = {}
del busy
self.sendDownloadError = True
def OnAllowAuiFloating(self, event):
self.allowAuiFloating = event.Checked()
for pane in self.mgr.GetAllPanes():
if pane.name != "Notebook":
pane.Floatable(self.allowAuiFloating)
self.EnableAUIMenu()
self.mgr.Update()
def EnableAUIMenu(self):
menuItems = self.options_menu.GetMenuItems()
for indx in xrange(4, len(menuItems)-1):
item = menuItems[indx]
item.Enable(self.allowAuiFloating)
def OnAUIPerspectives(self, event):
perspective = self.perspectives_menu.GetLabel(event.GetId())
self.mgr.LoadPerspective(self.auiConfigurations[perspective])
self.mgr.Update()
def OnSavePerspective(self, event):
dlg = wx.TextEntryDialog(self, "Enter a name for the new perspective:", "AUI Configuration")
dlg.SetValue(("Perspective %d")%(len(self.auiConfigurations)+1))
if dlg.ShowModal() != wx.ID_OK:
return
perspectiveName = dlg.GetValue()
menuItems = self.perspectives_menu.GetMenuItems()
for item in menuItems:
if item.GetLabel() == perspectiveName:
wx.MessageBox("The selected perspective name:\n\n%s\n\nAlready exists."%perspectiveName,
"Error", style=wx.ICON_ERROR)
return
item = wx.MenuItem(self.perspectives_menu, -1, dlg.GetValue(),
"Load user perspective %d"%(len(self.auiConfigurations)+1),
wx.ITEM_RADIO)
self.Bind(wx.EVT_MENU, self.OnAUIPerspectives, item)
self.perspectives_menu.AppendItem(item)
item.Check(True)
self.auiConfigurations.update({dlg.GetValue(): self.mgr.SavePerspective()})
def OnDeletePerspective(self, event):
menuItems = self.perspectives_menu.GetMenuItems()
lst = []
loadDefault = False
for indx, item in enumerate(menuItems):
if indx > 0:
lst.append(item.GetLabel())
dlg = wx.MultiChoiceDialog(self,
"Please select the perspectives\nyou would like to delete:",
"Delete AUI Perspectives", lst)
if dlg.ShowModal() == wx.ID_OK:
selections = dlg.GetSelections()
strings = [lst[x] for x in selections]
for sel in strings:
self.auiConfigurations.pop(sel)
item = menuItems[lst.index(sel)+1]
if item.IsChecked():
loadDefault = True
self.perspectives_menu.GetMenuItems()[0].Check(True)
self.perspectives_menu.DeleteItem(item)
lst.remove(sel)
if loadDefault:
self.mgr.LoadPerspective(self.auiConfigurations[DEFAULT_PERSPECTIVE])
self.mgr.Update()
def OnTreeExpansion(self, event):
self.tree.SetExpansionState(self.expansionState)
def OnHelpAbout(self, event):
from About import MyAboutBox
about = MyAboutBox(self)
about.ShowModal()
about.Destroy()
def OnHelpFind(self, event):
if self.finddlg != None:
return
self.nb.SetSelection(1)
self.finddlg = wx.FindReplaceDialog(self, self.finddata, "Find",
wx.FR_NOMATCHCASE | wx.FR_NOWHOLEWORD)
self.finddlg.Show(True)
def OnUpdateFindItems(self, evt):
evt.Enable(self.finddlg == None)
def OnFind(self, event):
editor = self.codePage.editor
self.nb.SetSelection(1)
end = editor.GetLastPosition()
textstring = editor.GetRange(0, end).lower()
findstring = self.finddata.GetFindString().lower()
backward = not (self.finddata.GetFlags() & wx.FR_DOWN)
if backward:
start = editor.GetSelection()[0]
loc = textstring.rfind(findstring, 0, start)
else:
start = editor.GetSelection()[1]
loc = textstring.find(findstring, start)
if loc == -1 and start != 0:
# string not found, start at beginning
if backward:
start = end
loc = textstring.rfind(findstring, 0, start)
else:
start = 0
loc = textstring.find(findstring, start)
if loc == -1:
dlg = wx.MessageDialog(self, 'Find String Not Found',
'Find String Not Found in Demo File',
wx.OK | wx.ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
if self.finddlg:
if loc == -1:
self.finddlg.SetFocus()
return
else:
self.finddlg.Destroy()
self.finddlg = None
editor.ShowPosition(loc)
editor.SetSelection(loc, loc + len(findstring))
def OnFindNext(self, event):
if self.finddata.GetFindString():
self.OnFind(event)
else:
self.OnHelpFind(event)
def OnFindClose(self, event):
event.GetDialog().Destroy()
self.finddlg = None
def OnOpenShellWindow(self, evt):
if self.shell:
# if it already exists then just make sure it's visible
s = self.shell
if s.IsIconized():
s.Iconize(False)
s.Raise()
else:
# Make a PyShell window
from wx import py
namespace = { 'wx' : wx,
'app' : wx.GetApp(),
'frame' : self,
}
self.shell = py.shell.ShellFrame(None, locals=namespace)
self.shell.SetSize((640,480))
self.shell.Show()
# Hook the close event of the main frame window so that we
# close the shell at the same time if it still exists
def CloseShell(evt):
if self.shell:
self.shell.Close()
evt.Skip()
self.Bind(wx.EVT_CLOSE, CloseShell)
def OnOpenWidgetInspector(self, evt):
# Activate the widget inspection tool
from wx.lib.inspection import InspectionTool
if not InspectionTool().initialized:
InspectionTool().Init()
# Find a widget to be selected in the tree. Use either the
# one under the cursor, if any, or this frame.
wnd = wx.FindWindowAtPointer()
if not wnd:
wnd = self
InspectionTool().Show(wnd, True)
#---------------------------------------------
def OnCloseWindow(self, event):
self.mgr.UnInit()
self.dying = True
self.demoPage = None
self.codePage = None
self.mainmenu = None
self.StopDownload()
if self.tbicon is not None:
self.tbicon.Destroy()
config = GetConfig()
config.Write('ExpansionState', str(self.tree.GetExpansionState()))
config.Write('AUIPerspectives', str(self.auiConfigurations))
config.Write('AllowDownloads', str(self.allowDocs))
config.Write('AllowAUIFloating', str(self.allowAuiFloating))
config.Flush()
MakeDocDirs()
pickledFile = GetDocFile()
fid = open(pickledFile, "wb")
cPickle.dump(self.pickledData, fid, cPickle.HIGHEST_PROTOCOL)
fid.close()
self.Destroy()
#---------------------------------------------
def OnIdle(self, event):
if self.otherWin:
self.otherWin.Raise()
self.demoPage = self.otherWin
self.otherWin = None
#---------------------------------------------
def OnDownloadTimer(self, event):
self.downloadGauge.Pulse()
self.downloadImage += 1
if self.downloadImage > 9:
self.downloadImage = 3
self.nb.SetPageImage(0, self.downloadImage)
## wx.SafeYield()
#---------------------------------------------
def ShowTip(self):
config = GetConfig()
showTipText = config.Read("tips")
if showTipText:
showTip, index = eval(showTipText)
else:
showTip, index = (1, 0)
if showTip:
tp = wx.CreateFileTipProvider(opj("data/tips.txt"), index)
showTip = wx.ShowTip(self, tp)
index = tp.GetCurrentTip()
config.Write("tips", str( (showTip, index) ))
config.Flush()
#---------------------------------------------
def OnDemoMenu(self, event):
try:
selectedDemo = self.treeMap[self.mainmenu.GetLabel(event.GetId())]
except:
selectedDemo = None
if selectedDemo:
self.tree.SelectItem(selectedDemo)
self.tree.EnsureVisible(selectedDemo)
#---------------------------------------------
def OnIconfiy(self, evt):
wx.LogMessage("OnIconfiy: %s" % evt.Iconized())
evt.Skip()
#---------------------------------------------
def OnMaximize(self, evt):
wx.LogMessage("OnMaximize")
evt.Skip()
#---------------------------------------------
def OnActivate(self, evt):
wx.LogMessage("OnActivate: %s" % evt.GetActive())
evt.Skip()
#---------------------------------------------
def OnAppActivate(self, evt):
wx.LogMessage("OnAppActivate: %s" % evt.GetActive())
evt.Skip()
#---------------------------------------------------------------------------
#---------------------------------------------------------------------------
class MySplashScreen(wx.SplashScreen):
def __init__(self):
bmp = wx.Image(opj("bitmaps/splash.png")).ConvertToBitmap()
wx.SplashScreen.__init__(self, bmp,
wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT,
5000, None, -1)
self.Bind(wx.EVT_CLOSE, self.OnClose)
self.fc = wx.FutureCall(2000, self.ShowMain)
def OnClose(self, evt):
# Make sure the default handler runs too so this window gets
# destroyed
evt.Skip()
self.Hide()
# if the timer is still running then go ahead and show the
# main frame now
if self.fc.IsRunning():
self.fc.Stop()
self.ShowMain()
def ShowMain(self):
frame = wxPythonDemo(None, "wxPython: (A Demonstration)")
frame.Show()
if self.fc.IsRunning():
self.Raise()
wx.CallAfter(frame.ShowTip)
#---------------------------------------------------------------------------
from wx.lib.mixins.treemixin import ExpansionState
if USE_CUSTOMTREECTRL:
import wx.lib.customtreectrl as CT
TreeBaseClass = CT.CustomTreeCtrl
else:
TreeBaseClass = wx.TreeCtrl
class wxPythonDemoTree(ExpansionState, TreeBaseClass):
def __init__(self, parent):
TreeBaseClass.__init__(self, parent, style=wx.TR_DEFAULT_STYLE|
wx.TR_HAS_VARIABLE_ROW_HEIGHT)
self.BuildTreeImageList()
if USE_CUSTOMTREECTRL:
self.SetSpacing(10)
self.SetWindowStyle(self.GetWindowStyle() & ~wx.TR_LINES_AT_ROOT)
self.SetInitialSize((100,80))
def AppendItem(self, parent, text, image=-1, wnd=None):
if USE_CUSTOMTREECTRL:
item = TreeBaseClass.AppendItem(self, parent, text, image=image, wnd=wnd)
else:
item = TreeBaseClass.AppendItem(self, parent, text, image=image)
return item
def BuildTreeImageList(self):
imgList = wx.ImageList(16, 16)
for png in _demoPngs:
imgList.Add(images.catalog[png].GetBitmap())
# add the image for modified demos.
imgList.Add(images.catalog["custom"].GetBitmap())
self.AssignImageList(imgList)
def GetItemIdentity(self, item):
return self.GetPyData(item)
def Freeze(self):
if 'wxMSW' in wx.PlatformInfo:
return super(wxPythonDemoTree, self).Freeze()
def Thaw(self):
if 'wxMSW' in wx.PlatformInfo:
return super(wxPythonDemoTree, self).Thaw()
#---------------------------------------------------------------------------
class MyApp(wx.App, wx.lib.mixins.inspection.InspectionMixin):
def OnInit(self):
# Check runtime version
if version.VERSION_STRING != wx.VERSION_STRING:
wx.MessageBox(caption="Warning",
message="You're using version %s of wxPython, but this copy of the demo was written for version %s.\n"
"There may be some version incompatibilities..."
% (wx.VERSION_STRING, version.VERSION_STRING))
self.InitInspection() # for the InspectionMixin base class
# Now that we've warned the user about possibile problems,
# lets import images
import images as i
global images
images = i
# For debugging
#self.SetAssertMode(wx.PYAPP_ASSERT_DIALOG|wx.PYAPP_ASSERT_EXCEPTION)
wx.SystemOptions.SetOptionInt("mac.window-plain-transition", 1)
self.SetAppName("wxPyDemo")
# Create and show the splash screen. It will then create and
# show the main frame when it is time to do so. Normally when
# using a SplashScreen you would create it, show it and then
# continue on with the applicaiton's initialization, finally
# creating and showing the main application window(s). In
# this case we have nothing else to do so we'll delay showing
# the main frame until later (see ShowMain above) so the users
# can see the SplashScreen effect.
splash = MySplashScreen()
splash.Show()
return True
#---------------------------------------------------------------------------
def main():
try:
demoPath = os.path.dirname(__file__)
os.chdir(demoPath)
except:
pass
app = MyApp(False)
app.MainLoop()
#---------------------------------------------------------------------------
mainOverview = """<html><body>
<h2>wxPython</h2>
<p> wxPython is a <b>GUI toolkit</b> for the Python programming
language. It allows Python programmers to create programs with a
robust, highly functional graphical user interface, simply and easily.
It is implemented as a Python extension module (native code) that
wraps the popular wxWindows cross platform GUI library, which is
written in C++.
<p> Like Python and wxWindows, wxPython is <b>Open Source</b> which
means that it is free for anyone to use and the source code is
available for anyone to look at and modify. Or anyone can contribute
fixes or enhancements to the project.
<p> wxPython is a <b>cross-platform</b> toolkit. This means that the
same program will run on multiple platforms without modification.
Currently supported platforms are 32-bit Microsoft Windows, most Unix
or unix-like systems, and Macintosh OS X. Since the language is
Python, wxPython programs are <b>simple, easy</b> to write and easy to
understand.
<p> <b>This demo</b> is not only a collection of test cases for
wxPython, but is also designed to help you learn about and how to use
wxPython. Each sample is listed in the tree control on the left.
When a sample is selected in the tree then a module is loaded and run
(usually in a tab of this notebook,) and the source code of the module
is loaded in another tab for you to browse and learn from.
"""
#----------------------------------------------------------------------------
#----------------------------------------------------------------------------
if __name__ == '__main__':
__name__ = 'Main'
main()
#----------------------------------------------------------------------------
|