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
|
"""
@package gui_core.forms
@brief Construct simple wxPython GUI from a GRASS command interface
description.
Classes:
- forms::UpdateThread
- forms::UpdateQThread
- forms::TaskFrame
- forms::CmdPanel
- forms::GUI
- forms::GrassGUIApp
This program is just a coarse approach to automatically build a GUI
from a xml-based GRASS user interface description.
You need to have Python 2.4, wxPython 2.8 and python-xml.
The XML stream is read from executing the command given in the
command line, thus you may call it for instance this way:
python <this file.py> r.basins.fill
Or you set an alias or wrap the call up in a nice shell script, GUI
environment ... please contribute your idea.
Updated to wxPython 2.8 syntax and contrib widgets. Methods added to
make it callable by gui. Method added to automatically re-run with
pythonw on a Mac.
.. todo::
verify option value types
Copyright(C) 2000-2015 by the GRASS Development Team
This program is free software under the GPL(>=v2) Read the file
COPYING coming with GRASS for details.
@author Jan-Oliver Wagner <jan@intevation.de>
@author Bernhard Reiter <bernhard@intevation.de>
@author Michael Barton, Arizona State University
@author Daniel Calvelo <dca.gis@gmail.com>
@author Martin Landa <landa.martin@gmail.com>
@author Luca Delucchi <lucadeluge@gmail.com>
@author Stepan Turek <stepan.turek seznam.cz> (CoordinatesSelect)
"""
import sys
import string
import textwrap
import os
import copy
import locale
import Queue
import re
import codecs
from threading import Thread
if not os.getenv("GISBASE"):
sys.write("We don't seem to be properly installed, or we are being run "
"outside GRASS. Expect glitches.\n")
gisbase = os.path.join(os.path.dirname(sys.argv[0]), os.path.pardir)
import wx
try:
import wx.lib.agw.flatnotebook as FN
except ImportError:
import wx.lib.flatnotebook as FN
import wx.lib.colourselect as csel
import wx.lib.filebrowsebutton as filebrowse
from wx.lib.newevent import NewEvent
try:
import xml.etree.ElementTree as etree
except ImportError:
import elementtree.ElementTree as etree # Python <= 2.4
from grass.pydispatch.signal import Signal
from grass.script import core as grass
from grass.script import task as gtask
from grass.script.setup import set_gui_path
set_gui_path()
from core import globalvar
from gui_core.widgets import StaticWrapText, ScrolledPanel, ColorTablesComboBox, \
BarscalesComboBox, NArrowsComboBox
from gui_core.ghelp import HelpPanel
from gui_core import gselect
from core import gcmd
from core import utils
from core.utils import _
from core.settings import UserSettings
from gui_core.widgets import FloatValidator, GNotebook, FormNotebook, FormListbook
from core.giface import Notification
from gui_core.widgets import LayersList
from gui_core.wrap import GSpinCtrl as SpinCtrl
wxUpdateDialog, EVT_DIALOG_UPDATE = NewEvent()
"""Hide some options in the GUI"""
#_blackList = { 'enabled' : False,
# 'items' : { 'r.buffer' : {'params' : ['input', 'output'],
# 'flags' : ['z', 'overwrite']}}}
_blackList = {'enabled': False,
'items': {}}
def text_beautify(someString, width=70):
"""Make really long texts shorter, clean up whitespace and remove
trailing punctuation.
"""
if width > 0:
return escape_ampersand(
string.strip(
os.linesep.join(
textwrap.wrap(
utils.normalize_whitespace(someString),
width)),
".,;:"))
else:
return escape_ampersand(string.strip(
utils.normalize_whitespace(someString), ".,;:"))
def escape_ampersand(text):
"""Escapes ampersands with additional ampersand for GUI"""
return string.replace(text, "&", "&&")
class UpdateThread(Thread):
"""Update dialog widgets in the thread"""
def __init__(self, parent, event, eventId, task):
Thread.__init__(self)
self.parent = parent
self.event = event
self.eventId = eventId
self.task = task
self.setDaemon(True)
# list of functions which updates the dialog
self.data = {}
def run(self):
# get widget id
if not self.eventId:
for p in self.task.params:
if p.get('gisprompt', False) == False:
continue
prompt = p.get('element', '')
if prompt == 'vector':
name = p.get('name', '')
if name in ('map', 'input'):
self.eventId = p['wxId'][0]
if self.eventId is None:
return
p = self.task.get_param(self.eventId, element='wxId', raiseError=False)
if not p or 'wxId-bind' not in p:
return
# is this check necessary?
# get widget prompt
# pType = p.get('prompt', '')
# if not pType:
# return
# check for map/input parameter
pMap = self.task.get_param('map', raiseError=False)
if not pMap:
pMap = self.task.get_param('input', raiseError=False)
if pMap:
map = pMap.get('value', '')
else:
map = None
# avoid running db.describe several times
cparams = dict()
cparams[map] = {'dbInfo': None,
'layers': None, }
# update reference widgets
for uid in p['wxId-bind']:
win = self.parent.FindWindowById(uid)
if not win:
continue
name = win.GetName()
# @todo: replace name by isinstance() and signals
pBind = self.task.get_param(uid, element='wxId', raiseError=False)
if pBind:
pBind['value'] = ''
# set appropriate types in t.* modules and g.list/remove element
# selections
if name == 'Select':
type_param = self.task.get_param(
'type', element='name', raiseError=False)
if 'all' in type_param.get('value'):
etype = type_param.get('values')[:]
if 'all' in etype:
etype.remove('all')
etype = ','.join(etype)
else:
etype = type_param.get('value')
if globalvar.CheckWxVersion([3]):
self.data[win.SetElementList] = {'type': etype}
else:
self.data[win.GetParent().SetElementList] = {'type': etype}
# t.(un)register has one type for 'input', 'maps'
maps_param = self.task.get_param(
'maps', element='name', raiseError=False)
if self.task.get_name().startswith('t') and maps_param is not None:
if maps_param['wxId'][0] != uid:
element_dict = {
'raster': 'strds',
'vector': 'stvds',
'raster_3d': 'str3ds'}
self.data[
win.GetParent().SetType] = {
'etype': element_dict[
type_param.get('value')]}
map = layer = None
driver = db = None
if name in ('LayerSelect', 'ColumnSelect'):
if p.get('element', '') == 'vector': # -> vector
# get map name
map = p.get('value', '')
# get layer
for bid in p['wxId-bind']:
p = self.task.get_param(
bid, element='wxId', raiseError=False)
if not p:
continue
if p.get('element', '') in ['layer', 'layer_all']:
layer = p.get('value', '')
if layer != '':
layer = p.get('value', '')
else:
layer = p.get('default', '')
break
elif p.get('element', '') in ['layer', 'layer_all']: # -> layer
# get layer
layer = p.get('value', '')
if layer != '':
layer = p.get('value', '')
else:
layer = p.get('default', '')
# get map name
pMapL = self.task.get_param(
p['wxId'][0], element='wxId-bind', raiseError=False)
if pMapL:
map = pMapL.get('value', '')
if name == 'TableSelect' or \
(name == 'ColumnSelect' and not map):
pDriver = self.task.get_param(
'dbdriver', element='prompt', raiseError=False)
if pDriver:
driver = pDriver.get('value', '')
pDb = self.task.get_param(
'dbname', element='prompt', raiseError=False)
if pDb:
db = pDb.get('value', '')
if name == 'ColumnSelect':
pTable = self.task.get_param(
'dbtable', element='element', raiseError=False)
if pTable:
table = pTable.get('value', '')
if name == 'LayerSelect':
# determine format
native = True
for id in pMap['wxId']:
winVec = self.parent.FindWindowById(id)
if winVec.GetName() == 'VectorFormat' and \
winVec.GetSelection() != 0:
native = False
break
# TODO: update only if needed
if native:
if map:
self.data[win.InsertLayers] = {'vector': map}
else:
self.data[win.InsertLayers] = {}
else:
if map:
self.data[win.InsertLayers] = {
'dsn': map.rstrip('@OGR')}
else:
self.data[win.InsertLayers] = {}
elif name == 'TableSelect':
self.data[win.InsertTables] = {'driver': driver,
'database': db}
elif name == 'ColumnSelect':
if map:
if map in cparams:
if not cparams[map]['dbInfo']:
cparams[map]['dbInfo'] = gselect.VectorDBInfo(map)
self.data[win.GetParent().InsertColumns] = {
'vector': map, 'layer': layer,
'dbInfo': cparams[map]['dbInfo']}
else: # table
if driver and db:
self.data[win.GetParent().InsertTableColumns] = {
'table': pTable.get('value'),
'driver': driver, 'database': db}
elif pTable:
self.data[win.GetParent().InsertTableColumns] = {
'table': pTable.get('value')}
elif name == 'SubGroupSelect':
self.data[win.Insert] = {'group': p.get('value', '')}
elif name == 'SignatureSelect':
if p.get('prompt', 'group') == 'group':
group = p.get('value', '')
pSubGroup = self.task.get_param(
'subgroup', element='prompt', raiseError=False)
if pSubGroup:
subgroup = pSubGroup.get('value', '')
else:
subgroup = None
else:
subgroup = p.get('value', '')
pGroup = self.task.get_param(
'group', element='prompt', raiseError=False)
if pGroup:
group = pGroup.get('value', '')
else:
group = None
self.data[win.Insert] = {'group': group,
'subgroup': subgroup}
elif name == 'LocationSelect':
pDbase = self.task.get_param(
'dbase', element='element', raiseError=False)
if pDbase:
self.data[
win.UpdateItems] = {
'dbase': pDbase.get(
'value', '')}
elif name == 'MapsetSelect':
pDbase = self.task.get_param(
'dbase', element='element', raiseError=False)
pLocation = self.task.get_param(
'location', element='element', raiseError=False)
if pDbase and pLocation:
self.data[
win.UpdateItems] = {
'dbase': pDbase.get(
'value', ''), 'location': pLocation.get(
'value', '')}
elif name == 'ProjSelect':
pDbase = self.task.get_param(
'dbase', element='element', raiseError=False)
pLocation = self.task.get_param(
'location', element='element', raiseError=False)
pMapset = self.task.get_param(
'mapset', element='element', raiseError=False)
if pDbase and pLocation and pMapset:
self.data[
win.UpdateItems] = {
'dbase': pDbase.get(
'value', ''), 'location': pLocation.get(
'value', ''), 'mapset': pMapset.get(
'value', '')}
def UpdateDialog(parent, event, eventId, task):
return UpdateThread(parent, event, eventId, task)
class UpdateQThread(Thread):
"""Update dialog widgets in the thread"""
requestId = 0
def __init__(self, parent, requestQ, resultQ, **kwds):
Thread.__init__(self, **kwds)
self.parent = parent # cmdPanel
self.setDaemon(True)
self.requestQ = requestQ
self.resultQ = resultQ
self.start()
def Update(self, callable, *args, **kwds):
UpdateQThread.requestId += 1
self.request = None
self.requestQ.put((UpdateQThread.requestId, callable, args, kwds))
return UpdateQThread.requestId
def run(self):
while True:
requestId, callable, args, kwds = self.requestQ.get()
self.request = callable(*args, **kwds)
self.resultQ.put((requestId, self.request.run()))
if self.request:
event = wxUpdateDialog(data=self.request.data)
wx.PostEvent(self.parent, event)
class TaskFrame(wx.Frame):
"""This is the Frame containing the dialog for options input.
The dialog is organized in a notebook according to the guisections
defined by each GRASS command.
If run with a parent, it may Apply, Ok or Cancel; the latter two
close the dialog. The former two trigger a callback.
If run standalone, it will allow execution of the command.
The command is checked and sent to the clipboard when clicking
'Copy'.
"""
def __init__(self, parent, giface, task_description, id=wx.ID_ANY,
get_dcmd=None, layer=None,
style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL, **kwargs):
self.get_dcmd = get_dcmd
self.layer = layer
self.task = task_description
self.parent = parent # LayerTree | Modeler | None | ...
self._giface = giface
self.dialogClosing = Signal('TaskFrame.dialogClosing')
# module name + keywords
title = self.task.get_name()
try:
if self.task.keywords != ['']:
title += " [" + ', '.join(self.task.keywords) + "]"
except ValueError:
pass
wx.Frame.__init__(self, parent=parent, id=id, title=title,
name="MainFrame", style=style, **kwargs)
self.locale = wx.Locale(language=wx.LANGUAGE_DEFAULT)
self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
# statusbar
self.CreateStatusBar()
# icon
self.SetIcon(
wx.Icon(
os.path.join(
globalvar.ICONDIR,
'grass_dialog.ico'),
wx.BITMAP_TYPE_ICO))
guisizer = wx.BoxSizer(wx.VERTICAL)
# set apropriate output window
if self.parent:
self.standalone = False
else:
self.standalone = True
# logo + description
topsizer = wx.BoxSizer(wx.HORIZONTAL)
# GRASS logo
self.logo = wx.StaticBitmap(
parent=self.panel,
bitmap=wx.Bitmap(
name=os.path.join(
globalvar.IMGDIR,
'grass_form.png'),
type=wx.BITMAP_TYPE_PNG))
topsizer.Add(item=self.logo, proportion=0, border=3,
flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL)
# add module description
if self.task.label:
module_desc = self.task.label + ' ' + self.task.description
else:
module_desc = self.task.description
self.description = StaticWrapText(parent=self.panel,
label=module_desc)
topsizer.Add(item=self.description, proportion=1, border=5,
flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
guisizer.Add(item=topsizer, proportion=0, flag=wx.EXPAND)
self.panel.SetSizerAndFit(guisizer)
self.Layout()
# notebooks
self.notebookpanel = CmdPanel(
parent=self.panel,
giface=self._giface,
task=self.task,
frame=self)
self._gconsole = self.notebookpanel._gconsole
if self._gconsole:
self._gconsole.mapCreated.connect(self.OnMapCreated)
self._gconsole.updateMap.connect(
lambda: self._giface.updateMap.emit())
self.goutput = self.notebookpanel.goutput
if self.goutput:
self.goutput.showNotification.connect(
lambda message: self.SetStatusText(message))
self.notebookpanel.OnUpdateValues = self.updateValuesHook
guisizer.Add(item=self.notebookpanel, proportion=1, flag=wx.EXPAND)
# status bar
status_text = _("Enter parameters for '") + self.task.name + "'"
try:
self.task.get_cmd()
self.updateValuesHook()
except ValueError:
self.SetStatusText(status_text)
# buttons
btnsizer = wx.BoxSizer(orient=wx.HORIZONTAL)
# cancel
if sys.platform == 'darwin':
# stock id automatically adds ctrl-c shortcut to close dialog
self.btn_cancel = wx.Button(parent=self.panel, label=_("Close"))
else:
self.btn_cancel = wx.Button(parent=self.panel, id=wx.ID_CLOSE)
self.btn_cancel.SetToolTipString(
_("Close this window without executing the command (Ctrl+Q)"))
btnsizer.Add(
item=self.btn_cancel,
proportion=0,
flag=wx.ALL | wx.ALIGN_CENTER,
border=10)
self.btn_cancel.Bind(wx.EVT_BUTTON, self.OnCancel)
# bind closing to ESC and CTRL+Q
self.Bind(wx.EVT_MENU, self.OnCancel, id=wx.ID_CLOSE)
accelTableList = [(wx.ACCEL_NORMAL, wx.WXK_ESCAPE, wx.ID_CLOSE)]
accelTableList.append((wx.ACCEL_CTRL, ord('Q'), wx.ID_CLOSE))
# TODO: bind Ctrl-t for tile windows here (trac #2004)
if self.get_dcmd is not None: # A callback has been set up
btn_apply = wx.Button(parent=self.panel, id=wx.ID_APPLY)
btn_ok = wx.Button(parent=self.panel, id=wx.ID_OK)
btn_ok.SetDefault()
btnsizer.Add(item=btn_apply, proportion=0,
flag=wx.ALL | wx.ALIGN_CENTER,
border=10)
btnsizer.Add(item=btn_ok, proportion=0,
flag=wx.ALL | wx.ALIGN_CENTER,
border=10)
btn_apply.Bind(wx.EVT_BUTTON, self.OnApply)
btn_ok.Bind(wx.EVT_BUTTON, self.OnOK)
else: # We're standalone
# run
self.btn_run = wx.Button(
parent=self.panel, id=wx.ID_OK, label=_("&Run"))
self.btn_run.SetToolTipString(_("Run the command (Ctrl+R)"))
self.btn_run.SetDefault()
self.btn_run.SetForegroundColour(wx.Colour(35, 142, 35))
btnsizer.Add(item=self.btn_run, proportion=0,
flag=wx.ALL | wx.ALIGN_CENTER,
border=10)
self.btn_run.Bind(wx.EVT_BUTTON, self.OnRun)
self.Bind(wx.EVT_MENU, self.OnRun, id=wx.ID_OK)
accelTableList.append((wx.ACCEL_CTRL, ord('R'), wx.ID_OK))
# copy
if sys.platform == 'darwin':
# stock id automatically adds ctrl-c shortcut to copy command
self.btn_clipboard = wx.Button(parent=self.panel, label=_("Copy"))
else:
self.btn_clipboard = wx.Button(parent=self.panel, id=wx.ID_COPY)
self.btn_clipboard.SetToolTipString(
_("Copy the current command string to the clipboard"))
btnsizer.Add(item=self.btn_clipboard, proportion=0,
flag=wx.ALL | wx.ALIGN_CENTER,
border=10)
self.btn_clipboard.Bind(wx.EVT_BUTTON, self.OnCopy)
# help
self.btn_help = wx.Button(parent=self.panel, id=wx.ID_HELP)
self.btn_help.SetToolTipString(
_("Show manual page of the command (Ctrl+H)"))
self.btn_help.Bind(wx.EVT_BUTTON, self.OnHelp)
self.Bind(wx.EVT_MENU, self.OnHelp, id=wx.ID_HELP)
accelTableList.append((wx.ACCEL_CTRL, ord('H'), wx.ID_HELP))
if self.notebookpanel.notebook.GetPageIndexByName('manual') < 0:
self.btn_help.Hide()
# add help button
btnsizer.Add(
item=self.btn_help,
proportion=0,
flag=wx.ALL | wx.ALIGN_CENTER,
border=10)
guisizer.Add(
item=btnsizer,
proportion=0,
flag=wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT,
border=30)
# abort key bindings
abortId = wx.NewId()
self.Bind(wx.EVT_MENU, self.OnAbort, id=abortId)
accelTableList.append((wx.ACCEL_CTRL, ord('S'), abortId))
# set accelerator table
accelTable = wx.AcceleratorTable(accelTableList)
self.SetAcceleratorTable(accelTable)
if self._giface and self._giface.GetLayerTree():
addLayer = False
for p in self.task.params:
if p.get('age', 'old') == 'new' and \
p.get('prompt', '') in ('raster', 'vector', 'raster_3d'):
addLayer = True
if addLayer:
# add newly created map into layer tree
self.addbox = wx.CheckBox(
parent=self.panel,
label=_('Add created map(s) into layer tree'),
style=wx.NO_BORDER)
self.addbox.SetValue(
UserSettings.Get(
group='cmd',
key='addNewLayer',
subkey='enabled'))
guisizer.Add(item=self.addbox, proportion=0,
flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
border=5)
hasNew = False
for p in self.task.params:
if p.get('age', 'old') == 'new':
hasNew = True
break
if self.get_dcmd is None and hasNew:
# close dialog when command is terminated
self.closebox = wx.CheckBox(
parent=self.panel,
label=_('Close dialog on finish'),
style=wx.NO_BORDER)
self.closebox.SetValue(
UserSettings.Get(
group='cmd',
key='closeDlg',
subkey='enabled'))
self.closebox.SetToolTipString(
_(
"Close dialog when command is successfully finished. "
"Change this settings in Preferences dialog ('Command' tab)."))
guisizer.Add(item=self.closebox, proportion=0,
flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
border=5)
# bindings
self.Bind(wx.EVT_CLOSE, self.OnCancel)
# do layout
# called automatically by SetSizer()
self.panel.SetAutoLayout(True)
self.panel.SetSizerAndFit(guisizer)
sizeFrame = self.GetBestSize()
self.SetMinSize(sizeFrame)
if hasattr(self, "closebox"):
scale = 0.33
else:
scale = 0.50
self.SetSize(
wx.Size(
sizeFrame[0],
sizeFrame[1] + scale * max(
self.notebookpanel.panelMinHeight,
self.notebookpanel.constrained_size[1])))
# thread to update dialog
# create queues
self.requestQ = Queue.Queue()
self.resultQ = Queue.Queue()
self.updateThread = UpdateQThread(
self.notebookpanel, self.requestQ, self.resultQ)
self.Layout()
# keep initial window size limited for small screens
width, height = self.GetSizeTuple()
self.SetSize(wx.Size(min(width, 650),
min(height, 500)))
# fix goutput's pane size (required for Mac OSX)
if self.goutput:
self.goutput.SetSashPosition(int(self.GetSize()[1] * .75))
def updateValuesHook(self, event=None):
"""Update status bar data"""
self.SetStatusText(
' '.join(
[gcmd.DecodeString(each)
if isinstance(each, str) else each
for each in self.notebookpanel.createCmd(
ignoreErrors=True)]))
if event:
event.Skip()
def OnDone(self, event):
"""This function is launched from OnRun() when command is
finished
"""
if hasattr(self, "btn_cancel"):
self.btn_cancel.Enable(True)
if hasattr(self, "btn_clipboard"):
self.btn_clipboard.Enable(True)
if hasattr(self, "btn_help"):
self.btn_help.Enable(True)
if hasattr(self, "btn_run"):
self.btn_run.Enable(True)
if hasattr(self, "get_dcmd") and \
self.get_dcmd is None and \
hasattr(self, "closebox") and \
self.closebox.IsChecked() and \
(event.returncode == 0):
# was closed also when aborted but better is leave it open
wx.FutureCall(2000, self.Close)
def OnMapCreated(self, name, ltype):
"""Map created or changed
:param name: map name
:param ltype: layer type (prompt value)
"""
if hasattr(self, "addbox") and self.addbox.IsChecked():
add = True
else:
add = False
if self._giface:
self._giface.mapCreated.emit(name=name, ltype=ltype, add=add)
def OnOK(self, event):
"""OK button pressed"""
cmd = self.OnApply(event)
if cmd is not None and self.get_dcmd is not None:
self.OnCancel(event)
def OnApply(self, event):
"""Apply the command"""
if self._giface and hasattr(self._giface, "_model"):
cmd = self.createCmd(ignoreErrors=True, ignoreRequired=True)
else:
cmd = self.createCmd()
if cmd is not None and self.get_dcmd is not None:
# return d.* command to layer tree for rendering
self.get_dcmd(cmd, self.layer, {"params": self.task.params,
"flags": self.task.flags},
self)
# echo d.* command to output console
# self.parent.writeDCommand(cmd)
return cmd
def OnRun(self, event):
"""Run the command"""
cmd = self.createCmd()
if not cmd or len(cmd) < 1:
return
ret = 0
if self.standalone or cmd[0][0:2] != "d.":
# Send any non-display command to parent window (probably wxgui.py)
# put to parents switch to 'Command output'
self.notebookpanel.notebook.SetSelectionByName('output')
try:
if self.task.path:
cmd[0] = self.task.path # full path
ret = self._gconsole.RunCmd(cmd, onDone=self.OnDone)
except AttributeError as e:
print >> sys.stderr, "%s: Probably not running in wxgui.py session?" % (
e)
print >>sys.stderr, "parent window is: %s" % (
str(self.parent))
else:
gcmd.Command(cmd)
if ret != 0:
self.notebookpanel.notebook.SetSelection(0)
return
# update buttons status
for btn in (self.btn_run,
self.btn_cancel,
self.btn_clipboard,
self.btn_help):
btn.Enable(False)
def OnAbort(self, event):
"""Abort running command"""
from core.gconsole import wxCmdAbort
event = wxCmdAbort(aborted=True)
wx.PostEvent(self._gconsole, event)
def OnCopy(self, event):
"""Copy the command"""
cmddata = wx.TextDataObject()
# list -> string
cmdlist = self.createCmd(ignoreErrors=True)
# TODO: better protect whitespace with quotes
for i in range(1, len(cmdlist)):
if ' ' in cmdlist[i]:
optname, val = cmdlist[i].split("=", 1)
cmdlist[i] = '%s="%s"' % (optname, val)
cmdstring = ' '.join(cmdlist)
cmddata.SetText(cmdstring)
if wx.TheClipboard.Open():
# wx.TheClipboard.UsePrimarySelection(True)
wx.TheClipboard.SetData(cmddata)
wx.TheClipboard.Close()
self.SetStatusText(_("'%s' copied to clipboard") %
(cmdstring))
def OnCancel(self, event):
"""Cancel button pressed"""
self.MakeModal(False)
self.dialogClosing.emit()
if self.get_dcmd and \
self.parent and \
self.parent.GetName() in ('LayerTree',
'MapWindow'):
# display decorations and
# pressing OK or cancel after setting layer properties
if self.task.name in ['d.barscale', 'd.legend', 'd.northarrow', 'd.histogram', 'd.text', 'd.legend.vect'] \
or len(self.parent.GetLayerInfo(self.layer, key='cmd')) >= 1:
self.Hide()
# canceled layer with nothing set
elif len(self.parent.GetLayerInfo(self.layer, key='cmd')) < 1:
try:
self.parent.Delete(self.layer)
except ValueError:
# happens when closing dialog of a new layer which was
# removed from tree
pass
self.Destroy()
else:
# cancel for non-display commands
self.Destroy()
def OnHelp(self, event):
"""Show manual page (switch to the 'Manual' notebook page)"""
if self.notebookpanel.notebook.GetPageIndexByName('manual') > -1:
self.notebookpanel.notebook.SetSelectionByName('manual')
self.notebookpanel.OnPageChange(None)
if event:
event.Skip()
def createCmd(self, ignoreErrors=False, ignoreRequired=False):
"""Create command string (python list)"""
return self.notebookpanel.createCmd(ignoreErrors=ignoreErrors,
ignoreRequired=ignoreRequired)
class CmdPanel(wx.Panel):
"""A panel containing a notebook dividing in tabs the different
guisections of the GRASS cmd.
"""
def __init__(self, parent, giface, task, id=wx.ID_ANY,
frame=None, *args, **kwargs):
if frame:
self.parent = frame
else:
self.parent = parent
self.task = task
self._giface = giface
wx.Panel.__init__(self, parent, id=id, *args, **kwargs)
self.mapCreated = Signal
self.updateMap = Signal
# Determine tab layout
sections = []
is_section = {}
not_hidden = [
p for p in self.task.params +
self.task.flags if not p.get(
'hidden',
False) == True]
self.label_id = [] # wrap titles on resize
self.Bind(wx.EVT_SIZE, self.OnSize)
for task in not_hidden:
if task.get('required', False) and not task.get('guisection', ''):
# All required go into Main, even if they had defined another
# guisection
task['guisection'] = _('Required')
if task.get('guisection', '') == '':
# Undefined guisections end up into Options
task['guisection'] = _('Optional')
if task['guisection'] not in is_section:
# We do it like this to keep the original order, except for
# Main which goes first
is_section[task['guisection']] = 1
sections.append(task['guisection'])
else:
is_section[task['guisection']] += 1
del is_section
# 'Required' tab goes first, 'Optional' as the last one
for (newidx, content) in [(0, _('Required')),
(len(sections) - 1, _('Optional'))]:
if content in sections:
idx = sections.index(content)
sections[idx:idx + 1] = []
sections[newidx:newidx] = [content]
panelsizer = wx.BoxSizer(orient=wx.VERTICAL)
# build notebook
style = UserSettings.Get(
group='appearance',
key='commandNotebook',
subkey='selection')
if style == 0: # basic top
self.notebook = FormNotebook(self, style=wx.BK_TOP)
self.notebook.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnPageChange)
elif style == 1: # basic left
self.notebook = FormNotebook(self, style=wx.BK_LEFT)
self.notebook.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnPageChange)
elif style == 2: # fancy green
self.notebook = GNotebook(
self, style=globalvar.FNPageStyle | FN.FNB_NO_X_BUTTON)
self.notebook.SetTabAreaColour(globalvar.FNPageColor)
self.notebook.Bind(
FN.EVT_FLATNOTEBOOK_PAGE_CHANGED,
self.OnPageChange)
elif style == 3:
self.notebook = FormListbook(self, style=wx.BK_LEFT)
self.notebook.Bind(wx.EVT_LISTBOOK_PAGE_CHANGED, self.OnPageChange)
self.notebook.Refresh()
tab = {}
tabsizer = {}
for section in sections:
tab[section] = ScrolledPanel(parent=self.notebook)
tab[section].SetScrollRate(10, 10)
tabsizer[section] = wx.BoxSizer(orient=wx.VERTICAL)
#
# flags
#
visible_flags = [
f for f in self.task.flags if not f.get(
'hidden', False) == True]
for f in visible_flags:
# we don't want another help (checkbox appeared in r58783)
if f['name'] == 'help':
continue
which_sizer = tabsizer[f['guisection']]
which_panel = tab[f['guisection']]
# if label is given: description -> tooltip
if f.get('label', '') != '':
title = text_beautify(f['label'])
tooltip = text_beautify(f['description'], width=-1)
else:
title = text_beautify(f['description'])
tooltip = None
title_sizer = wx.BoxSizer(wx.HORIZONTAL)
rtitle_txt = wx.StaticText(parent=which_panel,
label='(' + f['name'] + ')')
chk = wx.CheckBox(
parent=which_panel,
label=title,
style=wx.NO_BORDER)
self.label_id.append(chk.GetId())
if tooltip:
chk.SetToolTipString(tooltip)
chk.SetValue(f.get('value', False))
title_sizer.Add(item=chk, proportion=1,
flag=wx.EXPAND)
title_sizer.Add(item=rtitle_txt, proportion=0,
flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
which_sizer.Add(
item=title_sizer,
proportion=0,
flag=wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT,
border=5)
f['wxId'] = [chk.GetId(), ]
chk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
if self.parent.GetName() == 'MainFrame' and (
self._giface and hasattr(self._giface, "_model")):
parChk = wx.CheckBox(parent=which_panel, id=wx.ID_ANY,
label=_("Parameterized in model"))
parChk.SetName('ModelParam')
parChk.SetValue(f.get('parameterized', False))
if 'wxId' in f:
f['wxId'].append(parChk.GetId())
else:
f['wxId'] = [parChk.GetId()]
parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
which_sizer.Add(item=parChk, proportion=0,
flag=wx.LEFT, border=20)
if f['name'] in ('verbose', 'quiet'):
chk.Bind(wx.EVT_CHECKBOX, self.OnVerbosity)
vq = UserSettings.Get(
group='cmd', key='verbosity', subkey='selection')
if f['name'] == vq:
chk.SetValue(True)
f['value'] = True
if f['name'] == 'overwrite':
value = UserSettings.Get(
group='cmd', key='overwrite', subkey='enabled')
if value: # override only when enabled
f['value'] = value
chk.SetValue(f['value'])
#
# parameters
#
visible_params = [
p for p in self.task.params if not p.get(
'hidden', False) == True]
try:
first_param = visible_params[0]
except IndexError:
first_param = None
for p in visible_params:
which_sizer = tabsizer[p['guisection']]
which_panel = tab[p['guisection']]
# if label is given -> label and description -> tooltip
# otherwise description -> lavel
if p.get('label', '') != '':
title = text_beautify(p['label'])
tooltip = text_beautify(p['description'], width=-1)
else:
title = text_beautify(p['description'])
tooltip = None
prompt = p.get('prompt', '')
# title sizer (description, name, type)
if (len(p.get('values', [])) > 0) and \
p.get('multiple', False) and \
p.get('gisprompt', False) == False and \
p.get('type', '') == 'string':
title_txt = wx.StaticBox(parent=which_panel, id=wx.ID_ANY)
else:
title_sizer = wx.BoxSizer(wx.HORIZONTAL)
title_txt = wx.StaticText(parent=which_panel)
if p['key_desc']:
ltype = ','.join(p['key_desc'])
else:
ltype = p['type']
# red star for required options
if p.get('required', False):
required_txt = wx.StaticText(parent=which_panel, label="*")
required_txt.SetForegroundColour(wx.RED)
required_txt.SetToolTipString(_("This option is required"))
else:
required_txt = wx.StaticText(parent=which_panel, label="")
rtitle_txt = wx.StaticText(
parent=which_panel,
label='(' + p['name'] + '=' + ltype + ')')
title_sizer.Add(item=title_txt, proportion=0,
flag=wx.LEFT | wx.TOP | wx.EXPAND, border=5)
title_sizer.Add(item=required_txt, proportion=1,
flag=wx.EXPAND, border=0)
title_sizer.Add(
item=rtitle_txt,
proportion=0,
flag=wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP,
border=5)
which_sizer.Add(item=title_sizer, proportion=0,
flag=wx.EXPAND)
self.label_id.append(title_txt.GetId())
# title expansion
if p.get('multiple', False) and len(p.get('values', '')) == 0:
title = _("[multiple]") + " " + title
if p.get('value', '') == '':
p['value'] = p.get('default', '')
if (len(p.get('values', [])) > 0):
valuelist = map(str, p.get('values', []))
valuelist_desc = map(unicode, p.get('values_desc', []))
required_text = "*" if p.get('required', False) else ""
if p.get('multiple', False) and \
p.get('gisprompt', False) == False and \
p.get('type', '') == 'string':
title_txt.SetLabel(
" %s:%s (%s=%s) " %
(title, required_text, p['name'], p['type']))
stSizer = wx.StaticBoxSizer(
box=title_txt, orient=wx.VERTICAL)
if valuelist_desc:
hSizer = wx.FlexGridSizer(cols=1, vgap=1)
else:
hSizer = wx.FlexGridSizer(cols=6, vgap=1, hgap=1)
isEnabled = {}
# copy default values
if p['value'] == '':
p['value'] = p.get('default', '')
for defval in p.get('value', '').split(','):
isEnabled[defval] = 'yes'
# for multi checkboxes, this is an array of all wx IDs
# for each individual checkbox
p['wxId'] = list()
idx = 0
for val in valuelist:
try:
label = valuelist_desc[idx]
except IndexError:
label = val
chkbox = wx.CheckBox(parent=which_panel,
label=text_beautify(label))
p['wxId'].append(chkbox.GetId())
if val in isEnabled:
chkbox.SetValue(True)
hSizer.Add(item=chkbox, proportion=0)
chkbox.Bind(wx.EVT_CHECKBOX, self.OnUpdateSelection)
chkbox.Bind(wx.EVT_CHECKBOX, self.OnCheckBoxMulti)
idx += 1
stSizer.Add(item=hSizer, proportion=0,
flag=wx.ADJUST_MINSIZE | wx.ALL, border=1)
which_sizer.Add(
item=stSizer,
proportion=0,
flag=wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT,
border=5)
elif p.get('gisprompt', False) is False:
if len(valuelist) == 1: # -> textctrl
title_txt.SetLabel(
"%s (%s %s):" %
(title, _('valid range'),
str(valuelist[0])))
if p.get('type', '') == 'integer' and \
not p.get('multiple', False):
# for multiple integers use textctrl instead of
# spinsctrl
try:
minValue, maxValue = map(
int, valuelist[0].rsplit('-', 1))
except ValueError:
minValue = -1e6
maxValue = 1e6
txt2 = SpinCtrl(
parent=which_panel,
id=wx.ID_ANY,
size=globalvar.DIALOG_SPIN_SIZE,
min=minValue,
max=maxValue)
style = wx.BOTTOM | wx.LEFT
else:
txt2 = wx.TextCtrl(
parent=which_panel, value=p.get(
'default', ''))
style = wx.EXPAND | wx.BOTTOM | wx.LEFT
value = self._getValue(p)
# parameter previously set
if value:
if isinstance(txt2, SpinCtrl):
txt2.SetValue(int(value))
else:
txt2.SetValue(value)
which_sizer.Add(item=txt2, proportion=0,
flag=style, border=5)
p['wxId'] = [txt2.GetId(), ]
txt2.Bind(wx.EVT_TEXT, self.OnSetValue)
else:
title_txt.SetLabel(title + ':')
value = self._getValue(p)
if p['name'] in ('icon', 'icon_area', 'icon_line'): # symbols
bitmap = wx.Bitmap(
os.path.join(
globalvar.SYMBDIR,
value) + '.png')
bb = wx.BitmapButton(
parent=which_panel, id=wx.ID_ANY, bitmap=bitmap)
iconLabel = wx.StaticText(
parent=which_panel, id=wx.ID_ANY)
iconLabel.SetLabel(value)
p['value'] = value
p['wxId'] = [bb.GetId(), iconLabel.GetId()]
bb.Bind(wx.EVT_BUTTON, self.OnSetSymbol)
this_sizer = wx.BoxSizer(wx.HORIZONTAL)
this_sizer.Add(
item=bb, proportion=0, flag=wx.ADJUST_MINSIZE |
wx.BOTTOM | wx.LEFT, border=5)
this_sizer.Add(
item=iconLabel,
proportion=0,
flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.ALIGN_CENTER_VERTICAL,
border=5)
which_sizer.Add(item=this_sizer, proportion=0,
flag=wx.ADJUST_MINSIZE, border=0)
else:
# list of values (combo)
cb = wx.ComboBox(
parent=which_panel, id=wx.ID_ANY, value=p.get(
'default', ''),
size=globalvar.DIALOG_COMBOBOX_SIZE,
choices=valuelist, style=wx.CB_DROPDOWN)
if value:
cb.SetValue(value) # parameter previously set
which_sizer.Add(
item=cb, proportion=0, flag=wx.ADJUST_MINSIZE |
wx.BOTTOM | wx.LEFT, border=5)
p['wxId'] = [cb.GetId(), ]
cb.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
cb.Bind(wx.EVT_TEXT, self.OnSetValue)
if p.get('guidependency', ''):
cb.Bind(
wx.EVT_COMBOBOX, self.OnUpdateSelection)
# text entry
if (p.get('type', 'string') in ('string', 'integer', 'float')
and len(p.get('values', [])) == 0
and p.get('gisprompt', False) == False
and p.get('prompt', '') != 'color'):
title_txt.SetLabel(title + ':')
p['wxId'] = []
if p.get('multiple', False) or \
p.get('type', 'string') == 'string' or \
len(p.get('key_desc', [])) > 1:
win = wx.TextCtrl(
parent=which_panel, value=p.get(
'default', ''))
value = self._getValue(p)
if value:
# parameter previously set
win.SetValue(str(value))
win.Bind(wx.EVT_TEXT, self.OnSetValue)
style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
if p.get('name', '') == 'font':
font_btn = wx.Button(parent=which_panel, label=_("Select font"))
font_btn.Bind(wx.EVT_BUTTON, self.OnSelectFont)
font_sizer = wx.BoxSizer(wx.HORIZONTAL)
font_sizer.Add(item=win, proportion=1,
flag=style, border=5)
font_sizer.Add(item=font_btn, proportion=0,
flag=style, border=5)
which_sizer.Add(item=font_sizer, proportion=0,
flag=style, border=5)
p['wxId'].append(font_btn.GetId())
else:
which_sizer.Add(item=win, proportion=0,
flag=style, border=5)
elif p.get('type', '') == 'integer':
minValue = -1e9
maxValue = 1e9
value = self._getValue(p)
win = SpinCtrl(
parent=which_panel,
value=p.get(
'default',
''),
size=globalvar.DIALOG_SPIN_SIZE,
min=minValue,
max=maxValue)
if value:
win.SetValue(int(value)) # parameter previously set
win.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
style = wx.BOTTOM | wx.LEFT | wx.RIGHT
which_sizer.Add(item=win, proportion=0,
flag=style, border=5)
else: # float
win = wx.TextCtrl(
parent=which_panel, value=p.get(
'default', ''), validator=FloatValidator())
style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
which_sizer.Add(item=win, proportion=0,
flag=style, border=5)
value = self._getValue(p)
if value:
win.SetValue(str(value)) # parameter previously set
win.Bind(wx.EVT_TEXT, self.OnSetValue)
p['wxId'].append(win.GetId())
#
# element selection tree combobox (maps, icons, regions, etc.)
#
if p.get('gisprompt', False):
title_txt.SetLabel(title + ':')
# GIS element entry
if p.get('prompt', '') not in ('color',
'cat',
'cats',
'subgroup',
'sigfile',
'separator',
'dbdriver',
'dbname',
'dbtable',
'dbcolumn',
'layer',
'location',
'mapset',
'dbase',
'coords',
'file',
'dir',
'colortable',
'barscale',
'northarrow',
'datasource',
'datasource_layer'):
multiple = p.get('multiple', False)
if p.get('age', '') == 'new':
mapsets = [grass.gisenv()['MAPSET'], ]
else:
mapsets = None
if self.task.name in ('r.proj', 'v.proj') \
and p.get('name', '') == 'input':
selection = gselect.ProjSelect(
parent=which_panel, isRaster=self.task.name == 'r.proj')
p['wxId'] = [selection.GetId(), ]
selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
else:
elem = p.get('element', None)
# hack for t.* modules
if elem in ('stds', 'map'):
orig_elem = elem
type_param = self.task.get_param(
'type', element='name', raiseError=False)
if type_param:
elem = type_param.get('default', None)
# for t.(un)register:
maps_param = self.task.get_param(
'maps', element='name', raiseError=False)
if maps_param and orig_elem == 'stds':
element_dict = {
'raster': 'strds', 'vector': 'stvds', 'raster_3d': 'str3ds'}
elem = element_dict[
type_param.get('default')]
extraItems = None
if self._giface:
if hasattr(self._giface, "_model"):
extraItems = {
_('Graphical Modeler'): self._giface.GetLayerList(
p.get('prompt'))}
else:
layers = self._giface.GetLayerList()
if len(layers) > 0:
mapList = []
extraItems = {_('Map Display'): mapList}
for layer in layers:
if layer.type != p.get('prompt'):
continue
mapList.append(str(layer))
selection = gselect.Select(
parent=which_panel, id=wx.ID_ANY,
size=globalvar.DIALOG_GSELECT_SIZE, type=elem,
multiple=multiple, nmaps=len(
p.get('key_desc', [])),
mapsets=mapsets, fullyQualified=p.get(
'age', 'old') == 'old', extraItems=extraItems)
value = self._getValue(p)
if value:
selection.SetValue(value)
formatSelector = True
# A gselect.Select is a combobox with two children: a textctl and a popupwindow;
# we target the textctl here
textWin = selection.GetTextCtrl()
if globalvar.CheckWxVersion([3]):
p['wxId'] = [selection.GetId(), ]
else:
p['wxId'] = [textWin.GetId(), ]
if prompt != 'vector':
self.FindWindowById(
p['wxId'][0]).Bind(
wx.EVT_TEXT, self.OnSetValue)
if prompt == 'vector':
win = self.FindWindowById(p['wxId'][0])
# handlers should be bound in this order
# OnUpdateSelection depends on calling OnSetValue first
# which is bad
win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
win.Bind(wx.EVT_TEXT, self.OnSetValue)
# if formatSelector and p.get('age', 'old') == 'old':
# # OGR supported (read-only)
# self.hsizer = wx.BoxSizer(wx.HORIZONTAL)
# self.hsizer.Add(item = selection,
# flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
# border = 5)
# # format (native / ogr)
# rbox = wx.RadioBox(parent = which_panel, id = wx.ID_ANY,
# label = " %s " % _("Format"),
# style = wx.RA_SPECIFY_ROWS,
# choices = [_("Native / Linked OGR"), _("Direct OGR")])
# if p.get('value', '').lower().rfind('@ogr') > -1:
# rbox.SetSelection(1)
# rbox.SetName('VectorFormat')
# rbox.Bind(wx.EVT_RADIOBOX, self.OnVectorFormat)
# self.hsizer.Add(item = rbox,
# flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
# wx.RIGHT | wx.ALIGN_TOP,
# border = 5)
# ogrSelection = gselect.GdalSelect(parent = self, panel = which_panel, ogr = True,
# default = 'dir',
# exclude = ['file'])
# self.Bind(gselect.EVT_GDALSELECT, self.OnUpdateSelection)
# self.Bind(gselect.EVT_GDALSELECT, self.OnSetValue)
# ogrSelection.SetName('OgrSelect')
# ogrSelection.Hide()
# which_sizer.Add(item = self.hsizer, proportion = 0)
# p['wxId'].append(rbox.GetId())
# p['wxId'].append(ogrSelection.GetId())
# for win in ogrSelection.GetDsnWin():
# p['wxId'].append(win.GetId())
# else:
which_sizer.Add(
item=selection,
proportion=0,
flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
border=5)
elif prompt == 'group':
win = self.FindWindowById(p['wxId'][0])
win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
win.Bind(wx.EVT_TEXT, self.OnSetValue)
which_sizer.Add(
item=selection,
proportion=0,
flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
border=5)
else:
if prompt in ('stds', 'strds', 'stvds', 'str3ds'):
showButton = True
try:
# if matplotlib is there
from timeline import frame
showButton = True
except ImportError:
showButton = False
else:
showButton = False
if showButton:
iconTheme = UserSettings.Get(
group='appearance', key='iconTheme', subkey='type')
bitmap = wx.Bitmap(
os.path.join(
globalvar.ICONDIR, iconTheme,
'map-info.png'))
bb = wx.BitmapButton(
parent=which_panel, bitmap=bitmap)
bb.Bind(wx.EVT_BUTTON, self.OnTimelineTool)
bb.SetToolTipString(
_("Show graphical representation of temporal extent of dataset(s) ."))
p['wxId'].append(bb.GetId())
hSizer = wx.BoxSizer(wx.HORIZONTAL)
hSizer.Add(
item=selection,
proportion=0,
flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
border=5)
hSizer.Add(
item=bb,
proportion=0,
flag=wx.EXPAND | wx.BOTTOM | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
border=5)
which_sizer.Add(hSizer)
else:
which_sizer.Add(
item=selection,
proportion=0,
flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
border=5)
# subgroup
elif prompt == 'subgroup':
selection = gselect.SubGroupSelect(parent=which_panel)
p['wxId'] = [selection.GetId()]
selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
selection.Bind(wx.EVT_TEXT, self.OnSetValue)
which_sizer.Add(
item=selection,
proportion=0,
flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
border=5)
# sigrature file
elif prompt == 'sigfile':
selection = gselect.SignatureSelect(
parent=which_panel, element=p.get('element', 'sig'))
p['wxId'] = [selection.GetId()]
selection.Bind(wx.EVT_TEXT, self.OnSetValue)
selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
which_sizer.Add(
item=selection,
proportion=0,
flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
border=5)
# separator
elif prompt == 'separator':
win = gselect.SeparatorSelect(parent=which_panel)
value = self._getValue(p)
win.SetValue(value)
p['wxId'] = [win.GetId()]
win.Bind(wx.EVT_TEXT, self.OnSetValue)
win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
which_sizer.Add(
item=win,
proportion=0,
flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
border=5)
# layer, dbdriver, dbname, dbcolumn, dbtable entry
elif prompt in ('dbdriver',
'dbname',
'dbtable',
'dbcolumn',
'layer',
'location',
'mapset',
'dbase'):
if p.get('multiple', 'no') == 'yes':
win = wx.TextCtrl(
parent=which_panel, value=p.get(
'default', ''), size=globalvar.DIALOG_TEXTCTRL_SIZE)
win.Bind(wx.EVT_TEXT, self.OnSetValue)
else:
value = self._getValue(p)
if prompt == 'layer':
if p.get('element', 'layer') == 'layer_all':
all = True
else:
all = False
if p.get('age', 'old') == 'old':
win = gselect.LayerSelect(parent=which_panel,
all=all,
default=p['default'])
win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
win.Bind(wx.EVT_TEXT, self.OnSetValue)
win.SetValue(
str(value)) # default or previously set value
else:
win = SpinCtrl(
parent=which_panel, id=wx.ID_ANY, min=1,
max=100, initial=int(p['default']))
win.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
win.SetValue(
int(value)) # default or previously set value
p['wxId'] = [win.GetId()]
elif prompt == 'dbdriver':
win = gselect.DriverSelect(
parent=which_panel, choices=p.get(
'values', []),
value=value)
win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
elif prompt == 'dbname':
win = gselect.DatabaseSelect(parent=which_panel,
value=value)
win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
win.Bind(wx.EVT_TEXT, self.OnSetValue)
elif prompt == 'dbtable':
if p.get('age', 'old') == 'old':
win = gselect.TableSelect(parent=which_panel)
win.Bind(
wx.EVT_COMBOBOX, self.OnUpdateSelection)
win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
else:
win = wx.TextCtrl(
parent=which_panel, value=p.get(
'default', ''),
size=globalvar.DIALOG_TEXTCTRL_SIZE)
win.Bind(wx.EVT_TEXT, self.OnSetValue)
elif prompt == 'dbcolumn':
win = gselect.ColumnSelect(
parent=which_panel, value=value, param=p,
multiple=p.get('multiple', False))
# A gselect.ColumnSelect is a combobox
# with two children: a textctl and a
# popupwindow; we target the textctl here
textWin = win.GetTextCtrl()
p['wxId'] = [textWin.GetId(), ]
textWin.Bind(wx.EVT_TEXT, self.OnSetValue)
win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
elif prompt == 'location':
win = gselect.LocationSelect(parent=which_panel,
value=value)
win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
elif prompt == 'mapset':
if p.get('age', 'old') == 'old':
new = False
else:
new = True
win = gselect.MapsetSelect(
parent=which_panel, value=value, new=new,
multiple=p.get('multiple', False))
textWin = win.GetTextCtrl()
p['wxId'] = [textWin.GetId(), win.GetId()]
textWin.Bind(wx.EVT_TEXT, self.OnSetValue)
win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
elif prompt == 'dbase':
win = gselect.DbaseSelect(
parent=which_panel, changeCallback=self.OnSetValue)
win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
p['wxId'] = [win.GetChildren()[1].GetId()]
if 'wxId' not in p:
try:
p['wxId'] = [win.GetId(), ]
except AttributeError:
pass
flags = wx.BOTTOM | wx.LEFT | wx.RIGHT
if prompt == 'dbname':
flags |= wx.EXPAND
which_sizer.Add(item=win, proportion=0,
flag=flags, border=5)
# color entry
elif prompt == 'color':
default_color = (200, 200, 200)
label_color = _("Select Color")
if p.get('default', '') != '':
default_color, label_color = utils.color_resolve(p[
'default'])
if p.get('value', '') != '' and p.get(
'value', '') != 'none': # parameter previously set
if not p.get('multiple', False):
default_color, label_color = utils.color_resolve(p[
'value'])
if p.get(
'element', '') == 'color_none' or p.get(
'multiple', False):
this_sizer = wx.BoxSizer(orient=wx.HORIZONTAL)
else:
this_sizer = which_sizer
colorSize = 150
# For color selectors, this is a three-member array, holding the IDs of
# the color picker, the text control for multiple colors (or None),
# and either a "transparent" checkbox or None
p['wxId'] = [None] * 3
if p.get('multiple', False):
txt = wx.TextCtrl(parent=which_panel, id=wx.ID_ANY)
this_sizer.Add(
item=txt,
proportion=1,
flag=wx.ADJUST_MINSIZE | wx.LEFT | wx.TOP,
border=5)
txt.Bind(wx.EVT_TEXT, self.OnSetValue)
if p.get('value', ''):
txt.SetValue(p['value'])
colorSize = 40
label_color = ''
p['wxId'][1] = txt.GetId()
which_sizer.Add(
this_sizer, flag=wx.EXPAND | wx.RIGHT, border=5)
btn_colour = csel.ColourSelect(
parent=which_panel, id=wx.ID_ANY, label=label_color,
colour=default_color, pos=wx.DefaultPosition,
size=(colorSize, 32))
this_sizer.Add(
item=btn_colour,
proportion=0,
flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT,
border=5)
btn_colour.Bind(csel.EVT_COLOURSELECT, self.OnColorChange)
p['wxId'][0] = btn_colour.GetId()
if p.get('element', '') == 'color_none':
none_check = wx.CheckBox(
which_panel, wx.ID_ANY, _("Transparent"))
if p.get('value', '') == "none":
none_check.SetValue(True)
else:
none_check.SetValue(False)
this_sizer.Add(
item=none_check, proportion=0,
flag=wx.ADJUST_MINSIZE | wx.LEFT | wx.RIGHT | wx.TOP,
border=5)
which_sizer.Add(this_sizer)
none_check.Bind(wx.EVT_CHECKBOX, self.OnColorChange)
p['wxId'][2] = none_check.GetId()
# file selector
elif p.get('prompt', '') != 'color' and p.get('prompt', '') == 'file':
if p.get('age', 'new') == 'new':
fmode = wx.FD_SAVE
else:
fmode = wx.FD_OPEN
# check wildcard
try:
fExt = os.path.splitext(
p.get('key_desc', ['*.*'])[0])[1]
except:
fExt = None
if not fExt:
fMask = '*'
else:
fMask = '%s files (*%s)|*%s|Files (*)|*' % (
fExt[1:].upper(), fExt, fExt)
fbb = filebrowse.FileBrowseButton(
parent=which_panel,
id=wx.ID_ANY,
fileMask=fMask,
size=globalvar.DIALOG_GSELECT_SIZE,
labelText='',
dialogTitle=_('Choose %s') %
p.get(
'description',
_('file')).lower(),
buttonText=_('Browse'),
startDirectory=os.getcwd(),
fileMode=fmode,
changeCallback=self.OnSetValue)
value = self._getValue(p)
if value:
fbb.SetValue(value) # parameter previously set
which_sizer.Add(item=fbb, proportion=0,
flag=wx.EXPAND | wx.RIGHT, border=5)
# A file browse button is a combobox with two children:
# a textctl and a button;
# we have to target the button here
p['wxId'] = [fbb.GetChildren()[1].GetId()]
if p.get(
'age', 'new') == 'old' and p.get(
'prompt', '') == 'file' and p.get(
'element', '') == 'file' and UserSettings.Get(
group='cmd', key='interactiveInput', subkey='enabled'):
# widget for interactive input
ifbb = wx.TextCtrl(parent=which_panel, id=wx.ID_ANY,
style=wx.TE_MULTILINE,
size=(-1, 75))
if p.get('value', '') and os.path.isfile(p['value']):
f = open(p['value'])
ifbb.SetValue(''.join(f.readlines()))
f.close()
ifbb.Bind(wx.EVT_TEXT, self.OnFileText)
btnLoad = wx.Button(
parent=which_panel, id=wx.ID_ANY, label=_("&Load"))
btnLoad.SetToolTipString(
_("Load and edit content of a file"))
btnLoad.Bind(wx.EVT_BUTTON, self.OnFileLoad)
btnSave = wx.Button(
parent=which_panel, id=wx.ID_ANY, label=_("&Save as"))
btnSave.SetToolTipString(
_("Save content to a file for further use"))
btnSave.Bind(wx.EVT_BUTTON, self.OnFileSave)
fileContentLabel = wx.StaticText(
parent=which_panel, id=wx.ID_ANY,
label=_('or enter values directly:'))
fileContentLabel.SetToolTipString(
_("Enter file content directly instead of specifying"
" a file."
" Temporary file will be automatically created."))
which_sizer.Add(
item=fileContentLabel,
proportion=0,
flag=wx.EXPAND | wx.RIGHT | wx.LEFT | wx.BOTTOM,
border=5)
which_sizer.Add(
item=ifbb,
proportion=1,
flag=wx.EXPAND | wx.RIGHT | wx.LEFT,
border=5)
btnSizer = wx.BoxSizer(wx.HORIZONTAL)
btnSizer.Add(item=btnLoad, proportion=0,
flag=wx.ALIGN_RIGHT | wx.RIGHT, border=10)
btnSizer.Add(item=btnSave, proportion=0,
flag=wx.ALIGN_RIGHT)
which_sizer.Add(
item=btnSizer,
proportion=0,
flag=wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP,
border=5)
p['wxId'].append(ifbb.GetId())
p['wxId'].append(btnLoad.GetId())
p['wxId'].append(btnSave.GetId())
# directory selector
elif p.get('prompt', '') != 'color' and p.get('prompt', '') == 'dir':
fbb = filebrowse.DirBrowseButton(
parent=which_panel,
id=wx.ID_ANY,
size=globalvar.DIALOG_GSELECT_SIZE,
labelText='',
dialogTitle=_('Choose %s') %
p.get(
'description',
_('Directory')),
buttonText=_('Browse'),
startDirectory=os.getcwd(),
changeCallback=self.OnSetValue)
value = self._getValue(p)
if value:
fbb.SetValue(value) # parameter previously set
which_sizer.Add(item=fbb, proportion=0,
flag=wx.EXPAND | wx.RIGHT, border=5)
# A file browse button is a combobox with two children:
# a textctl and a button;
# we have to target the button here
p['wxId'] = [fbb.GetChildren()[1].GetId()]
# interactive inserting of coordinates from map window
elif prompt == 'coords':
# interactive inserting if layer manager is accessible
if self._giface:
win = gselect.CoordinatesSelect(
parent=which_panel, giface=self._giface, multiple=p.get(
'multiple', False), param=p)
p['wxId'] = [win.GetTextWin().GetId()]
win.GetTextWin().Bind(wx.EVT_TEXT, self.OnSetValue)
# bind closing event because destructor is not working
# properly
if hasattr(self.parent, 'dialogClosing'):
self.parent.dialogClosing.connect(win.OnClose)
# normal text field
else:
win = wx.TextCtrl(parent=which_panel)
p['wxId'] = [win.GetId()]
win.Bind(wx.EVT_TEXT, self.OnSetValue)
which_sizer.Add(
item=win,
proportion=0,
flag=wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT,
border=5)
elif prompt in ('cat', 'cats'):
# interactive selection of vector categories if layer
# manager is accessible
if self._giface:
win = gselect.VectorCategorySelect(
parent=which_panel, giface=self._giface, task=self.task)
p['wxId'] = [win.GetTextWin().GetId()]
win.GetTextWin().Bind(wx.EVT_TEXT, self.OnSetValue)
# bind closing event because destructor is not working
# properly
if hasattr(self.parent, 'dialogClosing'):
self.parent.dialogClosing.connect(win.OnClose)
# normal text field
else:
win = wx.TextCtrl(parent=which_panel)
value = self._getValue(p)
win.SetValue(value)
p['wxId'] = [win.GetId()]
win.Bind(wx.EVT_TEXT, self.OnSetValue)
which_sizer.Add(
item=win,
proportion=0,
flag=wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT,
border=5)
elif prompt in ('colortable', 'barscale', 'northarrow'):
if prompt == 'colortable':
cb = ColorTablesComboBox(
parent=which_panel, value=p.get('default', ''),
size=globalvar.DIALOG_COMBOBOX_SIZE,
choices=valuelist)
elif prompt == 'barscale':
cb = BarscalesComboBox(
parent=which_panel, value=p.get('default', ''),
size=globalvar.DIALOG_COMBOBOX_SIZE,
choices=valuelist)
elif prompt == 'northarrow':
cb = NArrowsComboBox(
parent=which_panel, value=p.get('default', ''),
size=globalvar.DIALOG_COMBOBOX_SIZE,
choices=valuelist)
value = self._getValue(p)
if value:
cb.SetValue(value) # parameter previously set
which_sizer.Add(
item=cb,
proportion=0,
flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT,
border=5)
p['wxId'] = [cb.GetId(), cb.GetTextCtrl().GetId()]
cb.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
cb.GetTextCtrl().Bind(wx.EVT_TEXT, self.OnSetValue)
if p.get('guidependency', ''):
cb.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
elif prompt == 'datasource':
win = gselect.GdalSelect(parent=parent, panel=which_panel,
ogr=True)
win.Bind(wx.EVT_TEXT, self.OnSetValue)
win.Bind(wx.EVT_CHOICE, self.OnSetValue)
p['wxId'] = [
win.GetId(),
win.fileWidgets['browse'].GetChildren()[1].GetId(),
win.dirWidgets['browse'].GetChildren()[1].GetId(),
win.dbWidgets['choice'].GetId()]
value = self._getValue(p)
if value:
win.fileWidgets['browse'].GetChildren()[1].SetValue(
value) # parameter previously set
which_sizer.Add(item=win, proportion=0,
flag=wx.EXPAND)
elif prompt == 'datasource_layer':
self.win1 = LayersList(
parent=which_panel,
columns=[
_('Layer id'),
_('Layer name'),
_('Feature type'),
_('Projection match')])
which_sizer.Add(item=self.win1, proportion=0,
flag=wx.EXPAND | wx.ALL, border=3)
porf = self.task.get_param(
'input', element='name', raiseError=False)
if porf and 'wxId' in porf:
winDataSource = self.FindWindowById(porf['wxId'][0])
winDataSource.reloadDataRequired.connect(
lambda listData: self.win1.LoadData(
listData, False))
p['wxId'] = [self.win1.GetId()]
def OnCheckItem(index, flag):
layers = list()
for layer, match, listId in self.win1.GetLayers():
layers.append(layer)
porf = self.task.get_param(
'layer', element='name', raiseError=False)
porf['value'] = ','.join(layers)
self.OnUpdateValues() # TODO: replace by signal
self.win1.OnCheckItem = OnCheckItem
if self.parent.GetName() == 'MainFrame' and (
self._giface and hasattr(self._giface, "_model")):
parChk = wx.CheckBox(parent=which_panel, id=wx.ID_ANY,
label=_("Parameterized in model"))
parChk.SetName('ModelParam')
parChk.SetValue(p.get('parameterized', False))
if 'wxId' in p:
p['wxId'].append(parChk.GetId())
else:
p['wxId'] = [parChk.GetId()]
parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
which_sizer.Add(item=parChk, proportion=0,
flag=wx.LEFT, border=20)
if title_txt is not None:
# create tooltip if given
if len(p['values_desc']) > 0:
if tooltip:
tooltip += 2 * os.linesep
else:
tooltip = ''
if len(p['values']) == len(p['values_desc']):
for i in range(len(p['values'])):
tooltip += p['values'][i] + ': ' + \
p['values_desc'][i] + os.linesep
tooltip.strip(os.linesep)
if tooltip:
title_txt.SetToolTipString(tooltip)
if p == first_param:
if 'wxId' in p and len(p['wxId']) > 0:
win = self.FindWindowById(p['wxId'][0])
win.SetFocus()
#
# set widget relations for OnUpdateSelection
#
pMap = None
pLayer = []
pDriver = None
pDatabase = None
pTable = None
pColumn = []
pGroup = None
pSubGroup = None
pSigFile = []
pDbase = None
pLocation = None
pMapset = None
for p in self.task.params:
guidep = p.get('guidependency', '')
if guidep:
# fixed options dependency defined
options = guidep.split(',')
for opt in options:
pOpt = self.task.get_param(
opt, element='name', raiseError=False)
if pOpt and id:
if 'wxId-bind' not in p:
p['wxId-bind'] = list()
p['wxId-bind'] += pOpt['wxId']
continue
if p.get('gisprompt', False) == False:
continue
prompt = p.get('prompt', '')
if prompt in ('raster', 'vector'):
name = p.get('name', '')
if name in ('map', 'input'):
pMap = p
elif prompt == 'layer':
pLayer.append(p)
elif prompt == 'dbcolumn':
pColumn.append(p)
elif prompt == 'dbdriver':
pDriver = p
elif prompt == 'dbname':
pDatabase = p
elif prompt == 'dbtable':
pTable = p
elif prompt == 'group':
pGroup = p
elif prompt == 'subgroup':
pSubGroup = p
elif prompt == 'sigfile':
pSigFile.append(p)
elif prompt == 'dbase':
pDbase = p
elif prompt == 'location':
pLocation = p
elif prompt == 'mapset':
pMapset = p
# collect ids
pColumnIds = []
for p in pColumn:
pColumnIds += p['wxId']
pLayerIds = []
for p in pLayer:
pLayerIds += p['wxId']
pSigFileIds = []
for p in pSigFile:
pSigFileIds += p['wxId']
# set wxId-bindings
if pMap:
pMap['wxId-bind'] = []
if pLayer:
pMap['wxId-bind'] += pLayerIds
pMap['wxId-bind'] += copy.copy(pColumnIds)
if pLayer:
for p in pLayer:
p['wxId-bind'] = copy.copy(pColumnIds)
if pDriver and pTable:
pDriver['wxId-bind'] = pTable['wxId']
if pDatabase and pTable:
pDatabase['wxId-bind'] = pTable['wxId']
if pTable and pColumnIds:
pTable['wxId-bind'] = pColumnIds
if pGroup and pSubGroup:
if pSigFile:
pGroup['wxId-bind'] = pSigFileIds + pSubGroup['wxId']
pSubGroup['wxId-bind'] = pSigFileIds
else:
pGroup['wxId-bind'] = pSubGroup['wxId']
if pDbase and pLocation:
pDbase['wxId-bind'] = pLocation['wxId']
if pLocation and pMapset:
pLocation['wxId-bind'] = pMapset['wxId']
if pLocation and pMapset and pMap:
# pLocation['wxId-bind'] += pMap['wxId']
pMapset['wxId-bind'] = pMap['wxId']
#
# determine panel size
#
maxsizes = (0, 0)
for section in sections:
tab[section].SetSizer(tabsizer[section])
tabsizer[section].Fit(tab[section])
tab[section].Layout()
minsecsizes = tabsizer[section].GetSize()
maxsizes = map(lambda x: max(maxsizes[x], minsecsizes[x]), (0, 1))
# TODO: be less arbitrary with these 600
self.panelMinHeight = 100
self.constrained_size = (
min(600, maxsizes[0]) + 25, min(400, maxsizes[1]) + 25)
for section in sections:
tab[section].SetMinSize(
(self.constrained_size[0], self.panelMinHeight))
# add pages to notebook
imageList = wx.ImageList(16, 16)
self.notebook.AssignImageList(imageList)
for section in sections:
self.notebook.AddPage(
page=tab[section],
text=section, name=section)
index = self.AddBitmapToImageList(section, imageList)
if index >= 0:
self.notebook.SetPageImage(section, index)
# are we running from command line?
# add 'command output' tab regardless standalone dialog
if self.parent.GetName() == "MainFrame" and self.parent.get_dcmd is None:
from core.gconsole import GConsole, EVT_CMD_RUN, EVT_CMD_DONE
from gui_core.goutput import GConsoleWindow
self._gconsole = GConsole(
guiparent=self.notebook, giface=self._giface)
self.goutput = GConsoleWindow(
parent=self.notebook,
gconsole=self._gconsole,
margin=False)
self._gconsole.Bind(
EVT_CMD_RUN, lambda event: self._switchPageHandler(
event=event, notification=Notification.MAKE_VISIBLE))
self._gconsole.Bind(
EVT_CMD_DONE, lambda event: self._switchPageHandler(
event=event, notification=Notification.RAISE_WINDOW))
self.outpage = self.notebook.AddPage(
page=self.goutput, text=_("Command output"), name='output')
else:
self.goutput = None
self._gconsole = None
self.manualTab = HelpPanel(
parent=self.notebook,
command=self.task.get_name())
if not self.manualTab.GetFile():
self.manualTab.Hide()
else:
self.notebook.AddPage(
page=self.manualTab,
text=_("Manual"),
name='manual')
index = self.AddBitmapToImageList(
section='manual', imageList=imageList)
if index >= 0:
self.notebook.SetPageImage('manual', index)
if self.manualTab.IsLoaded():
self.manualTab.SetMinSize(
(self.constrained_size[0], self.panelMinHeight))
self.notebook.SetSelection(0)
panelsizer.Add(item=self.notebook, proportion=1, flag=wx.EXPAND)
self.SetSizer(panelsizer)
panelsizer.Fit(self.notebook)
self.Bind(EVT_DIALOG_UPDATE, self.OnUpdateDialog)
def _getValue(self, p):
"""Get value or default value of given parameter
:param p: parameter directory
"""
if p.get('value', '') != '':
return p['value']
return p.get('default', '')
def OnFileLoad(self, event):
"""Load file to interactive input"""
me = event.GetId()
win = dict()
for p in self.task.params:
if 'wxId' in p and me in p['wxId']:
win['file'] = self.FindWindowById(p['wxId'][0])
win['text'] = self.FindWindowById(p['wxId'][1])
break
if not win:
return
path = win['file'].GetValue()
if not path:
gcmd.GMessage(parent=self,
message=_("Nothing to load."))
return
data = ''
try:
f = open(path, "r")
except IOError as e:
gcmd.GError(parent=self, showTraceback=False,
message=_("Unable to load file.\n\nReason: %s") % e)
return
try:
data = f.read()
finally:
f.close()
win['text'].SetValue(data)
def OnFileSave(self, event):
"""Save interactive input to the file"""
wId = event.GetId()
win = {}
for p in self.task.params:
if wId in p.get('wxId', []):
win['file'] = self.FindWindowById(p['wxId'][0])
win['text'] = self.FindWindowById(p['wxId'][1])
break
if not win:
return
text = win['text'].GetValue()
if not text:
gcmd.GMessage(parent=self,
message=_("Nothing to save."))
return
dlg = wx.FileDialog(parent=self,
message=_("Save input as..."),
defaultDir=os.getcwd(),
style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
if dlg.ShowModal() == wx.ID_OK:
path = dlg.GetPath()
enc = locale.getdefaultlocale()[1]
f = codecs.open(path, encoding=enc, mode='w', errors='replace')
try:
f.write(text + os.linesep)
finally:
f.close()
win['file'].SetValue(path)
dlg.Destroy()
def OnFileText(self, event):
"""File input interactively entered"""
text = event.GetString()
p = self.task.get_param(
value=event.GetId(),
element='wxId',
raiseError=False)
if not p:
return # should not happen
win = self.FindWindowById(p['wxId'][0])
if text:
filename = win.GetValue()
if not filename or filename == p[
'default']: # m.proj has - as default
filename = grass.tempfile()
win.SetValue(filename)
enc = locale.getdefaultlocale()[1]
f = codecs.open(filename, encoding=enc, mode='w', errors='replace')
try:
f.write(text)
if text[-1] != os.linesep:
f.write(os.linesep)
finally:
f.close()
else:
win.SetValue('')
def OnVectorFormat(self, event):
"""Change vector format (native / ogr).
Currently unused.
"""
sel = event.GetSelection()
idEvent = event.GetId()
p = self.task.get_param(
value=idEvent,
element='wxId',
raiseError=False)
if not p:
return # should not happen
# detect windows
winNative = None
winOgr = None
for id in p['wxId']:
if id == idEvent:
continue
name = self.FindWindowById(id).GetName()
if name == 'Select':
# fix the mystery (also in nviz_tools.py)
winNative = self.FindWindowById(id + 1)
elif name == 'OgrSelect':
winOgr = self.FindWindowById(id)
# enable / disable widgets & update values
rbox = self.FindWindowByName('VectorFormat')
self.hsizer.Remove(rbox)
if sel == 0: # -> native
winOgr.Hide()
self.hsizer.Remove(winOgr)
self.hsizer.Add(
item=winNative,
flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
border=5)
winNative.Show()
p['value'] = winNative.GetValue()
elif sel == 1: # -> OGR
sizer = wx.BoxSizer(wx.VERTICAL)
winNative.Hide()
self.hsizer.Remove(winNative)
sizer.Add(item=winOgr)
winOgr.Show()
p['value'] = winOgr.GetDsn()
self.hsizer.Add(
item=sizer,
flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
border=5)
self.hsizer.Add(item=rbox,
flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
wx.RIGHT | wx.ALIGN_TOP,
border=5)
self.hsizer.Layout()
self.Layout()
self.OnUpdateValues()
self.OnUpdateSelection(event)
def OnUpdateDialog(self, event):
for fn, kwargs in event.data.iteritems():
fn(**kwargs)
self.parent.updateValuesHook()
def OnVerbosity(self, event):
"""Verbosity level changed"""
verbose = self.FindWindowById(self.task.get_flag('verbose')['wxId'][0])
quiet = self.FindWindowById(self.task.get_flag('quiet')['wxId'][0])
if event.IsChecked():
if event.GetId() == verbose.GetId():
if quiet.IsChecked():
quiet.SetValue(False)
self.task.get_flag('quiet')['value'] = False
else:
if verbose.IsChecked():
verbose.SetValue(False)
self.task.get_flag('verbose')['value'] = False
event.Skip()
def OnPageChange(self, event):
if not event:
sel = self.notebook.GetSelection()
else:
sel = event.GetSelection()
idx = self.notebook.GetPageIndexByName('manual')
if idx > -1 and sel == idx:
# calling LoadPage() is strangely time-consuming (only first call)
# FIXME: move to helpPage.__init__()
if not self.manualTab.IsLoaded():
wx.Yield()
self.manualTab.LoadPage()
self.Layout()
if event:
# skip is needed for wx.Notebook on Windows
event.Skip()
# this is needed for dialogs launched from layer manager
# event is somehow propagated?
event.StopPropagation()
def _switchPageHandler(self, event, notification):
self._switchPage(notification=notification)
event.Skip()
def _switchPage(self, notification):
"""Manages @c 'output' notebook page according to event notification."""
if notification == Notification.HIGHLIGHT:
self.notebook.HighlightPageByName('output')
if notification == Notification.MAKE_VISIBLE:
self.notebook.SetSelectionByName('output')
if notification == Notification.RAISE_WINDOW:
self.notebook.SetSelectionByName('output')
self.SetFocus()
self.Raise()
def OnColorChange(self, event):
myId = event.GetId()
for p in self.task.params:
if 'wxId' in p and myId in p['wxId']:
multiple = p['wxId'][1] is not None # multiple colors
hasTansp = p['wxId'][2] is not None
if multiple:
# selected color is added at the end of textCtrl
colorchooser = wx.FindWindowById(p['wxId'][0])
new_color = colorchooser.GetValue()[:]
new_label = utils.rgb2str.get(
new_color, ':'.join(map(str, new_color)))
textCtrl = wx.FindWindowById(p['wxId'][1])
val = textCtrl.GetValue()
sep = ','
if val and val[-1] != sep:
val += sep
val += new_label
textCtrl.SetValue(val)
p['value'] = val
elif hasTansp and wx.FindWindowById(p['wxId'][2]).GetValue():
p['value'] = 'none'
else:
colorchooser = wx.FindWindowById(p['wxId'][0])
new_color = colorchooser.GetValue()[:]
# This is weird: new_color is a 4-tuple and new_color[:] is a 3-tuple
# under wx2.8.1
new_label = utils.rgb2str.get(
new_color, ':'.join(map(str, new_color)))
colorchooser.SetLabel(new_label)
colorchooser.SetColour(new_color)
colorchooser.Refresh()
p['value'] = colorchooser.GetLabel()
self.OnUpdateValues()
def OnUpdateValues(self, event=None):
"""If we were part of a richer interface, report back the
current command being built.
This method should be set by the parent of this panel if
needed. It's a hook, actually. Beware of what is 'self' in
the method def, though. It will be called with no arguments.
"""
pass
def OnCheckBoxMulti(self, event):
"""Fill the values as a ','-separated string according to
current status of the checkboxes.
"""
me = event.GetId()
theParam = None
for p in self.task.params:
if 'wxId' in p and me in p['wxId']:
theParam = p
myIndex = p['wxId'].index(me)
# Unpack current value list
currentValues = {}
for isThere in theParam.get('value', '').split(','):
currentValues[isThere] = 1
theValue = theParam['values'][myIndex]
if event.Checked():
currentValues[theValue] = 1
else:
del currentValues[theValue]
# Keep the original order, so that some defaults may be recovered
currentValueList = []
for v in theParam['values']:
if v in currentValues:
currentValueList.append(v)
# Pack it back
theParam['value'] = ','.join(currentValueList)
self.OnUpdateValues()
event.Skip()
def OnSetValue(self, event):
"""Retrieve the widget value and set the task value field
accordingly.
Use for widgets that have a proper GetValue() method, i.e. not
for selectors.
"""
myId = event.GetId()
me = wx.FindWindowById(myId)
name = me.GetName()
found = False
for porf in self.task.params + self.task.flags:
if 'wxId' not in porf:
continue
if myId in porf['wxId']:
found = True
break
if not found:
return
if name == 'GdalSelect':
porf['value'] = event.dsn
elif name == 'ModelParam':
porf['parameterized'] = me.IsChecked()
elif name == 'GdalSelectDataSource':
win = self.FindWindowById(porf['wxId'][0])
porf['value'] = win.GetDsn()
pLayer = self.task.get_param(
'layer', element='name', raiseError=False)
if pLayer:
pLayer['value'] = ''
else:
if isinstance(me, SpinCtrl):
porf['value'] = str(me.GetValue())
elif isinstance(me, wx.ComboBox):
porf['value'] = me.GetValue()
elif isinstance(me, wx.Choice):
porf['value'] = me.GetStringSelection()
else:
porf['value'] = me.GetValue()
self.OnUpdateValues(event)
event.Skip()
def OnSetSymbol(self, event):
"""Shows dialog for symbol selection"""
myId = event.GetId()
for p in self.task.params:
if 'wxId' in p and myId in p['wxId']:
from gui_core.dialogs import SymbolDialog
dlg = SymbolDialog(self, symbolPath=globalvar.SYMBDIR,
currentSymbol=p['value'])
if dlg.ShowModal() == wx.ID_OK:
img = dlg.GetSelectedSymbolPath()
p['value'] = dlg.GetSelectedSymbolName()
bitmapButton = wx.FindWindowById(p['wxId'][0])
label = wx.FindWindowById(p['wxId'][1])
bitmapButton.SetBitmapLabel(wx.Bitmap(img + '.png'))
label.SetLabel(p['value'])
self.OnUpdateValues(event)
dlg.Destroy()
def OnTimelineTool(self, event):
"""Show Timeline Tool with dataset(s) from gselect.
.. todo::
update from gselect automatically
"""
myId = event.GetId()
for p in self.task.params:
if 'wxId' in p and myId in p['wxId']:
select = self.FindWindowById(p['wxId'][0])
if not select.GetValue():
gcmd.GMessage(parent=self, message=_("No dataset given."))
return
datasets = select.GetValue().split(',')
from timeline import frame
frame.run(parent=self, datasets=datasets)
def OnSelectFont(self, event):
"""Select font using font dialog"""
myId = event.GetId()
for p in self.task.params:
if 'wxId' in p and myId in p['wxId']:
from gui_core.dialogs import DefaultFontDialog
dlg = DefaultFontDialog(parent=self,
title=_('Select font'),
style=wx.DEFAULT_DIALOG_STYLE,
type='font')
if dlg.ShowModal() == wx.ID_OK:
if dlg.font:
p['value'] = dlg.font
self.FindWindowById(p['wxId'][1]).SetValue(dlg.font)
self.OnUpdateValues(event)
dlg.Destroy()
def OnUpdateSelection(self, event):
"""Update dialog (layers, tables, columns, etc.)
"""
if not hasattr(self.parent, "updateThread"):
if event:
event.Skip()
return
if event:
self.parent.updateThread.Update(UpdateDialog,
self,
event,
event.GetId(),
self.task)
else:
self.parent.updateThread.Update(UpdateDialog,
self,
None,
None,
self.task)
def createCmd(self, ignoreErrors=False, ignoreRequired=False):
"""Produce a command line string (list) or feeding into GRASS.
:param ignoreErrors: True then it will return whatever has been
built so far, even though it would not be
a correct command for GRASS
"""
try:
cmd = self.task.get_cmd(ignoreErrors=ignoreErrors,
ignoreRequired=ignoreRequired)
except ValueError as err:
dlg = wx.MessageDialog(parent=self,
message=gcmd.DecodeString(str(err)),
caption=_("Error in %s") % self.task.name,
style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
dlg.ShowModal()
dlg.Destroy()
cmd = None
return cmd
def OnSize(self, event):
width = event.GetSize()[0]
fontsize = self.GetFont().GetPointSize()
text_width = max(width / (fontsize - 3), 70)
for id in self.label_id:
win = self.FindWindowById(id)
label = win.GetLabel()
label_new = '\n'.join(textwrap.wrap(label, text_width))
win.SetLabel(label_new)
event.Skip()
def AddBitmapToImageList(self, section, imageList):
iconTheme = UserSettings.Get(
group='appearance',
key='iconTheme',
subkey='type')
iconSectionDict = {
'manual': os.path.join(
globalvar.ICONDIR,
iconTheme,
'help.png')}
if section in iconSectionDict.keys():
image = wx.Image(
iconSectionDict[section]).Scale(
16, 16, wx.IMAGE_QUALITY_HIGH)
idx = imageList.Add(wx.BitmapFromImage(image))
return idx
return -1
class GUI:
def __init__(self, parent=None, giface=None, show=True, modal=False,
centreOnParent=False, checkError=False):
"""Parses GRASS commands when module is imported and used from
Layer Manager.
"""
self.parent = parent
self.show = show
self.modal = modal
self._giface = giface
self.centreOnParent = centreOnParent
self.checkError = checkError
self.grass_task = None
self.cmd = list()
global _blackList
if self.parent:
_blackList['enabled'] = True
else:
_blackList['enabled'] = False
def GetCmd(self):
"""Get validated command"""
return self.cmd
def ParseCommand(self, cmd, completed=None):
"""Parse command
Note: cmd is given as list
If command is given with options, return validated cmd list:
- add key name for first parameter if not given
- change mapname to mapname@mapset
"""
dcmd_params = {}
if completed is None:
get_dcmd = None
layer = None
dcmd_params = None
else:
get_dcmd = completed[0]
layer = completed[1]
if completed[2]:
dcmd_params.update(completed[2])
# parse the interface decription
try:
global _blackList
self.grass_task = gtask.parse_interface(cmd[0],
blackList=_blackList)
except (grass.ScriptError, ValueError) as e:
raise gcmd.GException(e.value)
# if layer parameters previously set, re-insert them into dialog
if completed is not None:
if 'params' in dcmd_params:
self.grass_task.params = dcmd_params['params']
if 'flags' in dcmd_params:
self.grass_task.flags = dcmd_params['flags']
err = list()
# update parameters if needed && validate command
if len(cmd) > 1:
i = 0
cmd_validated = [cmd[0]]
for option in cmd[1:]:
if option[0] == '-': # flag
if len(option) == 1: # catch typo like 'g.proj - w'
raise gcmd.GException(
_("Unable to parse command '%s'") %
' '.join(cmd))
if option[1] == '-':
self.grass_task.set_flag(option[2:], True)
else:
self.grass_task.set_flag(option[1], True)
cmd_validated.append(option)
else: # parameter
try:
key, value = option.split('=', 1)
except ValueError:
if self.grass_task.firstParam:
if i == 0: # add key name of first parameter if not given
key = self.grass_task.firstParam
value = option
else:
raise gcmd.GException(
_("Unable to parse command '%s'") % ' '.join(cmd))
else:
continue
task = self.grass_task.get_param(key, raiseError=False)
if not task:
err.append(
_("%(cmd)s: parameter '%(key)s' not available") % {
'cmd': cmd[0],
'key': key})
continue
self.grass_task.set_param(key, value)
cmd_validated.append(key + '=' + value)
i += 1
# update original command list
cmd = cmd_validated
if self.show is not None:
self.mf = TaskFrame(parent=self.parent, giface=self._giface,
task_description=self.grass_task,
get_dcmd=get_dcmd, layer=layer)
else:
self.mf = None
if get_dcmd is not None:
# update only propwin reference
get_dcmd(dcmd=None, layer=layer, params=None,
propwin=self.mf)
if self.show is not None:
self.mf.notebookpanel.OnUpdateSelection(None)
if self.show is True:
if self.parent and self.centreOnParent:
self.mf.CentreOnParent()
else:
self.mf.CenterOnScreen()
self.mf.Show(self.show)
self.mf.MakeModal(self.modal)
else:
self.mf.OnApply(None)
self.cmd = cmd
if self.checkError:
return self.grass_task, err
else:
return self.grass_task
def GetCommandInputMapParamKey(self, cmd):
"""Get parameter key for input raster/vector map
:param cmd: module name
:return: parameter key
:return: None on failure
"""
# parse the interface decription
if not self.grass_task:
tree = etree.fromstring(gtask.get_interface_description(cmd))
self.grass_task = gtask.processTask(tree).get_task()
for p in self.grass_task.params:
if p.get('name', '') in ('input', 'map'):
age = p.get('age', '')
prompt = p.get('prompt', '')
element = p.get('element', '')
if age == 'old' and \
element in ('cell', 'grid3', 'vector') and \
prompt in ('raster', 'raster_3d', 'vector'):
return p.get('name', None)
return None
class GrassGUIApp(wx.App):
"""Stand-alone GRASS command GUI
"""
def __init__(self, grass_task):
self.grass_task = grass_task
wx.App.__init__(self, False)
def OnInit(self):
msg = self.grass_task.get_error_msg()
if msg:
gcmd.GError(
msg +
'\n\n' +
_('Try to set up GRASS_ADDON_PATH or GRASS_ADDON_BASE variable.'))
return True
self.mf = TaskFrame(
parent=None,
giface=None,
task_description=self.grass_task)
self.mf.CentreOnScreen()
self.mf.Show(True)
self.SetTopWindow(self.mf)
return True
USAGE_MESSAGE = """Usage:
{name} <grass module>
{name} <full path to file>
python {name} <grass module>
Test:
python {name} test
python {name} g.region
python {name} "g.region -p"
python {name} temporal/t.list/t.list.py"""
if __name__ == "__main__":
if len(sys.argv) == 1:
sys.exit(_(USAGE_MESSAGE).format(name=sys.argv[0]))
if sys.argv[1] != 'test':
q = wx.LogNull()
from core.debug import Debug
Debug.msg(1, "forms.py called using command: %s" % sys.argv[1])
cmd = utils.split(sys.argv[1])
task = gtask.grassTask(cmd[0])
task.set_options(cmd[1:])
Debug.msg(1, "forms.py opening form for: %s" %
task.get_cmd(ignoreErrors=True, ignoreRequired=True))
app = GrassGUIApp(task)
app.MainLoop()
else: # Test
# Test grassTask from within a GRASS session
if os.getenv("GISBASE") is not None:
task = gtask.grassTask("d.vect")
task.get_param('map')['value'] = "map_name"
task.get_flag('i')['value'] = True
task.get_param('layer')['value'] = 1
task.get_param('label_bcolor')['value'] = "red"
# the default parameter display is added automatically
assert ' '.join(
task.get_cmd()) == "d.vect -i map=map_name layer=1 display=shape label_bcolor=red"
print "Creation of task successful"
# Test interface building with handmade grassTask,
# possibly outside of a GRASS session.
print "Now creating a module dialog (task frame)"
task = gtask.grassTask()
task.name = "TestTask"
task.description = "This is an artificial grassTask() object intended for testing purposes."
task.keywords = ["grass", "test", "task"]
task.params = [
{
"name": "text",
"description": "Descriptions go into tooltips if labels are present, like this one",
"label": "Enter some text",
"key_desc": ["value"],
"values_desc": []
}, {
"name": "hidden_text",
"description": "This text should not appear in the form",
"hidden": True,
"key_desc": ["value"],
"values_desc": []
}, {
"name": "text_default",
"description": "Enter text to override the default",
"default": "default text",
"key_desc": ["value"],
"values_desc": []
}, {
"name": "text_prefilled",
"description": "You should see a friendly welcome message here",
"value": "hello, world",
"key_desc": ["value"],
"values_desc": []
}, {
"name": "plain_color",
"description": "This is a plain color, and it is a compulsory parameter",
"required": False,
"gisprompt": True,
"prompt": "color",
"key_desc": ["value"],
"values_desc": []
}, {
"name": "transparent_color",
"description": "This color becomes transparent when set to none",
"guisection": "tab",
"gisprompt": True,
"prompt": "color",
"key_desc": ["value"],
"values_desc": []
}, {
"name": "multi",
"description": "A multiple selection",
'default': u'red,green,blue',
'gisprompt': False,
'guisection': 'tab',
'multiple': u'yes',
'type': u'string',
'value': '',
'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
"key_desc": ["value"],
"values_desc": []
}, {
"name": "single",
"description": "A single multiple-choice selection",
'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
"guisection": "tab",
"key_desc": ["value"],
"values_desc": []
}, {
"name": "large_multi",
"description": "A large multiple selection",
"gisprompt": False,
"multiple": "yes",
# values must be an array of strings
"values": utils.str2rgb.keys() + map(str, utils.str2rgb.values()),
"key_desc": ["value"],
"values_desc": []
}, {
"name": "a_file",
"description": "A file selector",
"gisprompt": True,
"element": "file",
"key_desc": ["value"],
"values_desc": []
}
]
task.flags = [{"name": "a",
"description": "Some flag, will appear in Main since it is required",
"required": True,
"value": False,
"suppress_required": False},
{"name": "b",
"description": "pre-filled flag, will appear in options since it is not required",
"value": True,
"suppress_required": False},
{"name": "hidden_flag",
"description": "hidden flag, should not be changeable",
"hidden": "yes",
"value": True,
"suppress_required": False}]
q = wx.LogNull()
GrassGUIApp(task).MainLoop()
|