/usr/lib/python2.7/dist-packages/DisplayCAL/wxwindows.py is in dispcalgui 3.1.0.0-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 | # -*- coding: utf-8 -*-
from datetime import datetime
from time import gmtime, sleep, strftime, time
import errno
import math
import os
import re
import socket
import string
import subprocess as sp
import sys
import tarfile
import threading
import warnings
import xml.parsers.expat
import zipfile
import demjson
import ICCProfile as ICCP
import audio
import config
from config import (defaults, getbitmap, getcfg, geticon, get_data_path,
get_default_dpi, get_verified_path, pyname, setcfg,
confighome, appbasename, logdir, set_default_app_dpi)
from debughelpers import getevtobjname, getevttype, handle_error
from log import log as log_, safe_print
from meta import name as appname
from options import debug
from ordereddict import OrderedDict
from network import ScriptingClientSocket
from util_io import StringIOu as StringIO
from util_os import get_program_file, launch_file, waccess
from util_str import safe_str, safe_unicode, wrap
from util_xml import dict2xml
from wxaddons import (CustomEvent, FileDrop as _FileDrop,
get_platform_window_decoration_size, wx,
BetterWindowDisabler, BetterTimer, EVT_BETTERTIMER)
from wexpect import split_command_line
from wxfixes import (GenBitmapButton, GenButton, GTKMenuItemGetFixedLabel,
ThemedGenButton, adjust_font_size_for_gcdc,
get_dc_font_size, set_bitmap_labels)
from lib.agw import labelbook, pygauge
from lib.agw.gradientbutton import GradientButton, HOVER
from lib.agw.fourwaysplitter import (_TOLERANCE, FLAG_CHANGED, FLAG_PRESSED,
NOWHERE, FourWaySplitter,
FourWaySplitterEvent)
import localization as lang
import util_str
import floatspin
try:
from wx.lib.agw import aui
from wx.lib.agw.aui import AuiDefaultTabArt
except ImportError:
from wx import aui
from wx.aui import PyAuiTabArt as AuiDefaultTabArt
import wx.lib.filebrowsebutton as filebrowse
from wx.lib import fancytext
from wx.lib.statbmp import GenStaticBitmap
import wx.html
numpad_keycodes = [wx.WXK_NUMPAD0,
wx.WXK_NUMPAD1,
wx.WXK_NUMPAD2,
wx.WXK_NUMPAD3,
wx.WXK_NUMPAD4,
wx.WXK_NUMPAD5,
wx.WXK_NUMPAD6,
wx.WXK_NUMPAD7,
wx.WXK_NUMPAD8,
wx.WXK_NUMPAD9,
wx.WXK_NUMPAD_ADD,
wx.WXK_NUMPAD_DECIMAL,
wx.WXK_NUMPAD_ENTER,
wx.WXK_NUMPAD_EQUAL,
wx.WXK_NUMPAD_DIVIDE,
wx.WXK_NUMPAD_MULTIPLY,
wx.WXK_NUMPAD_SEPARATOR,
wx.WXK_NUMPAD_SUBTRACT]
def Property(func):
return property(**func())
class AboutDialog(wx.Dialog):
def __init__(self, *args, **kwargs):
kwargs["style"] = wx.DEFAULT_DIALOG_STYLE & ~(wx.RESIZE_BORDER |
wx.MAXIMIZE_BOX)
kwargs["name"] = "aboutdialog"
wx.Dialog.__init__(self, *args, **kwargs)
self.set_properties()
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(self.sizer)
def set_properties(self):
icon = wx.EmptyIcon()
self.SetIcon(icon)
def OnClose(self, event):
self.Hide()
def Layout(self):
self.sizer.SetSizeHints(self)
self.sizer.Layout()
def add_items(self, items):
self.ok = ThemedGenButton(self, -1, lang.getstr("ok"))
self.Bind(wx.EVT_BUTTON, self.OnClose, id=self.ok.GetId())
items.extend([self.ok, (1, 16)])
pointsize = 10
for item in items:
if isinstance(item, wx.Window):
font = item.GetFont()
if item.GetLabel() and font.GetPointSize() > pointsize:
font.SetPointSize(pointsize)
item.SetFont(font)
flag = wx.ALIGN_CENTER_HORIZONTAL
if isinstance(item, (wx.Panel, wx.PyPanel)):
flag |= wx.EXPAND
else:
flag |= wx.LEFT | wx.RIGHT
self.sizer.Add(item, 0, flag, 12)
self.ok.SetDefault()
self.ok.SetFocus()
class AnimatedBitmap(wx.PyControl):
""" Animated bitmap """
def __init__(self, parent, id=wx.ID_ANY, bitmaps=None, range=(0, -1),
loop=True, pos=wx.DefaultPosition, size=wx.DefaultSize,
style=wx.NO_BORDER):
"""
Create animated bitmap
bitmaps should be an array of bitmaps.
range should be the indexes of the range of frames that should be looped.
-1 means last frame.
"""
wx.PyControl.__init__(self, parent, id, pos, size, style)
self._minsize = size
self.SetBitmaps(bitmaps or [], range, loop)
# Avoid flickering under Windows
self.Bind(wx.EVT_ERASE_BACKGROUND, lambda event: None)
self.Bind(wx.EVT_PAINT, self.OnPaint)
self._timer = BetterTimer(self)
self.Bind(EVT_BETTERTIMER, self.OnTimer, self._timer)
self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
def OnDestroy(self, event):
self._timer.Stop()
del self._timer
def DoGetBestSize(self):
return self._minsize
def OnPaint(self, event):
dc = wx.BufferedPaintDC(self)
dc.SetBackground(wx.Brush(self.Parent.BackgroundColour))
dc.Clear()
if self._bitmaps:
if self.frame > len(self._bitmaps) - 1:
self.frame = len(self._bitmaps) - 1
dc.DrawBitmap(self._bitmaps[self.frame], 0, 0, True)
def OnTimer(self, event):
first_frame, last_frame = self.range
if first_frame < 0:
first_frame += len(self._bitmaps)
if last_frame < 0:
last_frame += len(self._bitmaps)
frame = self.frame
if frame < last_frame:
frame += 1
elif self.loop:
frame = first_frame
if frame != self.frame:
self.frame = frame
self.Refresh()
def Play(self, fps=24):
self._timer.Start(1000.0 / fps)
def Stop(self):
self._timer.Stop()
def SetBitmaps(self, bitmaps, range=(0, -1), loop=True):
w, h = self._minsize
for bitmap in bitmaps:
w = max(bitmap.Size[0], w)
h = max(bitmap.Size[0], h)
self._minsize = w, h
self._bitmaps = bitmaps
self.loop = loop
self.range = range
self.frame = 0
class AuiBetterTabArt(AuiDefaultTabArt):
def DrawTab(self, dc, wnd, page, in_rect, close_button_state, paint_control=False):
"""
Draws a single tab.
:param `dc`: a :class:`DC` device context;
:param `wnd`: a :class:`Window` instance object;
:param `page`: the tab control page associated with the tab;
:param Rect `in_rect`: rectangle the tab should be confined to;
:param integer `close_button_state`: the state of the close button on the tab;
:param bool `paint_control`: whether to draw the control inside a tab (if any) on a :class:`MemoryDC`.
"""
# if the caption is empty, measure some temporary text
caption = page.caption
if not caption:
caption = "Xj"
dc.SetFont(self._selected_font)
if hasattr(dc, "GetFullMultiLineTextExtent"):
# Phoenix
selected_textx, selected_texty = dc.GetMultiLineTextExtent(caption)
else:
# Classic
selected_textx, selected_texty, dummy = dc.GetMultiLineTextExtent(caption)
dc.SetFont(self._normal_font)
if hasattr(dc, "GetFullMultiLineTextExtent"):
# Phoenix
normal_textx, normal_texty = dc.GetMultiLineTextExtent(caption)
else:
# Classic
normal_textx, normal_texty, dummy = dc.GetMultiLineTextExtent(caption)
control = page.control
# figure out the size of the tab
tab_size, x_extent = self.GetTabSize(dc, wnd, page.caption, page.bitmap,
page.active, close_button_state, control)
tab_height = self._tab_ctrl_height - 3
tab_width = tab_size[0]
tab_x = in_rect.x
tab_y = in_rect.y + in_rect.height - tab_height
caption = page.caption
# select pen, brush and font for the tab to be drawn
if page.active:
dc.SetFont(self._selected_font)
textx, texty = selected_textx, selected_texty
else:
dc.SetFont(self._normal_font)
textx, texty = normal_textx, normal_texty
if not page.enabled:
dc.SetTextForeground(self._tab_disabled_text_colour)
pagebitmap = page.dis_bitmap
else:
dc.SetTextForeground(self._tab_text_colour(page))
pagebitmap = page.bitmap
# create points that will make the tab outline
clip_width = tab_width
if tab_x + clip_width > in_rect.x + in_rect.width:
clip_width = in_rect.x + in_rect.width - tab_x
# since the above code above doesn't play well with WXDFB or WXCOCOA,
# we'll just use a rectangle for the clipping region for now --
dc.SetClippingRegion(tab_x, tab_y, clip_width+1, tab_height-3)
border_points = [wx.Point() for i in xrange(6)]
agwFlags = self.GetAGWFlags()
if agwFlags & aui.AUI_NB_BOTTOM:
border_points[0] = wx.Point(tab_x, tab_y)
border_points[1] = wx.Point(tab_x, tab_y+tab_height-6)
border_points[2] = wx.Point(tab_x+2, tab_y+tab_height-4)
border_points[3] = wx.Point(tab_x+tab_width-2, tab_y+tab_height-4)
border_points[4] = wx.Point(tab_x+tab_width, tab_y+tab_height-6)
border_points[5] = wx.Point(tab_x+tab_width, tab_y)
else: #if (agwFlags & aui.AUI_NB_TOP)
border_points[0] = wx.Point(tab_x, tab_y+tab_height-4)
border_points[1] = wx.Point(tab_x, tab_y+2)
border_points[2] = wx.Point(tab_x+2, tab_y)
border_points[3] = wx.Point(tab_x+tab_width-2, tab_y)
border_points[4] = wx.Point(tab_x+tab_width, tab_y+2)
border_points[5] = wx.Point(tab_x+tab_width, tab_y+tab_height-4)
# TODO: else if (agwFlags & aui.AUI_NB_LEFT)
# TODO: else if (agwFlags & aui.AUI_NB_RIGHT)
drawn_tab_yoff = border_points[1].y
drawn_tab_height = border_points[0].y - border_points[1].y
if page.active:
# draw active tab
# draw base background colour
r = wx.Rect(tab_x, tab_y, tab_width, tab_height)
dc.SetPen(self._base_colour_pen)
dc.SetBrush(self._base_colour_brush)
dc.DrawRectangle(r.x+1, r.y+1, r.width-1, r.height-4)
# this white helps fill out the gradient at the top of the tab
dc.SetPen( wx.Pen(self._tab_gradient_highlight_colour) )
dc.SetBrush( wx.Brush(self._tab_gradient_highlight_colour) )
dc.DrawRectangle(r.x+2, r.y+1, r.width-3, r.height-4)
# these two points help the rounded corners appear more antialiased
dc.SetPen(self._base_colour_pen)
dc.DrawPoint(r.x+2, r.y+1)
dc.DrawPoint(r.x+r.width-2, r.y+1)
# set rectangle down a bit for gradient drawing
r.SetHeight(r.GetHeight()/2)
r.x += 2
r.width -= 3
r.y += r.height
r.y -= 2
# draw gradient background
top_colour = self._tab_bottom_colour
bottom_colour = self._tab_top_colour
dc.GradientFillLinear(r, bottom_colour, top_colour, wx.NORTH)
else:
# draw inactive tab
r = wx.Rect(tab_x, tab_y+1, tab_width, tab_height-3)
# start the gradent up a bit and leave the inside border inset
# by a pixel for a 3D look. Only the top half of the inactive
# tab will have a slight gradient
r.x += 2
r.y += 1
r.width -= 3
r.height /= 2
# -- draw top gradient fill for glossy look
top_colour = self._tab_inactive_top_colour
bottom_colour = self._tab_inactive_bottom_colour
dc.GradientFillLinear(r, bottom_colour, top_colour, wx.NORTH)
r.y += r.height
r.y -= 1
# -- draw bottom fill for glossy look
top_colour = self._tab_inactive_bottom_colour
bottom_colour = self._tab_inactive_bottom_colour
dc.GradientFillLinear(r, top_colour, bottom_colour, wx.SOUTH)
# draw tab outline
dc.SetPen(self._border_pen)
dc.SetBrush(wx.TRANSPARENT_BRUSH)
dc.DrawPolygon(border_points)
# there are two horizontal grey lines at the bottom of the tab control,
# this gets rid of the top one of those lines in the tab control
if page.active:
if agwFlags & aui.AUI_NB_BOTTOM:
dc.SetPen(wx.Pen(self._background_bottom_colour))
# TODO: else if (agwFlags & aui.AUI_NB_LEFT)
# TODO: else if (agwFlags & aui.AUI_NB_RIGHT)
else: # for aui.AUI_NB_TOP
dc.SetPen(self._base_colour_pen)
dc.DrawLine(border_points[0].x+1,
border_points[0].y,
border_points[5].x,
border_points[5].y)
text_offset = tab_x + 8
close_button_width = 0
if close_button_state != aui.AUI_BUTTON_STATE_HIDDEN:
close_button_width = self._active_close_bmp.GetWidth()
if agwFlags & aui.AUI_NB_CLOSE_ON_TAB_LEFT:
text_offset += close_button_width - 5
bitmap_offset = 0
if pagebitmap.IsOk():
bitmap_offset = tab_x + 8
if agwFlags & aui.AUI_NB_CLOSE_ON_TAB_LEFT and close_button_width:
bitmap_offset += close_button_width - 5
# draw bitmap
dc.DrawBitmap(pagebitmap,
bitmap_offset,
drawn_tab_yoff + (drawn_tab_height/2) - (pagebitmap.GetHeight()/2),
True)
text_offset = bitmap_offset + pagebitmap.GetWidth()
text_offset += 3 # bitmap padding
else:
if agwFlags & aui.AUI_NB_CLOSE_ON_TAB_LEFT == 0 or not close_button_width:
text_offset = tab_x + 8
draw_text = aui.ChopText(dc, caption, tab_width - (text_offset-tab_x) - close_button_width)
ypos = drawn_tab_yoff + (drawn_tab_height)/2 - (texty/2) - 1
offset_focus = text_offset
if control is not None:
try:
if control.GetPosition() != wx.Point(text_offset+1, ypos):
control.SetPosition(wx.Point(text_offset+1, ypos))
if not control.IsShown():
control.Show()
if paint_control:
bmp = aui.TakeScreenShot(control.GetScreenRect())
dc.DrawBitmap(bmp, text_offset+1, ypos, True)
controlW, controlH = control.GetSize()
text_offset += controlW + 4
textx += controlW + 4
except wx.PyDeadObjectError:
pass
# draw tab text
if hasattr(dc, "GetFullMultiLineTextExtent"):
# Phoenix
rectx, recty = dc.GetMultiLineTextExtent(draw_text)
else:
# Classic
rectx, recty, dummy = dc.GetMultiLineTextExtent(draw_text)
textfg = dc.GetTextForeground()
shadow = wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DLIGHT)
dc.SetTextForeground(shadow)
dc.DrawLabel(draw_text, wx.Rect(text_offset + 1, ypos + 1, rectx, recty))
dc.SetTextForeground(textfg)
dc.DrawLabel(draw_text, wx.Rect(text_offset, ypos, rectx, recty))
# draw focus rectangle
if (agwFlags & aui.AUI_NB_NO_TAB_FOCUS) == 0:
self.DrawFocusRectangle(dc, page, wnd, draw_text, offset_focus, bitmap_offset, drawn_tab_yoff, drawn_tab_height, rectx, recty)
out_button_rect = wx.Rect()
# draw close button if necessary
if close_button_state != aui.AUI_BUTTON_STATE_HIDDEN:
bmp = self._disabled_close_bmp
if close_button_state == aui.AUI_BUTTON_STATE_HOVER:
bmp = self._hover_close_bmp
elif close_button_state == aui.AUI_BUTTON_STATE_PRESSED:
bmp = self._pressed_close_bmp
shift = (agwFlags & aui.AUI_NB_BOTTOM and [1] or [0])[0]
if agwFlags & aui.AUI_NB_CLOSE_ON_TAB_LEFT:
rect = wx.Rect(tab_x + 4, tab_y + (tab_height - bmp.GetHeight())/2 - shift,
close_button_width, tab_height)
else:
rect = wx.Rect(tab_x + tab_width - close_button_width - 1,
tab_y + (tab_height - bmp.GetHeight())/2 - shift,
close_button_width, tab_height)
rect = aui.IndentPressedBitmap(rect, close_button_state)
dc.DrawBitmap(bmp, rect.x, rect.y, True)
out_button_rect = rect
out_tab_rect = wx.Rect(tab_x, tab_y, tab_width, tab_height)
dc.DestroyClippingRegion()
return out_tab_rect, out_button_rect, x_extent
def SetDefaultColours(self, base_colour=None):
"""
Sets the default colours, which are calculated from the given base colour.
:param `base_colour`: an instance of :class:`Colour`. If defaulted to ``None``, a colour
is generated accordingly to the platform and theme.
"""
if base_colour is None:
base_colour = aui.GetBaseColour()
self.SetBaseColour( base_colour )
self._border_colour = aui.StepColour(base_colour, 75)
self._border_pen = wx.Pen(self._border_colour)
self._background_top_colour = aui.StepColour(self._base_colour, 90)
self._background_bottom_colour = aui.StepColour(self._base_colour, 120)
self._tab_top_colour = self._base_colour
self._tab_bottom_colour = aui.StepColour(self._base_colour, 130)
self._tab_gradient_highlight_colour = aui.StepColour(self._base_colour, 130)
self._tab_inactive_top_colour = self._background_top_colour
self._tab_inactive_bottom_colour = aui.StepColour(self._base_colour, 110)
self._tab_text_colour = lambda page: page.text_colour
self._tab_disabled_text_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT)
class BaseApp(wx.App):
""" Application base class implementing common functionality. """
_exithandlers = []
_mainloopexit = False
def OnInit(self):
self.AppName = pyname
set_default_app_dpi()
return True
def MacOpenFiles(self, paths):
if (self.TopWindow and
isinstance(getattr(self.TopWindow, "droptarget", None), FileDrop)):
self.TopWindow.droptarget.OnDropFiles(0, 0, paths)
def MacReopenApp(self):
if self.TopWindow and self.TopWindow.IsShownOnScreen():
self.TopWindow.Raise()
def process_argv(self, count=0):
paths = []
for arg in sys.argv[1:]:
if os.path.isfile(arg):
paths.append(safe_unicode(arg))
if len(paths) == count:
break
if paths:
self.MacOpenFiles(paths)
return paths
def ExitMainLoop(self):
BaseApp._mainloopexit = True
try:
self.TopWindow.listening = False
except:
pass
BaseApp._run_exitfuncs()
return wx.App.ExitMainLoop(self)
@staticmethod
def IsMainLoopRunning():
return not BaseApp._mainloopexit and wx.App.IsMainLoopRunning()
def OnExit(self):
BaseApp._run_exitfuncs()
@staticmethod
def _run_exitfuncs():
"""run any registered exit functions
_exithandlers is traversed in reverse order so functions are executed
last in, first out.
"""
# Inspired by python's 'atexit' module.
# It's important that the exit handlers run *before* the actual main
# loop exits, otherwise they might not run at all if the app is closed
# externally (e.g. if the OS asks the app to close on logout).
# Using the 'atexit' module will NOT work!
exc_info = None
while BaseApp._exithandlers:
func, args, kwargs = BaseApp._exithandlers.pop()
try:
func(*args, **kwargs)
except SystemExit:
exc_info = sys.exc_info()
except:
import traceback
print >> sys.stderr, "Error in BaseApp._run_exitfuncs:"
traceback.print_exc()
exc_info = sys.exc_info()
if exc_info is not None:
raise exc_info[0], exc_info[1], exc_info[2]
@staticmethod
def register_exitfunc(func, *args, **kwargs):
BaseApp._exithandlers.append((func, args, kwargs))
active_window = None
responseformats = {}
class BaseFrame(wx.Frame):
""" Main frame base class. """
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs)
self.init()
def FindWindowByName(self, name):
""" wxPython Phoenix FindWindowByName descends into the parent windows,
we don't want that """
for child in self.GetAllChildren():
if hasattr(child, "Name") and child.Name == name:
return child
def OnClose(self, event):
self.listening = False
if wx.GetApp().TopWindow is self and wx.GetApp().GetExitOnFrameDelete():
BaseApp._mainloopexit = True
BaseApp._run_exitfuncs()
event.Skip()
def OnDestroy(self, event):
self.listening = False
event.Skip()
def init(self):
self.Bind(wx.EVT_ACTIVATE, self.activate_handler)
self.Bind(wx.EVT_CLOSE, self.OnClose)
self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
def init_menubar(self):
self.MenuBar = wx.MenuBar()
filemenu = wx.Menu()
quit = filemenu.Append(-1 if wx.VERSION < (2, 9) else wx.ID_EXIT,
"&%s\tCtrl+Q" % lang.getstr("menuitem.quit"))
self.Bind(wx.EVT_MENU, lambda event: self.Close(), quit)
if sys.platform != "darwin":
self.MenuBar.Append(filemenu, "&%s" % lang.getstr("menu.file"))
def activate_handler(self, event):
global active_window
active_window = self
def listen(self):
if isinstance(getattr(sys, "_appsocket", None), socket.socket):
addr, port = sys._appsocket.getsockname()
if addr == "0.0.0.0":
try:
addr = socket.gethostbyname(socket.gethostname())
except socket.error:
pass
safe_print(lang.getstr("app.listening", (addr, port)))
self.listening = True
self.listener = threading.Thread(target=self.connection_handler,
name="ScriptingHost.ConnectionHandler")
self.listener.start()
def connect(self, ip, port):
if getattr(self, "conn", None):
self.conn.disconnect()
self.conn = ScriptingClientSocket()
self.conn.settimeout(3)
try:
self.conn.connect((ip, port))
except socket.error, exception:
del self.conn
self.conn = None
return exception
return lang.getstr("connection.established")
def connection_handler(self):
""" Handle socket connections """
self._msghandlercount = 0
while self and getattr(self, "listening", False):
try:
# Wait for connection
conn, addrport = sys._appsocket.accept()
except socket.timeout:
continue
except socket.error, exception:
if exception.errno == errno.EWOULDBLOCK:
sleep(.05)
continue
break
if (addrport[0] != "127.0.0.1" and
not getcfg("app.allow_network_clients")):
# Network client disallowed
conn.close()
safe_print(lang.getstr("app.client.network.disallowed", addrport))
sleep(.2)
continue
try:
conn.settimeout(.2)
except socket.error, exception:
conn.close()
safe_print(lang.getstr("app.client.ignored", exception))
sleep(.2)
continue
safe_print(lang.getstr("app.client.connect", addrport))
self._msghandlercount += 1
threading.Thread(target=self.message_handler,
name="ScriptingHost.MessageHandler-%d" %
self._msghandlercount,
args=(conn, addrport)).start()
sys._appsocket.close()
def message_handler(self, conn, addrport):
""" Handle messages sent via socket """
responseformats[conn] = "plain"
buffer = ""
while self and getattr(self, "listening", False):
# Wait for incoming message
try:
incoming = conn.recv(4096)
except socket.timeout:
continue
except socket.error, exception:
if exception.errno == errno.EWOULDBLOCK:
sleep(.05)
continue
break
else:
if not incoming:
break
buffer += incoming
while "\n" in buffer and self and getattr(self, "listening", False):
end = buffer.find("\n")
line = buffer[:end].strip()
buffer = buffer[end + 1:]
if line:
command_timestamp = datetime.now().strftime("%Y-%m-%dTH:%M:%S.%f")
line = safe_unicode(line, "UTF-8")
safe_print(lang.getstr("app.incoming_message",
addrport + (line, )))
data = split_command_line(line)
response = None
# Non-UI commands
if data[0] == "getappname" and len(data) == 1:
response = pyname
elif data[0] == "getcfg" and len(data) < 3:
if len(data) == 2:
# Return cfg value
if data[1] in defaults:
if responseformats[conn].startswith("xml"):
response = {"name": data[1],
"value": getcfg(data[1])}
else:
response = {data[1]: getcfg(data[1])}
else:
response = "invalid"
else:
# Return whole cfg
if responseformats[conn] != "plain":
response = []
else:
response = OrderedDict()
for name in sorted(defaults):
value = getcfg(name, False)
if value is not None:
if responseformats[conn] != "plain":
response.append({"name": name,
"value": value})
else:
response[name] = value
elif data[0] == "getcommands" and len(data) == 1:
response = sorted(self.get_commands())
elif data[0] == "getdefault" and len(data) == 2:
if data[1] in defaults:
if responseformats[conn] != "plain":
response = {"name": data[1],
"value": defaults[data[1]]}
else:
response = {data[1]: defaults[data[1]]}
else:
response = "invalid"
elif data[0] == "getdefaults" and len(data) == 1:
if responseformats[conn] != "plain":
response = []
else:
response = OrderedDict()
for name in sorted(defaults):
if responseformats[conn] != "plain":
response.append({"name": name,
"value": defaults[name]})
else:
response[name] = defaults[name]
elif data[0] == "getvalid" and len(data) == 1:
if responseformats[conn] != "plain":
response = {}
for section, options in (("ranges",
config.valid_ranges),
("values",
config.valid_values)):
valid = response[section] = []
for name, values in options.iteritems():
valid.append({"name": name,
"values": values})
else:
response = {"ranges": config.valid_ranges,
"values": config.valid_values}
if responseformats[conn] == "plain":
valid = []
for section, options in response.iteritems():
valid.append("[%s]" % section)
for name, values in options.iteritems():
valid.append("%s = %s" %
(name,
" ".join(demjson.encode(value)
for value in values)))
response = valid
elif (data[0] == "setresponseformat" and
len(data) == 2 and
data[1] in ("json", "json.pretty", "plain", "xml",
"xml.pretty")):
responseformats[conn] = data[1]
response = "ok"
if response is not None:
self.send_response(response, data, conn,
command_timestamp)
continue
# UI commands
wx.CallAfter(self.finish_processing, data, conn,
command_timestamp)
try:
conn.shutdown(socket.SHUT_RDWR)
except socket.error, exception:
if exception.errno != errno.ENOTCONN:
safe_print("Warning - could not shutdown connection:", exception)
safe_print(lang.getstr("app.client.disconnect", addrport))
conn.close()
responseformats.pop(conn)
def get_app_state(self, format):
win = self.get_top_window()
if isinstance(win, wx.Dialog) and win.IsShown():
if isinstance(win, (DirDialog, FileDialog)):
response = format_ui_element(win, format)
if format != "plain":
response.update({"message": win.Message, "path": win.Path})
else:
response = [response, demjson.encode(win.Message),
"path", demjson.encode(win.Path)]
elif isinstance(win, (AboutDialog, BaseInteractiveDialog,
ProgressDialog)):
response = format_ui_element(win, format)
if format == "plain":
response = [response]
if hasattr(win, "message") and win.message:
if format != "plain":
response["message"] = win.message.Label
else:
response.append(demjson.encode(win.message.Label))
# Ordering in tab order
for child in win.GetAllChildren():
if (child and isinstance(child, (FlatShadedButton,
GenButton, wx.Button)) and
child.TopLevelParent is win and
child.IsShownOnScreen() and child.IsEnabled()):
if format != "plain":
if not "buttons" in response:
response["buttons"] = []
response["buttons"].append(child.Label)
else:
if not "buttons" in response:
response.append("buttons")
response.append(demjson.encode(child.Label))
elif win.__class__ is wx.Dialog:
response = format_ui_element(win, format)
if format == "plain":
response = [response]
else:
return "blocked"
if format == "plain":
response = " ".join(response)
return response
if hasattr(self, "worker") and self.worker.is_working():
return "busy"
return "idle"
def get_commands(self):
return self.get_common_commands()
def get_common_commands(self):
cmds = ["abort", "activate [window]",
"alt", "cancel", "ok [filename]", "close [window]",
"echo <string>", "getactivewindow", "getappname",
"getcellvalues [window] <grid>", "getcommands",
"getcfg [option]", "getdefault <option>", "getdefaults",
"getmenus", "getmenuitems [menu]", "getstate",
"getuielement [window] <element>", "getuielements [window]",
"getvalid", "getwindows",
"interact [window] <element> [setvalue value]",
"invokemenu <menu> <menuitem>",
"restore-defaults [category...]",
"setcfg <option> <value>", "setresponseformat <format>"]
if hasattr(self, "update_controls"):
cmds.append("refresh")
if hasattr(self, "panel"):
cmds.append("setlanguage <languagecode>")
return cmds
def get_scripting_hosts(self):
scripting_hosts = []
lockfilebasenames = [appbasename]
for module in ["3DLUT-maker", "curve-viewer", "profile-info",
"scripting-client", "synthprofile", "testchart-editor",
"VRML-to-X3D-converter", "apply-profiles"]:
lockfilebasenames.append("%s-%s" % (appbasename, module))
for lockfilebasename in lockfilebasenames:
lockfilename = os.path.join(confighome, "%s.lock" %
lockfilebasename)
if os.path.isfile(lockfilename):
try:
with open(lockfilename) as lockfile:
ports = lockfile.read().splitlines()
except EnvironmentError, exception:
# This shouldn't happen
safe_print("Warning - could not read lockfile %s:" %
lockfilename, exception)
else:
for port in ports:
scripting_hosts.append("127.0.0.1:%s %s" %
(port, lockfilebasename))
scripting_hosts.sort()
return scripting_hosts
def get_top_window(self):
windows = [active_window or self] + list(wx.GetTopLevelWindows())
while windows:
win = windows.pop()
if win and isinstance(win, wx.Dialog) and win.IsShown():
break
return (win and win.IsShown() and win) or self
def process_data(self, data):
""" Override this method in derived classes """
return "invalid"
def finish_processing(self, data, conn, command_timestamp):
if not responseformats.get(conn):
# Client connection has broken down in the meantime
return
state = self.get_app_state("plain")
dialog = isinstance(self.get_top_window(), wx.Dialog)
if ((state in ("blocked", "busy") or dialog) and
data[0] not in ("abort", "alt", "cancel", "close",
"getactivewindow", "getcellvalues",
"getmenus", "getmenuitems",
"getstate", "getuielement", "getuielements",
"getwindows", "interact", "ok")):
if dialog:
state = "blocked"
self.send_response(state, data, conn, command_timestamp)
return
win = None
child = None
response = "ok"
if data[0] in ("abort", "close"):
if (hasattr(self, "worker") and not self.worker.abort_all() and
self.worker.is_working()):
response = "failed"
elif data[0] == "close":
if len(data) == 2:
win = get_toplevel_window(data[1])
else:
win = self.get_top_window()
if win:
state = self.get_app_state("plain")
if state == "blocked":
response = state
elif (state not in ("busy", "idle") and
win is not self.get_top_window()):
response = "blocked"
elif (isinstance(win, (AboutDialog, BaseInteractiveDialog,
ProgressDialog)) or
win.__class__ is wx.Dialog):
if win.IsModal():
wx.CallAfter(win.EndModal, wx.ID_CANCEL)
else:
wx.CallAfter(win.Close)
elif isinstance(win, wx.Frame):
wx.CallAfter(win.Close)
else:
response = "failed"
else:
response = "invalid"
else:
response = "invalid"
elif data[0] == "activate" and len(data) < 3:
response = "ok"
if len(data) < 2:
win = wx.GetApp().TopWindow
else:
try:
id_name_label = int(data[1])
except ValueError:
id_name_label = data[1]
for win in reversed(wx.GetTopLevelWindows()):
if (win.Id == id_name_label or win.Name == id_name_label or
win.Label == id_name_label) and win.IsShown():
break
else:
win = None
if win and win.IsShown():
if win.IsIconized():
win.Restore()
win.Raise()
else:
response = "invalid"
elif data[0] in ("alt", "cancel", "ok") and (len(data) == 1 or
(data[0] == "ok" and
len(data) == 2)):
response = "invalid"
win = self.get_top_window()
if isinstance(win, (DirDialog, FileDialog)):
if data[0] in ("ok", "cancel"):
if len(data) > 1:
# Path
win.SetPath(data[1])
if win.IsModal():
wx.CallAfter(win.EndModal,
{"ok": wx.ID_OK,
"cancel": wx.ID_CANCEL}[data[0]])
elif data[0] == "cancel":
wx.CallAfter(win.Close)
response = "ok"
elif isinstance(win, (AboutDialog, BaseInteractiveDialog,
ProgressDialog)):
if hasattr(win, data[0]):
ctrl = getattr(win, data[0])
if ctrl.IsEnabled():
if win.IsModal():
wx.CallAfter(win.EndModal, ctrl.Id)
elif isinstance(ctrl, (FlatShadedButton, GenButton,
wx.Button)):
event = wx.CommandEvent(wx.EVT_BUTTON.typeId,
ctrl.Id)
event.SetEventObject(ctrl)
wx.CallAfter(ctrl.ProcessEvent, event)
response = "ok"
else:
response = "forbidden"
elif (data[0] == "echo" and
"echo <string>" in self.get_common_commands() and len(data) > 1):
txt = " ".join(data[1:])
safe_print(txt)
elif data[0] == "invokemenu" and len(data) == 3:
if self.get_app_state("plain") == "idle":
menubar = self.GetMenuBar()
response = "invalid"
else:
menubar = None
response = "forbidden"
if menubar:
try:
menu_pos = int(data[1])
except ValueError:
menu_pos = menubar.FindMenu(data[1])
if (menu_pos not in (wx.NOT_FOUND, None) and
menu_pos > -1 and menu_pos < menubar.GetMenuCount() and
menubar.IsEnabledTop(menu_pos)):
menu = menubar.GetMenu(menu_pos)
try:
menuitem_id = int(data[2])
except ValueError:
menuitem_id = menu.FindItem(data[2])
if menuitem_id not in (wx.NOT_FOUND, None):
menuitem = menu.FindItemById(menuitem_id)
if menuitem.IsEnabled():
event = wx.CommandEvent(wx.EVT_MENU.typeId,
menuitem_id)
event.SetEventObject(menu)
wx.CallAfter(self.ProcessEvent, event)
response = "ok"
else:
response = "forbidden"
elif data[0] == "getactivewindow" and len(data) == 1:
win = self.get_top_window()
response = format_ui_element(win, responseformats[conn])
win = None
elif data[0] == "getcellvalues" and len(data) in (2, 3):
response = "invalid"
if len(data) == 3:
win = get_toplevel_window(data[1])
else:
win = self.get_top_window()
if win:
name = data[-1]
child = get_widget(win, name)
if (child and isinstance(child, wx.grid.Grid) and
child.IsShownOnScreen()):
response = []
for row in xrange(child.GetNumberRows()):
values = []
for col in xrange(child.GetNumberCols()):
values.append(child.GetCellValue(row, col))
if responseformats[conn] == "plain":
values = demjson.encode(values).strip("[]").replace('","', '" "')
response.append(values)
elif child is False:
response = "forbidden"
child = None
elif data[0] == "getmenus" and len(data) == 1:
menus = []
menubar = self.GetMenuBar()
if menubar:
for i, (menu, label) in enumerate(menubar.GetMenus()):
label = label.lstrip("&_")
if responseformats[conn] != "plain":
menus.append({"label": label, "position": i,
"enabled": menubar.IsEnabledTop(i)})
else:
menus.append("%s %s %s" % (i,
demjson.encode(label),
"enabled"
if menubar.IsEnabledTop(i)
else "disabled"))
response = menus
elif data[0] == "getmenuitems" and len(data) < 3:
menuitems = []
menulabels = []
menus = []
menubar = self.GetMenuBar()
if menubar:
if len(data) == 2:
try:
menu_pos_label = int(data[1])
except ValueError:
menu_pos_label = data[1]
for i, (menu, label) in enumerate(menubar.GetMenus()):
label = label.lstrip("&_")
if (len(data) == 2 and label != menu_pos_label and
i != menu_pos_label):
continue
if (responseformats[conn] != "plain" and
not label in menulabels):
menuitems = []
menulabels.append(label)
menus.append({"label": label, "position": i,
"enabled": menubar.IsEnabledTop(i),
"menuitems": menuitems})
for menuitem in menu.GetMenuItems():
if menuitem.IsSeparator():
continue
if responseformats[conn] != "plain":
menuitems.append({"label": menuitem.Label,
"id": menuitem.Id,
"enabled": menubar.IsEnabledTop(i) and
menuitem.IsEnabled(),
"checkable": menuitem.IsCheckable(),
"checked": menuitem.IsChecked()})
else:
menuitems.append("%s %s %s %s %s%s%s" %
(i, demjson.encode(label),
menuitem.Id,
demjson.encode(menuitem.Label),
"enabled"
if menubar.IsEnabledTop(i) and
menuitem.IsEnabled()
else "disabled",
" checkable" if menuitem.IsCheckable()
else "",
" checked" if menuitem.IsChecked()
else ""))
if responseformats[conn] != "plain":
response = menus
else:
response = menuitems
elif data[0] == "getstate" and len(data) == 1:
response = self.get_app_state(responseformats[conn])
elif data[0] == "getuielement" and len(data) in (2, 3):
response = "invalid"
if len(data) == 3:
win = get_toplevel_window(data[1])
else:
win = self.get_top_window()
if win:
name = data[-1]
child = get_widget(win, name)
if child and child.IsShownOnScreen():
response = format_ui_element(child, responseformats[conn])
elif child is False:
response = "forbidden"
child = None
elif data[0] == "getuielements" and len(data) < 3:
uielements = []
if len(data) == 2:
win = get_toplevel_window(data[1])
else:
win = self.get_top_window()
if win:
# Ordering in tab order
for child in win.GetAllChildren():
if is_scripting_allowed(win, child):
uielements.append(format_ui_element(child,
responseformats[conn]))
child = None
response = uielements
else:
response = "invalid"
elif data[0] == "getwindows" and len(data) == 1:
windows = filter(lambda win: win.IsShown(), wx.GetTopLevelWindows())
response = [format_ui_element(win, responseformats[conn])
for win in windows]
win = None
elif data[0] == "interact" and len(data) > 1 and len(data) < 6:
response = "invalid"
value = None
args = data[1:]
if len(args) > 2 and args[-2] == "setvalue":
value = args.pop()
args.pop()
name = args.pop()
state = self.get_app_state("plain")
if state == "blocked":
win = None
response = state
elif args:
# Window name specified
win = get_toplevel_window(args[0])
if state not in ("busy",
"idle") and win is not self.get_top_window():
win = None
response = "blocked"
else:
win = self.get_top_window()
if win:
child = get_widget(win, name)
if child is False or (child and (not child.IsShownOnScreen() or
not child.IsEnabled())):
response = "forbidden"
elif child:
event = None
if value is not None:
# Set value
values = value.split(",", 2)
if isinstance(child, floatspin.FloatSpin):
try:
child.SetValue(float(value))
except:
response = "failed"
else:
event = floatspin.EVT_FLOATSPIN
elif (isinstance(child, (CustomCheckBox,
wx.CheckBox)) and
value in ("0", "1", "false", "true")):
child.SetValue(bool(demjson.decode(value)))
event = wx.EVT_CHECKBOX
elif isinstance(child, wx.ComboBox):
child.SetValue(value)
event = wx.EVT_TEXT
elif isinstance(child, wx.Choice):
# NOTE: Check for wx.ComboBox first because it is a
# subclass of wx.Choice!
if value in child.Items:
child.SetStringSelection(value)
event = wx.EVT_CHOICE
elif isinstance(child, (aui.AuiNotebook,
labelbook.FlatBookBase,
wx.Notebook)):
for page_idx in xrange(child.GetPageCount()):
if child.GetPageText(page_idx) == value:
child.SetSelection(page_idx)
event = wx.EVT_NOTEBOOK_PAGE_CHANGED
break
elif isinstance(child, wx.grid.Grid) and len(values) == 3:
try:
row, col = (int(v) for v in values[:2])
except ValueError:
row, col = -1, -1
if (row > -1 and col > -1 and
row < child.GetNumberRows() and
col < child.GetNumberCols()):
if (child.IsEditable() and
not child.IsReadOnly(row, col)):
child.SetCellValue(row, col, values[2])
event = wx.grid.GridEvent(-1,
wx.grid.EVT_GRID_CELL_CHANGE.evtType[0],
child,
row,
col)
else:
response = "forbidden"
elif isinstance(child, wx.ListCtrl):
for row in xrange(child.GetItemCount()):
item = []
for col in xrange(child.GetColumnCount()):
item.append(child.GetItem(row, col).GetText())
if " ".join(item) == value:
state = child.GetItemState(row, wx.LIST_STATE_SELECTED)
child.Select(row, not state &
wx.LIST_STATE_SELECTED)
if state & wx.LIST_STATE_SELECTED:
event = wx.EVT_LIST_ITEM_DESELECTED
else:
event = wx.EVT_LIST_ITEM_SELECTED
break
elif (isinstance(child, wx.RadioButton) and
value in ("0", "1", "false", "true")):
child.SetValue(bool(demjson.decode(value)))
event = wx.EVT_RADIOBUTTON
elif isinstance(child, wx.Slider):
try:
child.SetValue(int(value))
except:
response = "failed"
else:
event = wx.EVT_SLIDER
elif isinstance(child, wx.SpinCtrl):
try:
child.SetValue(int(value))
except:
response = "failed"
else:
event = wx.EVT_SPINCTRL
elif isinstance(child, wx.TextCtrl):
child.ChangeValue(value)
event = wx.EVT_TEXT
elif isinstance(child, (FlatShadedButton,
GenButton, wx.Button)):
event = wx.EVT_BUTTON
if event:
if isinstance(child, CustomCheckBox):
ctrl = child._cb
else:
ctrl = child
events = [event]
if event is wx.EVT_SPINCTRL:
events.append(wx.EVT_TEXT)
elif event is wx.EVT_TEXT and win.FindFocus() != ctrl:
events.append(wx.EVT_KILL_FOCUS)
for event in events:
if not isinstance(event, wx.Event):
event = wx.CommandEvent(event.typeId, ctrl.Id)
if isinstance(child, (CustomCheckBox, wx.CheckBox,
wx.RadioButton)):
event.SetInt(int(ctrl.Value))
event.SetEventObject(ctrl)
if not isinstance(ctrl, wx.Notebook):
# Bus error under Mac OS X
wx.CallAfter(ctrl.ProcessEvent, event)
wx.CallLater(1, child.Refresh)
response = "ok"
elif data[0] == "setcfg" and len(data) == 3:
# Set configuration option
if data[1] in defaults:
value = data[2]
if value == "null":
value = None
elif value == "false":
value = 0
elif value == "true":
value = 1
elif defaults[data[1]] is not None:
try:
value = type(defaults[data[1]])(value)
except (UnicodeEncodeError, ValueError):
pass
setcfg(data[1], value)
if getcfg(data[1], False) != value:
response = "failed"
else:
response = "invalid"
else:
try:
response = self.process_data(data)
except Exception, exception:
safe_print(exception)
if responseformats[conn] != "plain":
response = {"class": exception.__class__.__name__,
"error": safe_unicode(exception)}
else:
response = "error " + demjson.encode(safe_unicode(exception))
else:
# Some commands can be overriden, check response
if response == "invalid":
if (data[0] == "refresh" and len(data) == 1 and
hasattr(self, "update_controls")):
self.update_controls()
self.update_layout()
response = "ok"
elif data[0] == "restore-defaults":
for name in defaults:
if len(data) > 1:
include = False
for category in data[1:]:
if name.startswith(data[1]):
include = True
break
if not include:
continue
setcfg(name, None)
response = "ok"
elif (data[0] == "setlanguage" and len(data) == 2 and
hasattr(self, "panel") and
hasattr(self, "update_controls")):
setcfg("lang", data[1])
self.panel.Freeze()
self.setup_language()
self.update_controls()
self.update_layout()
self.panel.Thaw()
response = "ok"
if (data[0].startswith("get") or data[0] in ("refresh",
"restore-defaults",
"setcfg") or
response != "ok"):
# No interaction with UI
relayfunc = lambda func, *args: func(*args)
else:
# Interaction with UI
# Prevent actual file dialogs blocking the UI - need to restore
# original values after processing
wx.DirDialog = DirDialog
wx.FileDialog = FileDialog
# Use CallLater so GUI methods have a chance to run before we send
# our response
relayfunc = lambda func, *args: wx.CallLater(55, func, *args)
relayfunc(restore_path_dialog_classes)
relayfunc(self.send_response, response, data, conn, command_timestamp,
child or win)
def send_response(self, response, data, conn, command_timestamp, win=None):
if not responseformats.get(conn):
# Client connection has broken down in the meantime
return
if response == "invalid":
safe_print(lang.getstr("app.incoming_message.invalid"))
if responseformats[conn] != "plain":
if not isinstance(response, (basestring, list)):
response = [response]
command = {"name": data[0], "timestamp": command_timestamp}
if data[1:]:
command["arguments"] = data[1:]
response = {"command": command,
"result": response,
"timestamp": datetime.now().strftime("%Y-%m-%dTH:%M:%S.%f")}
if win:
response["object"] = format_ui_element(win, responseformats[conn])
if responseformats[conn].startswith("json"):
response = demjson.encode(response,
compactly=responseformats[conn] == "json")
elif responseformats[conn].startswith("xml"):
response = ('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
(responseformats[conn] == "xml.pretty" and "\n" or "") +
dict2xml(response, "response",
pretty=responseformats[conn] == "xml.pretty"))
else:
if isinstance(response, dict):
response = ["%s = %s" % (name, value) for name, value in
response.iteritems()]
if isinstance(response, list):
response = "\n".join(response)
try:
conn.sendall("%s\4" % safe_str(response, "UTF-8"))
except socket.error, exception:
safe_print(exception)
def focus_handler(self, event=None):
# IMPORTANT: event can either be EVT_TEXT, EVT_SET_FOCUS, EVT_CLOSE,
# EVT_MENU or EVT_BUTTON.
# This means the available event methods will be different, e.g.
# only EVT_SET_FOCUS will have a GetWindow method, and EVT_MENU's
# GetEventObject method returns the menu item which doesn't have
# most methods that controls would have.
if not event:
event = CustomEvent(wx.EVT_SET_FOCUS.evtType[0], self)
if debug:
if hasattr(event.GetEventObject(), "GetId"):
safe_print("[D] focus_handler called for ID %s %s %s, event type "
"%s %s" % (event.GetEventObject().GetId(),
getevtobjname(event, self),
event.GetEventObject().__class__,
event.GetEventType(), getevttype(event)))
else:
safe_print("[D] focus_handler called for %s %s, event type "
"%s %s" % (getevtobjname(event, self),
event.GetEventObject().__class__,
event.GetEventType(), getevttype(event)))
if (hasattr(event, "GetWindow") and event.GetWindow() and
event.GetEventObject() != event.GetWindow()):
safe_print("[D] Focus moving from control ID %s %s %s" %
(event.GetWindow().GetId(),
event.GetWindow().GetName(),
event.GetWindow().__class__))
if getattr(self, "last_focused_ctrl", None):
safe_print("[D] Last focused control: ID %s %s %s" %
(self.last_focused_ctrl.GetId(),
self.last_focused_ctrl.GetName(),
self.last_focused_ctrl.__class__))
if (getattr(self, "last_focused_ctrl", None) and
isinstance(self.last_focused_ctrl, wx.ComboBox) and
self.last_focused_ctrl != event.GetEventObject() and
self.last_focused_ctrl.IsShownOnScreen() and
event.GetEventObject() and
(not hasattr(event.GetEventObject(), "IsShownOnScreen") or
event.GetEventObject().IsShownOnScreen())):
catchup_event = wx.FocusEvent(wx.EVT_KILL_FOCUS.evtType[0],
self.last_focused_ctrl.GetId())
if debug:
safe_print("[D] Last focused control ID %s %s %s processing "
"catchup event type %s %s" %
(self.last_focused_ctrl.GetId(),
self.last_focused_ctrl.GetName(),
self.last_focused_ctrl.__class__,
catchup_event.GetEventType(),
getevttype(catchup_event)))
if self.last_focused_ctrl.ProcessEvent(catchup_event):
if debug:
safe_print("[D] Last focused control processed catchup "
"event")
self.last_focused_ctrl = None
if (hasattr(event.GetEventObject(), "GetId") and
callable(event.GetEventObject().GetId) and
isinstance(event.GetEventObject(), wx.Control) and
event.GetEventObject() != getattr(self, "last_focused_ctrl", None) and
hasattr(event.GetEventObject(), "IsShownOnScreen") and
event.GetEventObject().IsShownOnScreen()):
if debug:
safe_print("[D] Setting last focused control to ID %s %s %s"
% (event.GetEventObject().GetId(),
getevtobjname(event, self),
event.GetEventObject().__class__))
self.last_focused_ctrl = event.GetEventObject()
event.Skip()
def setup_language(self):
"""
Substitute translated strings for menus, controls, labels and tooltips.
"""
if not hasattr(self, "_menulabels"):
# Needed for Phoenix because custom attributes attached to menus
# are not retained
self._menulabels = {}
if not hasattr(self, "_ctrllabels"):
# Needed for Phoenix because custom attributes attached to controls
# may not be retained
self._ctrllabels = {}
if not hasattr(self, "_tooltipstrings"):
# Needed for Phoenix because custom attributes attached to controls
# may not be retained
self._tooltipstrings = {}
# Title
if not hasattr(self, "_Title"):
# Backup un-translated label
title = self._Title = self.Title
else:
# Restore un-translated label
title = self._Title
translated = lang.getstr(title)
if translated != title:
self.Title = translated
# Menus
menubar = self.menubar if hasattr(self, "menubar") else self.GetMenuBar()
if menubar:
for menu, label in menubar.GetMenus():
menu_pos = menubar.FindMenu(label)
if not menu in self._menulabels:
# Backup un-translated label
self._menulabels[menu] = label
menubar.SetMenuLabel(menu_pos, "&" + lang.getstr(
GTKMenuItemGetFixedLabel(self._menulabels[menu])))
if not hasattr(menu, "_Items"):
# Backup un-translated labels
menu._Items = [(item, item.Label) for item in
menu.GetMenuItems()]
for item, label in menu._Items:
if item.Label:
label = GTKMenuItemGetFixedLabel(label)
if item.Accel:
item.Text = lang.getstr(label) + "\t" + \
item.Accel.ToString()
else:
item.Text = lang.getstr(label)
if sys.platform == "darwin":
wx.GetApp().SetMacHelpMenuTitleName(lang.getstr("menu.help"))
self.SetMenuBar(menubar)
# Controls and labels
for child in self.GetAllChildren():
if isinstance(child, (wx.StaticText, wx.Control,
BetterStaticFancyText,
BitmapBackgroundPanelText)):
if not child in self._ctrllabels:
# Backup un-translated label
label = self._ctrllabels[child] = child.Label
else:
# Restore un-translated label
label = self._ctrllabels[child]
translated = lang.getstr(label)
if translated != label:
if isinstance(child, wx.Button):
translated = translated.replace("&", "&&")
child.Label = translated
if child.ToolTip:
if not child in self._tooltipstrings:
# Backup un-translated tooltip
tooltipstr = self._tooltipstrings[child] = child.ToolTip.Tip
else:
# Restore un-translated tooltip
tooltipstr = self._tooltipstrings[child]
translated = lang.getstr(tooltipstr)
if translated != tooltipstr:
child.SetToolTipString(translated)
elif isinstance(child, FileBrowseBitmapButtonWithChoiceHistory):
if child.history:
selection = child.textControl.GetSelection()
child.textControl.Clear()
for path in child.history:
child.textControl.Append(child.GetName(path))
child.textControl.SetSelection(selection)
def update_layout(self):
""" Update main window layout. """
minsize, clientsize = self.Sizer.MinSize, self.ClientSize
if not self.IsIconized() and not self.IsMaximized():
if ((minsize[0] > clientsize[0] or minsize[1] > clientsize[1] or not
getattr(self, "_layout", False))):
self.Sizer.SetMinSize((max(minsize[0], clientsize[0]),
max(minsize[1], clientsize[1])))
self.GetSizer().SetSizeHints(self)
self.GetSizer().Layout()
self.Sizer.SetMinSize((-1, -1))
self._layout = True
else:
self.Layout()
if hasattr(self, "ClientToWindowSize"):
# wxPython 2.8.12
self.SetMinSize(self.ClientToWindowSize(minsize))
else:
# wxPython >= 2.9
self.MinClientSize = minsize
def set_child_ctrls_as_attrs(self, parent=None):
"""
Set child controls and labels as attributes of the frame.
Will also set a maximum font size of 11 pt.
parent is the window over which children will be iterated and
defaults to self.
"""
if not parent:
parent = self
scale = getcfg("app.dpi") / get_default_dpi()
for child in parent.GetAllChildren():
if debug:
safe_print(child.__class__, child.Name)
if isinstance(child, (wx.StaticText, wx.Control,
filebrowse.FileBrowseButton,
floatspin.FloatSpin)):
if (isinstance(child, wx.Choice) and
((wx.VERSION < (2, 9) and
sys.platform not in ("darwin", "win32")) or
"gtk3" in wx.PlatformInfo) and
child.MinSize[1] == -1):
# wx.Choice with wxPython < 2.9 under Gnome 3 Adwaita theme
# has varying height. We can't easily check for Gnome 3 or
# Adwaita, so simply always set wx.Choice height to
# wx.ComboBox height with wxPython < 2.9 under Linux
if not hasattr(BaseFrame, "_comboboxheight"):
combobox = wx.ComboBox(self, -1)
BaseFrame._comboboxheight = combobox.Size[1]
combobox.Destroy()
child.MinSize = child.MinSize[0], BaseFrame._comboboxheight
elif isinstance(child, wx.BitmapButton):
if "gtk3" in wx.PlatformInfo:
# GTK3 doesn't respect NO_BORDER in hovered state when
# using wx.BitmapButton and looks ugly
orig_child = child
child = GenBitmapButton(child.Parent, -1, child.BitmapLabel,
child.Position, child.MinSize,
child.WindowStyle, child.Validator or
wx.DefaultValidator,
child.Name)
child.BackgroundColour = orig_child.Parent.BackgroundColour
child.Enabled = orig_child.Enabled
if orig_child.ToolTipString:
child.ToolTipString = orig_child.ToolTipString
orig_child.ContainingSizer.Replace(orig_child, child)
orig_child.Destroy()
else:
set_bitmap_labels(child)
elif (isinstance(child, wx._SpinCtrl) and
not hasattr(child, "_spinwidth") and
"gtk3" in wx.PlatformInfo):
if not getattr(wx.SpinCtrl, "_spinwidth", 0):
spin = wx.SpinCtrl(self, -1)
text = wx.TextCtrl(self, -1)
wx.SpinCtrl._spinwidth = spin.Size[0] - text.Size[0] + 11
spin.Destroy()
text.Destroy()
child.MinSize = (child.MinSize[0] + wx.SpinCtrl._spinwidth,
child.MinSize[1])
elif (isinstance(child, wx._StaticText) and
"gtk3" in wx.PlatformInfo):
if child.__class__.SetLabel is not wx.StaticText.__dict__['SetLabel']:
child.__class__.SetLabel = wx.StaticText.__dict__['SetLabel']
if child.__class__.Label is not wx.StaticText.__dict__['Label']:
child.__class__.Label = property(child.__class__.GetLabel,
child.__class__.SetLabel)
child.SetMaxFontSize(11)
if sys.platform == "darwin":
# Work around ComboBox issues on Mac OS X
# (doesn't receive EVT_KILL_FOCUS)
if isinstance(child, wx.ComboBox):
if child.IsEditable():
if debug:
safe_print("[D]", child.Name,
"binds EVT_TEXT to focus_handler")
child.Bind(wx.EVT_TEXT, self.focus_handler)
else:
child.Bind(wx.EVT_SET_FOCUS, self.focus_handler)
if not hasattr(self, child.Name):
setattr(self, child.Name, child)
if (sys.platform == "win32" and sys.getwindowsversion() >= (6, ) and
isinstance(child, wx.Panel)):
# No need to enable double buffering under Linux and Mac OS X.
# Under Windows, enabling double buffering on the panel seems
# to work best to reduce flicker.
child.SetDoubleBuffered(True)
class BaseInteractiveDialog(wx.Dialog):
""" Base class for informational and confirmation dialogs """
def __init__(self, parent=None, id=-1, title=appname, msg="",
ok=None, bitmap=None, pos=(-1, -1), size=(400, -1),
show=True, log=True,
style=wx.DEFAULT_DIALOG_STYLE, nowrap=False, wrap=70,
name=wx.DialogNameStr, bitmap_margin=None):
if not ok:
ok = lang.getstr("ok")
if log:
safe_print(msg)
if parent:
pos = list(pos)
i = 0
for coord in pos:
if coord > -1:
pos[i] += parent.GetScreenPosition()[i]
i += 1
pos = tuple(pos)
scale = getcfg("app.dpi") / get_default_dpi()
if scale > 1 and size == (400, -1):
size = size[0] * scale, size[1]
wx.Dialog.__init__(self, parent, id, title, pos, size, style, name)
if sys.platform == "win32":
bgcolor = self.BackgroundColour
self.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW))
self.SetPosition(pos) # yes, this is needed
self.set_icons()
self.Bind(wx.EVT_SHOW, self.OnShow, self)
margin = 12
if bitmap_margin is None:
bitmap_margin = margin
self.sizer0 = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(self.sizer0)
if bitmap:
self.sizer1 = wx.FlexGridSizer(1, 2, 0, 0)
else:
self.sizer1 = wx.BoxSizer(wx.HORIZONTAL)
self.sizer2 = wx.BoxSizer(wx.HORIZONTAL)
self.sizer3 = wx.FlexGridSizer(0, 1, 0, 0)
self.sizer0.Add(self.sizer1, flag = wx.ALIGN_LEFT | wx.RIGHT,
border=margin)
self.buttonpanel = wx.Panel(self)
self.buttonpanel.SetSizer(wx.BoxSizer(wx.VERTICAL))
self.buttonpanel.Sizer.Add(self.sizer2, 1, flag=wx.ALIGN_RIGHT | wx.ALL,
border=margin)
if sys.platform == "win32":
self.buttonpanel_line = wx.Panel(self, size=(-1,1))
self.buttonpanel_line.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DLIGHT))
self.sizer0.Add(self.buttonpanel_line, flag=wx.TOP | wx.EXPAND,
border=margin)
self.buttonpanel.SetBackgroundColour(bgcolor)
self.sizer0.Add(self.buttonpanel, flag=wx.EXPAND)
if bitmap_margin:
flags = wx.RIGHT | wx.LEFT | wx.TOP
else:
flags = 0
if bitmap:
self.bitmap = wx.StaticBitmap(self, -1, bitmap)
self.sizer1.Add(self.bitmap, flag=flags, border=margin)
self.sizer1.Add(self.sizer3, flag=wx.ALIGN_LEFT | wx.TOP, border=margin)
msg = msg.replace("&", "&&")
self.message = wx.StaticText(self, -1, msg if nowrap else
util_str.wrap(msg, wrap))
self.sizer3.Add(self.message)
btnwidth = 80
self.ok = wx.Button(self.buttonpanel, wx.ID_OK, ok)
self.sizer2.Add(self.ok)
self.Bind(wx.EVT_BUTTON, self.OnClose, id=wx.ID_OK)
self.buttonpanel.Layout()
self.sizer0.SetSizeHints(self)
self.sizer0.Layout()
self.pos = pos
if show:
self.ok.SetDefault()
self.ShowModalThenDestroy(parent)
def ShowModalThenDestroy(self, parent=None):
if parent:
if getattr(parent, "modaldlg", None):
wx.CallLater(250, self.ShowModalThenDestroy, parent)
return
parent.modaldlg = self
self.ShowModal()
if parent:
parent.modaldlg = None
del parent.modaldlg
self.Destroy()
def OnShow(self, event):
event.Skip()
if not getattr(event, "IsShown", getattr(event, "GetShow", bool))():
return
if not wx.GetApp().IsActive() and wx.GetApp().GetTopWindow():
wx.GetApp().GetTopWindow().RequestUserAttention()
def OnClose(self, event):
if event.GetEventObject() == self:
id = wx.ID_OK
else:
id = event.GetId()
self.EndModal(id)
def Show(self, show=True):
if show:
self.set_position()
return wx.Dialog.Show(self, show)
def ShowModal(self):
self.set_position()
return wx.Dialog.ShowModal(self)
def set_icons(self):
parent = self.Parent
while parent:
if isinstance(parent, wx.Frame):
break
parent = parent.Parent
if (parent and parent.Icon and parent.Icon.IsOk() and
parent.Name in ("lut3dframe", "lut_viewer", "profile_info",
"scriptingframe", "synthiccframe", "tcgen",
"vrml2x3dframe")):
self.Icon = parent.Icon
else:
self.SetIcons(config.get_icon_bundle([256, 48, 32, 16], appname))
def set_position(self):
if self.Parent and self.Parent.IsIconized():
self.Parent.Restore()
if not getattr(self, "pos", None) or self.pos == (-1, -1):
self.Center(wx.BOTH)
elif self.pos[0] == -1:
self.Center(wx.HORIZONTAL)
elif self.pos[1] == -1:
self.Center(wx.VERTICAL)
class HtmlInfoDialog(BaseInteractiveDialog):
def __init__(self, parent=None, id=-1, title=appname, msg="", html="",
ok="OK", bitmap=None, pos=(-1, -1), size=(400, -1),
show=True, log=True, bitmap_margin=None):
BaseInteractiveDialog.__init__(self, parent, id, title, msg, ok,
bitmap, pos, size, False, log,
bitmap_margin=bitmap_margin)
scale = getcfg("app.dpi") / config.get_default_dpi()
if scale < 1:
scale = 1
htmlwnd = wx.html.HtmlWindow(self, -1, size=(332 * scale, 200 * scale),
style=wx.BORDER_THEME)
if "gtk3" in wx.PlatformInfo:
size = int(round(self.message.Font.PointSize * scale))
else:
size = -1
htmlwnd.SetStandardFonts(size)
htmlwnd.SetPage(html)
htmlwnd.Bind(wx.html.EVT_HTML_LINK_CLICKED,
lambda event: launch_file(event.GetLinkInfo().Href))
self.sizer3.Add(htmlwnd, 1, flag=wx.TOP | wx.ALIGN_LEFT | wx.EXPAND,
border=12)
self.sizer0.SetSizeHints(self)
self.sizer0.Layout()
if show:
self.ok.SetDefault()
self.ShowModalThenDestroy(parent)
class BitmapBackgroundBitmapButton(wx.BitmapButton):
""" A BitmapButton that will use its parent bitmap background.
The parent needs to have a GetBitmap() method.
"""
def __init__(self, *args, **kwargs):
wx.BitmapButton.__init__(self, *args, **kwargs)
self.Bind(wx.EVT_PAINT, self.OnPaint)
def OnPaint(self, dc):
dc = wx.PaintDC(self)
try:
dc = wx.GCDC(dc)
except Exception, exception:
pass
dc.DrawBitmap(self.Parent.GetBitmap(), 0, -self.GetPosition()[1])
dc.DrawBitmap(self.GetBitmapLabel(), 0, 0)
bitmaps = {}
class BitmapBackgroundPanel(wx.PyPanel):
""" A panel with a background bitmap """
def __init__(self, *args, **kwargs):
wx.PyPanel.__init__(self, *args, **kwargs)
self._bitmap = None
self.alpha = 1.0
self.blend = False
self.borderbtmcolor = wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DSHADOW)
self.bordertopcolor = wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DLIGHT)
self.drawborderbtm = False
self.drawbordertop = False
self.repeat_sub_bitmap_h = None
self.scalebitmap = (True, False)
self.scalequality = wx.IMAGE_QUALITY_NORMAL
self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.Bind(wx.EVT_SIZE, self.OnSize)
def AcceptsFocus(self):
return False
def AcceptsFocusFromKeyboard(self):
return False
def GetBitmap(self):
return self._bitmap
def SetBitmap(self, bitmap):
self._bitmap = bitmap
def OnPaint(self, event):
if sys.platform != "win32":
# AutoBufferedPaintDCFactory is the magic needed for crisp text
# rendering in HiDPI mode under OS X and Linux
cls = wx.AutoBufferedPaintDCFactory
else:
cls = wx.BufferedPaintDC
dc = cls(self)
self._draw(dc)
def OnSize(self,event):
self.Refresh()
def _draw(self, dc):
bgcolor = self.BackgroundColour
bbr = wx.Brush(bgcolor, wx.SOLID)
dc.SetBackground(bbr)
dc.SetBackgroundMode(wx.SOLID)
dc.Clear()
dc.SetTextForeground(self.GetForegroundColour())
bmp = self._bitmap
if bmp:
if self.alpha < 1.0 or self.blend:
key = (id(bmp), bgcolor, self.alpha)
bmp = bitmaps.get(key)
if not bmp:
bmp = self._bitmap
image = bmp.ConvertToImage()
if self.alpha < 1.0:
if not image.HasAlpha():
image.InitAlpha()
alphabuffer = image.GetAlphaBuffer()
for i, byte in enumerate(alphabuffer):
if byte > "\0":
alphabuffer[i] = chr(int(round(ord(byte) *
self.alpha)))
if self.blend:
databuffer = image.GetDataBuffer()
for i, byte in enumerate(databuffer):
if byte > "\0":
databuffer[i] = chr(int(round(ord(byte) *
(bgcolor[i % 3] /
255.0))))
bmp = image.ConvertToBitmap()
bitmaps[key] = bmp
if True in self.scalebitmap:
img = bmp.ConvertToImage()
img.Rescale(self.GetSize()[0] if self.scalebitmap[0]
else img.GetSize()[0],
self.GetSize()[1] if self.scalebitmap[1]
else img.GetSize()[1], quality=self.scalequality)
bmp = img.ConvertToBitmap()
dc.DrawBitmap(bmp, 0, 0)
if (self.repeat_sub_bitmap_h and self.Size[0] > bmp.Size[0] and
bmp.Size[0] >= self.repeat_sub_bitmap_h[0] and
bmp.Size[1] >= self.repeat_sub_bitmap_h[1]):
sub_bmp = bmp.GetSubBitmap(self.repeat_sub_bitmap_h)
sub_img = sub_bmp.ConvertToImage()
sub_img.Rescale(self.GetSize()[0] -
bmp.GetSize()[0],
bmp.GetSize()[1] if self.scalebitmap[1]
else sub_bmp.GetSize()[1],
quality=self.scalequality)
dc.DrawBitmap(sub_img.ConvertToBitmap(), bmp.GetSize()[0], 0)
if self.drawbordertop:
pen = wx.Pen(self.bordertopcolor, 1, wx.SOLID)
pen.SetCap(wx.CAP_BUTT)
dc.SetPen(pen)
dc.DrawLine(0, 0, self.GetSize()[0], 0)
if self.drawborderbtm:
pen = wx.Pen(self.borderbtmcolor, 1, wx.SOLID)
pen.SetCap(wx.CAP_BUTT)
dc.SetPen(pen)
dc.DrawLine(0, self.GetSize()[1] - 1, self.GetSize()[0], self.GetSize()[1] - 1)
class BitmapBackgroundPanelText(BitmapBackgroundPanel):
""" A panel with a background bitmap and text label """
def __init__(self, *args, **kwargs):
BitmapBackgroundPanel.__init__(self, *args, **kwargs)
self.label_x = None
self.label_y = None
self.textalpha = 1.0
self.textshadow = True
self.textshadowcolor = wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DLIGHT)
self.use_gcdc = False
self._label = ""
def _set_font(self, dc):
font = self.GetFont()
if self.use_gcdc:
# NOTE: Drawing text to wx.GCDC has problems with unicode chars
# being replaced with boxes under wxGTK
try:
dc = wx.GCDC(dc)
except Exception, exception:
pass
font.SetPointSize(get_dc_font_size(font.GetPointSize(), dc))
dc.SetFont(font)
return dc
def GetLabel(self):
return self._label
@Property
def Label():
def fget(self):
return self.GetLabel()
def fset(self, label):
self.SetLabel(label)
return locals()
def SetLabel(self, label):
self._label = label
def _draw(self, dc):
BitmapBackgroundPanel._draw(self, dc)
dc.SetBackgroundMode(wx.TRANSPARENT)
dc = self._set_font(dc)
label = self.Label.splitlines()
for i, line in enumerate(label):
w1, h1 = self.GetTextExtent(line)
w2, h2 = dc.GetTextExtent(line)
if self.label_x is None:
w = (max(w1, w2) - min(w1, w2)) / 2.0 + min(w1, w2)
x = self.GetSize()[0] / 2.0 - w / 2.0
else:
x = self.label_x
h = (max(h1, h2) - min(h1, h2)) / 2.0 + min(h1, h2)
if self.label_y is None:
y = self.GetSize()[1] / 2.0 - h / 2.0
else:
y = self.label_y + h * i
if self.textshadow:
dc.SetTextForeground(self.textshadowcolor)
dc.DrawText(line, x + 1, y + 1)
color = self.GetForegroundColour()
if self.textalpha < 1:
bgcolor = self.BackgroundColour
bgblend = (1.0 - self.textalpha)
blend = self.textalpha
color = wx.Colour(int(round(bgblend * bgcolor.Red() +
blend * color.Red())),
int(round(bgblend * bgcolor.Green() +
blend * color.Green())),
int(round(bgblend * bgcolor.Blue() +
blend * color.Blue())))
dc.SetTextForeground(color)
dc.DrawText(line, x, y)
class ConfirmDialog(BaseInteractiveDialog):
""" Confirmation dialog with OK and Cancel buttons """
def __init__(self, parent=None, id=-1, title=appname, msg="",
ok=None, cancel=None, bitmap=None, pos=(-1, -1),
size=(400, -1), alt=None, log=False,
style=wx.DEFAULT_DIALOG_STYLE, nowrap=False, wrap=70,
name=wx.DialogNameStr, bitmap_margin=None):
if not ok:
ok = lang.getstr("ok")
if not cancel:
cancel = lang.getstr("cancel")
BaseInteractiveDialog.__init__(self, parent, id, title, msg, ok,
bitmap, pos, size, show=False,
log=log, style=style,
nowrap=nowrap, wrap=wrap,
name=name,
bitmap_margin=bitmap_margin)
self.Bind(wx.EVT_CLOSE, self.OnClose, self)
margin = 12
if alt:
self.alt = wx.Button(self.buttonpanel, -1, alt)
self.sizer2.Prepend((margin, margin))
self.sizer2.Prepend(self.alt)
self.Bind(wx.EVT_BUTTON, self.OnClose, id=self.alt.GetId())
self.cancel = wx.Button(self.buttonpanel, wx.ID_CANCEL, cancel)
self.sizer2.Prepend((margin, margin))
self.sizer2.Prepend(self.cancel)
self.Bind(wx.EVT_BUTTON, self.OnClose, id=wx.ID_CANCEL)
self.buttonpanel.Layout()
self.sizer0.SetSizeHints(self)
self.sizer0.Layout()
def OnClose(self, event):
if hasattr(self, "OnCloseIntercept"):
try:
self.OnCloseIntercept(event)
except Exception, exception:
handle_error(exception, self)
return
if event.GetEventObject() == self:
id = wx.ID_CANCEL
else:
id = event.GetId()
self.EndModal(id)
class FileBrowseBitmapButtonWithChoiceHistory(filebrowse.FileBrowseButtonWithHistory):
def __init__(self, *arguments, **namedarguments):
self.history = namedarguments.get("history") or []
if 'history' in namedarguments:
del namedarguments["history"]
self.historyCallBack = None
if callable(self.history):
self.historyCallBack = self.history
self.history = []
name = namedarguments.get('name', 'fileBrowseButtonWithHistory')
if 'name' in namedarguments:
del namedarguments['name']
filebrowse.FileBrowseButton.__init__(self, *arguments, **namedarguments)
self.SetName(name)
self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
if "__WXGTK__" in wx.PlatformInfo and wx.VERSION < (2, 9):
self.textControl.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
self.browseButton.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
def OnSetFocus(self, event):
if event.EventObject is self:
floatspin.focus_next_keyboard_focusable_control(self)
event.Skip()
def OnKeyDown(self, event):
if event.KeyCode == wx.WXK_TAB:
floatspin.focus_next_keyboard_focusable_control(event.EventObject)
else:
event.Skip()
def Disable(self):
self.Enable(False)
def Enable(self, enable=True):
self.textControl.Enable(enable and self.history != [""])
self.browseButton.Enable(enable)
def GetName(self, path):
"""
Return a name for a path. Return value may be a translated string.
"""
name = None
if os.path.splitext(path)[1].lower() in (".icc", ".icm"):
try:
profile = ICCP.ICCProfile(path)
except (IOError, ICCP.ICCProfileInvalidError):
pass
else:
name = profile.getDescription()
if not name:
name = os.path.basename(path)
return lang.getstr(name)
def GetValue(self):
"""
retrieve current value of text control
"""
if self.textControl.GetSelection() > -1:
return self.history[self.textControl.GetSelection()]
return ""
GetPath = GetValue
def OnChanged(self, evt):
self.textControl.SetToolTipString(self.history[self.textControl.GetSelection()])
if self.callCallback and self.changeCallback:
self.changeCallback(evt)
def SetBackgroundColour(self,color):
wx.Panel.SetBackgroundColour(self,color)
def SetHistory(self, value=(), selectionIndex=None, control=None):
"""Set the current history list"""
if control is None:
control = self.textControl
if self.history == value:
return
index = control.GetSelection()
if self.history and index > -1:
tempValue = self.history[index]
else:
tempValue = ""
self.history = []
control.Clear()
for path in list(value) + [tempValue]:
if path:
self.history.append(path)
control.Append(self.GetName(path))
self.setupControl(selectionIndex, control)
def SetMaxFontSize(self, pointsize=11):
self.textControl.SetMaxFontSize(pointsize)
def SetValue(self, value, callBack=1, clear_on_empty_value=False):
if not value:
if clear_on_empty_value and self.history:
index = self.textControl.GetSelection()
if index > -1:
self.history.pop(index)
self.textControl.Delete(index)
if not value in self.history:
self.history.append(value)
self.textControl.Append(self.GetName(value))
self.setupControl(self.history.index(value))
if callBack:
self.changeCallback(CustomEvent(wx.EVT_CHOICE.typeId,
self.textControl))
def SetPath(self, path):
self.SetValue(path, 0, clear_on_empty_value=True)
def createBrowseButton(self):
"""Create the browse-button control"""
button = GenBitmapButton(self, -1, geticon(16, "document-open"),
style=wx.NO_BORDER)
button.SetToolTipString(self.toolTip)
button.Bind(wx.EVT_BUTTON, self.OnBrowse)
return button
def createDialog(self, parent, id, pos, size, style, name=None):
"""Setup the graphic representation of the dialog"""
wx.Panel.__init__ (self, parent, id, pos, size, style)
self.SetMinSize(size) # play nice with sizers
box = wx.BoxSizer(wx.HORIZONTAL)
self.textControl = self.createTextControl()
if sys.platform == "darwin" and wx.VERSION > (2, 9):
# Prevent 1px cut-off at left-hand side
box.Add((1, 1))
box.Add(self.textControl, 1, wx.ALIGN_CENTER_VERTICAL | wx.TOP |
wx.BOTTOM, 4)
self.browseButton = self.createBrowseButton()
box.Add(self.browseButton, 0, wx.ALIGN_CENTER_VERTICAL | wx.LEFT, 8)
if self.history:
history = self.history
self.history = []
self.SetHistory(history)
self.SetAutoLayout(True)
self.SetSizer(box)
self.Layout()
def createLabel(self):
return (0, 0)
def createTextControl(self):
"""Create the text control"""
textControl = wx.Choice(self, -1)
textControl.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
if self.changeCallback:
textControl.Bind(wx.EVT_CHOICE, self.OnChanged)
return textControl
def setupControl(self, selectionIndex=None, control=None):
if control is None:
control = self.textControl
if selectionIndex is None:
selectionIndex = len(self.history) - 1
control.SetSelection(selectionIndex)
toolTip = (self.history[selectionIndex] if selectionIndex > -1 else
self.toolTip)
control.SetToolTipString(toolTip)
control.Enable(self.browseButton.Enabled and self.history != [""])
class PathDialog(ConfirmDialog):
def __init__(self, parent, msg, name):
ConfirmDialog.__init__(self, parent, msg=msg,
ok=lang.getstr("browse"),
cancel=lang.getstr("cancel"), name=name)
self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
self.ok.Bind(wx.EVT_BUTTON, self.filedialog_handler)
def OnDestroy(self, event):
self.filedialog.Destroy()
event.Skip()
def __getattr__(self, name):
return getattr(self.filedialog, name)
def filedialog_handler(self, event):
self.EndModal(self.filedialog.ShowModal())
_DirDialog = wx.DirDialog
class DirDialog(PathDialog):
""" wx.DirDialog cannot be interacted with programmatically after
ShowModal(), a functionality we need for scripting. """
def __init__(self, *args, **kwargs):
PathDialog.__init__(self, args[0], args[1], "dirdialog")
self.filedialog = _DirDialog(*args, **kwargs)
_FileDialog = wx.FileDialog
class FileDialog(PathDialog):
""" wx.FileDialog cannot be interacted with programmatically after
ShowModal(), a functionality we need for scripting. """
def __init__(self, *args, **kwargs):
PathDialog.__init__(self, args[0], args[1], "filedialog")
self.filedialog = _FileDialog(*args, **kwargs)
class FileDrop(_FileDrop):
def __init__(self, parent, drophandlers=None):
self.parent = parent
_FileDrop.__init__(self, drophandlers)
self.unsupported_handler = self.drop_unsupported_handler
def drop_unsupported_handler(self):
"""
Drag'n'drop handler for unsupported files.
Shows an error message.
"""
if (not hasattr(self.parent, "worker") or
not self.parent.worker.is_working()):
InfoDialog(self.parent, msg=lang.getstr("error.file_type_unsupported") +
"\n\n" + "\n".join(self._filenames),
ok=lang.getstr("ok"),
bitmap=geticon(32, "dialog-error"))
class FlatShadedButton(GradientButton):
def __init__(self, parent, id=wx.ID_ANY, bitmap=None, label="",
pos=wx.DefaultPosition, size=wx.DefaultSize,
style=wx.NO_BORDER, validator=wx.DefaultValidator,
name="gradientbutton", bgcolour=None, fgcolour=None):
GradientButton.__init__(self, parent, id, bitmap, label, pos, size,
style, validator, name)
self._setcolours(bgcolour, fgcolour)
self.SetFont(adjust_font_size_for_gcdc(self.GetFont()))
def _setcolours(self, bgcolour=None, fgcolour=None):
self.SetTopStartColour(bgcolour or wx.Colour(0x22, 0x22, 0x22))
self.SetTopEndColour(bgcolour or wx.Colour(0x22, 0x22, 0x22))
self.SetBottomStartColour(bgcolour or wx.Colour(0x22, 0x22, 0x22))
self.SetBottomEndColour(bgcolour or wx.Colour(0x22, 0x22, 0x22))
self.SetForegroundColour(fgcolour or wx.Colour(0xdd, 0xdd, 0xdd))
self.SetPressedBottomColour(bgcolour or wx.Colour(0x22, 0x22, 0x22))
self.SetPressedTopColour(bgcolour or wx.Colour(0x22, 0x22, 0x22))
def Disable(self):
self.Enable(False)
def DoGetBestSize(self):
"""
Overridden base class virtual. Determines the best size of the
button based on the label and bezel size.
"""
if not getattr(self, "_lastBestSize", None):
dummy = u"FfGgJjPpYy"
label = self.GetLabel() or dummy
dc = wx.MemoryDC(wx.EmptyBitmap(1, 1))
try:
dc = wx.GCDC(dc)
except:
pass
dc.SetFont(self.GetFont())
retWidth, retHeight = dc.GetTextExtent(label)
if label == dummy:
retWidth = 0
elif wx.VERSION < (2, 9):
retWidth += 5
bmpWidth = bmpHeight = 0
if self._bitmap:
if label != dummy:
constant = 10
if wx.VERSION < (2, 9):
retWidth += 5
else:
constant = 0
# Pin the bitmap height to 10
bmpWidth, bmpHeight = self._bitmap.GetWidth()+constant, 10
retWidth += bmpWidth
retHeight = max(bmpHeight, retHeight)
self._lastBestSize = wx.Size(retWidth + 20, retHeight + 15)
return self._lastBestSize
def OnGainFocus(self, event):
"""
Handles the ``wx.EVT_SET_FOCUS`` event for L{GradientButton}.
:param `event`: a `wx.FocusEvent` event to be processed.
"""
self._hasFocus = True
self._mouseAction = HOVER
self.Refresh()
self.Update()
def OnLoseFocus(self, event):
"""
Handles the ``wx.EVT_LEAVE_WINDOW`` event for L{GradientButton}.
:param `event`: a `wx.MouseEvent` event to be processed.
"""
self._hasFocus = False
self._mouseAction = None
self.Refresh()
event.Skip()
def OnPaint(self, event):
"""
Handles the ``wx.EVT_PAINT`` event for L{GradientButton}.
:param `event`: a `wx.PaintEvent` event to be processed.
"""
if sys.platform != "win32":
# AutoBufferedPaintDCFactory is the magic needed for crisp text
# rendering in HiDPI mode under OS X and Linux
cls = wx.AutoBufferedPaintDCFactory
else:
cls = wx.BufferedPaintDC
dc = cls(self)
gc = wx.GraphicsContext.Create(dc)
dc.SetBackground(wx.Brush(self.GetParent().GetBackgroundColour()))
dc.Clear()
clientRect = self.GetClientRect()
gradientRect = wx.Rect(*clientRect)
capture = wx.Window.GetCapture()
x, y, width, height = clientRect
gradientRect.SetHeight(gradientRect.GetHeight()/2 + ((capture==self and [1] or [0])[0]))
if capture != self:
if self._mouseAction == HOVER:
topStart, topEnd = self.LightColour(self._topStartColour, 10), self.LightColour(self._topEndColour, 10)
else:
topStart, topEnd = self._topStartColour, self._topEndColour
rc1 = wx.Rect(x, y, width, height/2)
path1 = self.GetPath(gc, rc1, 8)
br1 = gc.CreateLinearGradientBrush(x, y, x, y+height/2, topStart, topEnd)
gc.SetBrush(br1)
gc.FillPath(path1) #draw main
path4 = gc.CreatePath()
path4.AddRectangle(x, y+height/2-8, width, 8)
path4.CloseSubpath()
gc.SetBrush(br1)
gc.FillPath(path4)
else:
rc1 = wx.Rect(x, y, width, height)
path1 = self.GetPath(gc, rc1, 8)
gc.SetPen(wx.Pen(self._pressedTopColour))
gc.SetBrush(wx.Brush(self._pressedTopColour))
gc.FillPath(path1)
gradientRect.Offset((0, gradientRect.GetHeight()))
if capture != self:
if self._mouseAction == HOVER:
bottomStart, bottomEnd = self.LightColour(self._bottomStartColour, 10), self.LightColour(self._bottomEndColour, 10)
else:
bottomStart, bottomEnd = self._bottomStartColour, self._bottomEndColour
rc3 = wx.Rect(x, y+height/2, width, height/2)
path3 = self.GetPath(gc, rc3, 8)
br3 = gc.CreateLinearGradientBrush(x, y+height/2, x, y+height, bottomStart, bottomEnd)
gc.SetBrush(br3)
gc.FillPath(path3) #draw main
path4 = gc.CreatePath()
path4.AddRectangle(x, y+height/2, width, 8)
path4.CloseSubpath()
gc.SetBrush(br3)
gc.FillPath(path4)
shadowOffset = 0
else:
rc2 = wx.Rect(x+1, gradientRect.height/2, gradientRect.width, gradientRect.height)
path2 = self.GetPath(gc, rc2, 8)
gc.SetPen(wx.Pen(self._pressedBottomColour))
gc.SetBrush(wx.Brush(self._pressedBottomColour))
gc.FillPath(path2)
shadowOffset = 1
font = gc.CreateFont(self.GetFont(), self.GetForegroundColour())
gc.SetFont(font)
label = self.GetLabel()
if label and self._bitmap:
label = " " + label
tw, th = gc.GetTextExtent(label)
if self._bitmap:
bw, bh = self._bitmap.GetWidth(), self._bitmap.GetHeight()
if tw:
tw += 5
if wx.VERSION < (2, 9):
tw += 5
else:
bw = bh = 0
pos_x = (width-bw-tw)/2+shadowOffset # adjust for bitmap and text to centre
if self._bitmap:
pos_y = (height-bh)/2+shadowOffset
gc.DrawBitmap(self._bitmap, pos_x, pos_y, bw, bh) # draw bitmap if available
pos_x = pos_x + 5 # extra spacing from bitmap
gc.DrawText(label, pos_x + bw + shadowOffset, (height-th)/2-.5+shadowOffset)
def Enable(self, enable=True):
if enable:
self._setcolours()
else:
self._setcolours(wx.Colour(0x66, 0x66, 0x66))
GradientButton.Enable(self, enable)
def SetBitmap(self, bitmap):
self._bitmap = bitmap
self.Refresh()
class BorderGradientButton(GradientButton):
def __init__(self, parent, id=wx.ID_ANY, bitmap=None, label="",
pos=wx.DefaultPosition, size=wx.DefaultSize,
style=wx.NO_BORDER, validator=wx.DefaultValidator,
name="gradientbutton"):
GradientButton.__init__(self, parent, id, bitmap, label, pos, size,
style, validator, name)
self.SetFont(adjust_font_size_for_gcdc(self.GetFont()))
self._bitmapdisabled = self._bitmap
self._bitmapfocus = self._bitmap
self._bitmaphover = self._bitmap
self._bitmapselected = self._bitmap
set_bitmap_labels(self)
self._enabled = True
BitmapLabel = property(lambda self: self._bitmap,
lambda self, bitmap: self.SetBitmap(bitmap))
def Disable(self):
self.Enable(False)
def DoGetBestSize(self):
"""
Overridden base class virtual. Determines the best size of the
button based on the label and bezel size.
"""
label = self.GetLabel()
if not label:
return wx.Size(112, 48)
dc = wx.ClientDC(self)
dc.SetFont(self.GetFont())
retWidth, retHeight = dc.GetTextExtent(label)
bmpWidth = bmpHeight = 0
constant = 15
if self._bitmap:
bmpWidth, bmpHeight = self._bitmap.GetWidth()+20, self._bitmap.GetHeight()
retWidth += bmpWidth
retHeight = max(bmpHeight, retHeight)
constant = 15
return wx.Size(retWidth+constant, retHeight+constant)
def Enable(self, enable=True):
self._enabled = enable
GradientButton.Enable(self, enable)
self.Update()
def IsEnabled(self):
return self._enabled
Enabled = property(IsEnabled, Enable)
def OnPaint(self, event):
"""
Handles the ``wx.EVT_PAINT`` event for L{GradientButton}.
:param `event`: a `wx.PaintEvent` event to be processed.
"""
if sys.platform != "win32":
# AutoBufferedPaintDCFactory is the magic needed for crisp text
# rendering in HiDPI mode under OS X and Linux
cls = wx.AutoBufferedPaintDCFactory
else:
cls = wx.BufferedPaintDC
dc = cls(self)
gc = wx.GraphicsContext.Create(dc)
dc.SetBackground(wx.Brush(self.GetParent().GetBackgroundColour()))
dc.Clear()
clientRect = self.GetClientRect()
gradientRect = wx.Rect(*clientRect)
capture = wx.Window.GetCapture()
x, y, width, height = clientRect
gradientRect.SetHeight(gradientRect.GetHeight()/2 + ((capture==self and [1] or [0])[0]))
if capture != self:
if self._mouseAction == HOVER:
topStart, topEnd = self.LightColour(self._topStartColour, 10), self.LightColour(self._bottomEndColour, 10)
else:
topStart, topEnd = self._topStartColour, self._bottomEndColour
brush = gc.CreateLinearGradientBrush(0, 1, 0, height, topStart,
topEnd)
else:
brush = gc.CreateLinearGradientBrush(0, 1, 0, height,
self._pressedTopColour,
self._pressedBottomColour)
fgcolor = self.ForegroundColour
if not self.IsEnabled():
fgcolor = self.LightColour(fgcolor, 40)
gc.SetBrush(brush)
gc.SetPen(wx.Pen(self.LightColour(fgcolor, 20)))
gc.DrawRoundedRectangle(1, 1, width - 2, height - 2, height / 2)
if capture != self:
shadowOffset = 0
else:
shadowOffset = 1
font = gc.CreateFont(self.GetFont(), fgcolor)
gc.SetFont(font)
label = self.GetLabel()
if label and self._bitmap:
label = " " + label
tw, th = gc.GetTextExtent(label)
if self._bitmap:
bw, bh = self._bitmap.GetWidth(), self._bitmap.GetHeight()
if tw:
tw += 5
if wx.VERSION < (2, 9):
tw += 5
else:
bw = bh = 0
pos_x = (width-bw-tw)/2+shadowOffset # adjust for bitmap and text to centre
if self.IsEnabled():
if self._mouseAction == HOVER:
bitmap = self._bitmaphover
else:
bitmap = self._bitmap
else:
bitmap = self._bitmapdisabled
if bitmap:
pos_y = (height-bh)/2+shadowOffset
gc.DrawBitmap(bitmap, pos_x, pos_y, bw, bh) # draw bitmap if available
pos_x = pos_x + 5 # extra spacing from bitmap
gc.DrawText(label, pos_x + bw + shadowOffset, (height-th)/2-.5+shadowOffset)
def SetBitmap(self, bitmap):
self._bitmap = bitmap
def SetBitmapDisabled(self, bitmap):
self._bitmapdisabled = bitmap
def SetBitmapFocus(self, bitmap):
self._bitmapfocus = bitmap
def SetBitmapHover(self, bitmap):
self._bitmaphover = bitmap
def SetBitmapSelected(self, bitmap):
self._bitmapselected = bitmap
class CustomGrid(wx.grid.Grid):
def __init__(self, *args, **kwargs):
wx.grid.Grid.__init__(self, *args, **kwargs)
self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
self.Bind(wx.EVT_SIZE, self.OnResize)
self.Bind(wx.grid.EVT_GRID_ROW_SIZE, self.OnResize)
self.Bind(wx.grid.EVT_GRID_COL_SIZE, self.OnResize)
self.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self.OnCellLeftClick)
self.Bind(wx.grid.EVT_GRID_CELL_LEFT_DCLICK, self.OnCellLeftClick)
self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
self.Bind(wx.grid.EVT_GRID_SELECT_CELL, self.OnCellSelect)
self.Bind(wx.grid.EVT_GRID_LABEL_LEFT_CLICK, self.OnLabelLeftClick)
self.GetGridCornerLabelWindow().Bind(wx.EVT_PAINT, self.OnPaintCornerLabel)
self.GetGridColLabelWindow().Bind(wx.EVT_PAINT, self.OnPaintColLabels)
self.GetGridRowLabelWindow().Bind(wx.EVT_PAINT, self.OnPaintRowLabels)
self.SetDefaultCellAlignment(wx.ALIGN_LEFT, wx.ALIGN_CENTER)
self.SetDefaultCellBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW))
self.SetDefaultEditor(CustomCellEditor(self))
self._default_cell_renderer = CustomCellRenderer()
self.SetDefaultRenderer(self._default_cell_renderer)
self.SetRowLabelAlignment(wx.ALIGN_CENTER, wx.ALIGN_CENTER)
self.headerbitmap = None
if sys.platform == "darwin" or "gtk3" in wx.PlatformInfo:
# wxMac draws a too short native header
self.rendernative = False
self.style = "Mavericks"
else:
self.rendernative = True
self.style = ""
self._default_col_label_renderer = CustomColLabelRenderer()
self._default_row_label_renderer = CustomRowLabelRenderer()
self._col_label_renderers = {}
self._overwrite_cell_values = True
self._row_label_renderers = {}
self.alternate_cell_background_color = True
self.alternate_col_label_background_color = False
self.alternate_row_label_background_color = True
self.draw_col_labels = True
self.draw_row_labels = True
self.draw_horizontal_grid_lines = True
self.draw_vertical_grid_lines = True
self.selection_alpha = 1.0
self.show_cursor_outline = True
if not hasattr(wx.grid.Grid, "CalcCellsExposed"):
# wxPython < 2.8.10
def CalcCellsExposed(self, region):
rows = self.CalcRowLabelsExposed(region)
cols = self.CalcColLabelsExposed(region)
cells = []
for row in rows:
for col in cols:
if row > -1 and col > -1:
cells.append((row, col))
return cells
if not hasattr(wx.grid.Grid, "CalcColLabelsExposed"):
# wxPython < 2.8.10
def CalcColLabelsExposed(self, region):
x, y = self.CalcUnscrolledPosition((0,0))
ri = wx.RegionIterator(region)
cols = []
while ri:
rect = ri.GetRect()
rect.Offset((x,0))
colPos = self.GetColPos(self.XToCol(rect.left))
while colPos < self.GetNumberCols() and colPos >= 0:
col = self.GetColAt(colPos)
cl, cr = self.GetColLeftRight(col)
if cr < rect.left:
continue
if cl > rect.right:
break
cols.append(col)
colPos += 1
ri.Next()
return cols
if not hasattr(wx.grid.Grid, "CalcRowLabelsExposed"):
# wxPython < 2.8.10
def CalcRowLabelsExposed(self, region):
x, y = self.CalcUnscrolledPosition((0,0))
ri = wx.RegionIterator(region)
rows = []
while ri:
rect = ri.GetRect()
rect.Offset((0,y))
row = self.YToRow(rect.top)
while row < self.GetNumberRows() and row >= 0:
rt, rb = self.GetRowTopBottom(row)
if rb < rect.top:
continue
if rt > rect.bottom:
break
rows.append(row)
row += 1
ri.Next()
return rows
def GetColLeftRight(self, col, c=0):
left = 0
while c < col:
left += self.GetColSize(c)
c += 1
right = left + self.GetColSize(col) - 1
return left, right
def GetRowTopBottom(self, row, r=0):
top = 0
while r < row:
top += self.GetRowSize(r)
r += 1
bottom = top + self.GetRowSize(row) - 1
return top, bottom
def OnCellLeftClick(self, event):
if (event.CmdDown() or event.ControlDown() or event.ShiftDown() or
not isinstance(self.GetCellEditor(self.GetGridCursorRow(),
self.GetGridCursorCol()),
CustomCellEditor)):
event.Skip()
else:
self.SetGridCursor(event.Row, event.Col)
def OnCellSelect(self, event):
row, col = event.GetRow(), event.GetCol()
self._anchor_row = row
self._overwrite_cell_values = True
self.SelectBlock(event.Row, event.Col, event.Row, event.Col)
self.Refresh()
event.Skip()
def OnKeyDown(self, event):
keycode = event.KeyCode
if event.CmdDown() or event.ControlDown():
# CTRL (Linux/Mac/Windows) / CMD (Mac)
if keycode == 65:
# A
self.SelectAll()
return
elif keycode in (67, 88):
# C / X
clip = []
cells = self.GetSelection()
i = -1
start_col = self.GetNumberCols()
for cell in cells:
row = cell[0]
col = cell[1]
if i < row:
clip.append([])
i = row
offset = 0
# Skip cols without label
if self.GetColLabelSize() and not self.GetColLabelValue(col):
offset += 1
continue
if col - offset < start_col:
start_col = col - offset
while len(clip[-1]) - 1 < col - offset:
clip[-1].append("")
clip[-1][col - offset] = self.GetCellValue(row, col)
for i, row in enumerate(clip):
clip[i] = "\t".join(row[start_col:])
clipdata = wx.TextDataObject()
clipdata.SetText("\n".join(clip))
wx.TheClipboard.Open()
wx.TheClipboard.SetData(clipdata)
wx.TheClipboard.Close()
return
elif keycode == 86 and self.IsEditable():
# V
do = wx.TextDataObject()
wx.TheClipboard.Open()
success = wx.TheClipboard.GetData(do)
wx.TheClipboard.Close()
if success:
lines = do.GetText().splitlines()
for i, line in enumerate(lines):
lines[i] = re.sub(" +", "\t", line).split("\t")
# Translate from selected cells into a grid with None values
# for not selected cells
grid = []
cells = self.GetSelection()
i = -1
start_col = self.GetNumberCols()
for cell in cells:
row = cell[0]
col = cell[1]
if i < row:
grid.append([])
i = row
offset = 0
# Skip read-only cells and cols without label
if (self.IsReadOnly(row, col) or
(self.GetColLabelSize() and
not self.GetColLabelValue(col))):
offset += 1
continue
if col - offset < start_col:
start_col = col - offset
while len(grid[-1]) - 1 < col - offset:
grid[-1].append(None)
grid[-1][col - offset] = cell
for i, row in enumerate(grid):
grid[i] = row[start_col:]
# 'Paste' values from clipboard
self.BeginBatch()
for i, row in enumerate(grid):
for j, cell in enumerate(row):
if (cell is not None and len(lines) > i and
len(lines[i]) > j):
self.SetCellValue(cell[0], cell[1], lines[i][j])
self.ProcessEvent(wx.grid.GridEvent(-1,
wx.grid.EVT_GRID_CELL_CHANGE.evtType[0],
self,
cell[0],
cell[1]))
self.EndBatch()
return
elif self.IsEditable() and not self.IsCurrentCellReadOnly():
if isinstance(self.GetCellEditor(self.GetGridCursorRow(),
self.GetGridCursorCol()),
CustomCellEditor):
ch = None
if keycode in [wx.WXK_NUMPAD0, wx.WXK_NUMPAD1, wx.WXK_NUMPAD2,
wx.WXK_NUMPAD3, wx.WXK_NUMPAD4, wx.WXK_NUMPAD5,
wx.WXK_NUMPAD6, wx.WXK_NUMPAD7, wx.WXK_NUMPAD8,
wx.WXK_NUMPAD9]:
ch = chr(ord('0') + keycode - wx.WXK_NUMPAD0)
elif keycode in (wx.WXK_NUMPAD_DECIMAL,
wx.WXK_NUMPAD_SEPARATOR):
ch = "."
elif keycode < 256 and keycode >= 32:
ch = safe_unicode(chr(keycode))
if ch is not None or keycode in (wx.WXK_BACK, wx.WXK_DELETE):
changed = 0
batch = False
for i, (row, col) in enumerate(self.GetSelection()):
if row > -1 and col > -1 and not self.IsReadOnly(row, col):
if changed and not batch:
self.BeginBatch()
batch = True
if (self._overwrite_cell_values or
keycode == wx.WXK_DELETE):
value = ""
else:
value = self.GetCellValue(row, col)
if keycode == wx.WXK_BACK:
value = value[:-1]
elif keycode != wx.WXK_DELETE:
value += ch
self.SetCellValue(row, col, value)
self.ProcessEvent(wx.grid.GridEvent(-1,
wx.grid.EVT_GRID_CELL_CHANGE.evtType[0],
self,
row,
col))
changed += 1
if batch:
self.EndBatch()
self._overwrite_cell_values = False
if not changed:
wx.Bell()
return
elif (event.KeyCode == wx.WXK_RETURN or
event.KeyCode == wx.WXK_NUMPAD_ENTER):
self.EnableCellEditControl()
return
event.Skip()
def OnKillFocus(self, event):
self.Refresh()
event.Skip()
def OnLabelLeftClick(self, event):
row, col = event.GetRow(), event.GetCol()
if row == -1 and col > -1:
# Col label clicked
self.SetFocus()
self.SetGridCursor(max(self.GetGridCursorRow(), 0), col)
self.MakeCellVisible(max(self.GetGridCursorRow(), 0), col)
elif col == -1 and row > -1:
# Row label clicked
if self.select_row(row, event.ShiftDown(),
event.ControlDown() or event.CmdDown()):
return
event.Skip()
def OnPaintColLabels(self, evt):
window = evt.GetEventObject()
dc = wx.PaintDC(window)
cols = self.CalcColLabelsExposed(window.GetUpdateRegion())
if -1 in cols:
return
x, y = self.CalcUnscrolledPosition((0,0))
pt = dc.GetDeviceOrigin()
dc.SetDeviceOrigin(pt.x-x, pt.y)
leftoffset = 0
for i, col in enumerate(cols):
left, right = self.GetColLeftRight(col, cols[0] if i > 0 else 0)
if i > 0:
left += leftoffset
right += leftoffset
else:
leftoffset = left
rect = wx.Rect()
rect.left = left
rect.right = right
rect.y = 0
rect.height = self.GetColLabelSize()
renderer = self._col_label_renderers.get(col,
self._default_col_label_renderer)
renderer.Draw(self, dc, rect, col)
def OnPaintCornerLabel(self, evt):
window = evt.GetEventObject()
dc = wx.PaintDC(window)
rect = wx.Rect()
rect.width = self.GetRowLabelSize()
rect.height = self.GetColLabelSize()
rect.x = 0
rect.y = 0
self._default_col_label_renderer.Draw(self, dc, rect)
def OnPaintRowLabels(self, evt):
window = evt.GetEventObject()
dc = wx.PaintDC(window)
rows = self.CalcRowLabelsExposed(window.GetUpdateRegion())
if -1 in rows:
return
x, y = self.CalcUnscrolledPosition((0,0))
pt = dc.GetDeviceOrigin()
dc.SetDeviceOrigin(pt.x, pt.y-y)
topoffset = 0
for i, row in enumerate(rows):
top, bottom = self.GetRowTopBottom(row, rows[0] if i > 0 else 0)
if i > 0:
top += topoffset
bottom += topoffset
else:
topoffset = top
rect = wx.Rect()
rect.top = top
rect.bottom = bottom
rect.x = 0
rect.width = self.GetRowLabelSize()
renderer = self._row_label_renderers.get(row,
self._default_row_label_renderer)
renderer.Draw(self, dc, rect, row)
def OnResize(self, event):
region = wx.Region(*self.ClientRect.Get())
for row, col in self.CalcCellsExposed(region):
cell_renderer = self.GetCellRenderer(row, col)
if (isinstance(cell_renderer, CustomCellRenderer) and
cell_renderer._selectionbitmaps):
# On resize, we need to tell any CustomCellRenderer that its
# bitmaps are no longer valid and are garbage collected
cell_renderer._selectionbitmaps = {}
event.Skip()
def SetColLabelRenderer(self, renderer):
"""
Register a renderer to be used for drawing the label for the
given column.
"""
if renderer is None:
if col in self._col_label_renderers:
del self._col_label_renderers[col]
else:
self._col_label_renderers[col] = renderer
def SetDefaultCellBackgroundColour(self, color):
# Set alpha to 0 so we can detect the default color
if not isinstance(color, wx.Colour):
color_str = color
color = wx.Colour()
if hasattr(wx.Colour, "SetFromString"):
color.SetFromString(color_str)
else:
color.SetFromName(color_str)
color.Set(color.Red(), color.Green(), color.Blue(), 0)
wx.grid.Grid.SetDefaultCellBackgroundColour(self, color)
def SetRowLabelRenderer(self, row, renderer):
"""
Register a renderer to be used for drawing the label for the
given row.
"""
if renderer is None:
if row in self._row_label_renderers:
del self._row_label_renderers[row]
else:
self._row_label_renderers[row] = renderer
def select_row(self, row, shift=False, ctrl=False):
self.SetFocus()
if not shift and not ctrl:
self.SetGridCursor(row, max(self.GetGridCursorCol(), 0))
self.SelectRow(row)
self._anchor_row = row
self.MakeCellVisible(row, max(self.GetGridCursorCol(), 0))
if self.IsSelection():
if shift:
self.BeginBatch()
rows = self.GetSelectionRows()
sel = range(min(self._anchor_row, row),
max(self._anchor_row, row) + 1)
desel = []
add = []
for i in rows:
if i not in sel:
desel.append(i)
for i in sel:
if i not in rows:
add.append(i)
if len(desel) >= len(add):
# in this case deselecting rows will take as long or longer than selecting, so use SelectRow to speed up the operation
self.SelectRow(row)
else:
for i in desel:
self.DeselectRow(i)
for i in add:
self.SelectRow(i, True)
self.EndBatch()
return False
elif ctrl:
if self.IsInSelection(row, 0):
self.DeselectRow(row)
return True
else:
self.SelectRow(row, True)
return False
class CustomCheckBox(wx.Panel):
"""
A custom checkbox where the label is independent from the checkbox itself.
Works around wxMac not taking into account text (foreground) color on
a default checkbox label.
"""
def __init__(self, parent, id=wx.ID_ANY, label="", pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.NO_BORDER,
validator=wx.DefaultValidator, name="CustomCheckBox"):
wx.Panel.__init__(self, parent, id, pos, size, style, name)
self.BackgroundColour = parent.BackgroundColour
self.SetSizer(wx.BoxSizer(wx.HORIZONTAL))
self._cb = wx.CheckBox(self, -1)
self._enabled = True
self.Sizer.Add(self._cb, flag=wx.ALIGN_CENTER_VERTICAL)
if sys.platform == "darwin":
self._label = wx.StaticText(self, -1, "")
self.Sizer.Add(self._label, 1, wx.ALIGN_CENTER_VERTICAL)
self._label.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
self._label.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
self._up = True
else:
self._label = self._cb
self._label.Label = label
def Bind(self, event_id, handler):
self._cb.Bind(event_id, handler)
def Disable(self):
self.Enable(False)
def Enable(self, enable=True):
enable = bool(enable)
if self.Enabled is enable:
return
self._enabled = enable
self._cb.Enable(enable)
if self._label is not self._cb:
if not hasattr(self, "_fgcolor"):
self._fgcolor = self.ForegroundColour
color = self._fgcolor
if not enable:
bgcolor = self.Parent.BackgroundColour
bgblend = .5
blend = .5
color = wx.Colour(int(round(bgblend * bgcolor.Red() +
blend * color.Red())),
int(round(bgblend * bgcolor.Green() +
blend * color.Green())),
int(round(bgblend * bgcolor.Blue() +
blend * color.Blue())))
self._label.ForegroundColour = color
@Property
def Enabled():
def fget(self):
return self.IsEnabled()
def fset(self, enable=True):
self.Enable(enable)
return locals()
def IsEnabled(self):
return self._enabled
def OnLeftDown(self, event):
if not self.Enabled:
return
self._up = False
self._cb.SetFocus()
event.Skip()
def OnLeftUp(self, event):
if not self.Enabled:
return
if not self._up and self.ClientRect.Contains(event.GetPosition()):
# if the checkbox was down when the mouse was released...
self.SendCheckBoxEvent()
self._up = True
def SendCheckBoxEvent(self):
""" Actually sends the event to the checkbox. """
self.Value = not self.Value
checkEvent = wx.CommandEvent(wx.wxEVT_COMMAND_CHECKBOX_CLICKED,
self._cb.GetId())
checkEvent.SetInt(int(self.Value))
# Set the originating object for the event (the checkbox)
checkEvent.SetEventObject(self._cb)
# Watch for a possible listener of this event that will catch it and
# eventually process it
self._cb.GetEventHandler().ProcessEvent(checkEvent)
def SetMaxFontSize(self, pointsize=11):
self._label.SetMaxFontSize(pointsize)
def GetValue(self):
"""
Returns the state of CustomCheckBox, True if checked, False
otherwise.
"""
return self._cb.Value
def IsChecked(self):
"""
This is just a maybe more readable synonym for GetValue: just as the
latter, it returns True if the CustomCheckBox is checked and False
otherwise.
"""
return self._cb.Value
def SetValue(self, state):
"""
Sets the CustomCheckBox to the given state. This does not cause a
wx.wxEVT_COMMAND_CHECKBOX_CLICKED event to get emitted.
"""
self._cb.Value = state
def GetLabel(self):
return self._label.Label
def SetLabel(self, label):
self._label.Label = label
def SetForegroundColour(self, color):
wx.Panel.SetForegroundColour(self, color)
self._label.ForegroundColour = color
@Property
def Label():
def fget(self):
return self.GetLabel()
def fset(self, label):
self.SetLabel(label)
return locals()
@Property
def Value():
def fget(self):
return self.GetValue()
def fset(self, state):
self.SetValue(state)
return locals()
@Property
def ForegroundColour():
def fget(self):
return self.GetForegroundColour()
def fset(self, color):
self.SetForegroundColour(color)
return locals()
class CustomCellEditor(wx.grid.PyGridCellEditor):
def __init__(self, grid):
wx.grid.PyGridCellEditor.__init__(self)
self._grid = grid
self._cell_renderer = CustomCellRenderer()
def Create(self, parent, id, evtHandler):
"""
Called to create the control, which must derive from wx.Control.
"""
safe_print("CustomCellEditor.Create(%r, %r, %r) was called. This "
"should not happen, but is unlikely an issue." %
(parent, id, evtHandler))
self.SetControl(wx.StaticText(parent, -1, ""))
def SetSize(self, rect):
"""
Called to position/size the edit control within the cell rectangle.
If you don't fill the cell (the rect) then be sure to override
PaintBackground and do something meaningful there.
"""
safe_print("CustomCellEditor.SetSize(%r) was called. This should not "
"happen, but is unlikely an issue." % rect)
self.Control.SetDimensions(rect.x, rect.y, rect.width, rect.height,
wx.SIZE_ALLOW_MINUS_ONE)
def Show(self, show, attr):
"""
Show or hide the edit control. You can use the attr (if not None)
to set colours or fonts for the control.
"""
safe_print("CustomCellEditor.Show(%r, %r) was called. This should "
"not happen, but is unlikely an issue." % (show, attr))
super(self.__class__, self).Show(show, attr)
def PaintBackground(self, dc, rect, attr=None):
"""
Draws the part of the cell not occupied by the edit control. The
base class version just fills it with background colour from the
attribute. In this class the edit control fills the whole cell so
don't do anything at all in order to reduce flicker.
"""
self._cell_renderer.Draw(self._grid, attr, dc, rect,
self._grid.GetGridCursorRow(),
self._grid.GetGridCursorCol(), True)
def BeginEdit(self, row, col, grid):
"""
Fetch the value from the table and prepare the edit control
to begin editing. Set the focus to the edit control.
"""
safe_print("CustomCellEditor.BeginEdit(%r, %r, %r) was called. This "
"should not happen, but is unlikely an issue." %
(row, col, grid))
def EndEdit(self, row, col, grid, value=None):
"""
Complete the editing of the current cell. Returns True if the value
has changed. If necessary, the control may be destroyed.
"""
safe_print("CustomCellEditor.EndEdit(%r, %r, %r, %r) was called. This "
"should not happen, but is unlikely an issue." %
(row, col, grid, value))
if wx.VERSION >= (2, 9):
changed = None
else:
changed = False
return changed
def Reset(self):
"""
Reset the value in the control back to its starting value.
"""
safe_print("CustomCellEditor.Reset() was called. This should "
"not happen, but is unlikely an issue.")
def IsAcceptedKey(self, evt):
"""
Return True to allow the given key to start editing: the base class
version only checks that the event has no modifiers. F2 is special
and will always start the editor.
"""
return False
def StartingKey(self, evt):
"""
If the editor is enabled by pressing keys on the grid, this will be
called to let the editor do something about that first key if desired.
"""
safe_print("CustomCellEditor.StartingKey(%r) was called. This should "
"not happen, but is unlikely an issue." % evt)
evt.Skip()
def StartingClick(self):
"""
If the editor is enabled by clicking on the cell, this method will be
called to allow the editor to simulate the click on the control if
needed.
"""
def Destroy(self):
"""final cleanup"""
super(self.__class__, self).Destroy()
def Clone(self):
"""
Create a new object which is the copy of this one
*Must Override*
"""
return self.__class__()
class CustomCellRenderer(wx.grid.PyGridCellRenderer):
def __init__(self, *args, **kwargs):
wx.grid.PyGridCellRenderer.__init__(self)
self.specialbitmap = getbitmap("theme/checkerboard-10x10x2-333-444")
self._selectionbitmaps = {}
def Clone(self):
return self.__class__()
def Draw(self, grid, attr, dc, rect, row, col, isSelected):
orect = rect
#if col == grid.GetNumberCols() - 1:
## Last column
#w = max(grid.ClientSize[0] - rect[0], rect[2])
#rect = wx.Rect(rect[0], rect[1], w, rect[3])
bgcolor = grid.GetCellBackgroundColour(row, col)
col_label = grid.GetColLabelValue(col)
is_default_bgcolor = bgcolor == grid.GetDefaultCellBackgroundColour()
is_read_only = grid.IsReadOnly(row, col)
if is_default_bgcolor:
if (is_read_only or not grid.IsEditable()) and col_label:
bgcolor = grid.GetLabelBackgroundColour()
if row % 2 == 0 and grid.alternate_cell_background_color:
bgcolor = wx.Colour(*[int(v * .98) for v in bgcolor])
elif bgcolor.Alpha() < 255:
# Make sure it's opaque
bgcolor = wx.Colour(bgcolor.Red(), bgcolor.Green(),
bgcolor.Blue())
special = bgcolor.Get(True) == (0, 0, 0, 0)
mavericks = getattr(grid, "style", None) == "Mavericks"
if (not special and mavericks and bgcolor.Red() < 255):
# Use Mavericks-like color scheme
newcolor = [int(round(min(bgcolor.Get()[i] * (v / 102.0), 255)))
for i, v in enumerate((98, 100, 102))]
bgcolor.Set(*newcolor)
rowselect = grid.GetSelectionMode() == wx.grid.Grid.wxGridSelectRows
isCursor = (grid.show_cursor_outline and
((row, col) == (grid.GetGridCursorRow(),
grid.GetGridCursorCol()) or
(rowselect and row == grid.GetGridCursorRow())))
if (isSelected or isCursor) and is_default_bgcolor and col_label:
color = grid.GetSelectionBackground()
if isSelected:
textcolor = grid.GetSelectionForeground()
else:
textcolor = grid.GetCellTextColour(row, col)
focus = grid.Parent.FindFocus()
if not focus or grid not in (focus, focus.GetParent(),
focus.GetGrandParent()):
if mavericks or sys.platform == "darwin" or "gtk3" in wx.PlatformInfo:
# Use Mavericks-like color scheme
color = wx.Colour(202, 202, 202)
if isSelected:
textcolor = wx.Colour(51, 51, 51)
else:
rgb = int((color.Red() + color.Green() + color.Blue()) / 3.0)
color = wx.Colour(rgb, rgb, rgb)
elif mavericks or sys.platform == "darwin" or "gtk3" in wx.PlatformInfo:
# Use Mavericks-like color scheme
color = wx.Colour(44, 93, 205)
if isSelected:
textcolor = wx.WHITE
else:
alpha = (grid.selection_alpha * 255 or
grid.GetSelectionBackground().Alpha())
# Blend with bg color
if alpha < 255:
# Alpha blending
bgblend = (255 - alpha) / 255.0
blend = alpha / 255.0
color = wx.Colour(int(round(bgblend * bgcolor.Red() +
blend * color.Red())),
int(round(bgblend * bgcolor.Green() +
blend * color.Green())),
int(round(bgblend * bgcolor.Blue() +
blend * color.Blue())))
else:
color = bgcolor
textcolor = grid.GetCellTextColour(row, col)
if special:
# Special
image = self.specialbitmap.ConvertToImage()
image.Rescale(rect[2], rect[3])
dc.DrawBitmap(image.ConvertToBitmap(), rect[0], rect[1])
else:
if (isSelected or isCursor) and col_label:
dc.SetBrush(wx.Brush(bgcolor))
dc.SetPen(wx.TRANSPARENT_PEN)
dc.DrawRectangleRect(rect)
rect = orect
if not rowselect:
w = 60 + rect[3] * 2
if rect.Width > w:
rect.Left += (rect.Width - w) / 2.0
rect.Width = w
offset = 1 # Selection offset from cell boundary
cb = 2 # Cursor border
left = (not rowselect or
col == 0 or not grid.GetColLabelValue(col - 1))
right = (not rowselect or
col == grid.GetNumberCols() - 1 or
not grid.GetColLabelValue(col + 1))
# We could use wx.GCDC, but it is buggy under wxGTK
# (grid doesn't refresh properly when scrolling).
# Implement our own supersampling antialiasing method
# using wx.MemoryDC and cached bitmaps.
# This has the drawback that it may use a lot of memory if
# a grid has many cells with different dimensions or color
# properties, but we make sure that old bitmaps are garbage
# collected if the grid or rows/cols are resized by binding
# resize events in CustomGrid initialization.
key = rect[2:] + bgcolor.Get() + color.Get() + (left, right,
not isSelected
and isCursor)
if not self._selectionbitmaps.get(key):
scale = 4.0 # Supersampling factor
offset *= scale
cb *= scale
x, y, w, h = 0, 0, rect[2] * scale, rect[3] * scale
self._selectionbitmaps[key] = wx.EmptyBitmap(w, h)
paintdc = dc
dc = mdc = wx.MemoryDC(self._selectionbitmaps[key])
dc.SetBrush(wx.Brush(bgcolor))
dc.SetPen(wx.TRANSPARENT_PEN)
dc.DrawRectangle(x, y, w, h)
dc.SetBrush(wx.Brush(color))
dc.SetPen(wx.TRANSPARENT_PEN)
draw = dc.DrawRoundedRectangle
draw(x + offset, y + offset, w - offset * 2,
h - offset * 2, h / 2.0 - offset)
if not left:
dc.DrawRectangle(x, y + offset, h / 2.0,
h - offset * 2)
if not right:
dc.DrawRectangle(x + w - h / 2.0, y + offset, h / 2.0,
h - offset * 2)
if not isSelected and isCursor:
dc.SetBrush(wx.Brush(bgcolor))
draw(x + offset + cb, y + offset + cb,
w - (offset + cb) * 2, h - (offset + cb) * 2,
h / 2.0 - (offset + cb))
if not left:
dc.DrawRectangle(x, y + offset + cb, h / 2.0,
h - (offset + cb) * 2)
if not right:
dc.DrawRectangle(x + w - h / 2.0, y + offset + cb,
h / 2.0, h - (offset + cb) * 2)
mdc.SelectObject(wx.NullBitmap)
dc = paintdc
img = self._selectionbitmaps[key].ConvertToImage()
# Scale down to original size ("antialiasing")
img.Rescale(rect[2], rect[3])
self._selectionbitmaps[key] = img.ConvertToBitmap()
bmp = self._selectionbitmaps.get(key)
if bmp:
dc.DrawBitmap(bmp, rect[0], rect[1])
else:
dc.SetBrush(wx.Brush(color))
dc.SetPen(wx.TRANSPARENT_PEN)
dc.DrawRectangleRect(rect)
dc.SetFont(grid.GetCellFont(row, col))
dc.SetTextForeground(textcolor)
self.DrawLabel(grid, dc, orect, row, col)
def DrawLabel(self, grid, dc, rect, row, col):
align = grid.GetCellAlignment(row, col)
if align[1] == wx.ALIGN_CENTER:
align = align[0], wx.ALIGN_CENTER_VERTICAL
dc.DrawLabel(grid.GetCellValue(row, col), rect,
align[0] | align[1])
def GetBestSize(self, grid, attr, dc, row, col):
dc.SetFont(grid.GetCellFont(row, col))
return dc.GetTextExtent(grid.GetCellValue(row, col))
class CustomCellBoolRenderer(CustomCellRenderer):
def __init__(self, *args, **kwargs):
CustomCellRenderer.__init__(self)
self._bitmap = geticon(16, "checkmark")
self._bitmap_unchecked = geticon(16, "x")
def DrawLabel(self, grid, dc, rect, row, col):
if grid.GetCellValue(row, col) == "1":
bitmap = self._bitmap
else:
bitmap = self._bitmap_unchecked
x = rect[0] + int((rect[2] - self._bitmap.Size[0]) / 2.0)
y = rect[1] + int((rect[3] - self._bitmap.Size[1]) / 2.0)
dc.DrawBitmap(bitmap, x, y)
def GetBestSize(self, grid, attr, dc, row, col):
return self._bitmap.Size
class CustomColLabelRenderer(object):
def __init__(self, bgcolor=None):
self.bgcolor = bgcolor
def Draw(self, grid, dc, rect, col=-1):
if not grid.GetNumberCols():
return
orect = rect
if col == grid.GetNumberCols() - 1:
# Last column
w = max(grid.ClientSize[0] - rect[0], rect[2])
rect = wx.Rect(rect[0], rect[1], w, rect[3])
mavericks = (getattr(grid, "style", None) == "Mavericks" or
sys.platform == "darwin")
if grid.headerbitmap:
img = grid.headerbitmap.ConvertToImage()
img.Rescale(rect[2], rect[3], quality=wx.IMAGE_QUALITY_NORMAL)
dc.DrawBitmap(img.ConvertToBitmap(), rect[0], 0)
pen = wx.Pen(wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DSHADOW), 1,
wx.SOLID)
pen.SetCap(wx.CAP_BUTT)
dc.SetPen(pen)
dc.DrawLine(rect[0], rect[1] + rect[3] - 1, rect[0] + rect[2],
rect[1] + rect[3] - 1)
elif grid.rendernative:
render = wx.RendererNative.Get()
render.DrawHeaderButton(grid, dc, rect)
else:
if self.bgcolor:
color = self.bgcolor
else:
if mavericks:
# Use Mavericks-like color scheme
color = wx.Colour(255, 255, 255)
else:
color = grid.GetLabelBackgroundColour()
if col % 2 == 0 and grid.alternate_col_label_background_color:
color = wx.Colour(*[int(v * .98) for v in color])
elif color.Alpha() < 255:
# Make sure it's opaque
color = wx.Colour(color.Red(), color.Green(), color.Blue())
dc.SetBrush(wx.Brush(color))
dc.SetPen(wx.TRANSPARENT_PEN)
dc.DrawRectangleRect(rect)
pen = wx.Pen(grid.GetGridLineColour())
dc.SetPen(pen)
if getattr(grid, "draw_horizontal_grid_lines", True) or (mavericks and
not self.bgcolor):
dc.DrawLine(rect[0], rect[1] + rect[3] - 1, rect[0] + rect[2] - 1,
rect[1] + rect[3] - 1)
if getattr(grid, "draw_vertical_grid_lines", True):
dc.DrawLine(rect[0] + rect[2] - 1, rect[1],
rect[0] + rect[2] - 1, rect[3])
if getattr(grid, "draw_col_labels", True) and col > -1:
dc.SetFont(grid.GetLabelFont())
if mavericks and not self.bgcolor:
# Use Mavericks-like color scheme
color = wx.Colour(80, 100, 120)
else:
color = grid.GetLabelTextColour()
dc.SetTextForeground(color)
align = grid.GetColLabelAlignment()
if align[1] == wx.ALIGN_CENTER:
align = align[0], wx.ALIGN_CENTER_VERTICAL
dc.DrawLabel(" %s " % grid.GetColLabelValue(col), orect,
align[0] | align[1])
class CustomRowLabelRenderer(object):
def __init__(self, bgcolor=None):
self.bgcolor = bgcolor
def Draw(self, grid, dc, rect, row):
if self.bgcolor:
color = self.bgcolor
else:
color = grid.GetLabelBackgroundColour()
if row % 2 == 0 and grid.alternate_row_label_background_color:
color = wx.Colour(*[int(v * .98) for v in color])
elif color.Alpha() < 255:
# Make sure it's opaque
color = wx.Colour(color.Red(), color.Green(), color.Blue())
if getattr(grid, "style", None) == "Mavericks" and color.Red() < 255:
# Use Mavericks-like color scheme
newcolor = [int(round(color.Get()[i] * (v / 102.0)))
for i, v in enumerate((98, 100, 102))]
color.Set(*newcolor)
dc.SetBrush(wx.Brush(color))
dc.SetPen(wx.TRANSPARENT_PEN)
dc.DrawRectangleRect(rect)
pen = wx.Pen(grid.GetGridLineColour())
dc.SetPen(pen)
if getattr(grid, "draw_horizontal_grid_lines", True):
dc.DrawLine(rect[0], rect[1] + rect[3] - 1, rect[0] + rect[2] - 1,
rect[1] + rect[3] - 1)
if getattr(grid, "draw_vertical_grid_lines", True):
dc.DrawLine(rect[0] + rect[2] - 1, rect[1], rect[0] + rect[2] - 1,
rect[3])
if getattr(grid, "draw_row_labels", True):
dc.SetFont(grid.GetLabelFont())
dc.SetTextForeground(grid.GetLabelTextColour())
align = grid.GetRowLabelAlignment()
if align[1] == wx.ALIGN_CENTER:
align = align[0], wx.ALIGN_CENTER_VERTICAL
dc.DrawLabel(" %s " % grid.GetRowLabelValue(row), rect,
align[0] | align[1])
class HStretchStaticBitmap(wx.StaticBitmap):
"""
A StaticBitmap that will automatically stretch horizontally.
To be used with sizers.
"""
def __init__(self, *args, **kwargs):
wx.StaticBitmap.__init__(self, *args, **kwargs)
if sys.platform in ("darwin", "win32"):
# Works (only) under Mac OS X / Windows.
# Works better (no jump to correct width) under Mac OS X than
# EVT_SIZE method.
self.Bind(wx.EVT_PAINT, self.OnPaint)
else:
# Works under Mac OS X, Windows and Linux.
# Under Mac OS X, this visibly jumps to the correct width when
# first shown on screen.
self.Bind(wx.EVT_SIZE, self.OnPaint)
self._init = False
def OnPaint(self, event):
if self.GetBitmap() and self.GetBitmap().IsOk():
if hasattr(self, "_bmp"):
bmp = self._bmp
else:
bmp = self.GetBitmap()
self._bmp = bmp
w = self.Size[0]
if getattr(self, "_width", -1) != w:
img = bmp.ConvertToImage()
img.Rescale(w, img.GetSize()[1])
bmp = img.ConvertToBitmap()
self._width = w
# Avoid flicker under Windows
if self._init:
self.Freeze()
self.SetBitmap(bmp)
self.MinSize = self._bmp.GetSize()
if self._init:
self.Thaw()
elif self.IsShownOnScreen():
self._init = True
if event:
event.Skip()
class HyperLinkCtrl(wx.HyperlinkCtrl):
def __init__(self, parent, id=wx.ID_ANY, label="",
pos=wx.DefaultPosition, size=wx.DefaultSize,
style=wx.HL_DEFAULT_STYLE, name=wx.HyperlinkCtrlNameStr, URL=""):
wx.HyperlinkCtrl.__init__(self, parent, id, label, URL, pos, size,
style, name)
class BetterLinkCtrl(wx.StaticText):
""" HyperLinkCtrl colors can't be chnaged under Windows """
def __init__(self, parent, id=wx.ID_ANY, label="",
pos=wx.DefaultPosition, size=wx.DefaultSize,
style=wx.HL_DEFAULT_STYLE, name=wx.HyperlinkCtrlNameStr, URL=""):
wx.StaticText.__init__(self, parent, id, label, pos, size,
style, name)
self.URL = URL
self.Visited = False
font = self.GetFont()
font.SetUnderlined(True)
self.SetFont(font)
self.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
# Colors recommended for HTML5
self._normalcolor = "#0000EE"
self._visitedcolor = "#551A8B"
# Firefox uses this
self._hovercolor = "#EE0000"
self._hover = False
self.Bind(wx.EVT_LEFT_UP, self.OnClick)
def GetHoverColour(self):
return self._hovercolour
def GetNormalColour(self):
return self._normalcolor
def GetURL(self):
return self.URL
def GetVisited(self):
return self.Visited
def GetVisitedColour(self):
return self._visitedcolor
@Property
def HoverColour():
def fget(self):
return self._hoverlcolor
def fset(self, color):
self.SetHoverColour(color)
return locals()
@Property
def NormalColour():
def fget(self):
return self._normalcolor
def fset(self, color):
self.SetNormalColour(color)
return locals()
def OnClick(self, event):
wx.LaunchDefaultBrowser(self.URL)
self.Visited = True
@Property
def VisitedColour():
def fget(self):
return self._visitedcolor
def fset(self, color):
self.SetVisitedColour(color)
return locals()
def SetHoverColour(self, color):
self._hovercolor = color
if self._hover:
self.ForegroundColour = color
def SetNormalColour(self, color):
self._normalcolor = color
if not self.Visited and not self._hover:
self.ForegroundColour = color
def SetURL(self, url):
self.URL = url
def SetVisited(self, visited):
self.Visited = visited
def SetVisitedColour(self, color):
self._visitedcolor = color
if self.Visited and not self._hover:
self.ForegroundColour = color
def fancytext_Renderer_getCurrentFont(self):
font = self.fonts[-1]
_font = self._font or wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
if "encoding" in font:
_font.SetEncoding(font["encoding"])
if "family" in font:
_font.SetFamily(font["family"])
if "size" in font:
_font.SetPointSize(font["size"])
if "gtk3" in wx.PlatformInfo:
scale = getcfg("app.dpi") / get_default_dpi()
_font.SetPointSize(_font.GetPointSize() * scale)
if "style" in font:
_font.SetStyle(font["style"])
if "weight" in font:
_font.SetWeight(font["weight"])
return _font
fancytext.Renderer._font = None
fancytext.Renderer.getCurrentFont = fancytext_Renderer_getCurrentFont
def fancytext_RenderToRenderer(str, renderer, enclose=True):
str = safe_str(str, "UTF-8")
try:
if enclose:
str = '<?xml version="1.0"?><FancyText>%s</FancyText>' % str
p = xml.parsers.expat.ParserCreate()
p.returns_unicode = 1
p.StartElementHandler = renderer.startElement
p.EndElementHandler = renderer.endElement
p.CharacterDataHandler = renderer.characterData
p.Parse(str, 1)
except xml.parsers.expat.error, err:
raise ValueError('error parsing text text "%s": %s' % (str, err))
fancytext.RenderToRenderer = fancytext_RenderToRenderer
class BetterPyGauge(pygauge.PyGauge):
def __init__(self, *args, **kwargs):
pygauge.PyGauge.__init__(self, *args, **kwargs)
self._indeterminate = False
self.gradientindex = 0
self._gradients = []
self._indeterminate_gradients = []
self._timer = BetterTimer(self, self._timerId)
self.Unbind(wx.EVT_TIMER)
self.Bind(EVT_BETTERTIMER, self.OnTimer, self._timer)
self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
self.Start()
def OnDestroy(self, event):
self._timer.Stop()
del self._timer
def OnPaint(self, event):
"""
Handles the ``wx.EVT_PAINT`` event for L{PyGauge}.
:param `event`: a `wx.PaintEvent` event to be processed.
"""
dc = wx.BufferedPaintDC(self)
gc = wx.GraphicsContext.Create(dc)
dc.SetBackground(wx.Brush(self.Parent.BackgroundColour))
dc.Clear()
rect = self.GetClientRect()
if self._border_colour:
gc.SetPen(wx.Pen(self._border_colour))
else:
gc.SetPen(wx.Pen(self.BackgroundColour))
gc.SetBrush(wx.Brush(self.BackgroundColour))
gc.DrawRoundedRectangle(rect.X, rect.Y, rect.Width - 1,
rect.Height - 1, (rect.Height - 1) / 2)
pad = self.GetBorderPadding()
if self._border_colour:
pad += 1
if pad:
rect.Deflate(pad, pad)
if self._barGradientSorted:
for i, gradient in enumerate(self._barGradientSorted):
c1, c2 = gradient
w = max(rect.Width * (float(self._valueSorted[i]) / self._range),
rect.Height)
gc.SetBrush(gc.CreateLinearGradientBrush(rect.X, rect.Y,
rect.Y + w,
rect.Y, c1, c2))
gc.SetPen(wx.TRANSPARENT_PEN)
gc.DrawRoundedRectangle(rect.X, rect.Y, w, rect.Height,
(rect.Height) / 2)
def OnTimer(self, event):
gradient = self._barGradient
if self._indeterminate:
if self.gradientindex < len(self._indeterminate_gradients) - 1:
self.gradientindex += 1
else:
self.gradientindex = 0
self._barGradient = [self._indeterminate_gradients[self.gradientindex]]
else:
if self.gradientindex < len(self._gradients) - 1:
self.gradientindex += 1
else:
self.gradientindex = 0
self._barGradient = [self._gradients[self.gradientindex]]
if hasattr(self, "_update_step") and not self._indeterminate:
stop = True
for i, v in enumerate(self._value):
self._value[i] += self._update_step[i]
if self._update_step[i] > 0:
if self._value[i] > self._update_value[i]:
self._value[i] = self._update_value[i]
else: stop = False
else:
if self._value[i] < self._update_value[i]:
self._value[i] = self._update_value[i]
else: stop = False
if stop:
del self._update_step
updated = True
else:
updated = False
if gradient != self._barGradient or updated:
self.SortForDisplay()
if self._indeterminate:
self._valueSorted = [self.GetRange()]
self.Refresh()
def IsRunning(self):
return self._timer.IsRunning()
def Pulse(self):
self._indeterminate = True
def SetBarGradients(self, gradients):
self._gradients = gradients
def SetIndeterminateBarGradients(self, gradients):
self._indeterminate_gradients = gradients
def SetValue(self, value):
self._indeterminate = False
pygauge.PyGauge.SetValue(self, value)
self.Refresh()
def Start(self, milliseconds=67):
self._timer.Start(milliseconds)
def Stop(self):
self._timer.Stop()
def Update(self, value, time=0):
"""
Update the gauge by adding `value` to it over `time` milliseconds. The `time` parameter
**must** be a multiple of 50 milliseconds.
:param `value`: The value to be added to the gauge;
:param `time`: The length of time in milliseconds that it will take to move the gauge.
"""
self._indeterminate = False
if type(value) != type([]):
value = [value]
if len(value) != len(self._value):
raise Exception("ERROR:\n len(value) != len(self.GetValue())")
self._update_value = []
self._update_step = []
for i, v in enumerate(self._value):
if value[i] < 0 or value[i] > self._range:
warnings.warn("Gauge value %r is invalid - must be between 0 "
"and %s" % (value[i], self._range), Warning)
if value[i] < 0:
value[i] = 0
else:
value[i] = self._range
self._update_value.append(value[i])
self._update_step.append((float(value[i]) - v)/(time/50))
class BetterStaticFancyText(GenStaticBitmap):
"""
Based on wx.lib.fancytext functionality.
Renders crisp on 'Retina' displays under OS X and in high DPI mode
under Linux/Windows.
"""
_enabled = True
_textlabel = ""
def __init__(self, window, id, text, *args, **kargs):
args = list(args)
kargs.setdefault('name', 'staticFancyText')
# Ignore background, always use parent background
if 'background' in kargs:
kargs.pop('background')
elif args:
args.pop(0)
bmp = wx.EmptyBitmap(1, 1)
GenStaticBitmap.__init__(self, window, id, bmp, *args, **kargs)
self.Label = text
def Disable(self):
self.Enable(False)
def Enable(self, enable=True):
self._enabled = enable
if sys.platform != "win32":
return
if enable:
bmp = self._enabledbitmap
else:
bmp = self._enabledbitmap.ConvertToImage().AdjustChannels(1, 1, 1, .5).ConvertToBitmap()
self.SetBitmap(bmp)
def IsEnabled(self):
return self._enabled
Enabled = property(IsEnabled, Enable)
def GetFont(self):
return fancytext.Renderer._font or wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
def GetLabel(self):
return self._textlabel
@Property
def Label():
def fget(self):
return self._textlabel
def fset(self, label):
self.SetLabel(label)
return locals()
def OnPaint(self, event):
if sys.platform != "win32":
# AutoBufferedPaintDCFactory is the magic needed for crisp text
# rendering in HiDPI mode under OS X and Linux
cls = wx.AutoBufferedPaintDCFactory
else:
cls = wx.BufferedPaintDC
dc = cls(self)
dc.SetBackground(wx.Brush(self.Parent.BackgroundColour, wx.SOLID))
dc.SetBackgroundMode(wx.TRANSPARENT)
dc.Clear()
if sys.platform != "win32":
fancytext.RenderToDC(self._label, dc, 0, 0)
elif self._bitmap:
dc.DrawBitmap(self._bitmap, 0, 0, True)
def SetFont(self, font):
fancytext.Renderer._font = font
def SetLabel(self, label):
self._textlabel = label
# Wrap ignoring tags, only break in whitespace
wrapped = ""
llen = 0
intag = False
maxlen = 119
hyphens = u"-\u2012\u2013\u2014\u2015"
whitespace = "\n\t "
for c in label:
if c == "<":
intag = True
if c in hyphens:
hyphen = True
else:
hyphen = False
if intag and c == ">":
intag = False
elif not intag:
llen += 1
if llen > maxlen and (c in whitespace or hyphen):
if hyphen:
wrapped += c
elif llen > maxlen + 1:
for i, rc in enumerate(reversed(wrapped)):
if rc == ">":
intag = True
elif not intag and rc in whitespace + hyphens:
line = wrapped[-i:]
llen = 1
for rc in reversed(line):
if rc == ">":
intag = True
if not intag:
llen += 1
elif rc == "<":
intag = False
wrapped = wrapped[:-i] + "\n" + line
break
elif intag and rc == "<":
intag = False
if llen > maxlen:
c = "\n"
if c == "\n":
llen = 0
wrapped += c
self._label = wrapped
background = wx.Brush(self.Parent.BackgroundColour, wx.SOLID)
try:
bmp = fancytext.RenderToBitmap(self._label, background)
except ValueError:
# XML parsing error, strip all tags
self._label = re.sub(r"<[^>]*?>", "", self._label)
self._label = self._label.replace("<", "")._label.replace(">", "")
bmp = fancytext.RenderToBitmap(self._label, background)
if sys.platform == "win32":
self._enabledbitmap = bmp
self.SetBitmap(bmp)
else:
self.Size = self.MinSize = bmp.Size
self.Refresh()
class InfoDialog(BaseInteractiveDialog):
""" Informational dialog with OK button """
def __init__(self, parent=None, id=-1, title=appname, msg="",
ok="OK", bitmap=None, pos=(-1, -1), size=(400, -1),
show=True, log=True, bitmap_margin=None):
BaseInteractiveDialog.__init__(self, parent, id, title, msg, ok,
bitmap, pos, size, show, log,
bitmap_margin=bitmap_margin)
class InvincibleFrame(BaseFrame):
""" A frame that won't be destroyed when closed """
def __init__(self, parent=None, id=-1, title="", pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE,
name=wx.FrameNameStr):
BaseFrame.__init__(self, parent, id, title, pos, size, style, name)
self.Bind(wx.EVT_CLOSE, self.OnClose, self)
def OnClose(self, event):
self.Hide()
class LogWindow(InvincibleFrame):
""" A log-type window with Clear and Save As buttons """
def __init__(self, parent=None, id=-1, title=None, pos=wx.DefaultPosition,
size=wx.DefaultSize, logctrlstyle=wx.TE_MULTILINE |
wx.TE_RICH | wx.NO_BORDER |
wx.TE_READONLY):
if not title:
title = lang.getstr("infoframe.title")
if pos == wx.DefaultPosition:
pos = getcfg("position.info.x"), getcfg("position.info.y")
if size == wx.DefaultSize:
size = getcfg("size.info.w"), getcfg("size.info.h")
InvincibleFrame.__init__(self, parent, id,
title,
pos=pos,
style=wx.DEFAULT_FRAME_STYLE,
name="info")
self.last_visible = False
self.panel = wx.Panel(self, -1)
# Fix wrong background color when disabled
self.panel.Enable = lambda enable=True: None
self.panel.Disable = lambda: None
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.panel.SetSizer(self.sizer)
self.log_txt = wx.TextCtrl(self.panel, -1, "", style=logctrlstyle)
# Fix wrong background color when disabled
self.log_txt.Enable = lambda enable=True: None
self.log_txt.Disable = lambda: None
if u"phoenix" in wx.PlatformInfo:
kwarg = "faceName"
else:
kwarg = "face"
if sys.platform == "win32":
font = wx.Font(9, wx.FONTFAMILY_TELETYPE, wx.FONTSTYLE_NORMAL,
wx.FONTWEIGHT_NORMAL,
**{kwarg: "Consolas"})
elif sys.platform == "darwin":
font = wx.Font(11, wx.FONTFAMILY_TELETYPE, wx.FONTSTYLE_NORMAL,
wx.FONTWEIGHT_NORMAL,
**{kwarg: "Monaco"})
else:
font = wx.Font(10, wx.FONTFAMILY_TELETYPE, wx.FONTSTYLE_NORMAL,
wx.FONTWEIGHT_NORMAL)
self.log_txt.SetFont(font)
self.log_txt.SetDefaultStyle(wx.TextAttr(self.log_txt.ForegroundColour,
self.log_txt.BackgroundColour,
font=font))
bgcol = wx.Colour(int(self.log_txt.BackgroundColour.Red() * .5),
int(self.log_txt.BackgroundColour.Green() * .5),
int(self.log_txt.BackgroundColour.Blue() * .5))
fgcol = wx.Colour(int(bgcol.Red() + self.log_txt.ForegroundColour.Red() * .5),
int(bgcol.Green() + self.log_txt.ForegroundColour.Green() * .5),
int(bgcol.Blue() + self.log_txt.ForegroundColour.Blue() * .5))
self._1stcolstyle = wx.TextAttr(fgcol, self.log_txt.BackgroundColour,
font=font)
self.sizer.Add(self.log_txt, 1, flag=wx.EXPAND)
self.log_txt.MinSize = (self.log_txt.GetTextExtent("=" * 95)[0] +
wx.SystemSettings_GetMetric(wx.SYS_VSCROLL_X),
defaults["size.info.h"] - 24 -
max(0, self.Size[1] - self.ClientSize[1]))
separator = BitmapBackgroundPanel(self.panel, size=(-1, 1))
separator.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DSHADOW))
self.sizer.Add(separator, flag=wx.EXPAND)
self.btnsizer = wx.BoxSizer(wx.HORIZONTAL)
self.sizer.Add(self.btnsizer, flag=wx.EXPAND)
self.save_as_btn = GenBitmapButton(self.panel, -1,
geticon(16, "media-floppy"),
style = wx.NO_BORDER)
self.save_as_btn.Bind(wx.EVT_BUTTON, self.OnSaveAs)
self.save_as_btn.SetToolTipString(lang.getstr("save_as"))
self.btnsizer.Add(self.save_as_btn, flag=wx.ALL, border=4)
self.archive_btn = GenBitmapButton(self.panel, -1,
geticon(16, "package-x-generic"),
style = wx.NO_BORDER)
self.archive_btn.Bind(wx.EVT_BUTTON, self.create_logs_archive)
self.archive_btn.SetToolTipString(lang.getstr("archive.create"))
self.btnsizer.Add(self.archive_btn, flag=wx.ALL, border=4)
self.clear_btn = GenBitmapButton(self.panel, -1,
geticon(16, "edit-delete"),
style = wx.NO_BORDER)
self.clear_btn.Bind(wx.EVT_BUTTON, self.OnClear)
self.clear_btn.SetToolTipString(lang.getstr("clear"))
self.btnsizer.Add(self.clear_btn, flag=wx.ALL, border=4)
self.sizer.SetSizeHints(self)
self.sizer.Layout()
self.SetSaneGeometry(*pos + size)
self.Bind(wx.EVT_MOVE, self.OnMove)
self.Bind(wx.EVT_SIZE, self.OnSize)
self.Children[0].Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
self._tspattern = re.compile(r"(?:\d{4}-\d{2}-\d{2} )?(\d{2}:\d{2}:\d{2},\d{3} )")
def Log(self, txt):
if not txt:
return
# TextCtrl.AppendText is an EXPENSIVE operation under OS X.
# For that reason, assemble the text to be added before calling it.
lines = []
start = self.log_txt.GetLastPosition()
ts = None
for line in safe_unicode(txt).split("\n"):
tsmatch = re.match(self._tspattern, line)
if tsmatch:
line = line[len(tsmatch.group()):]
ts = tsmatch.group(1)
for line in wrap(line, 80).split("\n"):
while 1:
if ts:
logline = ts + line
else:
ms = time() - int(time())
logline = strftime("%H:%M:%S,") + ("%.3f " % ms)[2:] + line[:80]
lines.append(logline)
line = line[80:]
if not line:
break
self.log_txt.AppendText("\n".join(lines) + "\n")
# TextCtrl.SetStyle is an EXPENSIVE operation, especially under OS X.
# Only set styles for (up to) the last 1000 lines.
for line in lines[:-1000]:
start += len(line + "\n")
for i, line in enumerate(lines[-1000:]):
line_lower = line.lower()
textattr = None
if (lang.getstr("warning").lower() in line_lower or
"warning" in line_lower):
textattr = wx.TextAttr("#F07F00", font=self.log_txt.Font)
elif (lang.getstr("error").lower() in line_lower or
"error" in line_lower):
textattr = wx.TextAttr("#FF3300", font=self.log_txt.Font)
self.log_txt.SetStyle(start, start + 12, self._1stcolstyle)
if textattr:
self.log_txt.SetStyle(start + 12, start + len(line),
textattr)
start += len(line + "\n")
def ScrollToBottom(self):
self.log_txt.ScrollLines(self.log_txt.GetNumberOfLines())
def OnClear(self, event):
self.log_txt.SetValue("")
def OnClose(self, event):
setcfg("log.show", 0)
self.Hide()
def OnDestroy(self, event):
event.Skip()
def OnMove(self, event=None):
if self.IsShownOnScreen() and not self.IsMaximized() and not \
self.IsIconized():
x, y = self.GetScreenPosition()
setcfg("position.info.x", x)
setcfg("position.info.y", y)
if event:
event.Skip()
def OnSaveAs(self, event):
defaultDir, defaultFile = (get_verified_path("last_filedialog_path")[0],
appname)
dlg = wx.FileDialog(self, lang.getstr("save_as"),
defaultDir=defaultDir, defaultFile=defaultFile,
wildcard=lang.getstr("filetype.log") + "|*.log",
style=wx.SAVE | wx.OVERWRITE_PROMPT)
dlg.Center(wx.BOTH)
result = dlg.ShowModal()
path = dlg.GetPath()
dlg.Destroy()
if result == wx.ID_OK:
if not waccess(path, os.W_OK):
InfoDialog(self, msg=lang.getstr("error.access_denied.write",
path),
ok=lang.getstr("ok"),
bitmap=geticon(32, "dialog-error"))
return
filename, ext = os.path.splitext(path)
if ext.lower() != ".log":
path += ".log"
if os.path.exists(path):
dlg = ConfirmDialog(self,
msg=lang.getstr("dialog."
"confirm_overwrite",
(path)),
ok=lang.getstr("overwrite"),
cancel=lang.getstr("cancel"),
bitmap=geticon(32, "dialog-warning"))
result = dlg.ShowModal()
dlg.Destroy()
if result != wx.ID_OK:
return
setcfg("last_filedialog_path", path)
try:
file_ = open(path, "w")
file_.write(self.log_txt.GetValue().encode("UTF-8", "replace"))
file_.close()
except Exception, exception:
InfoDialog(self, msg=safe_unicode(exception),
ok=lang.getstr("ok"),
bitmap=geticon(32, "dialog-error"))
def OnSize(self, event=None):
if self.IsShownOnScreen() and not self.IsMaximized() and not \
self.IsIconized():
w, h = self.GetSize()
setcfg("size.info.w", w)
setcfg("size.info.h", h)
if event:
event.Skip()
def create_logs_archive(self, event):
wildcard = lang.getstr("filetype.tgz") + "|*.tgz"
wildcard += "|" + lang.getstr("filetype.zip") + "|*.zip"
defaultDir, defaultFile = (get_verified_path("last_filedialog_path")[0],
appname + "-logs")
dlg = wx.FileDialog(self, lang.getstr("save_as"),
defaultDir=defaultDir, defaultFile=defaultFile,
wildcard=wildcard,
style=wx.SAVE | wx.OVERWRITE_PROMPT)
dlg.Center(wx.BOTH)
result = dlg.ShowModal()
path = dlg.GetPath()
dlg.Destroy()
if result == wx.ID_OK:
if not waccess(path, os.W_OK):
InfoDialog(self, msg=lang.getstr("error.access_denied.write",
path),
ok=lang.getstr("ok"),
bitmap=geticon(32, "dialog-error"))
return
filename, ext = os.path.splitext(path)
if path.lower().endswith(".tar.gz"):
format = "tgz"
else:
format = ext[1:]
if (ext.lower() != "." + format and
(format != "tgz" or not path.lower().endswith(".tar.gz"))):
path += "." + format
if os.path.exists(path):
dlg = ConfirmDialog(self,
msg=lang.getstr("dialog."
"confirm_overwrite",
(path)),
ok=lang.getstr("overwrite"),
cancel=lang.getstr("cancel"),
bitmap=geticon(32, "dialog-warning"))
result = dlg.ShowModal()
dlg.Destroy()
if result != wx.ID_OK:
return
setcfg("last_filedialog_path", path)
if format == "tgz":
# Create gzipped tar archive
with tarfile.open(path, "w:gz", encoding="UTF-8") as tar:
tar.add(logdir, arcname=os.path.basename(path))
else:
# Create ZIP archive
try:
with zipfile.ZipFile(path, 'w', zipfile.ZIP_DEFLATED) as zip:
for filename in os.listdir(logdir):
zip.write(os.path.join(logdir, filename), filename)
except Exception, exception:
InfoDialog(self, msg=safe_unicode(exception),
ok=lang.getstr("ok"),
bitmap=geticon(32, "dialog-error"))
class ProgressDialog(wx.Dialog):
""" A progress dialog. """
bitmaps = {}
def __init__(self, title=appname, msg="", maximum=100, parent=None, style=None,
handler=None, keyhandler=None, start_timer=True, pos=None,
pauseable=False, fancy=True, allow_close=False):
if style is None:
style = (wx.PD_APP_MODAL | wx.PD_ELAPSED_TIME |
wx.PD_REMAINING_TIME | wx.PD_CAN_ABORT | wx.PD_SMOOTH)
self._style = style
wx.Dialog.__init__(self, parent, wx.ID_ANY, title,
name="progressdialog")
if fancy:
self.BackgroundColour = "#141414"
self.ForegroundColour = "#FFFFFF"
if sys.platform == "win32":
if not fancy:
bgcolor = self.BackgroundColour
self.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW))
if sys.getwindowsversion() >= (6, ):
# No need to enable double buffering under Linux and Mac OS X.
# Under Windows, enabling double buffering on the panel seems
# to work best to reduce flicker.
self.SetDoubleBuffered(True)
self.set_icons()
self.Bind(wx.EVT_CLOSE, self.OnClose, self)
if not pos:
self.Bind(wx.EVT_MOVE, self.OnMove, self)
self.timer = BetterTimer(self)
self.Bind(EVT_BETTERTIMER, handler or self.OnTimer, self.timer)
self.indeterminate = True
self.keepGoing = True
self.skip = False
self.paused = False
self.progress_type = 0 # 0 = processing, 1 = measurement
self.allow_close = allow_close
margin = 12
self.sizer0 = wx.BoxSizer(wx.VERTICAL)
if fancy:
self.sizerH = wx.BoxSizer(wx.HORIZONTAL)
self.SetSizer(self.sizerH)
self.animbmp = AnimatedBitmap(self, -1, size=(200, 200))
self.sizerH.Add(self.animbmp, 0, flag=wx.ALIGN_CENTER_VERTICAL)
self.sizerH.Add(self.sizer0, 1, flag=wx.EXPAND)
try:
audio.init()
except Exception, exception:
safe_print(exception)
self.processor_sound = audio.Sound(get_data_path("theme/engine_hum_loop.wav"),
True)
self.generator_sound = audio.Sound(get_data_path("theme/pulsing_loop.wav"),
True)
self.sound = self.processor_sound
self.indicator_sound = audio.Sound(get_data_path("theme/beep_boop.wav"))
ProgressDialog.get_bitmaps(self.progress_type)
sizer0flag = 0
else:
self.SetSizer(self.sizer0)
sizer0flag = wx.LEFT
self.sizer1 = wx.BoxSizer(wx.VERTICAL)
self.sizer2 = wx.BoxSizer(wx.HORIZONTAL)
self.sizer0.Add(self.sizer1, flag = wx.ALIGN_LEFT | wx.TOP | wx.RIGHT |
sizer0flag, border=margin)
self.buttonpanel = wx.Panel(self)
self.buttonpanel.SetSizer(wx.BoxSizer(wx.VERTICAL))
self.buttonpanel.Sizer.Add(self.sizer2, 1, flag=wx.ALIGN_RIGHT | wx.ALL,
border=margin)
if sys.platform == "win32" and not fancy:
self.buttonpanel_line = wx.Panel(self, size=(-1,1))
self.buttonpanel_line.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DLIGHT))
self.sizer0.Add(self.buttonpanel_line, flag=wx.TOP | wx.EXPAND,
border=margin)
self.buttonpanel.SetBackgroundColour(bgcolor)
elif fancy:
self.buttonpanel.BackgroundColour = "#141414"
self.sizer0.Add(self.buttonpanel, flag=wx.EXPAND)
self.msg = wx.StaticText(self, -1, "", size=(-1, 74))
self.sizer1.Add(self.msg, flag=wx.EXPAND | wx.BOTTOM, border=margin)
self._fpprogress = 0.0
if fancy:
self.gauge = BetterPyGauge(self, wx.ID_ANY, range=maximum,
size=(-1, 4))
self.gauge.BackgroundColour = "#003366"
self.gauge.SetBarGradients([("#0099CC", "#00CCFF"),
("#0088BB", "#00BBEE"),
("#0077AA", "#00AADD"),
("#006699", "#0099CC"),
("#0077AA", "#00AADD"),
("#0088BB", "#00BBEE")])
self.gauge.SetIndeterminateBarGradients([("#00CCFF", "#001144"),
("#00BBEE", "#002255"),
("#00AADD", "#003366"),
("#0099CC", "#004477"),
("#0088BB", "#005588"),
("#0077AA", "#006699"),
("#006699", "#0077AA"),
("#005588", "#0088BB"),
("#004477", "#0099CC"),
("#003366", "#00AADD"),
("#002255", "#00BBEE"),
("#001144", "#00CCFF"),
("#002255", "#00BBEE"),
("#003366", "#00AADD"),
("#004477", "#0099CC"),
("#005588", "#0088BB"),
("#006699", "#0077AA"),
("#0077AA", "#006699"),
("#0088BB", "#005588"),
("#0099CC", "#004477"),
("#00AADD", "#003366"),
("#00BBEE", "#002255")])
self.gauge.SetValue(0)
else:
gauge_style = wx.GA_HORIZONTAL
if style & wx.PD_SMOOTH:
gauge_style |= wx.GA_SMOOTH
self.gauge = wx.Gauge(self, wx.ID_ANY, range=maximum, style=gauge_style)
self.sizer1.Add(self.gauge, flag=wx.EXPAND | wx.BOTTOM, border=margin)
if style & wx.PD_ELAPSED_TIME or style & wx.PD_REMAINING_TIME:
self.sizer3 = wx.FlexGridSizer(0, 2, 0, margin)
self.sizer1.Add(self.sizer3, flag=wx.ALIGN_LEFT)
if style & wx.PD_ELAPSED_TIME:
self.elapsed_time_label = wx.StaticText(self, -1,
lang.getstr("elapsed_time"))
self.elapsed_time_label.SetMaxFontSize(11)
self.sizer3.Add(self.elapsed_time_label)
self.elapsed_time = wx.StaticText(self, -1, "")
self.elapsed_time.SetMaxFontSize(11)
self.sizer3.Add(self.elapsed_time)
self.elapsed_timer = BetterTimer(self)
self.Bind(EVT_BETTERTIMER, self.elapsed_time_handler,
self.elapsed_timer)
if style & wx.PD_REMAINING_TIME:
self.remaining_time_label = wx.StaticText(self, -1,
lang.getstr("remaining_time"))
self.remaining_time_label.SetMaxFontSize(11)
self.sizer3.Add(self.remaining_time_label)
self.remaining_time = wx.StaticText(self, -1, "")
self.remaining_time.SetMaxFontSize(11)
self.sizer3.Add(self.remaining_time)
self.reset()
if fancy:
def buttoncls(parent, id, label):
return FlatShadedButton(parent, id, None, label,
fgcolour="#FFFFFF")
else:
buttoncls = wx.Button
if style & wx.PD_CAN_ABORT:
self.cancel = buttoncls(self.buttonpanel, wx.ID_ANY,
lang.getstr("cancel"))
self.sizer2.Add(self.cancel)
self.Bind(wx.EVT_BUTTON, self.OnClose, id=self.cancel.GetId())
self.pause_continue = buttoncls(self.buttonpanel, wx.ID_ANY,
lang.getstr("continue"))
self.sizer2.Prepend((margin, margin))
self.sizer2.Prepend(self.pause_continue, flag=wx.LEFT, border=margin)
self.Bind(wx.EVT_BUTTON, self.pause_continue_handler,
id=self.pause_continue.GetId())
self.pause_continue.Show(pauseable)
if fancy:
if getcfg("measurement.play_sound"):
bitmap = geticon(16, "sound_volume_full")
else:
bitmap = geticon(16, "sound_off")
im = bitmap.ConvertToImage()
im.AdjustMinMax(maxvalue=1.5)
bitmap = im.ConvertToBitmap()
self.sound_on_off_btn = FlatShadedButton(self.buttonpanel,
bitmap=bitmap,
fgcolour="#FFFFFF")
self.sizer2.Prepend(self.sound_on_off_btn)
self.sound_on_off_btn.Bind(wx.EVT_BUTTON,
self.play_sound_handler)
self.buttonpanel.Layout()
# Use an accelerator table for 0-9, a-z, numpad
keycodes = range(48, 58) + range(97, 123) + numpad_keycodes
self.id_to_keycode = {}
for keycode in keycodes:
self.id_to_keycode[wx.NewId()] = keycode
accels = []
for id, keycode in self.id_to_keycode.iteritems():
self.Bind(wx.EVT_MENU, keyhandler or self.key_handler, id=id)
accels.append((wx.ACCEL_NORMAL, keycode, id))
self.SetAcceleratorTable(wx.AcceleratorTable(accels))
self.msg.SetMaxFontSize(11)
self.msg.Label = "\n".join(["E" * 80] * 4)
w, h = self.msg.Size
self.msg.WindowStyle |= wx.ST_NO_AUTORESIZE
self.msg.SetMinSize((w, h))
self.msg.SetSize((w, h))
self.Sizer.SetSizeHints(self)
self.Sizer.Layout()
self.msg.SetLabel(msg.replace("&", "&&"))
self.pause_continue.Label = lang.getstr("pause")
self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy, self)
# set position
self.place(pos)
if start_timer:
self.start_timer()
self.Show()
if style & wx.PD_APP_MODAL:
self.MakeModal()
def MakeModal(self, modal=True):
# wxPython 3.0 deprecates MakeModal, use a replacement implementation
# based on http://wxpython.org/Phoenix/docs/html/MigrationGuide.html
if modal and not hasattr(self, '_disabler'):
self._disabler = BetterWindowDisabler(self)
if not modal and hasattr(self, '_disabler'):
del self._disabler
def OnClose(self, event):
self.keepGoing = False
if hasattr(self, "cancel"):
self.cancel.Disable()
self.pause_continue.Disable()
if not self.timer.IsRunning() and self.allow_close:
self.Destroy()
elif self.gauge.GetValue() == self.gauge.GetRange():
event.Skip()
def OnDestroy(self, event):
self.stop_timer()
del self.timer
def OnMove(self, event):
if self.IsShownOnScreen() and not self.IsIconized() and \
(not self.GetParent() or
not self.GetParent().IsShownOnScreen()):
prev_x = getcfg("position.progress.x")
prev_y = getcfg("position.progress.y")
x, y = self.GetScreenPosition()
if x != prev_x or y != prev_y:
setcfg("position.progress.x", x)
setcfg("position.progress.y", y)
def OnTimer(self, event):
if self.keepGoing:
if not self.pause_continue.IsEnabled():
self.set_progress_type(int(not self.progress_type))
self.pause_continue.Enable()
if self.paused:
return
if self._fpprogress < self.gauge.GetRange():
self.Update(self._fpprogress + self.gauge.GetRange() / 1000.0)
else:
self.stop_timer(False)
self.Update(self.gauge.GetRange(),
"Finished. You may now close this window.")
self.pause_continue.Disable()
if hasattr(self, "cancel"):
self.cancel.Disable()
else:
self.Pulse("Aborting...")
if not hasattr(self, "delayed_stop"):
self.delayed_stop = wx.CallLater(3000, self.stop_timer, False)
wx.CallLater(3000, self.Pulse,
"Aborted. You may now close this window.")
def GetValue(self):
return self._fpprogress
def SetValue(self, value):
self.Update(value)
Value = property(GetValue, SetValue)
def Pulse(self, msg=None):
if msg and msg != self.msg.Label:
self.msg.SetLabel(msg)
self.msg.Wrap(self.msg.ContainingSizer.Size[0])
self.msg.Refresh()
if getattr(self, "time2", 0):
self.time2 = 0
if not self.time3:
self.time3 = time()
if not self.indeterminate:
self.indeterminate = True
if hasattr(self, "remaining_time"):
self.remaining_time.Label = u"––:––:––"
self.gauge.Pulse()
return self.keepGoing, self.skip
def Resume(self):
self.keepGoing = True
if hasattr(self, "cancel"):
self.cancel.Enable()
if self.paused:
self.pause_continue_handler()
else:
self.pause_continue.Enable()
def Update(self, value, msg=None):
self.indeterminate = False
if msg and msg != self.msg.Label:
self.msg.SetLabel(msg)
self.msg.Wrap(self.msg.ContainingSizer.Size[0])
self.msg.Refresh()
prev_value = self._fpprogress
if value == prev_value:
return self.keepGoing, self.skip
self._fpprogress = value
value = int(round(value))
if hasattr(self, "time2"):
t = time()
if not self.time2:
if value < self.gauge.GetValue():
# Reset
self.time2 = t
else:
# Continue
self.time4 += time() - self.time3
self.time2 = self.time + self.time4
self.time3 = 0
if (getcfg("measurement.play_sound") and
self._fpprogress < prev_value and
hasattr(self, "indicator_sound") and
not self.indicator_sound.is_playing):
self.indicator_sound.safe_play()
if (isinstance(self.gauge, BetterPyGauge) and
self._style & wx.PD_SMOOTH):
if self._fpprogress >= prev_value:
update_value = abs(self._fpprogress - prev_value)
if update_value:
# Higher ms = smoother animation, but potentially
# increased "lag"
ms = 450 + 50 * update_value
self.gauge.Update(self._fpprogress, ms)
else:
self.gauge.Update(self._fpprogress, 50)
else:
self.gauge.SetValue(value)
return self.keepGoing, self.skip
UpdatePulse = Pulse
def anim_fadein(self):
bitmaps = ProgressDialog.get_bitmaps(self.progress_type)
if self.progress_type == 0:
# Processing
range = (60, 68)
loop = True
elif self.progress_type == 1:
# Measuring
range = (0, 9)
loop = False
else:
# Generating test patches
range = (27, 36)
loop = True
self.animbmp.SetBitmaps(bitmaps, range=range, loop=loop)
if self.progress_type == 1:
self.animbmp.frame = 4
wx.CallLater(50, lambda: self and self.IsShown() and
self.animbmp.Play(24))
def sound_fadein(self):
if getcfg("measurement.play_sound"):
wx.CallLater(50, lambda: self and self.IsShown() and
self.sound.safe_fade(self.sound_get_delay(),
True))
def anim_fadeout(self):
self.animbmp.loop = False
self.animbmp.range = self.animbmp.range[0], -1
def sound_fadeout(self):
if self.sound.is_playing:
self.sound.safe_stop(self.sound_get_delay())
def sound_get_delay(self):
if self.sound is self.processor_sound:
return 3000
else:
return 1500
def elapsed_time_handler(self, event):
self.elapsed_time.Label = strftime("%H:%M:%S",
gmtime(time() - self.time))
value = self._fpprogress
if getattr(self, "time2", 0) and value:
t = time()
if self.time2 < t:
remaining = ((t - self.time2) / value *
(self.gauge.GetRange() - value))
if remaining >= 0:
self.remaining_time.Label = strftime("%H:%M:%S",
gmtime(remaining))
@staticmethod
def get_bitmaps(progress_type=0):
if progress_type in ProgressDialog.bitmaps:
bitmaps = ProgressDialog.bitmaps[progress_type]
else:
bitmaps = ProgressDialog.bitmaps[progress_type] = []
if progress_type == 0:
# Animation for processing
for pth in get_data_path("theme/shutter_anim", r"\.png$") or []:
im = wx.Image(pth)
bitmaps.append(im)
for pth in get_data_path("theme/jet_anim", r"\.png$") or []:
im = wx.Image(pth)
# Blend red
im = im.AdjustChannels(1, .25, 0)
# Adjust for background
im.AdjustMinMax(1.0 / 255 * 0x14)
bitmaps.append(im)
# Needs to be exactly 17 images
if bitmaps and len(bitmaps) == 17:
for i in xrange(7):
bitmaps.extend(bitmaps[9:17])
bitmaps.extend(bitmaps[9:13])
# Fade in
for i, im in enumerate(bitmaps[9:19]):
bg = bitmaps[8].ConvertToBitmap()
im = im.AdjustChannels(1, 1, 1, i / 10.0)
bg.Blend(im.ConvertToBitmap(), 0, 0)
bitmaps[i + 9] = bg
for i, im in enumerate(bitmaps[:9]):
bitmaps[i] = im.ConvertToBitmap()
# Normal
for i in xrange(41):
im = bitmaps[i + 19].Copy()
im.RotateHue(.05 * (i / 50.0))
bitmaps[i + 19] = im.ConvertToBitmap()
for i, im in enumerate(bitmaps[60:]):
im = im.Copy()
im.RotateHue(.05)
bitmaps[i + 60] = im.ConvertToBitmap()
# Fade out
bitmaps.extend(reversed(bitmaps[:60]))
else:
bitmaps = []
elif progress_type == 1:
# Animation for measurements
for i, pth in enumerate(get_data_path("theme/shutter_anim", r"\.png$") or []):
if i < 5:
bmp = wx.Bitmap(pth)
bitmaps.insert(0, bmp)
if bitmaps and len(bitmaps) == 5:
bitmaps.extend(reversed(bitmaps[:5]))
bitmaps.extend(bitmaps[:5])
else:
# Animation for generating test patches
for pth in get_data_path("theme/patch_anim", r"\.png$") or []:
im = wx.Image(pth)
bitmaps.append(im)
# Needs to be exactly 9 images
if bitmaps and len(bitmaps) == 9:
for i in xrange(3):
bitmaps.extend(bitmaps[:9])
# Fade in
for i, im in enumerate(bitmaps[:27]):
im = im.AdjustChannels(1, 1, 1, i / 27.0)
bitmaps[i] = im.ConvertToBitmap()
# Normal
for i, im in enumerate(bitmaps[27:]):
bitmaps[i + 27] = im.ConvertToBitmap()
# Fade out
for i in xrange(3):
bitmaps.extend(bitmaps[27:36])
for i, bmp in enumerate(bitmaps[36:]):
im = bmp.ConvertToImage().AdjustChannels(1, 1, 1, 1 - i / 26.0)
bitmaps[i + 36] = im.ConvertToBitmap()
else:
bitmaps = []
return bitmaps
def key_handler(self, event):
pass
def pause_continue_handler(self, event=None):
self.paused = not self.paused
if self.paused:
self.pause_continue.Label = lang.getstr("continue")
else:
self.pause_continue.Label = lang.getstr("pause")
self.pause_continue.Enable(not event)
self.Layout()
if getattr(self, "time2", 0):
self.time2 = 0
if not self.time3:
self.time3 = time()
def place(self, pos=None):
""" Set position """
placed = False
if pos:
x, y = pos
else:
if self.Parent and self.Parent.IsShownOnScreen():
self.Center()
placed = True
else:
x = getcfg("position.progress.x")
y = getcfg("position.progress.y")
if not placed:
self.SetSaneGeometry(x, y)
def play_sound_handler(self, event):
setcfg("measurement.play_sound",
int(not(bool(getcfg("measurement.play_sound")))))
if getcfg("measurement.play_sound"):
bitmap = getbitmap("theme/icons/16x16/sound_volume_full")
if (self.progress_type in (0, 2) and self.keepGoing and
self._fpprogress < self.gauge.GetRange()):
self.sound.safe_play()
else:
bitmap = getbitmap("theme/icons/16x16/sound_off")
if self.sound.is_playing:
self.sound.safe_stop()
im = bitmap.ConvertToImage()
im.AdjustMinMax(maxvalue=1.5)
bitmap = im.ConvertToBitmap()
self.sound_on_off_btn._bitmap = bitmap
def reset(self):
self._fpprogress = 0
self.gauge.SetValue(0)
self.time = time()
if hasattr(self, "elapsed_time"):
self.elapsed_time_handler(None)
if hasattr(self, "remaining_time"):
self.time2 = 0
self.time3 = self.time
self.time4 = 0
self.remaining_time.Label = u"––:––:––"
set_icons = BaseInteractiveDialog.__dict__["set_icons"]
def set_progress_type(self, progress_type):
if progress_type != self.progress_type:
if self.progress_type == 0:
# Processing
delay = 4000
elif self.progress_type == 1:
# Measuring
delay = 500
else:
# Generating test patches
delay = 2000
if hasattr(self, "animbmp"):
self.anim_fadeout()
wx.CallLater(delay, lambda: self and
self.progress_type == progress_type and
self.anim_fadein())
if hasattr(self, "sound"):
self.sound_fadeout()
if progress_type in (0, 2):
self.set_sound(progress_type)
wx.CallLater(delay, lambda: self and
self.progress_type == progress_type and
self.sound_fadein())
self.progress_type = progress_type
def set_sound(self, progress_type=0):
if progress_type == 0 and hasattr(self, "processor_sound"):
self.sound = self.processor_sound
elif hasattr(self, "generator_sound"):
self.sound = self.generator_sound
def start_timer(self, ms=75):
self.timer.Start(ms)
if isinstance(self.gauge, BetterPyGauge) and not self.gauge.IsRunning():
self.gauge.Start()
if hasattr(self, "elapsed_timer"):
self.elapsed_timer.Start(1000)
if hasattr(self, "animbmp"):
self.anim_fadein()
if hasattr(self, "sound") and self.progress_type in (0, 2):
self.set_sound(self.progress_type)
self.sound_fadein()
def stop_timer(self, immediate=True):
self.timer.Stop()
if isinstance(self.gauge, BetterPyGauge) and immediate:
self.gauge.Stop()
if hasattr(self, "elapsed_timer"):
self.elapsed_timer.Stop()
if hasattr(self, "animbmp"):
if immediate:
self.animbmp.Stop()
elif self.animbmp.loop or self.animbmp.range[1] != -1:
self.anim_fadeout()
if hasattr(self, "sound"):
self.sound_fadeout()
class FancyProgressDialog(ProgressDialog):
def __init__(self, *args, **kwargs):
kwargs["fancy"] = True
ProgressDialog.__init__(self, *args, **kwargs)
class SimpleBook(labelbook.FlatBookBase):
def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,
style=0, agwStyle=0, name="SimpleBook"):
labelbook.FlatBookBase.__init__(self, parent, id, pos, size, style, agwStyle, name)
self._pages = self.CreateImageContainer()
# Label book specific initialization
self._mainSizer = wx.BoxSizer(wx.HORIZONTAL)
self.SetSizer(self._mainSizer)
def CreateImageContainer(self):
""" Creates the image container (LabelContainer) class for L{FlatImageBook}. """
return labelbook.ImageContainerBase(self, wx.ID_ANY, agwStyle=self.GetAGWWindowStyleFlag())
class SimpleTerminal(InvincibleFrame):
""" A simple terminal-like window. """
def __init__(self, parent=None, id=-1, title=appname, handler=None,
keyhandler=None, start_timer=True, pos=wx.DefaultPosition,
size=wx.DefaultSize, consolestyle=wx.TE_CHARWRAP |
wx.TE_MULTILINE |
wx.TE_READONLY | wx.VSCROLL |
wx.NO_BORDER, show=True,
name="simpleterminal"):
if pos == wx.DefaultPosition:
pos = getcfg("position.progress.x"), getcfg("position.progress.y")
if size == wx.DefaultSize:
size = getcfg("size.progress.w"), getcfg("size.progress.h")
InvincibleFrame.__init__(self, parent, id, title, pos=pos,
style=wx.DEFAULT_FRAME_STYLE, name=name)
self.Bind(wx.EVT_CLOSE, self.OnClose, self)
self.Bind(wx.EVT_MOVE, self.OnMove, self)
self.timer = BetterTimer(self)
if handler:
self.Bind(EVT_BETTERTIMER, handler, self.timer)
self.panel = wx.Panel(self, -1)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.panel.SetSizer(self.sizer)
self.console = wx.TextCtrl(self.panel, -1, "", style=consolestyle)
self.console.SetBackgroundColour("#272727")
self.console.SetForegroundColour("#808080")
if u"phoenix" in wx.PlatformInfo:
kwarg = "faceName"
else:
kwarg = "face"
if sys.platform == "win32":
font = wx.Font(9, wx.FONTFAMILY_TELETYPE, wx.FONTSTYLE_NORMAL,
wx.FONTWEIGHT_NORMAL,
**{kwarg: "Consolas"})
elif sys.platform == "darwin":
font = wx.Font(11, wx.FONTFAMILY_TELETYPE, wx.FONTSTYLE_NORMAL,
wx.FONTWEIGHT_NORMAL,
**{kwarg: "Monaco"})
else:
font = wx.Font(11, wx.FONTFAMILY_TELETYPE, wx.FONTSTYLE_NORMAL,
wx.FONTWEIGHT_NORMAL)
self.console.SetFont(font)
self.sizer.Add(self.console, 1, flag=wx.ALL | wx.EXPAND, border=0)
if sys.platform == "win32":
# Mac: TextCtrls don't receive EVT_KEY_DOWN
self.console.Bind(wx.EVT_KEY_DOWN, keyhandler or self.key_handler,
self.console)
else:
# Windows: EVT_CHAR_HOOK only receives "special" keys e.g. ESC, Tab
self.Bind(wx.EVT_CHAR_HOOK, keyhandler or self.key_handler)
# Use an accelerator table for space, 0-9, a-z, numpad
keycodes = [32] + range(48, 58) + range(97, 123) + numpad_keycodes
self.id_to_keycode = {}
for keycode in keycodes:
self.id_to_keycode[wx.NewId()] = keycode
# set size
text_extent = self.console.GetTextExtent(" ")
vscroll_w = wx.SystemSettings_GetMetric(wx.SYS_VSCROLL_X)
w, h = (text_extent[0] * 80 + vscroll_w + 4,
text_extent[1] * 24)
self.console.SetMinSize((w, h))
w, h = max(size[0], w), max(size[1], h)
self.console.SetSize((w, h))
self.sizer.SetSizeHints(self)
self.sizer.Layout()
# set position
placed = False
if parent:
if parent.IsShownOnScreen():
self.Center()
placed = True
else:
x = pos[0] or parent.GetScreenPosition()[0]
y = pos[1] or parent.GetScreenPosition()[1]
else:
x, y = pos
if not placed:
self.SetSaneGeometry(x, y, w, h)
self.lastmsg = ""
self.keepGoing = True
self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy, self)
if start_timer:
self.start_timer()
if show:
self.Show()
self.console.SetFocus()
def EndModal(self, returncode=wx.ID_OK):
return returncode
def MakeModal(self, makemodal=False):
pass
def OnClose(self, event):
if not self.timer.IsRunning():
self.Destroy()
else:
self.keepGoing = False
def OnDestroy(self, event):
self.stop_timer()
del self.timer
def OnMove(self, event):
if self.IsShownOnScreen() and not self.IsIconized() and \
(not self.GetParent() or
not self.GetParent().IsShownOnScreen()):
prev_x = getcfg("position.progress.x")
prev_y = getcfg("position.progress.y")
x, y = self.GetScreenPosition()
if x != prev_x or y != prev_y:
setcfg("position.progress.x", x)
setcfg("position.progress.y", y)
def Pulse(self, msg=""):
self.lastmsg = msg
return self.keepGoing, False
def Resume(self):
self.keepGoing = True
def Update(self, value, msg=""):
return self.Pulse(msg)
def UpdatePulse(self, msg=""):
return self.Pulse(msg)
def add_text(self, txt):
pos = self.console.GetLastPosition()
if txt.startswith("\r"):
txt = txt.lstrip("\r")
numlines = self.console.GetNumberOfLines()
start = pos - self.console.GetLineLength(numlines - 1)
self.console.Replace(start, pos, txt)
else:
self.console.AppendText(txt)
def flush(self):
pass
def isatty(self):
return True
def key_handler(self, event):
pass
def start_timer(self, ms=50):
self.timer.Start(ms)
def stop_timer(self):
self.timer.Stop()
def write(self, txt):
wx.CallAfter(self.add_text, txt)
class TooltipWindow(InvincibleFrame):
""" A tooltip-style window """
def __init__(self, parent=None, id=-1, title=appname, msg="", cols=1,
bitmap=None, pos=(-1, -1), size=(400, -1),
style=wx.DEFAULT_FRAME_STYLE | wx.FRAME_TOOL_WINDOW, wrap=70):
scale = getcfg("app.dpi") / get_default_dpi()
if scale > 1 and size == (400, -1):
size = size[0] * scale, size[1]
InvincibleFrame.__init__(self, parent, id, title, pos, size, style)
self.SetPosition(pos) # yes, this is needed
self.set_icons()
margin = 12
self.panel = wx.Panel(self, -1)
self.sizer0 = wx.BoxSizer(wx.VERTICAL)
self.panel.SetSizer(self.sizer0)
self.sizer1 = wx.BoxSizer(wx.HORIZONTAL)
self.sizer0.Add(self.sizer1, flag = wx.ALIGN_CENTER | wx.ALL,
border = margin)
if bitmap:
self.bitmap = wx.StaticBitmap(self.panel, -1, bitmap)
self.sizer1.Add(self.bitmap)
self.sizer2 = wx.BoxSizer(wx.VERTICAL)
self.sizer1.Add(self.sizer2)
msg = util_str.wrap(msg, wrap).splitlines()
for i, line in enumerate(msg):
if not line:
# Use as header
header = wx.StaticText(self.panel, -1, "\n".join(msg[:i + 1]))
self.sizer2.Add(header, flag=wx.LEFT, border=margin)
msg = msg[i + 1:]
break
self.sizer3 = wx.BoxSizer(wx.HORIZONTAL)
self.sizer2.Add(self.sizer3, flag=wx.EXPAND)
rowspercol = int(math.ceil(len(msg) / float(cols)))
msgs = []
while msg:
msgs.append(msg[:rowspercol])
msg = msg[rowspercol:]
for msg in msgs:
col = wx.StaticText(self.panel, -1, "")
col.SetMaxFontSize()
maxlinewidth = 0
for line in msg:
maxlinewidth = max(col.GetTextExtent(line)[0], maxlinewidth)
col.Label = "\n".join(msg)
col.MinSize = maxlinewidth + margin * 2, -1
self.sizer3.Add(col, flag=wx.LEFT, border=margin)
self.sizer0.SetSizeHints(self)
self.sizer0.Layout()
if not pos or pos == (-1, -1):
self.Center(wx.BOTH)
elif pos[0] == -1:
self.Center(wx.HORIZONTAL)
elif pos[1] == -1:
self.Center(wx.VERTICAL)
self.Show()
self.Raise()
set_icons = BaseInteractiveDialog.__dict__["set_icons"]
class TwoWaySplitter(FourWaySplitter):
def __init__(self, *args, **kwargs):
FourWaySplitter.__init__(self, *args, **kwargs)
self._minimum_pane_size = 0
self._sashbitmap = getbitmap("theme/sash")
self._splitsize = (800, 400)
self._expandedsize = (400, 400)
self._handcursor = wx.StockCursor(wx.CURSOR_HAND)
self.Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDClick)
# Redrawing the splitter in FourWaySplitter._RedrawIfHotSensitive
# which happens if the mouse enters or leaves the splitter causes blank
# windows managed by the splitter under wxGTK if using GTK3.
# We are using a custom splitter graphic without 'hot' state, so we can
# circumvent this.
self.Unbind(wx.EVT_ENTER_WINDOW)
def _GetSashSize(self):
""" Used internally. """
if self.HasFlag(wx.SP_NOSASH):
return 0
return self._sashbitmap.GetSize()[0]
# Recompute layout
def _SizeWindows(self):
"""
Recalculate the layout based on split positions and split fractions.
:see: L{SetHSplit} and L{SetVSplit} for more information about split fractions.
"""
win0 = self.GetTopLeft()
win1 = self.GetTopRight()
width, height = self.GetSize()
barSize = self._GetSashSize()
border = self._GetBorderSize()
if self._expanded < 0:
totw = width - barSize - 2*border
self._splitx = max((self._fhor*totw)/10000, self._minimum_pane_size)
self._splity = height
rightw = max(totw - self._splitx, 0)
if win0:
win0.SetPosition((0, 0))
win0.SetSize((self._splitx, self._splity))
win0.Show()
if win1:
win1.SetPosition((self._splitx + barSize, 0))
win1.SetSize((rightw, self._splity))
win1.Show()
else:
if self._expanded < len(self._windows):
for ii, win in enumerate(self._windows):
if ii == self._expanded:
win.SetDimensions(0, 0, width - barSize - 2*border, height-2*border)
win.Show()
else:
win.Hide()
# Draw the horizontal split
def DrawSplitter(self, dc):
"""
Actually draws the sashes.
:param `dc`: an instance of `wx.DC`.
"""
backColour = wx.Colour(*[int(v * .85) for v in self.BackgroundColour])
dc.SetBrush(wx.Brush(backColour, wx.SOLID))
dc.SetPen(wx.Pen(backColour))
dc.Clear()
width, height = self.GetSize()
if self._expanded > -1:
splitx = width - self._GetSashSize() - 2*self._GetBorderSize()
else:
splitx = self._splitx
if self._expanded < 0:
if splitx <= self._minimum_pane_size:
self._sashbitmap = getbitmap("theme/sash-right")
else:
self._sashbitmap = getbitmap("theme/sash")
else:
self._sashbitmap = getbitmap("theme/sash-left")
sashwidth, sashheight = self._sashbitmap.GetSize()
dc.DrawRectangle(splitx, 0, sashwidth, height)
dc.DrawBitmap(self._sashbitmap, splitx, height / 2 - sashheight / 2, True)
def GetExpandedSize(self):
return self._expandedsize
# Determine split mode
def GetMode(self, pt):
"""
Determines the split mode for L{FourWaySplitter}.
:param `pt`: the point at which the mouse has been clicked, an instance of
`wx.Point`.
:return: One of the following 3 split modes:
================= ==============================
Split Mode Description
================= ==============================
``wx.HORIZONTAL`` the user has clicked on the horizontal sash
``wx.VERTICAL`` The user has clicked on the vertical sash
``wx.BOTH`` The user has clicked at the intersection between the 2 sashes
================= ==============================
"""
barSize = self._GetSashSize()
flag = wx.BOTH
width, height = self.GetSize()
if self._expanded > -1:
splitx = width - self._GetSashSize() - 2*self._GetBorderSize()
else:
splitx = self._splitx
if pt.x < splitx - _TOLERANCE:
flag &= ~wx.VERTICAL
if pt.y < self._splity - _TOLERANCE:
flag &= ~wx.HORIZONTAL
if pt.x >= splitx + barSize + _TOLERANCE:
flag &= ~wx.VERTICAL
if pt.y >= self._splity + barSize + _TOLERANCE:
flag &= ~wx.HORIZONTAL
return flag
def GetSplitSize(self):
return self._splitsize
def OnLeaveWindow(self, event):
"""
Handles the ``wx.EVT_LEAVE_WINDOW`` event for L{FourWaySplitter}.
:param `event`: a `wx.MouseEvent` event to be processed.
"""
self.SetCursor(wx.STANDARD_CURSOR)
def OnLeftDClick(self, event):
if not self.IsEnabled():
return
pt = event.GetPosition()
if self.GetMode(pt):
width, height = self.GetSize()
barSize = self._GetSashSize()
border = self._GetBorderSize()
totw = width - barSize - 2*border
winborder, titlebar = get_platform_window_decoration_size()
winwidth, winheight = self.Parent.GetSize()
self.Freeze()
self.SetExpanded(-1 if self._expanded > -1 else 0)
if self._expanded < 0:
if self.GetExpandedSize()[0] < self.GetSplitSize()[0]:
self._fhor = int(math.ceil((self.GetExpandedSize()[0] -
barSize - winborder * 2) /
float(self.GetSplitSize()[0] -
barSize - winborder * 2) *
10000))
else:
self._fhor = int(math.ceil(self._minimum_pane_size /
float(self.GetSplitSize()[0] -
barSize - winborder * 2) *
10000))
self.Parent.SetMinSize((defaults["size.profile_info.split.w"] + winborder * 2,
self.Parent.GetMinSize()[1]))
if (not self.Parent.IsMaximized() and
self.Parent.GetSize()[0] < self.GetSplitSize()[0]):
self.Parent.SetSize((self.GetSplitSize()[0],
self.Parent.GetSize()[1]))
else:
self.Parent.SetMinSize((defaults["size.profile_info.w"] + winborder * 2,
self.Parent.GetMinSize()[1]))
w = max(self.GetExpandedSize()[0],
self._splitx + barSize + winborder * 2)
if (not self.Parent.IsMaximized() and
self.Parent.GetSize()[0] > w):
self.Parent.SetSize((w,
self.Parent.GetSize()[1]))
#wx.CallLater(25, self.Parent.redraw)
self.Parent.idle = False
self.Parent.resize_grid()
self.Thaw()
# Button being released
def OnLeftUp(self, event):
"""
Handles the ``wx.EVT_LEFT_UP`` event for L{FourWaySplitter}.
:param `event`: a `wx.MouseEvent` event to be processed.
"""
if not self.IsEnabled():
return
if self.HasCapture():
self.ReleaseMouse()
flgs = self._flags
self._flags &= ~FLAG_CHANGED
self._flags &= ~FLAG_PRESSED
if flgs & FLAG_PRESSED:
if not self.GetAGWWindowStyleFlag() & wx.SP_LIVE_UPDATE:
self.DrawTrackSplitter(self._splitx, self._splity)
self.DrawSplitter(wx.ClientDC(self))
self.AdjustLayout()
if flgs & FLAG_CHANGED:
event = FourWaySplitterEvent(wx.wxEVT_COMMAND_SPLITTER_SASH_POS_CHANGED, self)
event.SetSashIdx(self._mode)
event.SetSashPosition(wx.Point(self._splitx, self._splity))
self.GetEventHandler().ProcessEvent(event)
else:
self.OnLeftDClick(event)
self._mode = NOWHERE
def OnMotion(self, event):
"""
Handles the ``wx.EVT_MOTION`` event for L{FourWaySplitter}.
:param `event`: a `wx.MouseEvent` event to be processed.
"""
if self.HasFlag(wx.SP_NOSASH):
return
pt = event.GetPosition()
# Moving split
if self._flags & FLAG_PRESSED:
width, height = self.GetSize()
barSize = self._GetSashSize()
border = self._GetBorderSize()
totw = width - barSize - 2*border
if pt.x > totw - _TOLERANCE:
self._expanded = 0
self._offx += 1
elif self._expanded > -1 and pt.x > self._minimum_pane_size:
self._fhor = int((pt.x - barSize - 2*border) / float(totw) * 10000)
self._splitx = (self._fhor*totw)/10000
self._offx = pt.x - self._splitx + 1
self._expanded = -1
oldsplitx = self._splitx
oldsplity = self._splity
if self._mode == wx.BOTH:
self.MoveSplit(pt.x - self._offx, pt.y - self._offy)
elif self._mode == wx.VERTICAL:
self.MoveSplit(pt.x - self._offx, self._splity)
elif self._mode == wx.HORIZONTAL:
self.MoveSplit(self._splitx, pt.y - self._offy)
# Send a changing event
if not self.DoSendChangingEvent(wx.Point(self._splitx, self._splity)):
self._splitx = oldsplitx
self._splity = oldsplity
return
if oldsplitx != self._splitx or oldsplity != self._splity:
if not self.GetAGWWindowStyleFlag() & wx.SP_LIVE_UPDATE:
self.DrawTrackSplitter(oldsplitx, oldsplity)
self.DrawTrackSplitter(self._splitx, self._splity)
else:
self.AdjustLayout()
self._flags |= FLAG_CHANGED
self.Refresh()
# Change cursor based on position
ff = self.GetMode(pt)
if self._expanded > -1 and self._splitx <= self._minimum_pane_size:
self.SetCursor(self._handcursor)
elif ff == wx.BOTH:
self.SetCursor(self._sashCursorSIZING)
elif ff == wx.VERTICAL:
self.SetCursor(self._sashCursorWE)
elif ff == wx.HORIZONTAL:
self.SetCursor(self._sashCursorNS)
else:
self.SetCursor(self._handcursor)
event.Skip()
def SetExpandedSize(self, size):
self._expandedsize = size
def SetMinimumPaneSize(self, size=0):
self._minimum_pane_size = size
def SetSplitSize(self, size):
self._splitsize = size
def get_gradient_panel(parent, label, x=16):
gradientpanel = BitmapBackgroundPanelText(parent, size=(-1, 31))
gradientpanel.alpha = .75
gradientpanel.blend = True
gradientpanel.bordertopcolor = wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DSHADOW)
gradientpanel.drawbordertop = True
gradientpanel.label_x = x
gradientpanel.textalpha = .8
bitmap = bitmaps.get("gradient_panel")
if not bitmap:
bitmap = getbitmap("theme/gradient").GetSubBitmap((0, 1, 8, 15)).ConvertToImage().Mirror(False).ConvertToBitmap()
image = bitmap.ConvertToImage()
databuffer = image.GetDataBuffer()
for i, byte in enumerate(databuffer):
if byte > "\0":
databuffer[i] = chr(int(round(ord(byte) * (255.0 / 223.0))))
bitmap = image.ConvertToBitmap()
bitmaps["gradient_panel"] = bitmap
gradientpanel.SetBitmap(bitmap)
gradientpanel.SetMaxFontSize(11)
font = gradientpanel.Font
font.SetWeight(wx.BOLD)
gradientpanel.Font = font
gradientpanel.SetLabel(label)
return gradientpanel
def get_widget(win, id_name_label):
# hasattr, getattr, setattr silently convert attribute names to byte strings,
# we have to make sure there's no UnicodeEncodeError
if (id_name_label == safe_str(safe_unicode(id_name_label), "ascii") and
hasattr(win, id_name_label)):
# Attribute name
try:
# Trying to access some attributes of wx widgets may
# raise an exception
child = getattr(win, id_name_label)
except:
return False
if is_scripting_allowed(win, child):
return child
else:
# ID or label
try:
id_name_label = int(id_name_label)
except ValueError:
pass
for child in win.GetAllChildren():
if (is_scripting_allowed(win, child) and
(child.Id == id_name_label or child.Name == id_name_label or
child.Label == id_name_label)):
return child
def get_toplevel_window(id_name_label):
try:
id_name_label = int(id_name_label)
except ValueError:
pass
for win in reversed(wx.GetTopLevelWindows()):
if win and (win.Id == id_name_label or win.Name == id_name_label or
win.Label == id_name_label) and win.IsShown():
return win
def is_scripting_allowed(win, child):
return (child and child.TopLevelParent is win and
child.IsShownOnScreen() and
isinstance(child, (CustomCheckBox, aui.AuiNotebook,
labelbook.FlatBookBase, wx.Control, wx.Notebook,
wx.grid.Grid)) and
not isinstance(child, (SimpleBook, aui.AuiTabCtrl,
wx.StaticBitmap)))
_elementtable = {}
def format_ui_element(child, format="plain"):
if child.TopLevelParent:
if not hasattr(child.TopLevelParent, "_win2name"):
child.TopLevelParent._win2name = {}
for name, attr in child.TopLevelParent.__dict__.iteritems():
if isinstance(attr, wx.Window):
child.TopLevelParent._win2name[attr] = name
name = child.TopLevelParent._win2name.get(child, child.Name)
else:
name = child.Name
items = getattr(child, "Items", [])
value = None
if not items and isinstance(child, wx.ListCtrl):
for row in xrange(child.GetItemCount()):
item = []
for col in xrange(child.GetColumnCount()):
item.append(child.GetItem(row, col).GetText())
items.append(" ".join(item))
row = child.GetFirstSelected()
if row != wx.NOT_FOUND:
value = items[row]
elif isinstance(child, (aui.AuiNotebook, labelbook.FlatBookBase,
wx.Notebook)):
for page_idx in xrange(child.GetPageCount()):
items.append(child.GetPageText(page_idx))
page_idx = child.GetSelection()
if page_idx != wx.NOT_FOUND:
value = child.GetPageText(page_idx)
cols = []
if isinstance(child, wx.grid.Grid):
for col in xrange(child.GetNumberCols()):
cols.append(child.GetColLabelValue(col))
if format != "plain":
uielement = {"class": child.__class__.__name__, "name": name,
"enabled": child.IsEnabled(), "id": child.Id}
if child.Label:
uielement["label"] = child.Label
if isinstance(child, (CustomCheckBox, wx.CheckBox, wx.RadioButton)):
uielement["checked"] = child.GetValue()
elif hasattr(child, "GetValue") and not isinstance(child, wx.ListCtrl):
uielement["value"] = child.GetValue()
elif hasattr(child, "GetStringSelection"):
uielement["value"] = child.GetStringSelection()
elif value is not None:
uielement["value"] = value
if items:
uielement["items"] = items
if cols:
uielement["cols"] = cols
uielement["rows"] = child.GetNumberRows()
return uielement
return "%s %s %s%s %s%s%s%s" % (child.__class__.__name__, child.Id,
sp.list2cmdline([name]),
(child.Label and
" " + demjson.encode(child.Label)),
"enabled" if child.IsEnabled() else "disabled",
(isinstance(child, (CustomCheckBox, wx.CheckBox,
wx.RadioButton)) and
child.GetValue() and " checked") or
(getattr(child, "GetValue", "") and
not isinstance(child, (CustomCheckBox, wx.CheckBox,
wx.RadioButton, wx.ListCtrl)) and
" value " + demjson.encode(child.GetValue())) or
(getattr(child, "GetStringSelection", "") and
" value " + demjson.encode(child.GetStringSelection())) or
(value is not None and " value " +
demjson.encode(value) or ""),
(items and " items " +
demjson.encode(items).strip("[]").replace('","', '" "') or
""),
(cols and " rows %s cols %s" %
(child.GetNumberRows(),
demjson.encode(cols).strip("[]").replace('","', '" "')) or
""))
def restore_path_dialog_classes():
wx.DirDialog = _DirDialog
wx.FileDialog = _FileDialog
def test():
config.initcfg()
lang.init()
def key_handler(self, event):
if event.GetEventType() == wx.EVT_CHAR_HOOK.typeId:
print "Received EVT_CHAR_HOOK", event.GetKeyCode(), repr(unichr(event.GetKeyCode()))
elif event.GetEventType() == wx.EVT_KEY_DOWN.typeId:
print "Received EVT_KEY_DOWN", event.GetKeyCode(), repr(unichr(event.GetKeyCode()))
elif event.GetEventType() == wx.EVT_MENU.typeId:
print "Received EVT_MENU", self.id_to_keycode.get(event.GetId()), repr(unichr(self.id_to_keycode.get(event.GetId())))
event.Skip()
ProgressDialog.key_handler = key_handler
SimpleTerminal.key_handler = key_handler
app = BaseApp(0)
style = (wx.PD_ELAPSED_TIME | wx.PD_REMAINING_TIME | wx.PD_CAN_ABORT |
wx.PD_SMOOTH)
p = ProgressDialog(msg="".join(("Test " * 5)), maximum=10000, style=style,
pauseable=True, fancy=not "+fancy" in sys.argv[1:],
allow_close=True)
#t = SimpleTerminal(start_timer=False)
app.MainLoop()
if __name__ == "__main__":
test()
|