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
|
#!/usr/bin/env python
from __future__ import division
import sys
mac = sys.platform.startswith("darwin")
try:
import numpy as N
except ImportError:
raise ImportError("I could not import numpy")
from time import clock
import wx
from Utilities import BBox
import GUIMode
## A global variable to hold the Pixels per inch that wxWindows thinks is in use
## This is used for scaling fonts.
## This can't be computed on module __init__, because a wx.App might not have initialized yet.
global FontScale
## Custom Exceptions:
class FloatCanvasError(Exception):
pass
## Create all the mouse events -- this is for binding to Objects
EVT_FC_ENTER_WINDOW = wx.NewEventType()
EVT_FC_LEAVE_WINDOW = wx.NewEventType()
EVT_FC_LEFT_DOWN = wx.NewEventType()
EVT_FC_LEFT_UP = wx.NewEventType()
EVT_FC_LEFT_DCLICK = wx.NewEventType()
EVT_FC_MIDDLE_DOWN = wx.NewEventType()
EVT_FC_MIDDLE_UP = wx.NewEventType()
EVT_FC_MIDDLE_DCLICK = wx.NewEventType()
EVT_FC_RIGHT_DOWN = wx.NewEventType()
EVT_FC_RIGHT_UP = wx.NewEventType()
EVT_FC_RIGHT_DCLICK = wx.NewEventType()
EVT_FC_MOTION = wx.NewEventType()
EVT_FC_MOUSEWHEEL = wx.NewEventType()
## these two are for the hit-test stuff, I never make them real Events
## fixme: could I use the PyEventBinder for the Object events too?
EVT_FC_ENTER_OBJECT = wx.NewEventType()
EVT_FC_LEAVE_OBJECT = wx.NewEventType()
##Create all mouse event binding objects -- for binding to the Canvas
EVT_LEFT_DOWN = wx.PyEventBinder(EVT_FC_LEFT_DOWN)
EVT_LEFT_UP = wx.PyEventBinder(EVT_FC_LEFT_UP)
EVT_LEFT_DCLICK = wx.PyEventBinder(EVT_FC_LEFT_DCLICK)
EVT_MIDDLE_DOWN = wx.PyEventBinder(EVT_FC_MIDDLE_DOWN)
EVT_MIDDLE_UP = wx.PyEventBinder(EVT_FC_MIDDLE_UP)
EVT_MIDDLE_DCLICK = wx.PyEventBinder(EVT_FC_MIDDLE_DCLICK)
EVT_RIGHT_DOWN = wx.PyEventBinder(EVT_FC_RIGHT_DOWN)
EVT_RIGHT_UP = wx.PyEventBinder(EVT_FC_RIGHT_UP)
EVT_RIGHT_DCLICK = wx.PyEventBinder(EVT_FC_RIGHT_DCLICK)
EVT_MOTION = wx.PyEventBinder(EVT_FC_MOTION)
EVT_ENTER_WINDOW = wx.PyEventBinder(EVT_FC_ENTER_WINDOW)
EVT_LEAVE_WINDOW = wx.PyEventBinder(EVT_FC_LEAVE_WINDOW)
EVT_MOUSEWHEEL = wx.PyEventBinder(EVT_FC_MOUSEWHEEL)
class _MouseEvent(wx.PyCommandEvent):
"""
This event class takes a regular wxWindows mouse event as a parameter,
and wraps it so that there is access to all the original methods. This
is similar to subclassing, but you can't subclass a wxWindows event
The goal is to be able to it just like a regular mouse event.
It adds the method:
GetCoords() , which returns and (x,y) tuple in world coordinates.
Another difference is that it is a CommandEvent, which propagates up
the window hierarchy until it is handled.
"""
def __init__(self, EventType, NativeEvent, WinID, Coords = None):
wx.PyCommandEvent.__init__(self)
self.SetEventType( EventType )
self._NativeEvent = NativeEvent
self.Coords = Coords
def GetCoords(self):
return self.Coords
def __getattr__(self, name):
return getattr(self._NativeEvent, name)
## fixme: This should probably be re-factored into a class
_testBitmap = None
def _cycleidxs(indexcount, maxvalue, step):
"""
Utility function used by _colorGenerator
"""
def colormatch(color):
"""Return True if the color comes back from the bitmap identically."""
if len(color) < 3:
return True
global _testBitmap
dc = wx.MemoryDC()
if not _testBitmap:
_testBitmap = wx.EmptyBitmap(1, 1)
dc.SelectObject(_testBitmap)
dc.SetBackground(wx.BLACK_BRUSH)
dc.Clear()
dc.SetPen(wx.Pen(wx.Colour(*color), 4))
dc.DrawPoint(0,0)
if mac: # NOTE: can the Mac not jsut use the DC?
del dc # Mac can't work with bitmap when selected into a DC.
pdata = wx.AlphaPixelData(_testBitmap)
pacc = pdata.GetPixels()
pacc.MoveTo(pdata, 0, 0)
outcolor = pacc.Get()[:3]
else:
outcolor = dc.GetPixel(0,0)
return outcolor == color
if indexcount == 0:
yield ()
else:
for idx in xrange(0, maxvalue, step):
for tail in _cycleidxs(indexcount - 1, maxvalue, step):
color = (idx, ) + tail
if not colormatch(color):
continue
yield color
def _colorGenerator():
"""
Generates a series of unique colors used to do hit-tests with the Hit
Test bitmap
"""
return _cycleidxs(indexcount=3, maxvalue=256, step=1)
class DrawObject(object):
"""
This is the base class for all the objects that can be drawn.
One must subclass from this (and an assortment of mixins) to create
a new DrawObject.
note: This class contain a series of static dictionaries:
* BrushList
* PenList
* FillStyleList
* LineStyleList
Is this still necessary?
"""
def __init__(self, InForeground = False, IsVisible = True):
"""
:param InForeground=False: whether you want the object in the foreground
:param param IsVisible = True: whther the object is visible
"""
self.InForeground = InForeground
self._Canvas = None
#self._Actual_Canvas = None
self.HitColor = None
self.CallBackFuncs = {}
## these are the defaults
self.HitAble = False
self.HitLine = True
self.HitFill = True
self.MinHitLineWidth = 3
self.HitLineWidth = 3 ## this gets re-set by the subclasses if necessary
self.Brush = None
self.Pen = None
self.FillStyle = "Solid"
self.Visible = IsVisible
# I pre-define all these as class variables to provide an easier
# interface, and perhaps speed things up by caching all the Pens
# and Brushes, although that may not help, as I think wx now
# does that on it's own. Send me a note if you know!
## I'm caching fonts, because on GTK, getting a new font can take a
## while. However, it gets cleared after every full draw as hanging
## on to a bunch of large fonts takes a massive amount of memory.
## a dict to cache Font Objects while drawing -- for those that need fonts
FontList = {}
BrushList = {
( None,"Transparent") : wx.TRANSPARENT_BRUSH,
("Blue","Solid") : wx.BLUE_BRUSH,
("Green","Solid") : wx.GREEN_BRUSH,
("White","Solid") : wx.WHITE_BRUSH,
("Black","Solid") : wx.BLACK_BRUSH,
("Grey","Solid") : wx.GREY_BRUSH,
("MediumGrey","Solid") : wx.MEDIUM_GREY_BRUSH,
("LightGrey","Solid") : wx.LIGHT_GREY_BRUSH,
("Cyan","Solid") : wx.CYAN_BRUSH,
("Red","Solid") : wx.RED_BRUSH
}
PenList = {
(None,"Transparent",1) : wx.TRANSPARENT_PEN,
("Green","Solid",1) : wx.GREEN_PEN,
("White","Solid",1) : wx.WHITE_PEN,
("Black","Solid",1) : wx.BLACK_PEN,
("Grey","Solid",1) : wx.GREY_PEN,
("MediumGrey","Solid",1) : wx.MEDIUM_GREY_PEN,
("LightGrey","Solid",1) : wx.LIGHT_GREY_PEN,
("Cyan","Solid",1) : wx.CYAN_PEN,
("Red","Solid",1) : wx.RED_PEN
}
FillStyleList = {
"Transparent" : wx.TRANSPARENT,
"Solid" : wx.SOLID,
"BiDiagonalHatch": wx.BDIAGONAL_HATCH,
"CrossDiagHatch" : wx.CROSSDIAG_HATCH,
"FDiagonal_Hatch": wx.FDIAGONAL_HATCH,
"CrossHatch" : wx.CROSS_HATCH,
"HorizontalHatch": wx.HORIZONTAL_HATCH,
"VerticalHatch" : wx.VERTICAL_HATCH
}
LineStyleList = {
"Solid" : wx.SOLID,
"Transparent": wx.TRANSPARENT,
"Dot" : wx.DOT,
"LongDash" : wx.LONG_DASH,
"ShortDash" : wx.SHORT_DASH,
"DotDash" : wx.DOT_DASH,
}
# # made a property so sub-classes c
# @property
# def _Canvas(self):
# """
# getter for the _Canvas property
# """
# return self._Actual_Canvas
# @_Canvas.setter
# def _Canvas(self, canvas):
# """
# setter for Canvas property
# """
# self._Actual_Canvas = canvas
def Bind(self, Event, CallBackFun):
##fixme: Way too much Canvas Manipulation here!
self.CallBackFuncs[Event] = CallBackFun
self.HitAble = True
self._Canvas.UseHitTest = True
if self.InForeground and self._Canvas._ForegroundHTBitmap is None:
self._Canvas.MakeNewForegroundHTBitmap()
elif self._Canvas._HTBitmap is None:
self._Canvas.MakeNewHTBitmap()
if not self.HitColor:
if not self._Canvas.HitColorGenerator:
self._Canvas.HitColorGenerator = _colorGenerator()
self._Canvas.HitColorGenerator.next() # first call to prevent the background color from being used.
self.HitColor = self._Canvas.HitColorGenerator.next()
self.SetHitPen(self.HitColor,self.HitLineWidth)
self.SetHitBrush(self.HitColor)
# put the object in the hit dict, indexed by it's color
if not self._Canvas.HitDict:
self._Canvas.MakeHitDict()
self._Canvas.HitDict[Event][self.HitColor] = (self) # put the object in the hit dict, indexed by its color
def UnBindAll(self):
## fixme: this only removes one from each list, there could be more.
## + patch by Tim Ansel
if self._Canvas.HitDict:
for Event in self._Canvas.HitDict.itervalues():
try:
del Event[self.HitColor]
except KeyError:
pass
self.HitAble = False
def SetBrush(self, FillColor, FillStyle):
if FillColor is None or FillStyle is None:
#self.Brush = wx.TRANSPARENT_BRUSH
## wx.TRANSPARENT_BRUSH seems to have a bug in Phoenix...
self.Brush = wx.Brush(wx.Colour(0,0,0),wx.TRANSPARENT)
##fixme: should I really re-set the style?
self.FillStyle = "Transparent"
else:
self.Brush = self.BrushList.setdefault( (FillColor,FillStyle), wx.Brush(FillColor,self.FillStyleList[FillStyle] ) )
def SetPen(self,LineColor,LineStyle,LineWidth):
if (LineColor is None) or (LineStyle is None):
self.Pen = wx.TRANSPARENT_PEN
self.LineStyle = 'Transparent'
else:
self.Pen = self.PenList.setdefault( (LineColor,LineStyle,LineWidth), wx.Pen(LineColor,LineWidth,self.LineStyleList[LineStyle]) )
def SetHitBrush(self,HitColor):
if not self.HitFill:
self.HitBrush = wx.TRANSPARENT_BRUSH
else:
self.HitBrush = self.BrushList.setdefault( (HitColor,"solid"), wx.Brush(HitColor,self.FillStyleList["Solid"] ) )
def SetHitPen(self,HitColor,LineWidth):
if not self.HitLine:
self.HitPen = wx.TRANSPARENT_PEN
else:
self.HitPen = self.PenList.setdefault( (HitColor, "solid", self.HitLineWidth), wx.Pen(HitColor, self.HitLineWidth, self.LineStyleList["Solid"]) )
## Just to make sure that they will always be there
## the appropriate ones should be overridden in the subclasses
def SetColor(self, Color):
pass
def SetLineColor(self, LineColor):
pass
def SetLineStyle(self, LineStyle):
pass
def SetLineWidth(self, LineWidth):
pass
def SetFillColor(self, FillColor):
pass
def SetFillStyle(self, FillStyle):
pass
def PutInBackground(self):
if self._Canvas and self.InForeground:
self._Canvas._ForeDrawList.remove(self)
self._Canvas._DrawList.append(self)
self._Canvas._BackgroundDirty = True
self.InForeground = False
def PutInForeground(self):
if self._Canvas and (not self.InForeground):
self._Canvas._ForeDrawList.append(self)
self._Canvas._DrawList.remove(self)
self._Canvas._BackgroundDirty = True
self.InForeground = True
def Hide(self):
"""
Make an object hidden (not drawn)
"""
self.Visible = False
def Show(self):
"""
Make an object visible on the canvas.
"""
self.Visible = True
class Group(DrawObject):
"""
A group of other FloatCanvas Objects
Not all DrawObject methods may apply here.
Note that if an object is in more than one group, it will get drawn more than once.
"""
def __init__(self, ObjectList=[], InForeground = False, IsVisible = True):
self.ObjectList = []
DrawObject.__init__(self, InForeground, IsVisible)
# this one uses a proprty for _Canvas...
self._Actual_Canvas = None
for obj in ObjectList:
self.AddObject(obj, calcBB = False)
self.CalcBoundingBox()
## re-define _Canvas property so that the sub-objects get set up right
@property
def _Canvas(self):
"""
getter for the _Canvas property
"""
return self._Actual_Canvas
@_Canvas.setter
def _Canvas(self, canvas):
"""
setter for Canvas property
"""
self._Actual_Canvas = canvas
for obj in self.ObjectList:
obj._Canvas = canvas
def AddObject(self, obj, calcBB=True):
self.ObjectList.append(obj)
obj._Canvas = self._Canvas
if calcBB:
self.BoundingBox.Merge(obj.BoundingBox)
def AddObjects(self, Objects):
for o in Objects:
self.AddObject(o)
def CalcBoundingBox(self):
if self.ObjectList:
BB = BBox.BBox(self.ObjectList[0].BoundingBox).copy()
for obj in self.ObjectList[1:]:
BB.Merge(obj.BoundingBox)
else:
BB = BBox.NullBBox()
self.BoundingBox = BB
def SetColor(self, Color):
for o in self.ObjectList:
o.SetColor(Color)
def SetLineColor(self, Color):
for o in self.ObjectList:
o.SetLineColor(Color)
def SetLineStyle(self, LineStyle):
for o in self.ObjectList:
o.SetLineStyle(LineStyle)
def SetLineWidth(self, LineWidth):
for o in self.ObjectList:
o.SetLineWidth(LineWidth)
def SetFillColor(self, Color):
for o in self.ObjectList:
o.SetFillColor(Color)
def SetFillStyle(self, FillStyle):
for o in self.ObjectList:
o.SetFillStyle(FillStyle)
def Move(self, Delta):
for obj in self.ObjectList:
obj.Move(Delta)
self.BoundingBox += Delta
def Bind(self, Event, CallBackFun):
## slight variation on DrawObject Bind Method:
## fixme: There is a lot of repeated code from the DrawObject method, but
## it all needs a lot of cleaning up anyway.
self.CallBackFuncs[Event] = CallBackFun
self.HitAble = True
self._Canvas.UseHitTest = True
if self.InForeground and self._Canvas._ForegroundHTBitmap is None:
self._Canvas.MakeNewForegroundHTBitmap()
elif self._Canvas._HTBitmap is None:
self._Canvas.MakeNewHTBitmap()
if not self.HitColor:
if not self._Canvas.HitColorGenerator:
self._Canvas.HitColorGenerator = _colorGenerator()
self._Canvas.HitColorGenerator.next() # first call to prevent the background color from being used.
# Set all contained objects to the same Hit color:
self.HitColor = self._Canvas.HitColorGenerator.next()
# for obj in self.ObjectList:
# obj.SetHitPen(self.HitColor, self.HitLineWidth)
# obj.SetHitBrush(self.HitColor)
# obj.HitAble = True
# put the object in the hit dict, indexed by it's color
self._ChangeChildrenHitColor(self.ObjectList)
if not self._Canvas.HitDict:
self._Canvas.MakeHitDict()
self._Canvas.HitDict[Event][self.HitColor] = (self)
def _ChangeChildrenHitColor(self, objlist):
for obj in objlist:
obj.SetHitPen(self.HitColor, self.HitLineWidth)
obj.SetHitBrush(self.HitColor)
obj.HitAble = True
if isinstance(obj, Group):
self._ChangeChildrenHitColor(obj.ObjectList)
def _Draw(self, dc , WorldToPixel, ScaleWorldToPixel = None, HTdc=None):
for obj in self.ObjectList:
obj._Draw(dc, WorldToPixel, ScaleWorldToPixel, HTdc)
class ColorOnlyMixin:
"""
Mixin class for objects that have just one color, rather than a fill
color and line color
"""
def SetColor(self, Color):
self.SetPen(Color,"Solid",1)
self.SetBrush(Color,"Solid")
SetFillColor = SetColor # Just to provide a consistant interface
class LineOnlyMixin:
"""
Mixin class for objects that have just a line, rather than a fill
color and line color
"""
def SetLineColor(self, LineColor):
self.LineColor = LineColor
self.SetPen(LineColor,self.LineStyle,self.LineWidth)
SetColor = SetLineColor# so that it will do something reasonable
def SetLineStyle(self, LineStyle):
self.LineStyle = LineStyle
self.SetPen(self.LineColor,LineStyle,self.LineWidth)
def SetLineWidth(self, LineWidth):
self.LineWidth = LineWidth
self.SetPen(self.LineColor,self.LineStyle,LineWidth)
class LineAndFillMixin(LineOnlyMixin):
"""
Mixin class for objects that have both a line and a fill color and
style.
"""
def SetFillColor(self, FillColor):
self.FillColor = FillColor
self.SetBrush(FillColor, self.FillStyle)
def SetFillStyle(self, FillStyle):
self.FillStyle = FillStyle
self.SetBrush(self.FillColor,FillStyle)
def SetUpDraw(self, dc , WorldToPixel, ScaleWorldToPixel, HTdc):
dc.SetPen(self.Pen)
dc.SetBrush(self.Brush)
if HTdc and self.HitAble:
HTdc.SetPen(self.HitPen)
HTdc.SetBrush(self.HitBrush)
return ( WorldToPixel(self.XY),
ScaleWorldToPixel(self.WH) )
class XYObjectMixin:
"""
This is a mixin class that provides some methods suitable for use
with objects that have a single (x,y) coordinate pair.
"""
def Move(self, Delta ):
"""
Move(Delta): moves the object by delta, where delta is a
(dx,dy) pair. Ideally a Numpy array of shape (2,)
"""
Delta = N.asarray(Delta, N.float)
self.XY += Delta
self.BoundingBox += Delta
if self._Canvas:
self._Canvas.BoundingBoxDirty = True
def CalcBoundingBox(self):
## This may get overwritten in some subclasses
self.BoundingBox = BBox.asBBox((self.XY, self.XY))
def SetPoint(self, xy):
xy = N.array(xy, N.float)
xy.shape = (2,)
self.XY = xy
self.CalcBoundingBox()
if self._Canvas:
self._Canvas.BoundingBoxDirty = True
class PointsObjectMixin:
"""
This is a mixin class that provides some methods suitable for use
with objects that have a set of (x,y) coordinate pairs.
"""
def Move(self, Delta):
"""
Move(Delta): moves the object by delta, where delta is an (dx,
dy) pair. Ideally a Numpy array of shape (2,)
"""
Delta = N.asarray(Delta, N.float)
Delta.shape = (2,)
self.Points += Delta
self.BoundingBox += Delta
if self._Canvas:
self._Canvas.BoundingBoxDirty = True
def CalcBoundingBox(self):
self.BoundingBox = BBox.fromPoints(self.Points)
if self._Canvas:
self._Canvas.BoundingBoxDirty = True
def SetPoints(self, Points, copy = True):
"""
Sets the coordinates of the points of the object to Points (NX2 array).
By default, a copy is made, if copy is set to False, a reference
is used, iff Points is a NumPy array of Floats. This allows you
to change some or all of the points without making any copies.
For example:
Points = Object.Points
Points += (5,10) # shifts the points 5 in the x dir, and 10 in the y dir.
Object.SetPoints(Points, False) # Sets the points to the same array as it was
"""
if copy:
self.Points = N.array(Points, N.float)
self.Points.shape = (-1,2) # Make sure it is a NX2 array, even if there is only one point
else:
self.Points = N.asarray(Points, N.float)
self.CalcBoundingBox()
class Polygon(PointsObjectMixin, LineAndFillMixin, DrawObject):
"""
The Polygon class takes a list of 2-tuples, or a NX2 NumPy array of
point coordinates. so that Points[N][0] is the x-coordinate of
point N and Points[N][1] is the y-coordinate or Points[N,0] is the
x-coordinate of point N and Points[N,1] is the y-coordinate for
arrays.
The other parameters specify various properties of the Polygon, and
should be self explanatory.
"""
def __init__(self,
Points,
LineColor = "Black",
LineStyle = "Solid",
LineWidth = 1,
FillColor = None,
FillStyle = "Solid",
InForeground = False):
DrawObject.__init__(self, InForeground)
self.Points = N.array(Points ,N.float) # this DOES need to make a copy
self.CalcBoundingBox()
self.LineColor = LineColor
self.LineStyle = LineStyle
self.LineWidth = LineWidth
self.FillColor = FillColor
self.FillStyle = FillStyle
self.HitLineWidth = max(LineWidth,self.MinHitLineWidth)
self.SetPen(LineColor,LineStyle,LineWidth)
self.SetBrush(FillColor,FillStyle)
def _Draw(self, dc , WorldToPixel, ScaleWorldToPixel = None, HTdc=None):
Points = WorldToPixel(self.Points)#.tolist()
dc.SetPen(self.Pen)
dc.SetBrush(self.Brush)
dc.DrawPolygon(Points)
if HTdc and self.HitAble:
HTdc.SetPen(self.HitPen)
HTdc.SetBrush(self.HitBrush)
HTdc.DrawPolygon(Points)
class Line(PointsObjectMixin, LineOnlyMixin, DrawObject,):
"""
The Line class takes a list of 2-tuples, or a NX2 NumPy Float array
of point coordinates.
It will draw a straight line if there are two points, and a polyline
if there are more than two.
"""
def __init__(self,Points,
LineColor = "Black",
LineStyle = "Solid",
LineWidth = 1,
InForeground = False):
DrawObject.__init__(self, InForeground)
self.Points = N.array(Points,N.float)
self.CalcBoundingBox()
self.LineColor = LineColor
self.LineStyle = LineStyle
self.LineWidth = LineWidth
self.SetPen(LineColor,LineStyle,LineWidth)
self.HitLineWidth = max(LineWidth,self.MinHitLineWidth)
def _Draw(self, dc , WorldToPixel, ScaleWorldToPixel, HTdc=None):
Points = WorldToPixel(self.Points)
dc.SetPen(self.Pen)
dc.DrawLines(Points)
if HTdc and self.HitAble:
HTdc.SetPen(self.HitPen)
HTdc.DrawLines(Points)
class Spline(Line):
def __init__(self, *args, **kwargs):
Line.__init__(self, *args, **kwargs)
def _Draw(self, dc , WorldToPixel, ScaleWorldToPixel, HTdc=None):
Points = WorldToPixel(self.Points)
dc.SetPen(self.Pen)
dc.DrawSpline(Points)
if HTdc and self.HitAble:
HTdc.SetPen(self.HitPen)
HTdc.DrawSpline(Points)
class Arrow(XYObjectMixin, LineOnlyMixin, DrawObject):
"""
Arrow class definition.
API definition::
Arrow(XY, # coords of origin of arrow (x,y)
Length, # length of arrow in pixels
theta, # angle of arrow in degrees: zero is straight up
# +angle is to the right
LineColor = "Black",
LineStyle = "Solid",
LineWidth = 1,
ArrowHeadSize = 4, # size of arrowhead in pixels
ArrowHeadAngle = 45, # angle of arrow head in degrees
InForeground = False):
It will draw an arrow , starting at the point, (X,Y) pointing in
direction, theta.
"""
def __init__(self,
XY,
Length,
Direction,
LineColor = "Black",
LineStyle = "Solid",
LineWidth = 2, # pixels
ArrowHeadSize = 8, # pixels
ArrowHeadAngle = 30, # degrees
InForeground = False):
DrawObject.__init__(self, InForeground)
self.XY = N.array(XY, N.float)
self.XY.shape = (2,) # Make sure it is a length 2 vector
self.Length = Length
self.Direction = float(Direction)
self.ArrowHeadSize = ArrowHeadSize
self.ArrowHeadAngle = float(ArrowHeadAngle)
self.CalcArrowPoints()
self.CalcBoundingBox()
self.LineColor = LineColor
self.LineStyle = LineStyle
self.LineWidth = LineWidth
self.SetPen(LineColor,LineStyle,LineWidth)
##fixme: How should the HitTest be drawn?
self.HitLineWidth = max(LineWidth,self.MinHitLineWidth)
def SetDirection(self, Direction):
self.Direction = float(Direction)
self.CalcArrowPoints()
def SetLength(self, Length):
self.Length = Length
self.CalcArrowPoints()
def SetLengthDirection(self, Length, Direction):
self.Direction = float(Direction)
self.Length = Length
self.CalcArrowPoints()
## def CalcArrowPoints(self):
## L = self.Length
## S = self.ArrowHeadSize
## phi = self.ArrowHeadAngle * N.pi / 360
## theta = (self.Direction-90.0) * N.pi / 180
## ArrowPoints = N.array( ( (0, L, L - S*N.cos(phi),L, L - S*N.cos(phi) ),
## (0, 0, S*N.sin(phi), 0, -S*N.sin(phi) ) ),
## N.float )
## RotationMatrix = N.array( ( ( N.cos(theta), -N.sin(theta) ),
## ( N.sin(theta), N.cos(theta) ) ),
## N.float
## )
## ArrowPoints = N.matrixmultiply(RotationMatrix, ArrowPoints)
## self.ArrowPoints = N.transpose(ArrowPoints)
def CalcArrowPoints(self):
L = self.Length
S = self.ArrowHeadSize
phi = self.ArrowHeadAngle * N.pi / 360
theta = (270 - self.Direction) * N.pi / 180
AP = N.array( ( (0,0),
(0,0),
(N.cos(theta - phi), -N.sin(theta - phi) ),
(0,0),
(N.cos(theta + phi), -N.sin(theta + phi) ),
), N.float )
AP *= S
shift = (-L*N.cos(theta), L*N.sin(theta) )
AP[1:,:] += shift
self.ArrowPoints = AP
def _Draw(self, dc , WorldToPixel, ScaleWorldToPixel, HTdc=None):
dc.SetPen(self.Pen)
xy = WorldToPixel(self.XY)
ArrowPoints = xy + self.ArrowPoints
dc.DrawLines(ArrowPoints)
if HTdc and self.HitAble:
HTdc.SetPen(self.HitPen)
HTdc.DrawLines(ArrowPoints)
class ArrowLine(PointsObjectMixin, LineOnlyMixin, DrawObject):
"""
ArrowLine class definition.
API definition::
ArrowLine(Points, # coords of points
LineColor = "Black",
LineStyle = "Solid",
LineWidth = 1,
ArrowHeadSize = 4, # in pixels
ArrowHeadAngle = 45,
InForeground = False):
It will draw a set of arrows from point to point.
It takes a list of 2-tuples, or a NX2 NumPy Float array
of point coordinates.
"""
def __init__(self,
Points,
LineColor = "Black",
LineStyle = "Solid",
LineWidth = 1, # pixels
ArrowHeadSize = 8, # pixels
ArrowHeadAngle = 30, # degrees
InForeground = False):
DrawObject.__init__(self, InForeground)
self.Points = N.asarray(Points,N.float)
self.Points.shape = (-1,2) # Make sure it is a NX2 array, even if there is only one point
self.ArrowHeadSize = ArrowHeadSize
self.ArrowHeadAngle = float(ArrowHeadAngle)
self.CalcArrowPoints()
self.CalcBoundingBox()
self.LineColor = LineColor
self.LineStyle = LineStyle
self.LineWidth = LineWidth
self.SetPen(LineColor,LineStyle,LineWidth)
self.HitLineWidth = max(LineWidth,self.MinHitLineWidth)
def CalcArrowPoints(self):
S = self.ArrowHeadSize
phi = self.ArrowHeadAngle * N.pi / 360
Points = self.Points
n = Points.shape[0]
self.ArrowPoints = N.zeros((n-1, 3, 2), N.float)
for i in xrange(n-1):
dx, dy = self.Points[i] - self.Points[i+1]
theta = N.arctan2(dy, dx)
AP = N.array( (
(N.cos(theta - phi), -N.sin(theta-phi)),
(0,0),
(N.cos(theta + phi), -N.sin(theta + phi))
),
N.float )
self.ArrowPoints[i,:,:] = AP
self.ArrowPoints *= S
def _Draw(self, dc , WorldToPixel, ScaleWorldToPixel, HTdc=None):
Points = WorldToPixel(self.Points)
ArrowPoints = Points[1:,N.newaxis,:] + self.ArrowPoints
dc.SetPen(self.Pen)
dc.DrawLines(Points)
for arrow in ArrowPoints:
dc.DrawLines(arrow)
if HTdc and self.HitAble:
HTdc.SetPen(self.HitPen)
HTdc.DrawLines(Points)
for arrow in ArrowPoints:
HTdc.DrawLines(arrow)
class PointSet(PointsObjectMixin, ColorOnlyMixin, DrawObject):
"""
The PointSet class takes a list of 2-tuples, or a NX2 NumPy array of
point coordinates.
If Points is a sequence of tuples: Points[N][0] is the x-coordinate of
point N and Points[N][1] is the y-coordinate.
If Points is a NumPy array: Points[N,0] is the x-coordinate of point
N and Points[N,1] is the y-coordinate for arrays.
Each point will be drawn the same color and Diameter. The Diameter
is in screen pixels, not world coordinates.
The hit-test code does not distingish between the points, you will
only know that one of the points got hit, not which one. You can use
PointSet.FindClosestPoint(WorldPoint) to find out which one
In the case of points, the HitLineWidth is used as diameter.
"""
def __init__(self, Points, Color = "Black", Diameter = 1, InForeground = False):
DrawObject.__init__(self,InForeground)
self.Points = N.array(Points,N.float)
self.Points.shape = (-1,2) # Make sure it is a NX2 array, even if there is only one point
self.CalcBoundingBox()
self.Diameter = Diameter
self.HitLineWidth = min(self.MinHitLineWidth, Diameter)
self.SetColor(Color)
def SetDiameter(self,Diameter):
self.Diameter = Diameter
def FindClosestPoint(self, XY):
"""
Returns the index of the closest point to the point, XY, given
in World coordinates. It's essentially random which you get if
there are more than one that are the same.
This can be used to figure out which point got hit in a mouse
binding callback, for instance. It's a lot faster that using a
lot of separate points.
"""
d = self.Points - XY
return N.argmin(N.hypot(d[:,0],d[:,1]))
def DrawD2(self, dc, Points):
# A Little optimization for a diameter2 - point
dc.DrawPointList(Points)
dc.DrawPointList(Points + (1,0))
dc.DrawPointList(Points + (0,1))
dc.DrawPointList(Points + (1,1))
def _Draw(self, dc , WorldToPixel, ScaleWorldToPixel, HTdc=None):
dc.SetPen(self.Pen)
Points = WorldToPixel(self.Points)
if self.Diameter <= 1:
dc.DrawPointList(Points)
elif self.Diameter <= 2:
self.DrawD2(dc, Points)
else:
dc.SetBrush(self.Brush)
radius = int(round(self.Diameter/2))
##fixme: I really should add a DrawCircleList to wxPython
if len(Points) > 100:
xy = Points
xywh = N.concatenate((xy-radius, N.ones(xy.shape) * self.Diameter ), 1 )
dc.DrawEllipseList(xywh)
else:
for xy in Points:
dc.DrawCircle(xy[0],xy[1], radius)
if HTdc and self.HitAble:
HTdc.SetPen(self.HitPen)
HTdc.SetBrush(self.HitBrush)
if self.Diameter <= 1:
HTdc.DrawPointList(Points)
elif self.Diameter <= 2:
self.DrawD2(HTdc, Points)
else:
if len(Points) > 100:
xy = Points
xywh = N.concatenate((xy-radius, N.ones(xy.shape) * self.Diameter ), 1 )
HTdc.DrawEllipseList(xywh)
else:
for xy in Points:
HTdc.DrawCircle(xy[0],xy[1], radius)
class Point(XYObjectMixin, ColorOnlyMixin, DrawObject):
"""
The Point class takes a 2-tuple, or a (2,) NumPy array of point
coordinates.
The Diameter is in screen points, not world coordinates, So the
Bounding box is just the point, and doesn't include the Diameter.
The HitLineWidth is used as diameter for the
Hit Test.
"""
def __init__(self, XY, Color = "Black", Diameter = 1, InForeground = False):
DrawObject.__init__(self, InForeground)
self.XY = N.array(XY, N.float)
self.XY.shape = (2,) # Make sure it is a length 2 vector
self.CalcBoundingBox()
self.SetColor(Color)
self.Diameter = Diameter
self.HitLineWidth = self.MinHitLineWidth
def SetDiameter(self,Diameter):
self.Diameter = Diameter
def _Draw(self, dc , WorldToPixel, ScaleWorldToPixel, HTdc=None):
dc.SetPen(self.Pen)
xy = WorldToPixel(self.XY)
if self.Diameter <= 1:
dc.DrawPoint(xy[0], xy[1])
else:
dc.SetBrush(self.Brush)
radius = int(round(self.Diameter/2))
dc.DrawCircle(xy[0],xy[1], radius)
if HTdc and self.HitAble:
HTdc.SetPen(self.HitPen)
if self.Diameter <= 1:
HTdc.DrawPoint(xy[0], xy[1])
else:
HTdc.SetBrush(self.HitBrush)
HTdc.DrawCircle(xy[0],xy[1], radius)
class SquarePoint(XYObjectMixin, ColorOnlyMixin, DrawObject):
"""
The SquarePoint class takes a 2-tuple, or a (2,) NumPy array of point
coordinates. It produces a square dot, centered on Point
The Size is in screen points, not world coordinates, so the
Bounding box is just the point, and doesn't include the Size.
The HitLineWidth is used as diameter for the
Hit Test.
"""
def __init__(self, Point, Color = "Black", Size = 4, InForeground = False):
DrawObject.__init__(self, InForeground)
self.XY = N.array(Point, N.float)
self.XY.shape = (2,) # Make sure it is a length 2 vector
self.CalcBoundingBox()
self.SetColor(Color)
self.Size = Size
self.HitLineWidth = self.MinHitLineWidth
def SetSize(self,Size):
self.Size = Size
def _Draw(self, dc , WorldToPixel, ScaleWorldToPixel, HTdc=None):
Size = self.Size
dc.SetPen(self.Pen)
xc,yc = WorldToPixel(self.XY)
if self.Size <= 1:
dc.DrawPoint(xc, yc)
else:
x = xc - Size/2.0
y = yc - Size/2.0
dc.SetBrush(self.Brush)
dc.DrawRectangle(x, y, Size, Size)
if HTdc and self.HitAble:
HTdc.SetPen(self.HitPen)
if self.Size <= 1:
HTdc.DrawPoint(xc, xc)
else:
HTdc.SetBrush(self.HitBrush)
HTdc.DrawRectangle(x, y, Size, Size)
class RectEllipse(XYObjectMixin, LineAndFillMixin, DrawObject):
def __init__(self, XY, WH,
LineColor = "Black",
LineStyle = "Solid",
LineWidth = 1,
FillColor = None,
FillStyle = "Solid",
InForeground = False):
DrawObject.__init__(self,InForeground)
self.SetShape(XY, WH)
self.LineColor = LineColor
self.LineStyle = LineStyle
self.LineWidth = LineWidth
self.FillColor = FillColor
self.FillStyle = FillStyle
self.HitLineWidth = max(LineWidth,self.MinHitLineWidth)
# these define the behaviour when zooming makes the objects really small.
self.MinSize = 1
self.DisappearWhenSmall = True
self.SetPen(LineColor,LineStyle,LineWidth)
self.SetBrush(FillColor,FillStyle)
def SetShape(self, XY, WH):
self.XY = N.array( XY, N.float)
self.XY.shape = (2,)
self.WH = N.array( WH, N.float)
self.WH.shape = (2,)
self.CalcBoundingBox()
def CalcBoundingBox(self):
# you need this in case Width or Height are negative
corners = N.array((self.XY, (self.XY + self.WH) ), N.float)
self.BoundingBox = BBox.fromPoints(corners)
if self._Canvas:
self._Canvas.BoundingBoxDirty = True
class Rectangle(RectEllipse):
def _Draw(self, dc , WorldToPixel, ScaleWorldToPixel, HTdc=None):
( XY, WH ) = self.SetUpDraw(dc,
WorldToPixel,
ScaleWorldToPixel,
HTdc)
WH[N.abs(WH) < self.MinSize] = self.MinSize
if not( self.DisappearWhenSmall and N.abs(WH).min() <= self.MinSize) : # don't try to draw it too tiny
dc.DrawRectanglePointSize(XY, WH)
if HTdc and self.HitAble:
HTdc.DrawRectanglePointSize(XY, WH)
class Ellipse(RectEllipse):
def _Draw(self, dc , WorldToPixel, ScaleWorldToPixel, HTdc=None):
( XY, WH ) = self.SetUpDraw(dc,
WorldToPixel,
ScaleWorldToPixel,
HTdc)
WH[N.abs(WH) < self.MinSize] = self.MinSize
if not( self.DisappearWhenSmall and N.abs(WH).min() <= self.MinSize) : # don't try to draw it too tiny
dc.DrawEllipsePointSize(XY, WH)
if HTdc and self.HitAble:
HTdc.DrawEllipsePointSize(XY, WH)
class Circle(XYObjectMixin, LineAndFillMixin, DrawObject):
def __init__(self, XY, Diameter,
LineColor = "Black",
LineStyle = "Solid",
LineWidth = 1,
FillColor = None,
FillStyle = "Solid",
InForeground = False):
DrawObject.__init__(self, InForeground)
self.XY = N.array(XY, N.float)
self.WH = N.array((Diameter/2, Diameter/2), N.float) # just to keep it compatible with others
self.CalcBoundingBox()
self.LineColor = LineColor
self.LineStyle = LineStyle
self.LineWidth = LineWidth
self.FillColor = FillColor
self.FillStyle = FillStyle
self.HitLineWidth = max(LineWidth,self.MinHitLineWidth)
# these define the behaviour when zooming makes the objects really small.
self.MinSize = 1
self.DisappearWhenSmall = True
self.SetPen(LineColor,LineStyle,LineWidth)
self.SetBrush(FillColor,FillStyle)
def SetDiameter(self, Diameter):
self.WH = N.array((Diameter/2, Diameter/2), N.float) # just to keep it compatible with others
def CalcBoundingBox(self):
# you need this in case Width or Height are negative
self.BoundingBox = BBox.fromPoints( (self.XY+self.WH, self.XY-self.WH) )
if self._Canvas:
self._Canvas.BoundingBoxDirty = True
def _Draw(self, dc , WorldToPixel, ScaleWorldToPixel, HTdc=None):
( XY, WH ) = self.SetUpDraw(dc,
WorldToPixel,
ScaleWorldToPixel,
HTdc)
WH[N.abs(WH) < self.MinSize] = self.MinSize
if not( self.DisappearWhenSmall and N.abs(WH).min() <= self.MinSize) : # don't try to draw it too tiny
dc.DrawCirclePoint(XY, WH[0])
if HTdc and self.HitAble:
HTdc.DrawCirclePoint(XY, WH[0])
class TextObjectMixin(XYObjectMixin):
"""
A mix in class that holds attributes and methods that are needed by
the Text objects
"""
LayoutFontSize = 16 # font size used for calculating layout
def SetFont(self, Size, Family, Style, Weight, Underlined, FaceName):
self.Font = self.FontList.setdefault( (Size,
Family,
Style,
Weight,
Underlined,
FaceName),
#wx.FontFromPixelSize((0.45*Size,Size), # this seemed to give a decent height/width ratio on Windows
wx.Font(Size,
Family,
Style,
Weight,
Underlined,
FaceName) )
def SetColor(self, Color):
self.Color = Color
def SetBackgroundColor(self, BackgroundColor):
self.BackgroundColor = BackgroundColor
def SetText(self, String):
"""
Re-sets the text displayed by the object
In the case of the ScaledTextBox, it will re-do the layout as appropriate
Note: only tested with the ScaledTextBox
"""
self.String = String
self.LayoutText()
def LayoutText(self):
"""
A dummy method to re-do the layout of the text.
A derived object needs to override this if required.
"""
pass
## store the function that shift the coords for drawing text. The
## "c" parameter is the correction for world coordinates, rather
## than pixel coords as the y axis is reversed
## pad is the extra space around the text
## if world = 1, the vertical shift is done in y-up coordinates
ShiftFunDict = {'tl': lambda x, y, w, h, world=0, pad=0: (x + pad, y + pad - 2*world*pad),
'tc': lambda x, y, w, h, world=0, pad=0: (x - w/2, y + pad - 2*world*pad),
'tr': lambda x, y, w, h, world=0, pad=0: (x - w - pad, y + pad - 2*world*pad),
'cl': lambda x, y, w, h, world=0, pad=0: (x + pad, y - h/2 + world*h),
'cc': lambda x, y, w, h, world=0, pad=0: (x - w/2, y - h/2 + world*h),
'cr': lambda x, y, w, h, world=0, pad=0: (x - w - pad, y - h/2 + world*h),
'bl': lambda x, y, w, h, world=0, pad=0: (x + pad, y - h + 2*world*h - pad + world*2*pad) ,
'bc': lambda x, y, w, h, world=0, pad=0: (x - w/2, y - h + 2*world*h - pad + world*2*pad) ,
'br': lambda x, y, w, h, world=0, pad=0: (x - w - pad, y - h + 2*world*h - pad + world*2*pad)}
class Text(TextObjectMixin, DrawObject, ):
"""
This class creates a text object, placed at the coordinates,
x,y. the "Position" argument is a two charactor string, indicating
where in relation to the coordinates the string should be oriented.
The first letter is: t, c, or b, for top, center and bottom The
second letter is: l, c, or r, for left, center and right The
position refers to the position relative to the text itself. It
defaults to "tl" (top left).
Size is the size of the font in pixels, or in points for printing
(if it ever gets implimented). Those will be the same, If you assume
72 PPI.
* Family: Font family, a generic way of referring to fonts without
specifying actual facename. One of:
* wx.DEFAULT: Chooses a default font.
* wx.DECORATI: A decorative font.
* wx.ROMAN: A formal, serif font.
* wx.SCRIPT: A handwriting font.
* wx.SWISS: A sans-serif font.
* wx.MODERN: A fixed pitch font.
.. note:: these are only as good as the wxWindows defaults, which aren't so good.
* Style: One of wx.NORMAL, wx.SLANT and wx.ITALIC.
* Weight: One of wx.NORMAL, wx.LIGHT and wx.BOLD.
* Underlined: The value can be True or False. At present this may have an an
effect on Windows only.
Alternatively, you can set the kw arg: Font, to a wx.Font, and the
above will be ignored.
The size is fixed, and does not scale with the drawing.
The hit-test is done on the entire text extent
"""
def __init__(self,String, xy,
Size = 14,
Color = "Black",
BackgroundColor = None,
Family = wx.MODERN,
Style = wx.NORMAL,
Weight = wx.NORMAL,
Underlined = False,
Position = 'tl',
InForeground = False,
Font = None):
DrawObject.__init__(self,InForeground)
self.String = String
# Input size in in Pixels, compute points size from FontScaleinfo.
# fixme: for printing, we'll have to do something a little different
self.Size = Size * FontScale
self.Color = Color
self.BackgroundColor = BackgroundColor
if not Font:
FaceName = ''
else:
FaceName = Font.GetFaceName()
Family = Font.GetFamily()
Size = Font.GetPointSize()
Style = Font.GetStyle()
Underlined = Font.GetUnderlined()
Weight = Font.GetWeight()
self.SetFont(Size, Family, Style, Weight, Underlined, FaceName)
self.BoundingBox = BBox.asBBox((xy, xy))
self.XY = N.asarray(xy)
self.XY.shape = (2,)
(self.TextWidth, self.TextHeight) = (None, None)
self.ShiftFun = self.ShiftFunDict[Position]
def _Draw(self, dc , WorldToPixel, ScaleWorldToPixel, HTdc=None):
XY = WorldToPixel(self.XY)
dc.SetFont(self.Font)
dc.SetTextForeground(self.Color)
if self.BackgroundColor:
dc.SetBackgroundMode(wx.SOLID)
dc.SetTextBackground(self.BackgroundColor)
else:
dc.SetBackgroundMode(wx.TRANSPARENT)
if self.TextWidth is None or self.TextHeight is None:
(self.TextWidth, self.TextHeight) = dc.GetTextExtent(self.String)
XY = self.ShiftFun(XY[0], XY[1], self.TextWidth, self.TextHeight)
dc.DrawTextPoint(self.String, XY)
if HTdc and self.HitAble:
HTdc.SetPen(self.HitPen)
HTdc.SetBrush(self.HitBrush)
HTdc.DrawRectanglePointSize(XY, (self.TextWidth, self.TextHeight) )
class ScaledText(TextObjectMixin, DrawObject, ):
##fixme: this can be depricated and jsut use ScaledTextBox with different defaults.
"""
This class creates a text object that is scaled when zoomed. It is
placed at the coordinates, x,y. the "Position" argument is a two
charactor string, indicating where in relation to the coordinates
the string should be oriented.
The first letter is: t, c, or b, for top, center and bottom.
The second letter is: l, c, or r, for left, center and right.
The position refers to the position relative to the text itself.
It defaults to "tl" (top left).
Size is the size of the font in world coordinates.
* Family: Font family, a generic way of referring to fonts without
specifying actual facename. One of:
* wx.DEFAULT: Chooses a default font.
* wx.DECORATIVE: A decorative font.
* wx.ROMAN: A formal, serif font.
* wx.SCRIPT: A handwriting font.
* wx.SWISS: A sans-serif font.
* wx.MODERN: A fixed pitch font.
.. note:: these are only as good as the wxWindows defaults, which aren't so good.
* Style: One of wx.NORMAL, wx.SLANT and wx.ITALIC.
* Weight: One of wx.NORMAL, wx.LIGHT and wx.BOLD.
* Underlined: The value can be True or False. At present this may have an
effect on Windows only.
Alternatively, you can set the kw arg: Font, to a wx.Font, and the
above will be ignored. The size of the font you specify will be
ignored, but the rest of its attributes will be preserved.
The size will scale as the drawing is zoomed.
Bugs/Limitations:
As fonts are scaled, they do end up a little different, so you don't
get exactly the same picture as you scale up and down, but it's
pretty darn close.
On wxGTK1 on my Linux system, at least, using a font of over about
3000 pts. brings the system to a halt. It's the Font Server using
huge amounts of memory. My work around is to max the font size to
3000 points, so it won't scale past there. GTK2 uses smarter font
drawing, so that may not be an issue in future versions, so feel
free to test. Another smarter way to do it would be to set a global
zoom limit at that point.
The hit-test is done on the entire text extent. This could be made
optional, but I haven't gotten around to it.
"""
def __init__(self,
String,
XY,
Size,
Color = "Black",
BackgroundColor = None,
Family = wx.MODERN,
Style = wx.NORMAL,
Weight = wx.NORMAL,
Underlined = False,
Position = 'tl',
Font = None,
InForeground = False):
DrawObject.__init__(self,InForeground)
self.String = String
self.XY = N.array( XY, N.float)
self.XY.shape = (2,)
self.Size = Size
self.Color = Color
self.BackgroundColor = BackgroundColor
self.Family = Family
self.Style = Style
self.Weight = Weight
self.Underlined = Underlined
if not Font:
self.FaceName = ''
else:
self.FaceName = Font.GetFaceName()
self.Family = Font.GetFamily()
self.Style = Font.GetStyle()
self.Underlined = Font.GetUnderlined()
self.Weight = Font.GetWeight()
# Experimental max font size value on wxGTK2: this works OK on
# my system. If it's a lot larger, there is a crash, with the
# message:
#
# The application 'FloatCanvasDemo.py' lost its
# connection to the display :0.0; most likely the X server was
# shut down or you killed/destroyed the application.
#
# Windows and OS-X seem to be better behaved in this regard.
# They may not draw it, but they don't crash either!
self.MaxFontSize = 1000
self.MinFontSize = 1 # this can be changed to set a minimum size
self.DisappearWhenSmall = True
self.ShiftFun = self.ShiftFunDict[Position]
self.CalcBoundingBox()
def LayoutText(self):
# This will be called when the text is re-set
# nothing much to be done here
self.CalcBoundingBox()
def CalcBoundingBox(self):
## this isn't exact, as fonts don't scale exactly.
dc = wx.MemoryDC()
bitmap = wx.EmptyBitmap(1, 1)
dc.SelectObject(bitmap) #wxMac needs a Bitmap selected for GetTextExtent to work.
DrawingSize = 40 # pts This effectively determines the resolution that the BB is computed to.
ScaleFactor = float(self.Size) / DrawingSize
self.SetFont(DrawingSize, self.Family, self.Style, self.Weight, self.Underlined, self.FaceName)
dc.SetFont(self.Font)
(w,h) = dc.GetTextExtent(self.String)
w = w * ScaleFactor
h = h * ScaleFactor
x, y = self.ShiftFun(self.XY[0], self.XY[1], w, h, world = 1)
self.BoundingBox = BBox.asBBox(((x, y-h ),(x + w, y)))
def _Draw(self, dc , WorldToPixel, ScaleWorldToPixel, HTdc=None):
(X,Y) = WorldToPixel( (self.XY) )
# compute the font size:
Size = abs( ScaleWorldToPixel( (self.Size, self.Size) )[1] ) # only need a y coordinate length
## Check to see if the font size is large enough to blow up the X font server
## If so, limit it. Would it be better just to not draw it?
## note that this limit is dependent on how much memory you have, etc.
Size = min(Size, self.MaxFontSize)
Size = max(Size, self.MinFontSize) # smallest size you want - default to 0
# Draw the Text
if not( self.DisappearWhenSmall and Size <= self.MinFontSize) : # don't try to draw a zero sized font!
self.SetFont(Size, self.Family, self.Style, self.Weight, self.Underlined, self.FaceName)
dc.SetFont(self.Font)
dc.SetTextForeground(self.Color)
if self.BackgroundColor:
dc.SetBackgroundMode(wx.SOLID)
dc.SetTextBackground(self.BackgroundColor)
else:
dc.SetBackgroundMode(wx.TRANSPARENT)
(w,h) = dc.GetTextExtent(self.String)
# compute the shift, and adjust the coordinates, if neccesary
# This had to be put in here, because it changes with Zoom, as
# fonts don't scale exactly.
xy = self.ShiftFun(X, Y, w, h)
dc.DrawTextPoint(self.String, xy)
if HTdc and self.HitAble:
HTdc.SetPen(self.HitPen)
HTdc.SetBrush(self.HitBrush)
HTdc.DrawRectanglePointSize(xy, (w, h) )
class ScaledTextBox(TextObjectMixin, DrawObject):
"""
This class creates a TextBox object that is scaled when zoomed. It is
placed at the coordinates, x,y.
If the Width parameter is defined, the text will be wrapped to the width given.
A Box can be drawn around the text, be specifying:
LineWidth and/or FillColor
A space(margin) can be put all the way around the text, be specifying:
the PadSize argument in world coordinates.
The spacing between lines can be adjusted with the:
LineSpacing argument.
The "Position" argument is a two character string, indicating where
in relation to the coordinates the Box should be oriented.
-The first letter is: t, c, or b, for top, center and bottom.
-The second letter is: l, c, or r, for left, center and right The
position refers to the position relative to the text itself. It
defaults to "tl" (top left).
Size is the size of the font in world coordinates.
* Family: Font family, a generic way of referring to fonts without
specifying actual facename. One of:
* wx.DEFAULT: Chooses a default font.
* wx.DECORATI: A decorative font.
* wx.ROMAN: A formal, serif font.
* wx.SCRIPT: A handwriting font.
* wx.SWISS: A sans-serif font.
* wx.MODERN: A fixed pitch font.
.. note:: these are only as good as the wxWindows defaults, which aren't so good.
* Style: One of wx.NORMAL, wx.SLANT and wx.ITALIC.
* Weight: One of wx.NORMAL, wx.LIGHT and wx.BOLD.
* Underlined: The value can be True or False. At present this may have an an
effect on Windows only.
Alternatively, you can set the kw arg: Font, to a wx.Font, and the
above will be ignored. The size of the font you specify will be
ignored, but the rest of its attributes will be preserved.
The size will scale as the drawing is zoomed.
Bugs/Limitations:
As fonts are scaled, they do end up a little different, so you don't
get exactly the same picture as you scale up and down, but it's
pretty darn close.
On wxGTK1 on my Linux system, at least, using a font of over about
1000 pts. brings the system to a halt. It's the Font Server using
huge amounts of memory. My work around is to max the font size to
1000 points, so it won't scale past there. GTK2 uses smarter font
drawing, so that may not be an issue in future versions, so feel
free to test. Another smarter way to do it would be to set a global
zoom limit at that point.
The hit-test is done on the entire box. This could be made
optional, but I haven't gotten around to it.
"""
def __init__(self, String,
Point,
Size,
Color = "Black",
BackgroundColor = None,
LineColor = 'Black',
LineStyle = 'Solid',
LineWidth = 1,
Width = None,
PadSize = None,
Family = wx.MODERN,
Style = wx.NORMAL,
Weight = wx.NORMAL,
Underlined = False,
Position = 'tl',
Alignment = "left",
Font = None,
LineSpacing = 1.0,
InForeground = False):
DrawObject.__init__(self,InForeground)
self.XY = N.array(Point, N.float)
self.Size = Size
self.Color = Color
self.BackgroundColor = BackgroundColor
self.LineColor = LineColor
self.LineStyle = LineStyle
self.LineWidth = LineWidth
self.Width = Width
if PadSize is None: # the default is just a little bit of padding
self.PadSize = Size/10.0
else:
self.PadSize = float(PadSize)
self.Family = Family
self.Style = Style
self.Weight = Weight
self.Underlined = Underlined
self.Alignment = Alignment.lower()
self.LineSpacing = float(LineSpacing)
self.Position = Position
if not Font:
self.FaceName = ''
else:
self.FaceName = Font.GetFaceName()
self.Family = Font.GetFamily()
self.Style = Font.GetStyle()
self.Underlined = Font.GetUnderlined()
self.Weight = Font.GetWeight()
# Experimental max font size value on wxGTK2: this works OK on
# my system. If it's a lot larger, there is a crash, with the
# message:
#
# The application 'FloatCanvasDemo.py' lost its
# connection to the display :0.0; most likely the X server was
# shut down or you killed/destroyed the application.
#
# Windows and OS-X seem to be better behaved in this regard.
# They may not draw it, but they don't crash either!
self.MaxFontSize = 1000
self.MinFontSize = 1 # this can be changed to set a larger minimum size
self.DisappearWhenSmall = True
self.ShiftFun = self.ShiftFunDict[Position]
self.String = String
self.LayoutText()
self.CalcBoundingBox()
self.SetPen(LineColor,LineStyle,LineWidth)
self.SetBrush(BackgroundColor, "Solid")
def WrapToWidth(self):
dc = wx.MemoryDC()
bitmap = wx.EmptyBitmap(1, 1)
dc.SelectObject(bitmap) #wxMac needs a Bitmap selected for GetTextExtent to work.
DrawingSize = self.LayoutFontSize # pts This effectively determines the resolution that the BB is computed to.
ScaleFactor = float(self.Size) / DrawingSize
Width = (self.Width - 2*self.PadSize) / ScaleFactor #Width to wrap to
self.SetFont(DrawingSize, self.Family, self.Style, self.Weight, self.Underlined, self.FaceName)
dc.SetFont(self.Font)
NewStrings = []
for s in self.Strings:
#beginning = True
text = s.split(" ")
text.reverse()
LineLength = 0
NewText = text[-1]
del text[-1]
while text:
w = dc.GetTextExtent(' ' + text[-1])[0]
if LineLength + w <= Width:
NewText += ' '
NewText += text[-1]
LineLength = dc.GetTextExtent(NewText)[0]
else:
NewStrings.append(NewText)
NewText = text[-1]
LineLength = dc.GetTextExtent(text[-1])[0]
del text[-1]
NewStrings.append(NewText)
self.Strings = NewStrings
def ReWrap(self, Width):
self.Width = Width
self.LayoutText()
def LayoutText(self):
"""
Calculates the positions of the words of text.
This isn't exact, as fonts don't scale exactly.
To help this, the position of each individual word
is stored separately, so that the general layout stays
the same in world coordinates, as the fonts scale.
"""
self.Strings = self.String.split("\n")
if self.Width:
self.WrapToWidth()
dc = wx.MemoryDC()
bitmap = wx.EmptyBitmap(1, 1)
dc.SelectObject(bitmap) #wxMac needs a Bitmap selected for GetTextExtent to work.
DrawingSize = self.LayoutFontSize # pts This effectively determines the resolution that the BB is computed to.
ScaleFactor = float(self.Size) / DrawingSize
self.SetFont(DrawingSize, self.Family, self.Style, self.Weight, self.Underlined, self.FaceName)
dc.SetFont(self.Font)
TextHeight = dc.GetTextExtent("X")[1]
SpaceWidth = dc.GetTextExtent(" ")[0]
LineHeight = TextHeight * self.LineSpacing
LineWidths = N.zeros((len(self.Strings),), N.float)
y = 0
Words = []
AllLinePoints = []
for i, s in enumerate(self.Strings):
LineWidths[i] = 0
LineWords = s.split(" ")
LinePoints = N.zeros((len(LineWords),2), N.float)
for j, word in enumerate(LineWords):
if j > 0:
LineWidths[i] += SpaceWidth
Words.append(word)
LinePoints[j] = (LineWidths[i], y)
w = dc.GetTextExtent(word)[0]
LineWidths[i] += w
y -= LineHeight
AllLinePoints.append(LinePoints)
TextWidth = N.maximum.reduce(LineWidths)
self.Words = Words
if self.Width is None:
BoxWidth = TextWidth * ScaleFactor + 2*self.PadSize
else: # use the defined Width
BoxWidth = self.Width
Points = N.zeros((0,2), N.float)
for i, LinePoints in enumerate(AllLinePoints):
## Scale to World Coords.
LinePoints *= (ScaleFactor, ScaleFactor)
if self.Alignment == 'left':
LinePoints[:,0] += self.PadSize
elif self.Alignment == 'center':
LinePoints[:,0] += (BoxWidth - LineWidths[i]*ScaleFactor)/2.0
elif self.Alignment == 'right':
LinePoints[:,0] += (BoxWidth - LineWidths[i]*ScaleFactor-self.PadSize)
Points = N.concatenate((Points, LinePoints))
BoxHeight = -(Points[-1,1] - (TextHeight * ScaleFactor)) + 2*self.PadSize
#(x,y) = self.ShiftFun(self.XY[0], self.XY[1], BoxWidth, BoxHeight, world=1)
Points += (0, -self.PadSize)
self.Points = Points
self.BoxWidth = BoxWidth
self.BoxHeight = BoxHeight
self.CalcBoundingBox()
def CalcBoundingBox(self):
"""
Calculates the Bounding Box
"""
w, h = self.BoxWidth, self.BoxHeight
x, y = self.ShiftFun(self.XY[0], self.XY[1], w, h, world=1)
self.BoundingBox = BBox.asBBox(((x, y-h ),(x + w, y)))
def GetBoxRect(self):
wh = (self.BoxWidth, self.BoxHeight)
xy = (self.BoundingBox[0,0], self.BoundingBox[1,1])
return (xy, wh)
def _Draw(self, dc , WorldToPixel, ScaleWorldToPixel, HTdc=None):
xy, wh = self.GetBoxRect()
Points = self.Points + xy
Points = WorldToPixel(Points)
xy = WorldToPixel(xy)
wh = ScaleWorldToPixel(wh) * (1,-1)
# compute the font size:
Size = abs( ScaleWorldToPixel( (self.Size, self.Size) )[1] ) # only need a y coordinate length
## Check to see if the font size is large enough to blow up the X font server
## If so, limit it. Would it be better just to not draw it?
## note that this limit is dependent on how much memory you have, etc.
Size = min(Size, self.MaxFontSize)
Size = max(Size, self.MinFontSize) # smallest size you want - default to 1
# Draw The Box
if (self.LineStyle and self.LineColor) or self.BackgroundColor:
dc.SetBrush(self.Brush)
dc.SetPen(self.Pen)
dc.DrawRectanglePointSize(xy , wh)
# Draw the Text
if not( self.DisappearWhenSmall and Size <= self.MinFontSize) : # don't try to draw a zero sized font!
self.SetFont(Size, self.Family, self.Style, self.Weight, self.Underlined, self.FaceName)
dc.SetFont(self.Font)
dc.SetTextForeground(self.Color)
dc.SetBackgroundMode(wx.TRANSPARENT)
## NOTE: DrawTextList seems to have a memory leak if you call it with a numpy array.
# This has probably been fixed in the wxPython source (as of 9/4/2013),
# but for older versions it's this way for now.
dc.DrawTextList(self.Words, Points.tolist())
# Draw the hit box.
if HTdc and self.HitAble:
HTdc.SetPen(self.HitPen)
HTdc.SetBrush(self.HitBrush)
HTdc.DrawRectanglePointSize(xy, wh)
class Bitmap(TextObjectMixin, DrawObject, ):
"""
This class creates a bitmap object, placed at the coordinates,
x,y. the "Position" argument is a two charactor string, indicating
where in relation to the coordinates the bitmap should be oriented.
The first letter is: t, c, or b, for top, center and bottom The
second letter is: l, c, or r, for left, center and right The
position refers to the position relative to the text itself. It
defaults to "tl" (top left).
The size is fixed, and does not scale with the drawing.
"""
def __init__(self,Bitmap,XY,
Position = 'tl',
InForeground = False):
DrawObject.__init__(self,InForeground)
if type(Bitmap) == wx._gdi.Bitmap:
self.Bitmap = Bitmap
elif type(Bitmap) == wx._core.Image:
self.Bitmap = wx.BitmapFromImage(Bitmap)
# Note the BB is just the point, as the size in World coordinates is not fixed
self.BoundingBox = BBox.asBBox( (XY,XY) )
self.XY = XY
(self.Width, self.Height) = self.Bitmap.GetWidth(), self.Bitmap.GetHeight()
self.ShiftFun = self.ShiftFunDict[Position]
# no need for a line width with bitmaps
self.MinHitLineWidth = 0
self.HitLineWidth = 0
def _Draw(self, dc , WorldToPixel, ScaleWorldToPixel, HTdc=None):
XY = WorldToPixel(self.XY)
XY = self.ShiftFun(XY[0], XY[1], self.Width, self.Height)
dc.DrawBitmapPoint(self.Bitmap, XY, True)
if HTdc and self.HitAble:
HTdc.SetPen(self.HitPen)
HTdc.SetBrush(self.HitBrush)
HTdc.DrawRectanglePointSize(XY, (self.Width, self.Height) )
class ScaledBitmap(TextObjectMixin, DrawObject, ):
"""
This class creates a bitmap object, placed at the coordinates, XY,
of Height, H, in World coordinates. The width is calculated from the
aspect ratio of the bitmap.
the "Position" argument is a two character string, indicating
where in relation to the coordinates the bitmap should be oriented.
The first letter is: t, c, or b, for top, center and bottom The
second letter is: l, c, or r, for left, center and right The
position refers to the position relative to the text itself. It
defaults to "tl" (top left).
The size scales with the drawing
"""
def __init__(self,
Bitmap,
XY,
Height,
Position = 'tl',
InForeground = False,
Quality='normal'):
DrawObject.__init__(self,InForeground)
if type(Bitmap) == wx._gdi.Bitmap:
self.Image = Bitmap.ConvertToImage()
elif type(Bitmap) == wx._core.Image:
self.Image = Bitmap
self.XY = XY
self.Height = Height
(self.bmpWidth, self.bmpHeight) = self.Image.GetWidth(), self.Image.GetHeight()
self.Width = self.bmpWidth / self.bmpHeight * Height
self.ShiftFun = self.ShiftFunDict[Position]
self.CalcBoundingBox()
self.ScaledBitmap = None
self.ScaledHeight = None
self.Quality = Quality
# no need for a line width with bitmaps
self.MinHitLineWidth = 0
self.HitLineWidth = 0
@property
def Quality(self):
if self._scale_quality == wx.IMAGE_QUALITY_NORMAL:
return 'normal'
elif self._scale_quality == wx.IMAGE_QUALITY_HIGH:
return 'high'
else:
raise ValueError('the _scale_quality attribute should only be set to wx.IMAGE_QUALITY_NORMAL or wx.IMAGE_QUALITY_HIGH')
@Quality.setter
def Quality(self, qual):
if qual.lower() == 'normal':
self._scale_quality = wx.IMAGE_QUALITY_NORMAL
elif qual.lower() == 'high':
self._scale_quality = wx.IMAGE_QUALITY_HIGH
else:
raise ValueError('the Quality property can only be set to "normal" or "high"')
def CalcBoundingBox(self):
## this isn't exact, as fonts don't scale exactly.
w, h = self.Width, self.Height
x, y = self.ShiftFun(self.XY[0], self.XY[1], w, h, world = 1)
self.BoundingBox = BBox.asBBox( ( (x, y-h ), (x + w, y) ) )
def _Draw(self, dc , WorldToPixel, ScaleWorldToPixel, HTdc=None):
XY = WorldToPixel(self.XY)
H = int(round(ScaleWorldToPixel(self.Height)[0]))
W = int(round(H * (self.bmpWidth / self.bmpHeight)))
if W == 0 or H == 0: # nothign to draw
return
else:
if (self.ScaledBitmap is None) or (H <> self.ScaledHeight) :
self.ScaledHeight = H
Img = self.Image.Scale(W, H, quality=self._scale_quality)
self.ScaledBitmap = wx.BitmapFromImage(Img)
XY = self.ShiftFun(XY[0], XY[1], W, H)
dc.DrawBitmapPoint(self.ScaledBitmap, XY, True)
if HTdc and self.HitAble:
HTdc.SetPen(self.HitPen)
HTdc.SetBrush(self.HitBrush)
HTdc.DrawRectanglePointSize(XY, (W, H) )
class ScaledBitmap2(TextObjectMixin, DrawObject, ):
"""
An alternative scaled bitmap that only scaled the required amount of
the main bitmap when zoomed in: EXPERIMENTAL!
"""
def __init__(self,
Bitmap,
XY,
Height,
Width=None,
Position = 'tl',
InForeground = False,
Quality='normal'):
DrawObject.__init__(self,InForeground)
if type(Bitmap) == wx._gdi.Bitmap:
self.Image = Bitmap.ConvertToImage()
elif type(Bitmap) == wx._core.Image:
self.Image = Bitmap
self.XY = N.array(XY, N.float)
self.Height = Height
(self.bmpWidth, self.bmpHeight) = self.Image.GetWidth(), self.Image.GetHeight()
self.bmpWH = N.array((self.bmpWidth, self.bmpHeight), N.int32)
## fixme: this should all accommodate different scales for X and Y
if Width is None:
self.BmpScale = float(self.bmpHeight) / Height
self.Width = self.bmpWidth / self.BmpScale
self.WH = N.array((self.Width, Height), N.float)
##fixme: should this have a y = -1 to shift to y-up?
self.BmpScale = self.bmpWH / self.WH
self.ShiftFun = self.ShiftFunDict[Position]
self.CalcBoundingBox()
self.ScaledBitmap = None # cache of the last existing scaled bitmap
self.Quality = Quality
# no need for aline width with images.
self.MinHitLineWidth = 0
self.HitLineWidth = 0
@property
def Quality(self):
if self._scale_quality == wx.IMAGE_QUALITY_NORMAL:
return 'normal'
elif self._scale_quality == wx.IMAGE_QUALITY_HIGH:
return 'high'
else:
raise ValueError('the _scale_quality attribute should only be set to wx.IMAGE_QUALITY_NORMAL or wx.IMAGE_QUALITY_HIGH')
@Quality.setter
def Quality(self, qual):
if qual.lower() == 'normal':
self._scale_quality = wx.IMAGE_QUALITY_NORMAL
elif qual.lower() == 'high':
self._scale_quality = wx.IMAGE_QUALITY_HIGH
else:
raise ValueError('the Quality property can only be set to "normal" or "high"')
def CalcBoundingBox(self):
## this isn't exact, as fonts don't scale exactly.
w,h = self.Width, self.Height
x, y = self.ShiftFun(self.XY[0], self.XY[1], w, h, world = 1)
self.BoundingBox = BBox.asBBox( ((x, y-h ), (x + w, y)) )
def WorldToBitmap(self, Pw):
"""
computes bitmap coords from World coords
"""
delta = Pw - self.XY
Pb = delta * self.BmpScale
Pb *= (1, -1) ##fixme: this may only works for Y-up projection!
## and may only work for top left position
return Pb.astype(N.int_)
def _DrawEntireBitmap(self, dc , WorldToPixel, ScaleWorldToPixel, HTdc):
"""
this is pretty much the old code
Scales and Draws the entire bitmap.
"""
XY = WorldToPixel(self.XY)
H = int(round(ScaleWorldToPixel(self.Height)[0]))
W = int(round(H * (self.bmpWidth / self.bmpHeight)))
if W == 0 or H == 0: # nothing to draw
return
else:
if (self.ScaledBitmap is None) or (self.ScaledBitmap[0] != (0, 0, self.bmpWidth, self.bmpHeight, W, H) ):
#if True: #fixme: (self.ScaledBitmap is None) or (H <> self.ScaledHeight) :
self.ScaledHeight = H
Img = self.Image.Scale(W, H, quality=self._scale_quality)
bmp = wx.BitmapFromImage(Img)
self.ScaledBitmap = ((0, 0, self.bmpWidth, self.bmpHeight , W, H), bmp)# this defines the cached bitmap
else:
bmp = self.ScaledBitmap[1]
XY = self.ShiftFun(XY[0], XY[1], W, H)
dc.DrawBitmapPoint(bmp, XY, True)
if HTdc and self.HitAble:
HTdc.SetPen(self.HitPen)
HTdc.SetBrush(self.HitBrush)
HTdc.DrawRectanglePointSize(XY, (W, H) )
def _DrawSubBitmap(self, dc , WorldToPixel, ScaleWorldToPixel, HTdc):
"""
Subsets just the part of the bitmap that is visible
then scales and draws that.
"""
BBworld = BBox.asBBox(self._Canvas.ViewPortBB)
BBbitmap = BBox.fromPoints(self.WorldToBitmap(BBworld))
XYs = WorldToPixel(self.XY)
# figure out subimage:
# fixme: this should be able to be done more succinctly!
if BBbitmap[0,0] < 0:
Xb = 0
elif BBbitmap[0,0] > self.bmpWH[0]: # off the bitmap
Xb = 0
else:
Xb = BBbitmap[0,0]
XYs[0] = 0 # draw at origin
if BBbitmap[0,1] < 0:
Yb = 0
elif BBbitmap[0,1] > self.bmpWH[1]: # off the bitmap
Yb = 0
ShouldDraw = False
else:
Yb = BBbitmap[0,1]
XYs[1] = 0 # draw at origin
if BBbitmap[1,0] < 0:
#off the screen -- This should never happen!
Wb = 0
elif BBbitmap[1,0] > self.bmpWH[0]:
Wb = self.bmpWH[0] - Xb
else:
Wb = BBbitmap[1,0] - Xb
if BBbitmap[1,1] < 0:
# off the screen -- This should never happen!
Hb = 0
ShouldDraw = False
elif BBbitmap[1,1] > self.bmpWH[1]:
Hb = self.bmpWH[1] - Yb
else:
Hb = BBbitmap[1,1] - Yb
FullHeight = ScaleWorldToPixel(self.Height)[0]
scale = FullHeight / self.bmpWH[1]
Ws = int(scale * Wb + 0.5) # add the 0.5 to round
Hs = int(scale * Hb + 0.5)
if (self.ScaledBitmap is None) or (self.ScaledBitmap[0] != (Xb, Yb, Wb, Hb, Ws, Ws) ):
Img = self.Image.GetSubImage(wx.Rect(Xb, Yb, Wb, Hb))
Img.Rescale(Ws, Hs, quality=self._scale_quality)
bmp = wx.BitmapFromImage(Img)
self.ScaledBitmap = ((Xb, Yb, Wb, Hb, Ws, Ws), bmp)# this defines the cached bitmap
#XY = self.ShiftFun(XY[0], XY[1], W, H)
#fixme: get the shiftfun working!
else:
##fixme: The cached bitmap could be used if the one needed is the same scale, but
## a subset of the cached one.
bmp = self.ScaledBitmap[1]
dc.DrawBitmapPoint(bmp, XYs, True)
if HTdc and self.HitAble:
HTdc.SetPen(self.HitPen)
HTdc.SetBrush(self.HitBrush)
HTdc.DrawRectanglePointSize(XYs, (Ws, Hs) )
def _Draw(self, dc , WorldToPixel, ScaleWorldToPixel, HTdc=None):
BBworld = BBox.asBBox(self._Canvas.ViewPortBB)
## first see if entire bitmap is displayed:
if BBworld.Inside(self.BoundingBox):
# use od code to draw entire bitmap
self._DrawEntireBitmap(dc , WorldToPixel, ScaleWorldToPixel, HTdc)
return
elif BBworld.Overlaps(self.BoundingBox):
self._DrawSubBitmap(dc , WorldToPixel, ScaleWorldToPixel, HTdc)
else:
#Not Drawing -- no part of image is showing
return
class DotGrid:
"""
An example of a Grid Object -- it is set on the FloatCanvas with one of:
FloatCanvas.GridUnder = Grid
FloatCanvas.GridOver = Grid
It will be drawn every time, regardless of the viewport.
In its _Draw method, it computes what to draw, given the ViewPortBB
of the Canvas it's being drawn on.
"""
def __init__(self, Spacing, Size = 2, Color = "Black", Cross=False, CrossThickness = 1):
self.Spacing = N.array(Spacing, N.float)
self.Spacing.shape = (2,)
self.Size = Size
self.Color = Color
self.Cross = Cross
self.CrossThickness = CrossThickness
def CalcPoints(self, Canvas):
ViewPortBB = Canvas.ViewPortBB
Spacing = self.Spacing
minx, miny = N.floor(ViewPortBB[0] / Spacing) * Spacing
maxx, maxy = N.ceil(ViewPortBB[1] / Spacing) * Spacing
##fixme: this could use vstack or something with numpy
x = N.arange(minx, maxx+Spacing[0], Spacing[0]) # making sure to get the last point
y = N.arange(miny, maxy+Spacing[1], Spacing[1]) # an extra is OK
Points = N.zeros((len(y), len(x), 2), N.float)
x.shape = (1,-1)
y.shape = (-1,1)
Points[:,:,0] += x
Points[:,:,1] += y
Points.shape = (-1,2)
return Points
def _Draw(self, dc, Canvas):
Points = self.CalcPoints(Canvas)
Points = Canvas.WorldToPixel(Points)
dc.SetPen(wx.Pen(self.Color,self.CrossThickness))
if self.Cross: # Use cross shaped markers
#Horizontal lines
LinePoints = N.concatenate((Points + (self.Size,0),Points + (-self.Size,0)),1)
dc.DrawLineList(LinePoints)
# Vertical Lines
LinePoints = N.concatenate((Points + (0,self.Size),Points + (0,-self.Size)),1)
dc.DrawLineList(LinePoints)
pass
else: # use dots
## Note: this code borrowed from Pointset -- it really shouldn't be repeated here!.
if self.Size <= 1:
dc.DrawPointList(Points)
elif self.Size <= 2:
dc.DrawPointList(Points + (0,-1))
dc.DrawPointList(Points + (0, 1))
dc.DrawPointList(Points + (1, 0))
dc.DrawPointList(Points + (-1,0))
else:
dc.SetBrush(wx.Brush(self.Color))
radius = int(round(self.Size/2))
##fixme: I really should add a DrawCircleList to wxPython
if len(Points) > 100:
xy = Points
xywh = N.concatenate((xy-radius, N.ones(xy.shape) * self.Size ), 1 )
dc.DrawEllipseList(xywh)
else:
for xy in Points:
dc.DrawCircle(xy[0],xy[1], radius)
class Arc(XYObjectMixin, LineAndFillMixin, DrawObject):
def __init__(self,
StartXY,
EndXY,
CenterXY,
LineColor = "Black",
LineStyle = "Solid",
LineWidth = 1,
FillColor = None,
FillStyle = "Solid",
InForeground = False):
"""
Draws an arc of a circle, centered on point CenterXY, from
the first point (StartXY) to the second (EndXY).
The arc is drawn in an anticlockwise direction from the start point to
the end point.
Parameters:
StartXY : start point
EndXY : end point
CenterXY: center point
LineColor = "Black",
LineStyle = "Solid",
LineWidth = 1,
FillColor = None,
FillStyle = "Solid",
InForeground = False):
"""
DrawObject.__init__(self, InForeground)
# There is probably a more elegant way to do this next section
# The bounding box just gets set to the WH of a circle, with center at CenterXY
# This is suitable for a pie chart as it will be a circle anyway
radius = N.sqrt( (StartXY[0]-CenterXY[0])**2 + (StartXY[1]-CenterXY[1])**2 )
minX = CenterXY[0]-radius
minY = CenterXY[1]-radius
maxX = CenterXY[0]+radius
maxY = CenterXY[1]+radius
XY = [minX,minY]
WH = [maxX-minX,maxY-minY]
self.XY = N.asarray( XY, N.float).reshape((2,))
self.WH = N.asarray( WH, N.float).reshape((2,))
self.StartXY = N.asarray(StartXY, N.float).reshape((2,))
self.CenterXY = N.asarray(CenterXY, N.float).reshape((2,))
self.EndXY = N.asarray(EndXY, N.float).reshape((2,))
#self.BoundingBox = array((self.XY, (self.XY + self.WH)), Float)
self.CalcBoundingBox()
#Finish the setup; allocate color,style etc.
self.LineColor = LineColor
self.LineStyle = LineStyle
self.LineWidth = LineWidth
self.FillColor = FillColor
self.FillStyle = FillStyle
self.HitLineWidth = max(LineWidth,self.MinHitLineWidth)
self.SetPen(LineColor, LineStyle, LineWidth)
self.SetBrush(FillColor, FillStyle)
def Move(self, Delta ):
"""
Move(Delta): moves the object by delta, where delta is a
(dx,dy) pair. Ideally a Numpy array of shape (2,)
"""
Delta = N.asarray(Delta, N.float)
self.XY += Delta
self.StartXY += Delta
self.CenterXY += Delta
self.EndXY += Delta
self.BoundingBox += Delta
if self._Canvas:
self._Canvas.BoundingBoxDirty = True
def _Draw(self, dc , WorldToPixel, ScaleWorldToPixel, HTdc=None):
self.SetUpDraw(dc , WorldToPixel, ScaleWorldToPixel, HTdc)
StartXY = WorldToPixel(self.StartXY)
EndXY = WorldToPixel(self.EndXY)
CenterXY = WorldToPixel(self.CenterXY)
dc.DrawArcPoint(StartXY, EndXY, CenterXY)
if HTdc and self.HitAble:
HTdc.DrawArcPoint(StartXY, EndXY, CenterXY)
def CalcBoundingBox(self):
self.BoundingBox = BBox.asBBox( N.array((self.XY, (self.XY + self.WH) ), N.float) )
if self._Canvas:
self._Canvas.BoundingBoxDirty = True
#---------------------------------------------------------------------------
class FloatCanvas(wx.Panel):
"""
FloatCanvas.py
This is a high level window for drawing maps and anything else in an
arbitrary coordinate system.
The goal is to provide a convenient way to draw stuff on the screen
without having to deal with handling OnPaint events, converting to pixel
coordinates, knowing about wxWindows brushes, pens, and colors, etc. It
also provides virtually unlimited zooming and scrolling
I am using it for two things:
1) general purpose drawing in floating point coordinates
2) displaying map data in Lat-long coordinates
If the projection is set to None, it will draw in general purpose
floating point coordinates. If the projection is set to 'FlatEarth', it
will draw a FlatEarth projection, centered on the part of the map that
you are viewing. You can also pass in your own projection function.
It is double buffered, so re-draws after the window is uncovered by something
else are very quick.
It relies on NumPy, which is needed for speed (maybe, I havn't profiled it)
Bugs and Limitations:
Lots: patches, fixes welcome
For Map drawing: It ignores the fact that the world is, in fact, a
sphere, so it will do strange things if you are looking at stuff near
the poles or the date line. so far I don't have a need to do that, so I
havn't bothered to add any checks for that yet.
Zooming:
I have set no zoom limits. What this means is that if you zoom in really
far, you can get integer overflows, and get wierd results. It
doesn't seem to actually cause any problems other than wierd output, at
least when I have run it.
Speed:
I have done a couple of things to improve speed in this app. The one
thing I have done is used NumPy Arrays to store the coordinates of the
points of the objects. This allowed me to use array oriented functions
when doing transformations, and should provide some speed improvement
for objects with a lot of points (big polygons, polylines, pointsets).
The real slowdown comes when you have to draw a lot of objects, because
you have to call the wx.DC.DrawSomething call each time. This is plenty
fast for tens of objects, OK for hundreds of objects, but pretty darn
slow for thousands of objects.
The solution is to be able to pass some sort of object set to the DC
directly. I've used DC.DrawPointList(Points), and it helped a lot with
drawing lots of points. I havn't got a LineSet type object, so I havn't
used DC.DrawLineList yet. I'd like to get a full set of DrawStuffList()
methods implimented, and then I'd also have a full set of Object sets
that could take advantage of them. I hope to get to it some day.
Mouse Events:
At this point, there are a full set of custom mouse events. They are
just like the regular mouse events, but include an extra attribute:
Event.GetCoords(), that returns the (x,y) position in world
coordinates, as a length-2 NumPy vector of Floats.
Copyright: Christopher Barker
License: Same as the version of wxPython you are using it with
Please let me know if you're using this!!!
Contact me at:
Chris.Barker@noaa.gov
"""
def __init__(self, parent, id = -1,
size = wx.DefaultSize,
ProjectionFun = None,
BackgroundColor = "WHITE",
Debug = False,
**kwargs):
wx.Panel.__init__( self, parent, id, wx.DefaultPosition, size, **kwargs)
self.ComputeFontScale()
self.InitAll()
self.BackgroundBrush = wx.Brush(BackgroundColor,wx.SOLID)
self.Debug = Debug
wx.EVT_PAINT(self, self.OnPaint)
wx.EVT_SIZE(self, self.OnSize)
wx.EVT_LEFT_DOWN(self, self.LeftDownEvent)
wx.EVT_LEFT_UP(self, self.LeftUpEvent)
wx.EVT_LEFT_DCLICK(self, self.LeftDoubleClickEvent)
wx.EVT_MIDDLE_DOWN(self, self.MiddleDownEvent)
wx.EVT_MIDDLE_UP(self, self.MiddleUpEvent)
wx.EVT_MIDDLE_DCLICK(self, self.MiddleDoubleClickEvent)
wx.EVT_RIGHT_DOWN(self, self.RightDownEvent)
wx.EVT_RIGHT_UP(self, self.RightUpEvent)
wx.EVT_RIGHT_DCLICK(self, self.RightDoubleCLickEvent)
wx.EVT_MOTION(self, self.MotionEvent)
wx.EVT_MOUSEWHEEL(self, self.WheelEvent)
wx.EVT_KEY_DOWN(self, self.KeyDownEvent)
wx.EVT_KEY_UP(self, self.KeyUpEvent)
## CHB: I'm leaving these out for now.
#wx.EVT_ENTER_WINDOW(self, self. )
#wx.EVT_LEAVE_WINDOW(self, self. )
self.SetProjectionFun(ProjectionFun)
self.GUIMode = None # making sure the arrribute exists
self.SetMode(GUIMode.GUIMouse()) # make the default Mouse Mode.
# timer to give a delay when re-sizing so that buffers aren't re-built too many times.
self.SizeTimer = wx.PyTimer(self.OnSizeTimer)
# self.InitializePanel()
# self.MakeNewBuffers()
# self.CreateCursors()
def ComputeFontScale(self):
## A global variable to hold the scaling from pixel size to point size.
global FontScale
dc = wx.ScreenDC()
dc.SetFont(wx.Font(16, wx.ROMAN, wx.NORMAL, wx.NORMAL))
E = dc.GetTextExtent("X")
FontScale = 16/E[1]
del dc
def InitAll(self):
"""
InitAll() sets everything in the Canvas to default state.
It can be used to reset the Canvas
"""
self.HitColorGenerator = None
self.UseHitTest = False
self.NumBetweenBlits = 500
## create the Hit Test Dicts:
self.HitDict = None
self._HTdc = None
self._DrawList = []
self._ForeDrawList = []
self.InitializePanel()
self.MakeNewBuffers()
self.BoundingBox = BBox.NullBBox()
self.BoundingBoxDirty = False
self.MinScale = None
self.MaxScale = None
self.ViewPortCenter= N.array( (0,0), N.float)
self.SetProjectionFun(None)
self.MapProjectionVector = N.array( (1,1), N.float) # No Projection to start!
self.TransformVector = N.array( (1,-1), N.float) # default Transformation
self.Scale = 1
self.ObjectUnderMouse = None
self.GridUnder = None
self.GridOver = None
self._BackgroundDirty = True
def SetProjectionFun(self, ProjectionFun):
if ProjectionFun == 'FlatEarth':
self.ProjectionFun = self.FlatEarthProjection
elif callable(ProjectionFun):
self.ProjectionFun = ProjectionFun
elif ProjectionFun is None:
self.ProjectionFun = lambda x=None: N.array( (1,1), N.float)
else:
raise FloatCanvasError('Projectionfun must be either:'
' "FlatEarth", None, or a callable object '
'(function or callable object) that takes the '
'ViewPortCenter and returns a MapProjectionVector')
def FlatEarthProjection(self, CenterPoint):
MaxLatitude = 75 # these were determined essentially arbitrarily
MinLatitude = -75
Lat = min(CenterPoint[1],MaxLatitude)
Lat = max(Lat,MinLatitude)
return N.array((N.cos(N.pi*Lat/180),1),N.float)
def SetMode(self, Mode):
'''
Set the GUImode to any of the available mode.
'''
# Set mode
if self.GUIMode is not None:
self.GUIMode.UnSet() # this lets the old mode clean up.
Mode.Canvas = self # make sure the mode is linked to this canvas
self.GUIMode = Mode
self.SetCursor(self.GUIMode.Cursor)
def MakeHitDict(self):
##fixme: Should this just be None if nothing has been bound?
self.HitDict = {EVT_FC_LEFT_DOWN: {},
EVT_FC_LEFT_UP: {},
EVT_FC_LEFT_DCLICK: {},
EVT_FC_MIDDLE_DOWN: {},
EVT_FC_MIDDLE_UP: {},
EVT_FC_MIDDLE_DCLICK: {},
EVT_FC_RIGHT_DOWN: {},
EVT_FC_RIGHT_UP: {},
EVT_FC_RIGHT_DCLICK: {},
EVT_FC_ENTER_OBJECT: {},
EVT_FC_LEAVE_OBJECT: {},
EVT_FC_MOTION: {},
}
def _RaiseMouseEvent(self, Event, EventType):
"""
This is called in various other places to raise a Mouse Event
"""
pt = self.PixelToWorld( Event.GetPosition() )
evt = _MouseEvent(EventType, Event, self.GetId(), pt)
# called the Windows usual event handler
self.GetEventHandler().ProcessEvent(evt)
if wx.__version__ >= "2.8":
HitTestBitmapDepth = 32
def GetHitTestColor(self, xy):
if self._ForegroundHTBitmap:
pdata = wx.AlphaPixelData(self._ForegroundHTBitmap)
else:
pdata = wx.AlphaPixelData(self._HTBitmap)
if not pdata:
raise RuntimeError("Trouble Accessing Hit Test bitmap")
pacc = pdata.GetPixels()
pacc.MoveTo(pdata, xy[0], xy[1])
return pacc.Get()[:3]
else:
HitTestBitmapDepth = 24
#print "using pre-2.8 hit test code"
def GetHitTestColor(self, xy ):
dc = wx.MemoryDC()
if self._ForegroundHTBitmap:
dc.SelectObject(self._ForegroundHTBitmap)
else:
dc.SelectObject(self._HTBitmap)
hitcolor = dc.GetPixelPoint( xy )
return hitcolor.Get()
def UnBindAll(self):
"""
Removes all bindings to Objects
"""
self.HitDict = None
def _CallHitCallback(self, Object, xy, HitEvent):
"""
a little book keeping to be done when a callback is called
"""
Object.HitCoords = self.PixelToWorld( xy )
Object.HitCoordsPixel = xy
Object.CallBackFuncs[HitEvent](Object)
def HitTest(self, event, HitEvent):
"""
Does a hit test on objects that are "hit-able"
If an object is hit, its event handler is called,
and this method returns True
If no object is hit, this method returns False.
If the event is outside the Window, no object will be considered hit
"""
if self.HitDict:
# check if there are any objects in the dict for this event
if self.HitDict[ HitEvent ]:
xy = event.GetPosition()
winsize = self.Size
if not (xy[0] < 0 or xy[1] < 0 or xy[0] > winsize[0] or xy[1] > winsize[1]):
# The mouse event is in the Window
color = self.GetHitTestColor( xy )
if color in self.HitDict[ HitEvent ]:
Object = self.HitDict[ HitEvent ][color]
self._CallHitCallback(Object, xy, HitEvent)
return True
return False
def MouseOverTest(self, event):
##fixme: Can this be cleaned up?
if (self.HitDict and
(self.HitDict[EVT_FC_ENTER_OBJECT ] or
self.HitDict[EVT_FC_LEAVE_OBJECT ] )
):
xy = event.GetPosition()
color = self.GetHitTestColor( xy )
OldObject = self.ObjectUnderMouse
ObjectCallbackCalled = False
if color in self.HitDict[ EVT_FC_ENTER_OBJECT ]:
Object = self.HitDict[ EVT_FC_ENTER_OBJECT][color]
if (OldObject is None):
try:
self._CallHitCallback(Object, xy, EVT_FC_ENTER_OBJECT)
ObjectCallbackCalled = True
except KeyError:
pass # this means the enter event isn't bound for that object
elif OldObject == Object: # the mouse is still on the same object
pass
## Is the mouse on a different object as it was...
elif not (Object == OldObject):
# call the leave object callback
try:
self._CallHitCallback(OldObject, xy, EVT_FC_LEAVE_OBJECT)
ObjectCallbackCalled = True
except KeyError:
pass # this means the leave event isn't bound for that object
try:
self._CallHitCallback(Object, xy, EVT_FC_ENTER_OBJECT)
ObjectCallbackCalled = True
except KeyError:
pass # this means the enter event isn't bound for that object
## set the new object under mouse
self.ObjectUnderMouse = Object
elif color in self.HitDict[ EVT_FC_LEAVE_OBJECT ]:
Object = self.HitDict[ EVT_FC_LEAVE_OBJECT][color]
self.ObjectUnderMouse = Object
else:
# no objects under mouse bound to mouse-over events
self.ObjectUnderMouse = None
if OldObject:
try:
## Add the hit coords to the Object
self._CallHitCallback(OldObject, xy, EVT_FC_LEAVE_OBJECT)
ObjectCallbackCalled = True
except KeyError:
pass # this means the leave event isn't bound for that object
return ObjectCallbackCalled
return False
## fixme: There is a lot of repeated code here
## Is there a better way?
## probably -- shouldn't there always be a GUIMode?
## there cvould be a null GUI Mode, and use that instead of None
def LeftDoubleClickEvent(self, event):
if self.GUIMode:
self.GUIMode.OnLeftDouble(event)
event.Skip()
def MiddleDownEvent(self, event):
if self.GUIMode:
self.GUIMode.OnMiddleDown(event)
event.Skip()
def MiddleUpEvent(self, event):
if self.GUIMode:
self.GUIMode.OnMiddleUp(event)
event.Skip()
def MiddleDoubleClickEvent(self, event):
if self.GUIMode:
self.GUIMode.OnMiddleDouble(event)
event.Skip()
def RightDoubleCLickEvent(self, event):
if self.GUIMode:
self.GUIMode.OnRightDouble(event)
event.Skip()
def WheelEvent(self, event):
if self.GUIMode:
self.GUIMode.OnWheel(event)
event.Skip()
def LeftDownEvent(self, event):
if self.GUIMode:
self.GUIMode.OnLeftDown(event)
event.Skip()
def LeftUpEvent(self, event):
if self.HasCapture():
self.ReleaseMouse()
if self.GUIMode:
self.GUIMode.OnLeftUp(event)
event.Skip()
def MotionEvent(self, event):
if self.GUIMode:
self.GUIMode.OnMove(event)
event.Skip()
def RightDownEvent(self, event):
if self.GUIMode:
self.GUIMode.OnRightDown(event)
event.Skip()
def RightUpEvent(self, event):
if self.GUIMode:
self.GUIMode.OnRightUp(event)
event.Skip()
def KeyDownEvent(self, event):
if self.GUIMode:
self.GUIMode.OnKeyDown(event)
event.Skip()
def KeyUpEvent(self, event):
if self.GUIMode:
self.GUIMode.OnKeyUp(event)
event.Skip()
def MakeNewBuffers(self):
##fixme: this looks like tortured logic!
self._BackgroundDirty = True
# Make new offscreen bitmap:
self._Buffer = wx.EmptyBitmap(*self.PanelSize)
if self._ForeDrawList:
self._ForegroundBuffer = wx.EmptyBitmap(*self.PanelSize)
if self.UseHitTest:
self.MakeNewForegroundHTBitmap()
else:
self._ForegroundHTBitmap = None
else:
self._ForegroundBuffer = None
self._ForegroundHTBitmap = None
if self.UseHitTest:
self.MakeNewHTBitmap()
else:
self._HTBitmap = None
self._ForegroundHTBitmap = None
def MakeNewHTBitmap(self):
"""
Off screen Bitmap used for Hit tests on background objects
"""
self._HTBitmap = wx.EmptyBitmap(self.PanelSize[0],
self.PanelSize[1],
depth=self.HitTestBitmapDepth)
def MakeNewForegroundHTBitmap(self):
## Note: the foreground and backround HT bitmaps are in separate functions
## so that they can be created separate --i.e. when a foreground is
## added after the backgound is drawn
"""
Off screen Bitmap used for Hit tests on foreground objects
"""
self._ForegroundHTBitmap = wx.EmptyBitmap(self.PanelSize[0],
self.PanelSize[1],
depth=self.HitTestBitmapDepth)
def OnSize(self, event=None):
self.InitializePanel()
#self.SizeTimer.Start(50, oneShot=True)
self.OnSizeTimer()
def OnSizeTimer(self, event=None):
self.MakeNewBuffers()
self.Draw()
def InitializePanel(self):
PanelSize = N.array(self.GetClientSizeTuple(), N.int32)
self.PanelSize = N.maximum(PanelSize, (2,2)) ## OS-X sometimes gives a Size event when the panel is size (0,0)
self.HalfPanelSize = self.PanelSize / 2 # lrk: added for speed in WorldToPixel
self.AspectRatio = float(self.PanelSize[0]) / self.PanelSize[1]
def OnPaint(self, event):
dc = wx.PaintDC(self)
if self._ForegroundBuffer:
dc.DrawBitmap(self._ForegroundBuffer,0,0)
else:
dc.DrawBitmap(self._Buffer,0,0)
## this was so that rubber band boxes and the like could get drawn here
## but it looks like a wx.ClientDC is a better bet still.
#try:
# self.GUIMode.DrawOnTop(dc)
#except AttributeError:
# pass
def Draw(self, Force=False):
"""
Canvas.Draw(Force=False)
Re-draws the canvas.
Note that the buffer will not be re-drawn unless something has
changed. If you change a DrawObject directly, then the canvas
will not know anything has changed. In this case, you can force
a re-draw by passing in True for the Force flag:
Canvas.Draw(Force=True)
There is a main buffer set up to double buffer the screen, so
you can get quick re-draws when the window gets uncovered.
If there are any objects in self._ForeDrawList, then the
background gets drawn to a new buffer, and the foreground
objects get drawn on top of it. The final result is blitted to
the screen, and stored for future Paint events. This is done so
that you can have a complicated background, but have something
changing on the foreground, without having to wait for the
background to get re-drawn. This can be used to support simple
animation, for instance.
"""
if N.sometrue(self.PanelSize <= 2 ):
# it's possible for this to get called before being properly initialized.
return
if self.Debug: start = clock()
ScreenDC = wx.ClientDC(self)
ViewPortWorld = N.array(( self.PixelToWorld((0,0)),
self.PixelToWorld(self.PanelSize) )
)
self.ViewPortBB = N.array( ( N.minimum.reduce(ViewPortWorld),
N.maximum.reduce(ViewPortWorld) ) )
dc = wx.MemoryDC()
dc.SelectObject(self._Buffer)
if self._BackgroundDirty or Force:
dc.SetBackground(self.BackgroundBrush)
dc.Clear()
if self._HTBitmap is not None:
HTdc = wx.MemoryDC()
HTdc.SelectObject(self._HTBitmap)
HTdc.Clear()
else:
HTdc = None
if self.GridUnder is not None:
self.GridUnder._Draw(dc, self)
self._DrawObjects(dc, self._DrawList, ScreenDC, self.ViewPortBB, HTdc)
self._BackgroundDirty = False
del HTdc
if self._ForeDrawList:
## If an object was just added to the Foreground, there might not yet be a buffer
if self._ForegroundBuffer is None:
self._ForegroundBuffer = wx.EmptyBitmap(self.PanelSize[0],
self.PanelSize[1])
dc = wx.MemoryDC() ## I got some strange errors (linewidths wrong) if I didn't make a new DC here
dc.SelectObject(self._ForegroundBuffer)
dc.DrawBitmap(self._Buffer,0,0)
if self._ForegroundHTBitmap is not None:
ForegroundHTdc = wx.MemoryDC()
ForegroundHTdc.SelectObject( self._ForegroundHTBitmap)
ForegroundHTdc.Clear()
if self._HTBitmap is not None:
#Draw the background HT buffer to the foreground HT buffer
ForegroundHTdc.DrawBitmap(self._HTBitmap, 0, 0)
else:
ForegroundHTdc = None
self._DrawObjects(dc,
self._ForeDrawList,
ScreenDC,
self.ViewPortBB,
ForegroundHTdc)
if self.GridOver is not None:
self.GridOver._Draw(dc, self)
ScreenDC.Blit(0, 0, self.PanelSize[0],self.PanelSize[1], dc, 0, 0)
# If the canvas is in the middle of a zoom or move,
# the Rubber Band box needs to be re-drawn
##fixme: maybe GUIModes should never be None, and rather have a Do-nothing GUI-Mode.
if self.GUIMode is not None:
self.GUIMode.UpdateScreen()
if self.Debug:
print "Drawing took %f seconds of CPU time"%(clock()-start)
if self._HTBitmap is not None:
self._HTBitmap.SaveFile('junk.png', wx.BITMAP_TYPE_PNG)
## Clear the font cache. If you don't do this, the X font server
## starts to take up Massive amounts of memory This is mostly a
## problem with very large fonts, that you get with scaled text
## when zoomed in.
## fixme -- this should probably be in the FLoatCanvas,
## rather than DrawObject, but it works here.
DrawObject.FontList = {}
def _ShouldRedraw(DrawList, ViewPortBB):
# lrk: Returns the objects that should be redrawn
## fixme: should this check be moved into the object?
BB2 = ViewPortBB
redrawlist = []
for Object in DrawList:
if Object.BoundingBox.Overlaps(BB2):
redrawlist.append(Object)
return redrawlist
_ShouldRedraw = staticmethod(_ShouldRedraw)
def MoveImage(self, shift, CoordType, ReDraw=True):
"""
move the image in the window.
shift is an (x,y) tuple, specifying the amount to shift in each direction
It can be in any of three coordinates: Panel, Pixel, World,
specified by the CoordType parameter
Panel coordinates means you want to shift the image by some
fraction of the size of the displaed image
Pixel coordinates means you want to shift the image by some number of pixels
World coordinates mean you want to shift the image by an amount
in Floating point world coordinates
"""
shift = N.asarray(shift,N.float)
CoordType = CoordType.lower()
if CoordType == 'panel':# convert from panel coordinates
shift = shift * N.array((-1,1),N.float) *self.PanelSize/self.TransformVector
elif CoordType == 'pixel': # convert from pixel coordinates
shift = shift/self.TransformVector
elif CoordType == 'world': # No conversion
pass
else:
raise FloatCanvasError('CoordType must be either "Panel", "Pixel", or "World"')
self.ViewPortCenter = self.ViewPortCenter + shift
self.MapProjectionVector = self.ProjectionFun(self.ViewPortCenter)
self.TransformVector = N.array((self.Scale,-self.Scale),N.float) * self.MapProjectionVector
self._BackgroundDirty = True
if ReDraw:
self.Draw()
def Zoom(self, factor, center = None, centerCoords="world", keepPointInPlace=False):
"""
Zoom(factor, center) changes the amount of zoom of the image by factor.
If factor is greater than one, the image gets larger.
If factor is less than one, the image gets smaller.
:param factor: amount to zoom in or out If factor is greater than one,
the image gets larger. If factor is less than one, the
image gets smaller.
:param center: a tuple of (x,y) coordinates of the center of the viewport,
after zooming. If center is not given, the center will stay the same.
:param centerCoords: flag indicating whether the center given is in pixel or world
coords. Options are: "world" or "pixel"
:param keepPointInPlace: boolean flag. If False, the center point is what's given.
If True, the image is shifted so that the given center point
is kept in the same pixel space. This facilitates keeping the
same point under the mouse when zooming with the scroll wheel.
"""
if center is None:
center = self.ViewPortCenter
centerCoords = 'world' #override input if they don't give a center point.
if centerCoords == "pixel":
oldpoint = self.PixelToWorld( center )
else:
oldpoint = N.array(center, N.float)
self.Scale = self.Scale*factor
if keepPointInPlace:
self.SetToNewScale(False)
if centerCoords == "pixel":
newpoint = self.PixelToWorld( center )
else:
newpoint = N.array(center, N.float)
delta = (newpoint - oldpoint)
self.MoveImage(-delta, 'world')
else:
self.ViewPortCenter = oldpoint
self.SetToNewScale()
def ZoomToBB(self, NewBB=None, DrawFlag=True, margin_adjust=0.95):
"""
Zooms the image to the bounding box given, or to the bounding
box of all the objects on the canvas, if none is given.
:param NewBB=None: the bounding box you want to zoom in to.
If None, it will be calcuated from all the
objects on the Canvas.
:type NewBB: floatcanvas.utilities.BBox.BBox object (or something compatible).
:param DrawFlag=True: If True, will force a re-draw, regardless of whether
anythign has changed on the Canvas
:param margin_adjust=0.95: amount to adjust the scale so the BB will have a
bit of margin in the Canvas. 1.0 shoud be a tight fit.
:type margin_adjust: float
"""
if NewBB is not None:
BoundingBox = NewBB
else:
if self.BoundingBoxDirty:
self._ResetBoundingBox()
BoundingBox = self.BoundingBox
if (BoundingBox is not None) and (not BoundingBox.IsNull()):
self.ViewPortCenter = N.array(((BoundingBox[0,0]+BoundingBox[1,0])/2,
(BoundingBox[0,1]+BoundingBox[1,1])/2 ),N.float_)
self.MapProjectionVector = self.ProjectionFun(self.ViewPortCenter)
# Compute the new Scale
BoundingBox = BoundingBox*self.MapProjectionVector # this does need to make a copy!
try:
self.Scale = min(abs(self.PanelSize[0] / (BoundingBox[1,0]-BoundingBox[0,0])),
abs(self.PanelSize[1] / (BoundingBox[1,1]-BoundingBox[0,1])) )*margin_adjust
except ZeroDivisionError: # this will happen if the BB has zero width or height
try: #width == 0
self.Scale = (self.PanelSize[0] / (BoundingBox[1,0]-BoundingBox[0,0]))*margin_adjust
except ZeroDivisionError:
try: # height == 0
self.Scale = (self.PanelSize[1] / (BoundingBox[1,1]-BoundingBox[0,1]))*margin_adjust
except ZeroDivisionError: #zero size! (must be a single point)
self.Scale = 1
if DrawFlag:
self._BackgroundDirty = True
else:
# Reset the shifting and scaling to defaults when there is no BB
self.ViewPortCenter= N.array( (0,0), N.float)
self.Scale= 1
self.SetToNewScale(DrawFlag=DrawFlag)
def SetToNewScale(self, DrawFlag=True):
Scale = self.Scale
if self.MinScale is not None:
Scale = max(Scale, self.MinScale)
if self.MaxScale is not None:
Scale = min(Scale, self.MaxScale)
self.MapProjectionVector = self.ProjectionFun(self.ViewPortCenter)
self.TransformVector = N.array((Scale,-Scale),N.float) * self.MapProjectionVector
self.Scale = Scale
self._BackgroundDirty = True
if DrawFlag:
self.Draw()
def RemoveObjects(self, Objects):
for Object in Objects:
self.RemoveObject(Object, ResetBB=False)
self.BoundingBoxDirty = True
def RemoveObject(self, Object, ResetBB = True):
##fixme: Using the list.remove method is kind of slow
if Object.InForeground:
self._ForeDrawList.remove(Object)
if not self._ForeDrawList:
self._ForegroundBuffer = None
self._ForegroundHTdc = None
else:
self._DrawList.remove(Object)
self._BackgroundDirty = True
if ResetBB:
self.BoundingBoxDirty = True
def ClearAll(self, ResetBB=True):
"""
ClearAll(ResetBB=True)
Removes all DrawObjects from the Canvas
If ResetBB is set to False, the original bounding box will remain
"""
self._DrawList = []
self._ForeDrawList = []
self._BackgroundDirty = True
self.HitColorGenerator = None
self.UseHitTest = False
if ResetBB:
self._ResetBoundingBox()
self.MakeNewBuffers()
self.HitDict = None
def _ResetBoundingBox(self):
SetToNull=False
if self._DrawList or self._ForeDrawList:
bblist = []
for obj in self._DrawList + self._ForeDrawList:
if not obj.BoundingBox.IsNull():
bblist.append(obj.BoundingBox)
if bblist: # if there are only NullBBoxes in DrawLists
self.BoundingBox = BBox.fromBBArray(bblist)
else:
SetToNull = True
if self.BoundingBox.Width == 0 or self.BoundingBox.Height == 0:
SetToNull=True
else:
SetToNull=True
if SetToNull:
self.BoundingBox = BBox.NullBBox()
self.ViewPortCenter= N.array( (0,0), N.float)
self.TransformVector = N.array( (1,-1), N.float)
self.MapProjectionVector = N.array( (1,1), N.float)
self.Scale = 1
self.BoundingBoxDirty = False
def PixelToWorld(self, Points):
"""
Converts coordinates from Pixel coordinates to world coordinates.
Points is a tuple of (x,y) coordinates, or a list of such tuples,
or a NX2 Numpy array of x,y coordinates.
"""
return (((N.asarray(Points, N.float) -
(self.PanelSize/2))/self.TransformVector) +
self.ViewPortCenter)
def WorldToPixel(self,Coordinates):
"""
This function will get passed to the drawing functions of the objects,
to transform from world to pixel coordinates.
Coordinates should be a NX2 array of (x,y) coordinates, or
a 2-tuple, or sequence of 2-tuples.
"""
#Note: this can be called by users code for various reasons, so N.asarray is needed.
return (((N.asarray(Coordinates,N.float) -
self.ViewPortCenter)*self.TransformVector)+
(self.HalfPanelSize)).astype('i')
def ScaleWorldToPixel(self,Lengths):
"""
This function will get passed to the drawing functions of the objects,
to Change a length from world to pixel coordinates.
Lengths should be a NX2 array of (x,y) coordinates, or
a 2-tuple, or sequence of 2-tuples.
"""
return ( (N.asarray(Lengths, N.float)*self.TransformVector) ).astype('i')
def ScalePixelToWorld(self,Lengths):
"""
This function computes a pair of x.y lengths,
to change then from pixel to world coordinates.
Lengths should be a NX2 array of (x,y) coordinates, or
a 2-tuple, or sequence of 2-tuples.
"""
return (N.asarray(Lengths,N.float) / self.TransformVector)
def AddObject(self, obj):
# put in a reference to the Canvas, so remove and other stuff can work
obj._Canvas = self
if obj.InForeground:
self._ForeDrawList.append(obj)
self.UseForeground = True
else:
self._DrawList.append(obj)
self._BackgroundDirty = True
self.BoundingBoxDirty = True
return obj
def AddObjects(self, Objects):
for Object in Objects:
self.AddObject(Object)
def _DrawObjects(self, dc, DrawList, ScreenDC, ViewPortBB, HTdc = None):
"""
This is a convenience function;
This function takes the list of objects and draws them to specified
device context.
"""
dc.SetBackground(self.BackgroundBrush)
dc.BeginDrawing()
#i = 0
PanelSize0, PanelSize1 = self.PanelSize # for speed
WorldToPixel = self.WorldToPixel # for speed
ScaleWorldToPixel = self.ScaleWorldToPixel # for speed
Blit = ScreenDC.Blit # for speed
NumBetweenBlits = self.NumBetweenBlits # for speed
for i, Object in enumerate(self._ShouldRedraw(DrawList, ViewPortBB)):
if Object.Visible:
Object._Draw(dc, WorldToPixel, ScaleWorldToPixel, HTdc)
if (i+1) % NumBetweenBlits == 0:
Blit(0, 0, PanelSize0, PanelSize1, dc, 0, 0)
dc.EndDrawing()
def SaveAsImage(self, filename, ImageType=wx.BITMAP_TYPE_PNG):
"""
Saves the current image as an image file. The default is in the
PNG format. Other formats can be specified using the wx flags:
wx.BITMAP_TYPE_PNG
wx.BITMAP_TYPE_JPG
wx.BITMAP_TYPE_BMP
wx.BITMAP_TYPE_XBM
wx.BITMAP_TYPE_XPM
etc. (see the wx docs for the complete list)
"""
self._Buffer.SaveFile(filename, ImageType)
def _makeFloatCanvasAddMethods(): ## lrk's code for doing this in module __init__
classnames = ["Circle", "Ellipse", "Arc", "Rectangle", "ScaledText", "Polygon",
"Line", "Text", "PointSet","Point", "Arrow", "ArrowLine", "ScaledTextBox",
"SquarePoint","Bitmap", "ScaledBitmap", "ScaledBitmap2", "Spline", "Group"]
for classname in classnames:
klass = globals()[classname]
def getaddshapemethod(klass=klass):
def addshape(self, *args, **kwargs):
Object = klass(*args, **kwargs)
self.AddObject(Object)
return Object
return addshape
addshapemethod = getaddshapemethod()
methodname = "Add" + classname
setattr(FloatCanvas, methodname, addshapemethod)
docstring = "Creates %s and adds its reference to the canvas.\n" % classname
docstring += "Argument protocol same as %s class" % classname
if klass.__doc__:
docstring += ", whose docstring is:\n%s" % klass.__doc__
FloatCanvas.__dict__[methodname].__doc__ = docstring
_makeFloatCanvasAddMethods()
|