1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338
|
/*
* Copyright 2010-2014, Sikuli.org, Sikulix.com
* Released under the MIT License.
*
* modified RaiMan
*/
package org.sikuli.script;
import org.sikuli.util.ScreenHighlighter;
import java.awt.Rectangle;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.sikuli.basics.Debug;
import org.sikuli.basics.Settings;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
/**
* A Region is a rectengular area and lies always completely inside its parent screen
*
*/
public class Region {
static RunTime runTime = RunTime.get();
private static String me = "Region: ";
private static int lvl = 3;
private static void log(int level, String message, Object... args) {
Debug.logx(level, me + message, args);
}
/**
* The Screen containing the Region
*/
private IScreen scr;
protected boolean otherScreen = false;
/**
* The ScreenHighlighter for this Region
*/
private ScreenHighlighter overlay = null;
/**
* X-coordinate of the Region
*/
public int x;
/**
* Y-coordinate of the Region
*/
public int y;
/**
* Width of the Region
*/
public int w;
/**
* Height of the Region
*/
public int h;
/**
* Setting, how to react if an image is not found {@link FindFailed}
*/
private FindFailedResponse findFailedResponse = FindFailed.defaultFindFailedResponse;
/**
* Setting {@link Settings}, if exception is thrown if an image is not found
*/
private boolean throwException = Settings.ThrowException;
/**
* Default time to wait for an image {@link Settings}
*/
private double autoWaitTimeout = Settings.AutoWaitTimeout;
private float waitScanRate = Settings.WaitScanRate;
/**
* Flag, if an observer is running on this region {@link Settings}
*/
private boolean observing = false;
private float observeScanRate = Settings.ObserveScanRate;
private int repeatWaitTime = Settings.RepeatWaitTime;
/**
* The {@link Observer} Singleton instance
*/
private Observer regionObserver = null;
/**
* The last found {@link Match} in the Region
*/
private Match lastMatch = null;
/**
* The last found {@link Match}es in the Region
*/
private Iterator<Match> lastMatches = null;
private long lastSearchTime = -1;
private long lastFindTime = -1;
private boolean isScreenUnion = false;
private boolean isVirtual = false;
private long lastSearchTimeRepeat = -1;
/**
* in case of not found the total wait time
* @return the duration of the last find op
*/
public long getLastTime() {
return lastFindTime;
}
/**
* the area constants for use with get()
*/
public static final int NW = 300, NORTH_WEST = NW, TL = NW;
public static final int NM = 301, NORTH_MID = NM, TM = NM;
public static final int NE = 302, NORTH_EAST = NE, TR = NE;
public static final int EM = 312, EAST_MID = EM, RM = EM;
public static final int SE = 322, SOUTH_EAST = SE, BR = SE;
public static final int SM = 321, SOUTH_MID = SM, BM = SM;
public static final int SW = 320, SOUTH_WEST = SW, BL = SW;
public static final int WM = 310, WEST_MID = WM, LM = WM;
public static final int MM = 311, MIDDLE = MM, M3 = MM;
public static final int TT = 200;
public static final int RR = 201;
public static final int BB = 211;
public static final int LL = 210;
public static final int NH = 202, NORTH = NH, TH = NH;
public static final int EH = 221, EAST = EH, RH = EH;
public static final int SH = 212, SOUTH = SH, BH = SH;
public static final int WH = 220, WEST = WH, LH = WH;
public static final int MV = 441, MID_VERTICAL = MV, CV = MV;
public static final int MH = 414, MID_HORIZONTAL = MH, CH = MH;
public static final int M2 = 444, MIDDLE_BIG = M2, C2 = M2;
public static final int EN = NE, EAST_NORTH = NE, RT = TR;
public static final int ES = SE, EAST_SOUTH = SE, RB = BR;
public static final int WN = NW, WEST_NORTH = NW, LT = TL;
public static final int WS = SW, WEST_SOUTH = SW, LB = BL;
/**
* to support a raster over the region
*/
private int rows;
private int cols = 0;
private int rowH = 0;
private int colW = 0;
private int rowHd = 0;
private int colWd = 0;
/**
* {@inheritDoc}
*
* @return the description
*/
@Override
public String toString() {
return String.format("R[%d,%d %dx%d]@%s E:%s, T:%.1f",
x, y, w, h, (getScreen() == null ? "Screen null" : getScreen().toStringShort()),
throwException ? "Y" : "N", autoWaitTimeout);
}
/**
*
* @return a compact description
*/
public String toStringShort() {
return String.format("R[%d,%d %dx%d]@S(%s)", x, y, w, h, (getScreen() == null ? "?" : getScreen().getID()));
}
public String toJSON() {
return String.format("[\"R\", %d, %d, %d, %d]", x, y, w, h);
}
//<editor-fold defaultstate="collapsed" desc="OFF: Specials for scripting environment">
/*
public Object __enter__() {
Debug.error("Region: with(__enter__): Trying to make it a Jython Region for with: usage");
IScriptRunner runner = Settings.getScriptRunner("jython", null, null);
if (runner != null) {
Object[] jyreg = new Object[]{this};
if (runner.doSomethingSpecial("createRegionForWith", jyreg)) {
if (jyreg[0] != null) {
return jyreg[0];
}
}
}
Debug.error("Region: with(__enter__): Sorry, not possible");
return null;
}
public void __exit__(Object type, Object value, Object traceback) {
Debug.error("Region: with(__exit__): Sorry, not a Jython Region and not posssible!");
}
*/
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Initialization">
/**
* Detects on which Screen the Region is present. The region is cropped to the intersection with the given screen or
* the screen with the largest intersection
*
* @param iscr The Screen containing the Region
*/
public void initScreen(IScreen iscr) {
// check given screen first
Rectangle rect, screenRect;
IScreen screen, screenOn;
if (iscr != null) {
if (iscr.isOtherScreen()) {
if (x < 0) {
w = w + x;
x = 0;
}
if (y < 0) {
h = h + y;
y = 0;
}
this.scr = iscr;
this.otherScreen = true;
return;
}
if (iscr.getID() > -1) {
rect = regionOnScreen(iscr);
if (rect != null) {
x = rect.x;
y = rect.y;
w = rect.width;
h = rect.height;
this.scr = iscr;
return;
}
} else {
// is ScreenUnion
return;
}
}
// check all possible screens if no screen was given or the region is not on given screen
// crop to the screen with the largest intersection
screenRect = new Rectangle(0, 0, 0, 0);
screenOn = null;
if (true) {
for (int i = 0; i < Screen.getNumberScreens(); i++) {
screen = Screen.getScreen(i);
rect = regionOnScreen(screen);
if (rect != null) {
if (rect.width * rect.height > screenRect.width * screenRect.height) {
screenRect = rect;
screenOn = screen;
}
}
}
}
if (screenOn != null) {
x = screenRect.x;
y = screenRect.y;
w = screenRect.width;
h = screenRect.height;
this.scr = screenOn;
} else {
// no screen found
this.scr = null;
Debug.error("Region(%d,%d,%d,%d) outside any screen - subsequent actions might not work as expected", x, y, w, h);
}
}
private Location checkAndSetRemote(Location loc) {
if (!isOtherScreen()) {
return loc;
}
return loc.setOtherScreen(scr);
}
public static Region virtual(Rectangle rect) {
Region reg = new Region();
reg.x = rect.x;
reg.y = rect.y;
reg.w = rect.width;
reg.h = rect.height;
reg.setVirtual(true);
reg.scr = Screen.getPrimaryScreen();
return reg;
}
/**
* INTERNAL USE - EXPERIMENTAL
* if true: this region is not bound to any screen
* @return the current state
*/
public boolean isVirtual() {
return isVirtual;
}
/**
* INTERNAL USE - EXPERIMENTAL
* @param state if true: this region is not bound to any screen
*/
public void setVirtual(boolean state) {
isVirtual = state;
}
/**
* INTERNAL USE:
* checks wether this region belongs to a non-Desktop screen
* @return true/false
*/
public boolean isOtherScreen() {
return otherScreen;
}
/**
* INTERNAL USE:
* flags this region as belonging to a non-Desktop screen
*/
public void setOtherScreen() {
otherScreen = true;
}
/**
* Checks if the Screen contains the Region.
*
* @param screen The Screen in which the Region might be
* @return True, if the Region is on the Screen. False if the Region is not inside the Screen
*/
protected Rectangle regionOnScreen(IScreen screen) {
if (screen == null) {
return null;
}
// get intersection of Region and Screen
Rectangle rect = screen.getRect().intersection(getRect());
// no Intersection, Region is not on the Screen
if (rect.isEmpty()) {
return null;
}
return rect;
}
/**
* Check wether thie Region is contained by any of the available screens
* @return true if yes, false otherwise
*/
public boolean isValid() {
return scr != null && w != 0 && h != 0;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Constructors to be used with Jython">
/**
* Create a region with the provided coordinate / size and screen
*
* @param X X position
* @param Y Y position
* @param W width
* @param H heigth
* @param screenNumber The number of the screen containing the Region
*/
public Region(int X, int Y, int W, int H, int screenNumber) {
this(X, Y, W, H, Screen.getScreen(screenNumber));
this.rows = 0;
}
/**
* Create a region with the provided coordinate / size and screen
*
* @param X X position
* @param Y Y position
* @param W width
* @param H heigth
* @param parentScreen the screen containing the Region
*/
public Region(int X, int Y, int W, int H, IScreen parentScreen) {
this.rows = 0;
this.x = X;
this.y = Y;
this.w = W > 1 ? W : 1;
this.h = H > 1 ? H : 1;
initScreen(parentScreen);
}
/**
* Create a region with the provided coordinate / size
*
* @param X X position
* @param Y Y position
* @param W width
* @param H heigth
*/
public Region(int X, int Y, int W, int H) {
this(X, Y, W, H, null);
this.rows = 0;
log(lvl, "init: (%d, %d, %d, %d)", X, Y, W, H);
}
/**
* Create a region from a Rectangle
*
* @param r the Rectangle
*/
public Region(Rectangle r) {
this(r.x, r.y, r.width, r.height, null);
this.rows = 0;
}
/**
* Create a new region from another region<br>including the region's settings
*
* @param r the region
*/
public Region(Region r) {
init(r);
}
public void init(Region r) {
if (!r.isValid()) {
return;
}
x = r.x;
y = r.y;
w = r.w;
h = r.h;
scr = r.getScreen();
otherScreen =r.isOtherScreen();
rows = 0;
autoWaitTimeout = r.autoWaitTimeout;
findFailedResponse = r.findFailedResponse;
throwException = r.throwException;
waitScanRate = r.waitScanRate;
observeScanRate = r.observeScanRate;
repeatWaitTime = r.repeatWaitTime;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Quasi-Constructors to be used in Java">
/**
* internal use only, used for new Screen objects to get the Region behavior
*/
protected Region() {
this.rows = 0;
}
/**
* internal use only, used for new Screen objects to get the Region behavior
*/
protected Region(boolean isScreenUnion) {
this.isScreenUnion = isScreenUnion;
this.rows = 0;
}
/**
* Create a region with the provided top left corner and size
*
* @param X top left X position
* @param Y top left Y position
* @param W width
* @param H heigth
* @return then new region
*/
public static Region create(int X, int Y, int W, int H) {
return Region.create(X, Y, W, H, null);
}
/**
* Create a region with the provided top left corner and size
*
* @param X top left X position
* @param Y top left Y position
* @param W width
* @param H heigth
* @param scr the source screen
* @return the new region
*/
private static Region create(int X, int Y, int W, int H, IScreen scr) {
return new Region(X, Y, W, H, scr);
}
/**
* Create a region with the provided top left corner and size
*
* @param loc top left corner
* @param w width
* @param h height
* @return then new region
*/
public static Region create(Location loc, int w, int h) {
return Region.create(loc.x, loc.y, w, h, loc.getScreen());
}
/**
* Flag for the {@link #create(Location, int, int, int, int)} method. Sets the Location to be on the left corner of
* the new Region.
*/
public final static int CREATE_X_DIRECTION_LEFT = 0;
/**
* Flag for the {@link #create(Location, int, int, int, int)} method. Sets the Location to be on the right corner of
* the new Region.
*/
public final static int CREATE_X_DIRECTION_RIGHT = 1;
/**
* Flag for the {@link #create(Location, int, int, int, int)} method. Sets the Location to be on the top corner of the
* new Region.
*/
public final static int CREATE_Y_DIRECTION_TOP = 0;
/**
* Flag for the {@link #create(Location, int, int, int, int)} method. Sets the Location to be on the bottom corner of
* the new Region.
*/
public final static int CREATE_Y_DIRECTION_BOTTOM = 1;
/**
* create a region with a corner at the given point<br>as specified with x y<br> 0 0 top left<br> 0 1 bottom left<br>
* 1 0 top right<br> 1 1 bottom right<br>
*
* @param loc the refence point
* @param create_x_direction == 0 is left side !=0 is right side
* @param create_y_direction == 0 is top side !=0 is bottom side
* @param w the width
* @param h the height
* @return the new region
*/
public static Region create(Location loc, int create_x_direction, int create_y_direction, int w, int h) {
int X;
int Y;
int W = w;
int H = h;
if (create_x_direction == CREATE_X_DIRECTION_LEFT) {
if (create_y_direction == CREATE_Y_DIRECTION_TOP) {
X = loc.x;
Y = loc.y;
} else {
X = loc.x;
Y = loc.y - h;
}
} else {
if (create_y_direction == CREATE_Y_DIRECTION_TOP) {
X = loc.x - w;
Y = loc.y;
} else {
X = loc.x - w;
Y = loc.y - h;
}
}
return Region.create(X, Y, W, H, loc.getScreen());
}
/**
* create a region with a corner at the given point<br>as specified with x y<br> 0 0 top left<br> 0 1 bottom left<br>
* 1 0 top right<br> 1 1 bottom right<br>same as the corresponding create method, here to be naming compatible with
* class Location
*
* @param loc the refence point
* @param x ==0 is left side !=0 is right side
* @param y ==0 is top side !=0 is bottom side
* @param w the width
* @param h the height
* @return the new region
*/
public static Region grow(Location loc, int x, int y, int w, int h) {
return Region.create(loc, x, y, w, h);
}
/**
* Create a region from a Rectangle
*
* @param r the Rectangle
* @return the new region
*/
public static Region create(Rectangle r) {
return Region.create(r.x, r.y, r.width, r.height, null);
}
/**
* Create a region from a Rectangle on a given Screen
*
* @param r the Rectangle
* @param parentScreen the new parent screen
* @return the new region
*/
protected static Region create(Rectangle r, IScreen parentScreen) {
return Region.create(r.x, r.y, r.width, r.height, parentScreen);
}
/**
* Create a region from another region<br>including the region's settings
*
* @param r the region
* @return then new region
*/
public static Region create(Region r) {
Region reg = Region.create(r.x, r.y, r.w, r.h, r.getScreen());
reg.autoWaitTimeout = r.autoWaitTimeout;
reg.findFailedResponse = r.findFailedResponse;
reg.throwException = r.throwException;
return reg;
}
/**
* create a region with the given point as center and the given size
*
* @param loc the center point
* @param w the width
* @param h the height
* @return the new region
*/
public static Region grow(Location loc, int w, int h) {
int X = loc.x - (int) w / 2;
int Y = loc.y - (int) h / 2;
return Region.create(X, Y, w, h, loc.getScreen());
}
/**
* create a minimal region at given point with size 1 x 1
*
* @param loc the point
* @return the new region
*/
public static Region grow(Location loc) {
return Region.create(loc.x, loc.y, 1, 1, loc.getScreen());
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="handle coordinates">
/**
* check if current region contains given point
*
* @param point Point
* @return true/false
*/
public boolean contains(Location point) {
return getRect().contains(point.x, point.y);
}
/**
* check if mouse pointer is inside current region
*
* @return true/false
*/
public boolean containsMouse() {
return contains(Mouse.at());
}
/**
* new region with same offset to current screen's top left on given screen
*
* @param scrID number of screen
* @return new region
*/
public Region copyTo(int scrID) {
return copyTo(Screen.getScreen(scrID));
}
/**
* new region with same offset to current screen's top left on given screen
*
* @param screen new parent screen
* @return new region
*/
public Region copyTo(IScreen screen) {
Location o = new Location(getScreen().getBounds().getLocation());
Location n = new Location(screen.getBounds().getLocation());
return Region.create(n.x + x - o.x, n.y + y - o.y, w, h, screen);
}
/**
* used in Observer.callChangeObserving, Finder.next to adjust region relative coordinates of matches to
screen coordinates
*
* @param m
* @return the modified match
*/
protected Match toGlobalCoord(Match m) {
m.x += x;
m.y += y;
return m;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="handle Settings">
//TODO should be possible to reset to current global value resetXXX()
/**
* true - (initial setting) should throw exception FindFailed if findX unsuccessful in this region<br> false - do not
* abort script on FindFailed (might leed to null pointer exceptions later)
*
* @param flag true/false
*/
public void setThrowException(boolean flag) {
throwException = flag;
if (throwException) {
findFailedResponse = FindFailedResponse.ABORT;
} else {
findFailedResponse = FindFailedResponse.SKIP;
}
}
/**
* current setting for this region (see setThrowException)
*
* @return true/false
*/
public boolean getThrowException() {
return throwException;
}
/**
* the time in seconds a find operation should wait for the appearence of the target in this region<br> initial value
* is the global AutoWaitTimeout setting at time of Region creation
*
* @param sec seconds
*/
public void setAutoWaitTimeout(double sec) {
autoWaitTimeout = sec;
}
/**
* current setting for this region (see setAutoWaitTimeout)
*
* @return value of seconds
*/
public double getAutoWaitTimeout() {
return autoWaitTimeout;
}
/**
* FindFailedResponse.<br> ABORT - (initial value) abort script on FindFailed (= setThrowException(true) )<br> SKIP -
* ignore FindFailed (same as setThrowException(false) )<br>
* PROMPT - display prompt on FindFailed to let user decide how to proceed<br> RETRY - continue to wait for appearence
* on FindFailed (caution: endless loop)
*
* @param response the FindFailedResponse
*/
public void setFindFailedResponse(FindFailedResponse response) {
findFailedResponse = response;
}
/**
*
* @return the current setting (see setFindFailedResponse)
*/
public FindFailedResponse getFindFailedResponse() {
return findFailedResponse;
}
/**
*
* @return the regions current WaitScanRate
*/
public float getWaitScanRate() {
return waitScanRate;
}
/**
* set the regions individual WaitScanRate
*
* @param waitScanRate decimal number
*/
public void setWaitScanRate(float waitScanRate) {
this.waitScanRate = waitScanRate;
}
/**
*
* @return the regions current ObserveScanRate
*/
public float getObserveScanRate() {
return observeScanRate;
}
/**
* set the regions individual ObserveScanRate
*
* @param observeScanRate decimal number
*/
public void setObserveScanRate(float observeScanRate) {
this.observeScanRate = observeScanRate;
}
/**
* INTERNAL USE: Observe
* @return the regions current RepeatWaitTime time in seconds
*/
public int getRepeatWaitTime() {
return repeatWaitTime;
}
/**
* INTERNAL USE: Observe
* set the regions individual WaitForVanish
*
* @param time in seconds
*/
public void setRepeatWaitTime(int time) {
repeatWaitTime = time;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="getters / setters / modificators">
/**
*
* @return the Screen object containing the region
*/
public IScreen getScreen() {
return scr;
}
// to avoid NPE for Regions being outside any screen
private IRobot getRobotForRegion() {
if (getScreen() == null || isScreenUnion) {
return Screen.getPrimaryScreen().getRobot();
}
return getScreen().getRobot();
}
/**
*
* @return the screen, that contains the top left corner of the region. Returns primary screen if outside of any
* screen.
* @deprecated Only for compatibility, to get the screen containing this region, use {@link #getScreen()}
*/
@Deprecated
public IScreen getScreenContaining() {
return getScreen();
}
/**
* Sets a new Screen for this region.
*
* @param scr the containing screen object
* @return the region itself
*/
protected Region setScreen(IScreen scr) {
initScreen(scr);
return this;
}
/**
* Sets a new Screen for this region.
*
* @param id the containing screen object's id
* @return the region itself
*/
protected Region setScreen(int id) {
return setScreen(Screen.getScreen(id));
}
/**
* synonym for showMonitors
*/
public void showScreens() {
Screen.showMonitors();
}
/**
* synonym for resetMonitors
*/
public void resetScreens() {
Screen.resetMonitors();
}
// ************************************************
/**
*
* @return the center pixel location of the region
*/
public Location getCenter() {
return checkAndSetRemote(new Location(getX() + getW() / 2, getY() + getH() / 2));
}
/**
* convenience method
*
* @return the region's center
*/
public Location getTarget() {
return getCenter();
}
/**
* Moves the region to the area, whose center is the given location
*
* @param loc the location which is the new center of the region
* @return the region itself
*/
public Region setCenter(Location loc) {
Location c = getCenter();
x = x - c.x + loc.x;
y = y - c.y + loc.y;
initScreen(null);
return this;
}
/**
*
* @return top left corner Location
*/
public Location getTopLeft() {
return checkAndSetRemote(new Location(x, y));
}
/**
* Moves the region to the area, whose top left corner is the given location
*
* @param loc the location which is the new top left point of the region
* @return the region itself
*/
public Region setTopLeft(Location loc) {
return setLocation(loc);
}
/**
*
* @return top right corner Location
*/
public Location getTopRight() {
return checkAndSetRemote(new Location(x + w - 1, y));
}
/**
* Moves the region to the area, whose top right corner is the given location
*
* @param loc the location which is the new top right point of the region
* @return the region itself
*/
public Region setTopRight(Location loc) {
Location c = getTopRight();
x = x - c.x + loc.x;
y = y - c.y + loc.y;
initScreen(null);
return this;
}
/**
*
* @return bottom left corner Location
*/
public Location getBottomLeft() {
return checkAndSetRemote(new Location(x, y + h - 1));
}
/**
* Moves the region to the area, whose bottom left corner is the given location
*
* @param loc the location which is the new bottom left point of the region
* @return the region itself
*/
public Region setBottomLeft(Location loc) {
Location c = getBottomLeft();
x = x - c.x + loc.x;
y = y - c.y + loc.y;
initScreen(null);
return this;
}
/**
*
* @return bottom right corner Location
*/
public Location getBottomRight() {
return checkAndSetRemote(new Location(x + w - 1, y + h - 1));
}
/**
* Moves the region to the area, whose bottom right corner is the given location
*
* @param loc the location which is the new bottom right point of the region
* @return the region itself
*/
public Region setBottomRight(Location loc) {
Location c = getBottomRight();
x = x - c.x + loc.x;
y = y - c.y + loc.y;
initScreen(null);
return this;
}
// ************************************************
/**
*
* @return x of top left corner
*/
public int getX() {
return x;
}
/**
*
* @return y of top left corner
*/
public int getY() {
return y;
}
/**
*
* @return width of region
*/
public int getW() {
return w;
}
/**
*
* @return height of region
*/
public int getH() {
return h;
}
/**
*
* @param X new x position of top left corner
*/
public void setX(int X) {
x = X;
initScreen(null);
}
/**
*
* @param Y new y position of top left corner
*/
public void setY(int Y) {
y = Y;
initScreen(null);
}
/**
*
* @param W new width
*/
public void setW(int W) {
w = W > 1 ? W : 1;
initScreen(null);
}
/**
*
* @param H new height
*/
public void setH(int H) {
h = H > 1 ? H : 1;
initScreen(null);
}
// ************************************************
/**
*
* @param W new width
* @param H new height
* @return the region itself
*/
public Region setSize(int W, int H) {
w = W > 1 ? W : 1;
h = H > 1 ? H : 1;
initScreen(null);
return this;
}
/**
*
* @return the AWT Rectangle of the region
*/
public Rectangle getRect() {
return new Rectangle(x, y, w, h);
}
/**
* set the regions position/size<br>this might move the region even to another screen
*
* @param r the AWT Rectangle to use for position/size
* @return the region itself
*/
public Region setRect(Rectangle r) {
return setRect(r.x, r.y, r.width, r.height);
}
/**
* set the regions position/size<br>this might move the region even to another screen
*
* @param X new x of top left corner
* @param Y new y of top left corner
* @param W new width
* @param H new height
* @return the region itself
*/
public Region setRect(int X, int Y, int W, int H) {
x = X;
y = Y;
w = W > 1 ? W : 1;
h = H > 1 ? H : 1;
initScreen(null);
return this;
}
/**
* set the regions position/size<br>this might move the region even to another screen
*
* @param r the region to use for position/size
* @return the region itself
*/
public Region setRect(Region r) {
return setRect(r.x, r.y, r.w, r.h);
}
// ****************************************************
/**
* resets this region (usually a Screen object) to the coordinates of the containing screen
*
* Because of the wanted side effect for the containing screen, this should only be used with screen objects.
* For Region objects use setRect() instead.
*/
public void setROI() {
setROI(getScreen().getBounds());
}
/**
* resets this region to the given location, and size <br> this might move the region even to another screen
*
* <br>Because of the wanted side effect for the containing screen, this should only be used with screen objects.
* <br>For Region objects use setRect() instead.
*
* @param X new x
* @param Y new y
* @param W new width
* @param H new height
*/
public void setROI(int X, int Y, int W, int H) {
x = X;
y = Y;
w = W > 1 ? W : 1;
h = H > 1 ? H : 1;
initScreen(null);
}
/**
* resets this region to the given rectangle <br> this might move the region even to another screen
*
* <br>Because of the wanted side effect for the containing screen, this should only be used with screen objects.
* <br>For Region objects use setRect() instead.
*
* @param r AWT Rectangle
*/
public void setROI(Rectangle r) {
setROI(r.x, r.y, r.width, r.height);
}
/**
* resets this region to the given region <br> this might move the region even to another screen
*
* <br>Because of the wanted side effect for the containing screen, this should only be used with screen objects.
* <br>For Region objects use setRect() instead.
*
* @param reg Region
*/
public void setROI(Region reg) {
setROI(reg.getX(), reg.getY(), reg.getW(), reg.getH());
}
/**
* A function only for backward compatibility - Only makes sense with Screen objects
*
* @return the Region being the current ROI of the containing Screen
*/
public Region getROI() {
return new Region(getScreen().getRect());
}
// ****************************************************
/**
*
* @return the region itself
* @deprecated only for backward compatibility
*/
@Deprecated
public Region inside() {
return this;
}
/**
* set the regions position<br>this might move the region even to another screen
*
* @param loc new top left corner
* @return the region itself
* @deprecated to be like AWT Rectangle API use setLocation()
*/
@Deprecated
public Region moveTo(Location loc) {
return setLocation(loc);
}
/**
* set the regions position<br>this might move the region even to another screen
*
* @param loc new top left corner
* @return the region itself
*/
public Region setLocation(Location loc) {
x = loc.x;
y = loc.y;
initScreen(null);
return this;
}
/**
* set the regions position/size<br>this might move the region even to another screen
*
* @param r Region
* @return the region itself
* @deprecated to be like AWT Rectangle API use setRect() instead
*/
@Deprecated
public Region morphTo(Region r) {
return setRect(r);
}
/**
* resize the region using the given padding values<br>might be negative
*
* @param l padding on left side
* @param r padding on right side
* @param t padding at top side
* @param b padding at bottom side
* @return the region itself
*/
public Region add(int l, int r, int t, int b) {
x = x - l;
y = y - t;
w = w + l + r;
if (w < 1) {
w = 1;
}
h = h + t + b;
if (h < 1) {
h = 1;
}
initScreen(null);
return this;
}
/**
* extend the region, so it contains the given region<br>but only the part inside the current screen
*
* @param r the region to include
* @return the region itself
*/
public Region add(Region r) {
Rectangle rect = getRect();
rect.add(r.getRect());
setRect(rect);
initScreen(null);
return this;
}
/**
* extend the region, so it contains the given point<br>but only the part inside the current screen
*
* @param loc the point to include
* @return the region itself
*/
public Region add(Location loc) {
Rectangle rect = getRect();
rect.add(loc.x, loc.y);
setRect(rect);
initScreen(null);
return this;
}
// ************************************************
/**
* a find operation saves its match on success in the used region object<br>unchanged if not successful
*
* @return the Match object from last successful find in this region
*/
public Match getLastMatch() {
return lastMatch;
}
// ************************************************
/**
* a searchAll operation saves its matches on success in the used region object<br>unchanged if not successful
*
* @return a Match-Iterator of matches from last successful searchAll in this region
*/
public Iterator<Match> getLastMatches() {
return lastMatches;
}
// ************************************************
/**
* get the last image taken on this regions screen
*
* @return the stored ScreenImage
*/
public ScreenImage getLastScreenImage() {
return getScreen().getLastScreenImageFromScreen();
}
/**
* stores the lastScreenImage in the current bundle path with a created unique name
*
* @return the absolute file name
* @throws java.io.IOException if not possible
*/
public String getLastScreenImageFile() throws IOException {
return getScreen().getLastScreenImageFile(ImagePath.getBundlePath(), null);
}
/**
* stores the lastScreenImage in the current bundle path with the given name
*
* @param name file name (.png is added if not there)
* @return the absolute file name
* @throws java.io.IOException if not possible
*/
public String getLastScreenImageFile(String name) throws IOException {
return getScreen().getLastScreenImageFromScreen().getFile(ImagePath.getBundlePath(), name);
}
/**
* stores the lastScreenImage in the given path with the given name
*
* @param path path to use
* @param name file name (.png is added if not there)
* @return the absolute file name
* @throws java.io.IOException if not possible
*/
public String getLastScreenImageFile(String path, String name) throws IOException {
return getScreen().getLastScreenImageFromScreen().getFile(path, name);
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="spatial operators - new regions">
/**
* check if current region contains given region
*
* @param region the other Region
* @return true/false
*/
public boolean contains(Region region) {
return getRect().contains(region.getRect());
}
/**
* create a Location object, that can be used as an offset taking the width and hight of this Region
* @return a new Location object with width and height as x and y
*/
public Location asOffset() {
return new Location(w, h);
}
/**
* create region with same size at top left corner offset
*
* @param loc use its x and y to set the offset
* @return the new region
*/
public Region offset(Location loc) {
return Region.create(x + loc.x, y + loc.y, w, h, scr);
}
/**
* create region with same size at top left corner offset
*
* @param x horizontal offset
* @param y vertical offset
* @return the new region
*/
public Region offset(int x, int y) {
return Region.create(this.x + x, this.y + y, w, h, scr);
}
/**
* create a region enlarged Settings.DefaultPadding pixels on each side
*
* @return the new region
* @deprecated to be like AWT Rectangle API use grow() instead
*/
@Deprecated
public Region nearby() {
return grow(Settings.DefaultPadding, Settings.DefaultPadding);
}
/**
* create a region enlarged range pixels on each side
*
* @param range the margin to be added around
* @return the new region
* @deprecated to be like AWT Rectangle API use grow() instaed
*/
@Deprecated
public Region nearby(int range) {
return grow(range, range);
}
/**
* create a region enlarged n pixels on each side (n = Settings.DefaultPadding = 50 default)
*
* @return the new region
*/
public Region grow() {
return grow(Settings.DefaultPadding, Settings.DefaultPadding);
}
/**
* create a region enlarged range pixels on each side
*
* @param range the margin to be added around
* @return the new region
*/
public Region grow(int range) {
return grow(range, range);
}
/**
* create a region enlarged w pixels on left and right side
* and h pixels at top and bottom
*
* @param w pixels horizontally
* @param h pixels vertically
* @return the new region
*/
public Region grow(int w, int h) {
Rectangle r = getRect();
r.grow(w, h);
return Region.create(r.x, r.y, r.width, r.height, scr);
}
/**
* create a region enlarged l pixels on left and r pixels right side
* and t pixels at top side and b pixels a bottom side.
* negative values go inside (shrink)
*
* @param l add to the left
* @param r add to right
* @param t add above
* @param b add beneath
* @return the new region
*/
public Region grow(int l, int r, int t, int b) {
return Region.create(x - l, y - t, w + l + r, h + t + b, scr);
}
/**
* point middle on right edge
* @return point middle on right edge
*/
public Location rightAt() {
return rightAt(0);
}
/**
* positive offset goes to the right.
* might be off current screen
*
* @param offset pixels
* @return point with given offset horizontally to middle point on right edge
*/
public Location rightAt(int offset) {
return checkAndSetRemote(new Location(x + w + offset, y + h / 2));
}
/**
* create a region right of the right side with same height.
* the new region extends to the right screen border<br>
* use grow() to include the current region
*
* @return the new region
*/
public Region right() {
int distToRightScreenBorder = getScreen().getX() + getScreen().getW() - (getX() + getW());
return right(distToRightScreenBorder);
}
/**
* create a region right of the right side with same height and given width.
* negative width creates the right part with width inside the region<br>
* use grow() to include the current region
*
* @param width pixels
* @return the new region
*/
public Region right(int width) {
int _x;
if (width < 0) {
_x = x + w + width;
} else {
_x = x + w;
}
return Region.create(_x, y, Math.abs(width), h, scr);
}
/**
*
* @return point middle on left edge
*/
public Location leftAt() {
return leftAt(0);
}
/**
* negative offset goes to the left <br>might be off current screen
*
* @param offset pixels
* @return point with given offset horizontally to middle point on left edge
*/
public Location leftAt(int offset) {
return checkAndSetRemote(new Location(x + offset, y + h / 2));
}
/**
* create a region left of the left side with same height<br> the new region extends to the left screen border<br> use
* grow() to include the current region
*
* @return the new region
*/
public Region left() {
int distToLeftScreenBorder = getX() - getScreen().getX();
return left(distToLeftScreenBorder);
}
/**
* create a region left of the left side with same height and given width<br>
* negative width creates the left part with width inside the region use grow() to include the current region <br>
*
* @param width pixels
* @return the new region
*/
public Region left(int width) {
int _x;
if (width < 0) {
_x = x;
} else {
_x = x - width;
}
return Region.create(getScreen().getBounds().intersection(new Rectangle(_x, y, Math.abs(width), h)), scr);
}
/**
*
* @return point middle on top edge
*/
public Location aboveAt() {
return aboveAt(0);
}
/**
* negative offset goes towards top of screen <br>might be off current screen
*
* @param offset pixels
* @return point with given offset vertically to middle point on top edge
*/
public Location aboveAt(int offset) {
return checkAndSetRemote(new Location(x + w / 2, y + offset));
}
/**
* create a region above the top side with same width<br> the new region extends to the top screen border<br> use
* grow() to include the current region
*
* @return the new region
*/
public Region above() {
int distToAboveScreenBorder = getY() - getScreen().getY();
return above(distToAboveScreenBorder);
}
/**
* create a region above the top side with same width and given height<br>
* negative height creates the top part with height inside the region use grow() to include the current region
*
* @param height pixels
* @return the new region
*/
public Region above(int height) {
int _y;
if (height < 0) {
_y = y;
} else {
_y = y - height;
}
return Region.create(getScreen().getBounds().intersection(new Rectangle(x, _y, w, Math.abs(height))), scr);
}
/**
*
* @return point middle on bottom edge
*/
public Location belowAt() {
return belowAt(0);
}
/**
* positive offset goes towards bottom of screen <br>might be off current screen
*
* @param offset pixels
* @return point with given offset vertically to middle point on bottom edge
*/
public Location belowAt(int offset) {
return checkAndSetRemote(new Location(x + w / 2, y + h - offset));
}
/**
* create a region below the bottom side with same width<br> the new region extends to the bottom screen border<br>
* use grow() to include the current region
*
* @return the new region
*/
public Region below() {
int distToBelowScreenBorder = getScreen().getY() + getScreen().getH() - (getY() + getH());
return below(distToBelowScreenBorder);
}
/**
* create a region below the bottom side with same width and given height<br>
* negative height creates the bottom part with height inside the region use grow() to include the current region
*
* @param height pixels
* @return the new region
*/
public Region below(int height) {
int _y;
if (height < 0) {
_y = y + h + height;
} else {
_y = y + h;
}
return Region.create(x, _y, w, Math.abs(height), scr);
}
/**
* create a new region containing both regions
*
* @param ur region to unite with
* @return the new region
*/
public Region union(Region ur) {
Rectangle r = getRect().union(ur.getRect());
return Region.create(r.x, r.y, r.width, r.height, scr);
}
/**
* create a region that is the intersection of the given regions
*
* @param ir the region to intersect with like AWT Rectangle API
* @return the new region
*/
public Region intersection(Region ir) {
Rectangle r = getRect().intersection(ir.getRect());
return Region.create(r.x, r.y, r.width, r.height, scr);
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="parts of a Region">
/**
* select the specified part of the region.
*
* <br>Constants for the top parts of a region (Usage: Region.CONSTANT)<br>
* shown in brackets: possible shortcuts for the part constant<br>
* NORTH (NH, TH) - upper half <br>
* NORTH_WEST (NW, TL) - left third in upper third <br>
* NORTH_MID (NM, TM) - middle third in upper third <br>
* NORTH_EAST (NE, TR) - right third in upper third <br>
* ... similar for the other directions: <br>
* right side: EAST (Ex, Rx)<br>
* bottom part: SOUTH (Sx, Bx) <br>
* left side: WEST (Wx, Lx)<br>
* <br>
* specials for quartered:<br>
* TT top left quarter<br>
* RR top right quarter<br>
* BB bottom right quarter<br>
* LL bottom left quarter<br>
* <br>
* specials for the center parts:<br>
* MID_VERTICAL (MV, CV) half of width vertically centered <br>
* MID_HORIZONTAL (MH, CH) half of height horizontally centered <br>
* MID_BIG (M2, C2) half of width / half of height centered <br>
* MID_THIRD (MM, CC) third of width / third of height centered <br>
* <br>
* Based on the scheme behind these constants there is another possible usage:<br>
* specify part as e 3 digit integer
* where the digits xyz have the following meaning<br>
* 1st x: use a raster of x rows and x columns<br>
* 2nd y: the row number of the wanted cell<br>
* 3rd z: the column number of the wanted cell<br>
* y and z are counting from 0<br>
* valid numbers: 200 up to 999 (< 200 are invalid and return the region itself) <br>
* example: get(522) will use a raster of 5 rows and 5 columns and return the cell in the middle<br>
* special cases:<br>
* if either y or z are == or > x: returns the respective row or column<br>
* example: get(525) will use a raster of 5 rows and 5 columns and return the row in the middle<br>
* <br>
* internally this is based on {@link #setRaster(int, int) setRaster}
* and {@link #getCell(int, int) getCell} <br>
* <br>
* If you need only one row in one column with x rows or
* only one column in one row with x columns you can use {@link #getRow(int, int) getRow} or {@link #getCol(int, int) getCol}
* @param part the part to get (Region.PART long or short)
* @return new region
*/
public Region get(int part) {
return Region.create(getRectangle(getRect(), part));
}
protected static Rectangle getRectangle(Rectangle rect, int part) {
if (part < 200 || part > 999) {
return rect;
}
Region r = Region.create(rect);
int pTyp = (int) (part / 100);
int pPos = part - pTyp * 100;
int pRow = (int) (pPos / 10);
int pCol = pPos - pRow * 10;
r.setRaster(pTyp, pTyp);
if (pTyp == 3) {
// NW = 300, NORTH_WEST = NW;
// NM = 301, NORTH_MID = NM;
// NE = 302, NORTH_EAST = NE;
// EM = 312, EAST_MID = EM;
// SE = 322, SOUTH_EAST = SE;
// SM = 321, SOUTH_MID = SM;
// SW = 320, SOUTH_WEST = SW;
// WM = 310, WEST_MID = WM;
// MM = 311, MIDDLE = MM, M3 = MM;
return r.getCell(pRow, pCol).getRect();
}
if (pTyp == 2) {
// NH = 202, NORTH = NH;
// EH = 221, EAST = EH;
// SH = 212, SOUTH = SH;
// WH = 220, WEST = WH;
if (pRow > 1) {
return r.getCol(pCol).getRect();
} else if (pCol > 1) {
return r.getRow(pRow).getRect();
}
return r.getCell(pRow, pCol).getRect();
}
if (pTyp == 4) {
// MV = 441, MID_VERTICAL = MV;
// MH = 414, MID_HORIZONTAL = MH;
// M2 = 444, MIDDLE_BIG = M2;
if (pRow > 3) {
if (pCol > 3 ) {
return r.getCell(1, 1).union(r.getCell(2, 2)).getRect();
}
return r.getCell(0, 1).union(r.getCell(3, 2)).getRect();
} else if (pCol > 3) {
return r.getCell(1, 0).union(r.getCell(2, 3)).getRect();
}
return r.getCell(pRow, pCol).getRect();
}
return rect;
}
/**
* store info: this region is divided vertically into n even rows <br>
* a preparation for using getRow()
*
* @param n number of rows
* @return the top row
*/
public Region setRows(int n) {
return setRaster(n, 0);
}
/**
* store info: this region is divided horizontally into n even columns <br>
* a preparation for using getCol()
*
* @param n number of columns
* @return the leftmost column
*/
public Region setCols(int n) {
return setRaster(0, n);
}
/**
*
* @return the number of rows or null
*/
public int getRows() {
return rows;
}
/**
*
* @return the row height or 0
*/
public int getRowH() {
return rowH;
}
/**
*
* @return the number of columns or 0
*/
public int getCols() {
return cols;
}
/**
*
* @return the columnwidth or 0
*/
public int getColW() {
return colW;
}
/**
* Can be used to check, wether the Region currently has a valid raster
* @return true if it has a valid raster (either getCols or getRows or both would return > 0)
* false otherwise
*/
public boolean isRasterValid() {
return (rows > 0 || cols > 0);
}
/**
* store info: this region is divided into a raster of even cells <br>
* a preparation for using getCell()<br>
* @param r number of rows
* @param c number of columns
* @return the topleft cell
*/
public Region setRaster(int r, int c) {
rows = Math.max(r, h);
cols = Math.max(c, w);
if (r > 0) {
rowH = (int) (h / r);
rowHd = h - r * rowH;
}
if (c > 0) {
colW = (int) (w / c);
colWd = w - c * colW;
}
return getCell(0, 0);
}
/**
* get the specified row counting from 0, if rows or raster are setup negative counts reverse from the end (last = -1)
* values outside range are 0 or last respectively
*
* @param r row number
* @return the row as new region or the region itself, if no rows are setup
*/
public Region getRow(int r) {
if (rows == 0) {
return this;
}
if (r < 0) {
r = rows + r;
}
r = Math.max(0, r);
r = Math.min(r, rows - 1);
return Region.create(x, y + r * rowH, w, rowH);
}
public Region getRow(int r, int n) {
return this;
}
/**
* get the specified column counting from 0, if columns or raster are setup negative counts reverse from the end (last
* = -1) values outside range are 0 or last respectively
*
* @param c column number
* @return the column as new region or the region itself, if no columns are setup
*/
public Region getCol(int c) {
if (cols == 0) {
return this;
}
if (c < 0) {
c = cols + c;
}
c = Math.max(0, c);
c = Math.min(c, cols - 1);
return Region.create(x + c * colW, y, colW, h);
}
/**
* divide the region in n columns and select column c as new Region
* @param c the column to select counting from 0 or negative to count from the end
* @param n how many columns to devide in
* @return the selected part or the region itself, if parameters are invalid
*/
public Region getCol(int c, int n) {
Region r = new Region(this);
r.setCols(n);
return r.getCol(c);
}
/**
* get the specified cell counting from (0, 0), if a raster is setup <br>
* negative counts reverse from the end (last = -1) values outside range are 0 or last respectively
*
* @param r row number
* @param c column number
* @return the cell as new region or the region itself, if no raster is setup
*/
public Region getCell(int r, int c) {
if (rows == 0) {
return getCol(c);
}
if (cols == 0) {
return getRow(r);
}
if (rows == 0 && cols == 0) {
return this;
}
if (r < 0) {
r = rows - r;
}
if (c < 0) {
c = cols - c;
}
r = Math.max(0, r);
r = Math.min(r, rows - 1);
c = Math.max(0, c);
c = Math.min(c, cols - 1);
return Region.create(x + c * colW, y + r * rowH, colW, rowH);
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="highlight">
protected void updateSelf() {
if (overlay != null) {
highlight(false, null);
highlight(true, null);
}
}
protected Region silentHighlight(boolean onOff) {
if (onOff && overlay == null) {
return doHighlight(true, null, true);
}
if (!onOff && overlay != null) {
return doHighlight(true, null, true);
}
return this;
}
/**
* Toggle the regions Highlight visibility (red frame)
*
* @return the region itself
*/
public Region highlight() {
// Pass true if overlay is null, false otherwise
highlight(overlay == null, null);
return this;
}
/**
* Toggle the regions Highlight visibility (frame of specified color)<br>
* allowed color specifications for frame color: <br>
* - a color name out of: black, blue, cyan, gray, green, magenta, orange, pink, red, white, yellow
* (lowercase and uppercase can be mixed, internally transformed to all uppercase) <br>
* - these colornames exactly written: lightGray, LIGHT_GRAY, darkGray and DARK_GRAY <br>
* - a hex value like in HTML: #XXXXXX (max 6 hex digits)
* - an RGB specification as: #rrrgggbbb where rrr, ggg, bbb are integer values in range 0 - 255
* padded with leading zeros if needed (hence exactly 9 digits)
* @param color Color of frame
* @return the region itself
*/
public Region highlight(String color) {
// Pass true if overlay is null, false otherwise
highlight(overlay == null, color);
return this;
}
/**
* Sets the regions Highlighting border
*
* @param toEnable set overlay enabled or disabled
* @param color Color of frame (see method highlight(color))
*/
private Region highlight(boolean toEnable, String color) {
return doHighlight(toEnable, color, false);
}
private Region doHighlight(boolean toEnable, String color, boolean silent) {
if (isOtherScreen()) {
return this;
}
if (!silent) {
Debug.action("toggle highlight " + toString() + ": " + toEnable +
(color != null ? " color: " + color : ""));
}
if (toEnable) {
overlay = new ScreenHighlighter(getScreen(), color);
overlay.highlight(this);
} else {
if (overlay != null) {
overlay.close();
overlay = null;
}
}
return this;
}
/**
* show the regions Highlight for the given time in seconds (red frame)
* if 0 - use the global Settings.SlowMotionDelay
*
* @param secs time in seconds
* @return the region itself
*/
public Region highlight(float secs) {
return highlight(secs, null);
}
/**
* show the regions Highlight for the given time in seconds (frame of specified color)
* if 0 - use the global Settings.SlowMotionDelay
*
* @param secs time in seconds
* @param color Color of frame (see method highlight(color))
* @return the region itself
*/
public Region highlight(float secs, String color) {
if (isOtherScreen()) {
return this;
}
if (secs < 0.1) {
return highlight((int) secs, color);
}
Debug.action("highlight " + toString() + " for " + secs + " secs" +
(color != null ? " color: " + color : ""));
ScreenHighlighter _overlay = new ScreenHighlighter(getScreen(), color);
_overlay.highlight(this, secs);
return this;
}
/**
* hack to implement the getLastMatch() convenience 0 means same as highlight() < 0 same as highlight(secs) if
* available the last match is highlighted
*
* @param secs seconds
* @return this region
*/
public Region highlight(int secs) {
return highlight(secs, null);
}
/**
* Show highlight in selected color
*
* @param secs time in seconds
* @param color Color of frame (see method highlight(color))
* @return this region
*/
public Region highlight(int secs, String color) {
if (isOtherScreen()) {
return this;
}
if (secs > 0) {
return highlight((float) secs, color);
}
if (lastMatch != null) {
if (secs < 0) {
return lastMatch.highlight((float) -secs, color);
}
return lastMatch.highlight(Settings.DefaultHighlightTime, color);
}
return this;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="find public methods">
/**
* WARNING: wait(long timeout) is taken by Java Object as final. This method catches any interruptedExceptions
*
* @param timeout The time to wait
*/
public void wait(double timeout) {
try {
Thread.sleep((long) (timeout * 1000L));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* Returns the image of the given Pattern, String or Image
*
* @param target The Pattern, String or Image
* @return the Image
*/
private <PSI> Image getImage(PSI target) {
if (target instanceof Pattern) {
return ((Pattern) target).getImage();
} else if (target instanceof String) {
return Image.get((String) target);
} else if (target instanceof Image) {
return (Image) target;
} else {
return null;
}
}
/**
* return false to skip <br>
* return true to try again <br>
* throw FindFailed to abort
*
* @param target Handles a failed find action
* @throws FindFailed
*/
private <PSI> boolean handleFindFailed(PSI target) throws FindFailed {
return handleFindFailedShowDialog(target, false);
}
private <PSI> boolean handleFindFailedQuietly(PSI target) {
try {
return handleFindFailedShowDialog(target, false);
} catch (FindFailed ex) {
}
return false;
}
private <PSI> boolean handleFindFailedImageMissing(PSI target) {
boolean shouldHandle = false;
try {
shouldHandle = handleFindFailedShowDialog(target, true);
} catch (FindFailed ex) {
return false;
}
if (!shouldHandle) {
return false;
}
getRobotForRegion().delay(500);
ScreenImage img = getScreen().userCapture("capture missing image");
if (img != null) {
String path = ImagePath.getBundlePath();
if (path == null) {
return false;
}
String imgName = (String) target;
img.getFile(path, imgName);
return true;
}
return false;
}
private boolean handleFindFailedShowDialog(Object target, boolean shouldCapture) throws FindFailed {
FindFailedResponse response;
if (findFailedResponse == FindFailedResponse.PROMPT) {
FindFailedDialog fd = new FindFailedDialog(target, shouldCapture);
fd.setVisible(true);
response = fd.getResponse();
fd.dispose();
wait(0.5);
} else {
response = findFailedResponse;
}
if (response == FindFailedResponse.SKIP) {
return false;
} else if (response == FindFailedResponse.RETRY) {
return true;
} else if (response == FindFailedResponse.ABORT) {
String targetStr = target.toString();
if (target instanceof String) {
targetStr = targetStr.trim();
}
throw new FindFailed(String.format("can not find %s in %s", targetStr, this.toStringShort()));
}
return false;
}
/**
* finds the given Pattern, String or Image in the region and returns the best match. If AutoWaitTimeout
* is set, this is equivalent to wait(). Otherwise only one search attempt will be done.
*
* @param <PSI> Pattern, String or Image
* @param target A search criteria
* @return If found, the element. null otherwise
* @throws FindFailed if the Find operation failed
*/
public <PSI> Match find(PSI target) throws FindFailed {
if (autoWaitTimeout > 0) {
return wait(target, autoWaitTimeout);
}
lastMatch = null;
String targetStr = target.toString();
if (target instanceof String) {
targetStr = targetStr.trim();
}
while (true) {
try {
log(3, "find: waiting 0 secs for %s to appear in %s", targetStr, this.toStringShort());
lastMatch = doFind(target, null);
} catch (IOException ex) {
if (ex instanceof IOException) {
if (handleFindFailedImageMissing(target)) {
continue;
}
}
throw new FindFailed(ex.getMessage());
}
if (lastMatch != null) {
Image img = getImage(target);
lastMatch.setImage(img);
if (img != null) {
img.setLastSeen(lastMatch.getRect(), lastMatch.getScore());
}
log(lvl, "find: %s has appeared \nat %s", targetStr, lastMatch);
return lastMatch;
}
log(3, "find: %s has not appeared [%d msec]", targetStr, lastFindTime);
if (!handleFindFailed(target)) {
return null;
}
}
}
/**
* finds all occurences of the given Pattern, String or Image in the region and returns an Iterator of Matches.
*
*
* @param <PSI> Pattern, String or Image
* @param target A search criteria
* @return All elements matching
* @throws FindFailed if the Find operation failed
*/
public <PSI> Iterator<Match> findAll(PSI target) throws FindFailed {
lastMatches = null;
String targetStr = target.toString();
if (target instanceof String) {
targetStr = targetStr.trim();
}
while (true) {
try {
if (autoWaitTimeout > 0) {
RepeatableFindAll rf = new RepeatableFindAll(target);
rf.repeat(autoWaitTimeout);
lastMatches = rf.getMatches();
} else {
lastMatches = doFindAll(target, null);
}
} catch (Exception ex) {
if (ex instanceof IOException) {
if (handleFindFailedImageMissing(target)) {
continue;
}
}
throw new FindFailed(ex.getMessage());
}
if (lastMatches != null) {
return lastMatches;
}
if (!handleFindFailed(target)) {
return null;
}
}
}
public <PSI> Match[] findAllByRow(PSI target) {
Match[] matches = new Match[0];
List<Match> mList = findAllCollect(target);
if (mList.isEmpty()) {
return null;
}
Collections.sort(mList, new Comparator<Match>() {
@Override
public int compare(Match m1, Match m2) {
if (m1.y == m2.y) {
return m1.x - m2.x;
}
return m1.y - m2.y;
}
});
return mList.toArray(matches);
}
public <PSI> Match[] findAllByColumn(PSI target) {
Match[] matches = new Match[0];
List<Match> mList = findAllCollect(target);
if (mList.isEmpty()) {
return null;
}
Collections.sort(mList, new Comparator<Match>() {
@Override
public int compare(Match m1, Match m2) {
if (m1.x == m2.x) {
return m1.y - m2.y;
}
return m1.x - m2.x;
}
});
return mList.toArray(matches);
}
private <PSI> List<Match> findAllCollect(PSI target) {
Iterator<Match> mIter = null;
try {
mIter = findAll(target);
} catch (Exception ex) {
Debug.error("findAllByRow: %s", ex.getMessage());
return null;
}
List<Match> mList = new ArrayList<Match>();
while (mIter.hasNext()) {
mList.add(mIter.next());
}
return mList;
}
public <PSI> Match findBest(Object... args) {
Debug.log(lvl, "findBest: enter");
Match mResult = null;
List<Match> mList = findAnyCollect(args);
if (mList != null) {
Collections.sort(mList, new Comparator<Match>() {
@Override
public int compare(Match m1, Match m2) {
double ms = m2.getScore() - m1.getScore();
if (ms < 0) {
return -1;
} else if (ms > 0) {
return 1;
}
return 0;
}
});
mResult = mList.get(0);
}
return mResult;
}
private List<Match> findAnyCollect(Object... args) {
if (args == null) return null;
List<Match> mList = new ArrayList<Match>();
Match[] mArray = new Match[args.length];
SubFindRun[] theSubs = new SubFindRun[args.length];
int nobj = 0;
ScreenImage base = getScreen().capture(this);
for (Object obj : args) {
mArray[nobj] = null;
if (obj instanceof Pattern || obj instanceof String || obj instanceof Image) {
theSubs[nobj] = new SubFindRun(mArray, nobj, base, obj, this);
new Thread(theSubs[nobj]).start();
}
nobj++;
}
Debug.log(lvl, "findAnyCollect: waiting for SubFindRuns");
nobj = 0;
boolean all = false;
while (!all) {
all = true;
for (SubFindRun sub : theSubs) {
all &= sub.hasFinished();
}
}
Debug.log(lvl, "findAnyCollect: SubFindRuns finished");
nobj = 0;
for (Match match : mArray) {
if (match != null) {
match.setIndex(nobj);
mList.add(match);
} else {
}
nobj++;
}
return mList;
}
private class SubFindRun implements Runnable {
Match[] mArray;
ScreenImage base;
Object target;
Region reg;
boolean finished = false;
int subN;
public SubFindRun(Match[] pMArray, int pSubN,
ScreenImage pBase, Object pTarget, Region pReg) {
subN = pSubN;
base = pBase;
target = pTarget;
reg = pReg;
mArray = pMArray;
}
@Override
public void run() {
try {
mArray[subN] = reg.findInImage(base, target);
} catch (Exception ex) {
log(-1, "findAnyCollect: image file not found:\n", target);
}
hasFinished(true);
}
public boolean hasFinished() {
return hasFinished(false);
}
public synchronized boolean hasFinished(boolean state) {
if (state) {
finished = true;
}
return finished;
}
}
private Match findInImage(ScreenImage base, Object target) throws IOException {
Finder finder = null;
Match match = null;
boolean findingText = false;
Image img = null;
if (target instanceof String) {
if (((String) target).startsWith("\t") && ((String) target).endsWith("\t")) {
findingText = true;
} else {
img = Image.create((String) target);
if (img.isValid()) {
finder = doCheckLastSeenAndCreateFinder(base, img, 0.0, null);
if (!finder.hasNext()) {
runFinder(finder, img);
}
} else if (img.isText()) {
findingText = true;
} else {
throw new IOException("Region: findInImage: Image not loadable: " + target.toString());
}
}
if (findingText) {
if (TextRecognizer.getInstance() != null) {
log(lvl, "findInImage: Switching to TextSearch");
finder = new Finder(getScreen().capture(x, y, w, h), this);
finder.findText((String) target);
}
}
} else if (target instanceof Pattern) {
if (((Pattern) target).isValid()) {
img = ((Pattern) target).getImage();
finder = doCheckLastSeenAndCreateFinder(base, img, 0.0, (Pattern) target);
if (!finder.hasNext()) {
runFinder(finder, target);
}
} else {
throw new IOException("Region: findInImage: Image not loadable: " + target.toString());
}
} else if (target instanceof Image) {
if (((Image) target).isValid()) {
img = ((Image) target);
finder = doCheckLastSeenAndCreateFinder(base, img, 0.0, null);
if (!finder.hasNext()) {
runFinder(finder, img);
}
} else {
throw new IOException("Region: findInImage: Image not loadable: " + target.toString());
}
} else {
log(-1, "findInImage: invalid parameter: %s", target);
return null;
}
if (finder.hasNext()) {
match = finder.next();
match.setImage(img);
img.setLastSeen(match.getRect(), match.getScore());
}
return match;
}
/**
* Waits for the Pattern, String or Image to appear until the AutoWaitTimeout value is exceeded.
*
* @param <PSI> Pattern, String or Image
* @param target The target to search for
* @return The found Match
* @throws FindFailed if the Find operation finally failed
*/
public <PSI> Match wait(PSI target) throws FindFailed {
if (target instanceof Float || target instanceof Double) {
wait(0.0 + ((Double) target));
return null;
}
return wait(target, autoWaitTimeout);
}
/**
* Waits for the Pattern, String or Image to appear or timeout (in second) is passed
*
* @param <PSI> Pattern, String or Image
* @param target The target to search for
* @param timeout Timeout in seconds
* @return The found Match
* @throws FindFailed if the Find operation finally failed
*/
public <PSI> Match wait(PSI target, double timeout) throws FindFailed {
RepeatableFind rf;
lastMatch = null;
String targetStr = target.toString();
if (target instanceof String) {
targetStr = targetStr.trim();
}
while (true) {
try {
log(3, "find: waiting %.1f secs for %s to appear in %s", timeout, targetStr, this.toStringShort());
rf = new RepeatableFind(target);
rf.repeat(timeout);
lastMatch = rf.getMatch();
} catch (Exception ex) {
if (ex instanceof IOException) {
if (handleFindFailedImageMissing(target)) {
continue;
}
}
throw new FindFailed(ex.getMessage());
}
if (lastMatch != null) {
lastMatch.setImage(rf._image);
if (rf._image != null) {
rf._image.setLastSeen(lastMatch.getRect(), lastMatch.getScore());
}
log(lvl, "find: %s has appeared \nat %s", targetStr, lastMatch);
break;
}
log(3, "find: %s has not appeared [%d msec]", targetStr, lastFindTime);
if (!handleFindFailed(target)) {
return null;
}
}
return lastMatch;
}
//TODO 1.2.0 Region.compare as time optimized Region.exists
/**
* time optimized Region.exists, when image-size == region-size<br>
* 1.1.x: just using exists(img, 0), sizes not checked
* @param img image file name
* @return the match or null if not equal
*/
public Match compare(String img) {
return compare(Image.create(img));
}
/**
* time optimized Region.exists, when image-size == region-size<br>
* 1.1.x: just using exists(img, 0), sizes not checked
* @param img Image object
* @return the match or null if not equal
*/
public Match compare(Image img) {
return exists(img, 0);
}
/**
* Check if target exists (with the default autoWaitTimeout)
*
* @param <PSI> Pattern, String or Image
* @param target Pattern, String or Image
* @return the match (null if not found or image file missing)
*/
public <PSI> Match exists(PSI target) {
return exists(target, autoWaitTimeout);
}
/**
* Check if target exists with a specified timeout<br>
* timout = 0: returns immediately after first search
*
* @param <PSI> Pattern, String or Image
* @param target The target to search for
* @param timeout Timeout in seconds
* @return the match (null if not found or image file missing)
*/
public <PSI> Match exists(PSI target, double timeout) {
lastMatch = null;
String targetStr = target.toString();
if (target instanceof String) {
targetStr = targetStr.trim();
}
while (true) {
try {
log(3, "exists: waiting %.1f secs for %s to appear in %s", timeout, targetStr, this.toStringShort());
RepeatableFind rf = new RepeatableFind(target);
if (rf.repeat(timeout)) {
lastMatch = rf.getMatch();
Image img = rf._image;
lastMatch.setImage(img);
if (img != null) {
img.setLastSeen(lastMatch.getRect(), lastMatch.getScore());
}
log(lvl, "exists: %s has appeared \nat %s", targetStr, lastMatch);
return lastMatch;
} else {
if (!handleFindFailedQuietly(target)) {
break;
}
}
} catch (Exception ex) {
if (ex instanceof IOException) {
if (!handleFindFailedImageMissing(target)) {
break;
}
}
}
}
log(3, "exists: %s has not appeared [%d msec]", targetStr, lastFindTime);
return null;
}
/**
* Use findText() instead of find() in cases where the given string could be misinterpreted as an image filename
*
* @param text text
* @param timeout time
* @return the matched region containing the text
* @throws org.sikuli.script.FindFailed if not found
*/
public Match findText(String text, double timeout) throws FindFailed {
// the leading/trailing tab is used to internally switch to text search directly
return wait("\t" + text + "\t", timeout);
}
/**
* Use findText() instead of find() in cases where the given string could be misinterpreted as an image filename
*
* @param text text
* @return the matched region containing the text
* @throws org.sikuli.script.FindFailed if not found
*/
public Match findText(String text) throws FindFailed {
return findText(text, autoWaitTimeout);
}
/**
* Use findAllText() instead of findAll() in cases where the given string could be misinterpreted as an image filename
*
* @param text text
* @return the matched region containing the text
* @throws org.sikuli.script.FindFailed if not found
*/
public Iterator<Match> findAllText(String text) throws FindFailed {
// the leading/trailing tab is used to internally switch to text search directly
return findAll("\t" + text + "\t");
}
/**
* waits until target vanishes or timeout (in seconds) is
* passed (AutoWaitTimeout)
*
* @param <PSI> Pattern, String or Image
* @param target The target to wait for it to vanish
* @return true if the target vanishes, otherwise returns false.
*/
public <PSI> boolean waitVanish(PSI target) {
return waitVanish(target, autoWaitTimeout);
}
/**
* waits until target vanishes or timeout (in seconds) is
* passed
*
* @param <PSI> Pattern, String or Image
* @param target Pattern, String or Image
* @param timeout time in seconds
* @return true if target vanishes, false otherwise and if imagefile is missing.
*/
public <PSI> boolean waitVanish(PSI target, double timeout) {
while (true) {
try {
log(lvl, "waiting for " + target + " to vanish");
RepeatableVanish r = new RepeatableVanish(target);
if (r.repeat(timeout)) {
log(lvl, "" + target + " has vanished");
return true;
}
log(lvl, "" + target + " has not vanished before timeout");
return false;
} catch (Exception ex) {
if (ex instanceof IOException) {
if (handleFindFailedImageMissing(target)) {
continue;
}
}
break;
}
}
return false;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="find internal methods">
/**
* Match doFind( Pattern/String/Image ) finds the given pattern on the screen and returns the best match without
* waiting.
*/
private <PSI> Match doFind(PSI ptn, RepeatableFind repeating) throws IOException {
Finder f = null;
Match m = null;
IScreen s = null;
boolean findingText = false;
lastFindTime = (new Date()).getTime();
ScreenImage simg;
double findTimeout = autoWaitTimeout;
if (repeating != null) {
findTimeout = repeating.getFindTimeOut();
}
if (repeating != null && repeating._finder != null) {
simg = getScreen().capture(this);
f = repeating._finder;
f.setScreenImage(simg);
f.setRepeating();
if (Settings.FindProfiling) {
Debug.logp("[FindProfiling] Region.doFind repeat: %d msec",
new Date().getTime() - lastSearchTimeRepeat);
}
lastSearchTime = (new Date()).getTime();
f.findRepeat();
} else {
s = getScreen();
Image img = null;
if (ptn instanceof String) {
if (((String) ptn).startsWith("\t") && ((String) ptn).endsWith("\t")) {
findingText = true;
} else {
img = Image.create((String) ptn);
if (img.isValid()) {
lastSearchTime = (new Date()).getTime();
f = checkLastSeenAndCreateFinder(img, findTimeout, null);
if (!f.hasNext()) {
runFinder(f, img);
//f.find(img);
}
} else if (img.isText()) {
findingText = true;
} else {
throw new IOException("Region: doFind: Image not loadable: " + ptn.toString());
}
}
if (findingText) {
if (TextRecognizer.getInstance() != null) {
log(lvl, "doFind: Switching to TextSearch");
f = new Finder(getScreen().capture(x, y, w, h), this);
lastSearchTime = (new Date()).getTime();
f.findText((String) ptn);
}
}
} else if (ptn instanceof Pattern) {
if (((Pattern) ptn).isValid()) {
img = ((Pattern) ptn).getImage();
lastSearchTime = (new Date()).getTime();
f = checkLastSeenAndCreateFinder(img, findTimeout, (Pattern) ptn);
if (!f.hasNext()) {
runFinder(f, ptn);
//f.find((Pattern) ptn);
}
} else {
throw new IOException("Region: doFind: Image not loadable: " + ptn.toString());
}
} else if (ptn instanceof Image) {
if (((Image) ptn).isValid()) {
img = ((Image) ptn);
lastSearchTime = (new Date()).getTime();
f = checkLastSeenAndCreateFinder(img, findTimeout, null);
if (!f.hasNext()) {
runFinder(f, img);
//f.find(img);
}
} else {
throw new IOException("Region: doFind: Image not loadable: " + ptn.toString());
}
} else {
log(-1, "doFind: invalid parameter: %s", ptn);
Sikulix.terminate(999);
}
if (repeating != null) {
repeating._finder = f;
repeating._image = img;
}
}
lastSearchTimeRepeat = lastSearchTime;
lastSearchTime = (new Date()).getTime() - lastSearchTime;
lastFindTime = (new Date()).getTime() - lastFindTime;
if (f.hasNext()) {
m = f.next();
m.setTimes(lastFindTime, lastSearchTime);
if (Settings.FindProfiling) {
Debug.logp("[FindProfiling] Region.doFind final: %d msec", lastSearchTime);
}
}
return m;
}
private void runFinder(Finder f, Object target) {
if (Debug.shouldHighlight()) {
if (this.scr.getW() > w + 20 && this.scr.getH() > h + 20)
highlight(2, "#000255000");
}
if (target instanceof Image) {
f.find((Image) target);
} else if (target instanceof Pattern) {
f.find((Pattern) target);
}
}
private Finder checkLastSeenAndCreateFinder(Image img, double findTimeout, Pattern ptn) {
return doCheckLastSeenAndCreateFinder(null, img, findTimeout, ptn);
}
private Finder doCheckLastSeenAndCreateFinder(ScreenImage base, Image img, double findTimeout, Pattern ptn) {
if (base == null) {
base = getScreen().capture(this);
}
if (!Settings.UseImageFinder && Settings.CheckLastSeen && null != img.getLastSeen()) {
Region r = Region.create(img.getLastSeen());
float score = (float) (img.getLastSeenScore() - 0.01);
if (this.contains(r)) {
Finder f = null;
if (true) {
f = new Finder(base.getSub(r.getRect()), r);
if (Debug.shouldHighlight()) {
if (this.scr.getW() > w + 10 && this.scr.getH() > h + 10)
highlight(2, "#000255000");
}
}
if (ptn == null) {
f.find(new Pattern(img).similar(score));
} else {
f.find(new Pattern(ptn).similar(score));
}
if (f.hasNext()) {
log(lvl, "checkLastSeen: still there");
return f;
}
log(lvl, "checkLastSeen: not there");
}
}
if (Settings.UseImageFinder) {
ImageFinder f = new ImageFinder(this);
f.setFindTimeout(findTimeout);
return f;
} else {
return new Finder(base, this);
}
}
public void saveLastScreenImage() {
ScreenImage simg = getScreen().getLastScreenImageFromScreen();
if (simg != null) {
simg.saveLastScreenImage(runTime.fSikulixStore);
}
}
/**
* Match findAllNow( Pattern/String/Image ) finds all the given pattern on the screen and returns the best matches
* without waiting.
*/
private <PSI> Iterator<Match> doFindAll(PSI ptn, RepeatableFindAll repeating) throws IOException {
boolean findingText = false;
Finder f;
ScreenImage simg = getScreen().capture(x, y, w, h);
if (repeating != null && repeating._finder != null) {
f = repeating._finder;
f.setScreenImage(simg);
f.setRepeating();
f.findAllRepeat();
} else {
f = new Finder(simg, this);
Image img = null;
if (ptn instanceof String) {
if (((String) ptn).startsWith("\t") && ((String) ptn).endsWith("\t")) {
findingText = true;
} else {
img = Image.create((String) ptn);
if (img.isValid()) {
f.findAll(img);
} else if (img.isText()) {
findingText = true;
} else {
throw new IOException("Region: doFind: Image not loadable: " + (String) ptn);
}
}
if (findingText) {
if (TextRecognizer.getInstance() != null) {
log(lvl, "doFindAll: Switching to TextSearch");
f.findAllText((String) ptn);
}
}
} else if (ptn instanceof Pattern) {
if (((Pattern) ptn).isValid()) {
img = ((Pattern) ptn).getImage();
f.findAll((Pattern) ptn);
} else {
throw new IOException("Region: doFind: Image not loadable: " + (String) ptn);
}
} else if (ptn instanceof Image) {
if (((Image) ptn).isValid()) {
img = ((Image) ptn);
f.findAll((Image) ptn);
} else {
throw new IOException("Region: doFind: Image not loadable: " + (String) ptn);
}
} else {
log(-1, "doFind: invalid parameter: %s", ptn);
Sikulix.terminate(999);
}
if (repeating != null) {
repeating._finder = f;
repeating._image = img;
}
}
if (f.hasNext()) {
return f;
}
return null;
}
// Repeatable Find ////////////////////////////////
private abstract class Repeatable {
private double findTimeout;
abstract void run() throws Exception;
abstract boolean ifSuccessful();
double getFindTimeOut() {
return findTimeout;
}
// return TRUE if successful before timeout
// return FALSE if otherwise
// throws Exception if any unexpected error occurs
boolean repeat(double timeout) throws Exception {
findTimeout = timeout;
int MaxTimePerScan = (int) (1000.0 / waitScanRate);
int timeoutMilli = (int) (timeout * 1000);
long begin_t = (new Date()).getTime();
do {
long before_find = (new Date()).getTime();
run();
if (ifSuccessful()) {
return true;
} else if (timeoutMilli < MaxTimePerScan || Settings.UseImageFinder) {
// instant return on first search failed if timeout very small or 0
// or when using new ImageFinder
return false;
}
long after_find = (new Date()).getTime();
if (after_find - before_find < MaxTimePerScan) {
getRobotForRegion().delay((int) (MaxTimePerScan - (after_find - before_find)));
} else {
getRobotForRegion().delay(10);
}
} while (begin_t + timeout * 1000 > (new Date()).getTime());
return false;
}
}
private class RepeatableFind extends Repeatable {
Object _target;
Match _match = null;
Finder _finder = null;
Image _image = null;
public <PSI> RepeatableFind(PSI target) {
_target = target;
}
public Match getMatch() {
if (_finder != null) {
_finder.destroy();
}
return (_match == null) ? _match : new Match(_match);
}
@Override
public void run() throws IOException {
_match = doFind(_target, this);
}
@Override
boolean ifSuccessful() {
return _match != null;
}
}
private class RepeatableVanish extends RepeatableFind {
public <PSI> RepeatableVanish(PSI target) {
super(target);
}
@Override
boolean ifSuccessful() {
return _match == null;
}
}
private class RepeatableFindAll extends Repeatable {
Object _target;
Iterator<Match> _matches = null;
Finder _finder = null;
Image _image = null;
public <PSI> RepeatableFindAll(PSI target) {
_target = target;
}
public Iterator<Match> getMatches() {
return _matches;
}
@Override
public void run() throws IOException {
_matches = doFindAll(_target, this);
}
@Override
boolean ifSuccessful() {
return _matches != null;
}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Find internal support">
// private <PatternStringRegionMatch> Region getRegionFromTarget(PatternStringRegionMatch target) throws FindFailed {
// if (target instanceof Pattern || target instanceof String || target instanceof Image) {
// Match m = find(target);
// if (m != null) {
// return m.setScreen(scr);
// }
// return null;
// }
// if (target instanceof Region) {
// return ((Region) target).setScreen(scr);
// }
// return null;
// }
private <PSIMRL> Location getLocationFromTarget(PSIMRL target) throws FindFailed {
if (target instanceof Pattern || target instanceof String || target instanceof Image) {
Match m = find(target);
if (m != null) {
if (isOtherScreen()) {
return m.getTarget().setOtherScreen(scr);
} else {
return m.getTarget();
}
}
return null;
}
if (target instanceof Match) {
return ((Match) target).getTarget();
}
if (target instanceof Region) {
return ((Region) target).getCenter();
}
if (target instanceof Location) {
return new Location((Location) target);
}
return null;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Observing">
protected Observer getObserver() {
if (regionObserver == null) {
regionObserver = new Observer(this);
}
return regionObserver;
}
/**
* evaluate if at least one event observer is defined for this region (the observer need not be running)
* @return true, if the region has an observer with event observers
*/
public boolean hasObserver() {
if (regionObserver != null) {
return regionObserver.hasObservers();
}
return false;
}
/**
*
* @return true if an observer is running for this region
*/
public boolean isObserving() {
return observing;
}
/**
*
* @return true if any events have happened for this region, false otherwise
*/
public boolean hasEvents() {
return Observing.hasEvents(this);
}
/**
* the region's events are removed from the list
* @return the region's happened events as array if any (size might be 0)
*/
public ObserveEvent[] getEvents() {
return Observing.getEvents(this);
}
/**
* the event is removed from the list
* @param name event's name
* @return the named event if happened otherwise null
*/
public ObserveEvent getEvent(String name) {
return Observing.getEvent(name);
}
/**
* set the observer with the given name inactive (not checked while observing)
* @param name observers name
*/
public void setInactive(String name) {
if (!hasObserver()) {
return;
}
Observing.setActive(name, false);
}
/**
* set the observer with the given name active (not checked while observing)
* @param name observers name
*/
public void setActive(String name) {
if (!hasObserver()) {
return;
}
Observing.setActive(name, true);
}
/**
* a subsequently started observer in this region should wait for target
* and notify the given observer about this event<br>
* for details about the observe event handler: {@link ObserverCallBack}<br>
* for details about APPEAR/VANISH/CHANGE events: {@link ObserveEvent}<br>
* @param <PSI> Pattern, String or Image
* @param target Pattern, String or Image
* @param observer ObserverCallBack
* @return the event's name
*/
public <PSI> String onAppear(PSI target, Object observer) {
return onEvent(target, observer, ObserveEvent.Type.APPEAR);
}
/**
* a subsequently started observer in this region should wait for target
* success and details about the event can be obtained using @{link Observing}<br>
* for details about APPEAR/VANISH/CHANGE events: {@link ObserveEvent}<br>
* @param <PSI> Pattern, String or Image
* @param target Pattern, String or Image
* @return the event's name
*/
public <PSI> String onAppear(PSI target) {
return onEvent(target, null, ObserveEvent.Type.APPEAR);
}
private <PSIC> String onEvent(PSIC targetThreshhold, Object observer, ObserveEvent.Type obsType) {
if (observer != null && (observer.getClass().getName().contains("org.python") ||
observer.getClass().getName().contains("org.jruby"))) {
observer = new ObserverCallBack(observer, obsType);
}
String name = Observing.add(this, (ObserverCallBack) observer, obsType, targetThreshhold);
log(lvl, "%s: observer %s %s: %s with: %s", toStringShort(), obsType,
(observer == null ? "" : " with callback"), name, targetThreshhold);
return name;
}
/**
* a subsequently started observer in this region should wait for the target to vanish
* and notify the given observer about this event<br>
* for details about the observe event handler: {@link ObserverCallBack}<br>
* for details about APPEAR/VANISH/CHANGE events: {@link ObserveEvent}<br>
* @param <PSI> Pattern, String or Image
* @param target Pattern, String or Image
* @param observer ObserverCallBack
* @return the event's name
*/
public <PSI> String onVanish(PSI target, Object observer) {
return onEvent(target, observer, ObserveEvent.Type.VANISH);
}
/**
* a subsequently started observer in this region should wait for the target to vanish
* success and details about the event can be obtained using @{link Observing}<br>
* for details about APPEAR/VANISH/CHANGE events: {@link ObserveEvent}<br>
* @param <PSI> Pattern, String or Image
* @param target Pattern, String or Image
* @return the event's name
*/
public <PSI> String onVanish(PSI target) {
return onEvent(target, null, ObserveEvent.Type.VANISH);
}
/**
* a subsequently started observer in this region should wait for changes in the region
* and notify the given observer about this event
* for details about the observe event handler: {@link ObserverCallBack}
* for details about APPEAR/VANISH/CHANGE events: {@link ObserveEvent}
* @param threshold minimum size of changes (rectangle threshhold x threshold)
* @param observer ObserverCallBack
* @return the event's name
*/
public String onChange(int threshold, Object observer) {
return onEvent( (threshold > 0 ? threshold : Settings.ObserveMinChangedPixels),
observer, ObserveEvent.Type.CHANGE);
}
/**
* a subsequently started observer in this region should wait for changes in the region
* success and details about the event can be obtained using @{link Observing}<br>
* for details about APPEAR/VANISH/CHANGE events: {@link ObserveEvent}
* @param threshold minimum size of changes (rectangle threshhold x threshold)
* @return the event's name
*/
public String onChange(int threshold) {
return onEvent( (threshold > 0 ? threshold : Settings.ObserveMinChangedPixels),
null, ObserveEvent.Type.CHANGE);
}
/**
* a subsequently started observer in this region should wait for changes in the region
* and notify the given observer about this event <br>
* minimum size of changes used: Settings.ObserveMinChangedPixels
* for details about the observe event handler: {@link ObserverCallBack}
* for details about APPEAR/VANISH/CHANGE events: {@link ObserveEvent}
* @param observer ObserverCallBack
* @return the event's name
*/
public String onChange(Object observer) {
return onEvent(Settings.ObserveMinChangedPixels, observer, ObserveEvent.Type.CHANGE);
}
/**
* a subsequently started observer in this region should wait for changes in the region
* success and details about the event can be obtained using @{link Observing}<br>
* minimum size of changes used: Settings.ObserveMinChangedPixels
* for details about APPEAR/VANISH/CHANGE events: {@link ObserveEvent}
* @return the event's name
*/
public String onChange() {
return onEvent(Settings.ObserveMinChangedPixels, null, ObserveEvent.Type.CHANGE);
}
//<editor-fold defaultstate="collapsed" desc="obsolete">
// /**
// *INTERNAL USE ONLY: for use with scripting API bridges
// * @param <PSI> Pattern, String or Image
// * @param target Pattern, String or Image
// * @param observer ObserverCallBack
// * @return the event's name
// */
// public <PSI> String onAppearJ(PSI target, Object observer) {
// return onEvent(target, observer, ObserveEvent.Type.APPEAR);
// }
//
// /**
// *INTERNAL USE ONLY: for use with scripting API bridges
// * @param <PSI> Pattern, String or Image
// * @param target Pattern, String or Image
// * @param observer ObserverCallBack
// * @return the event's name
// */
// public <PSI> String onVanishJ(PSI target, Object observer) {
// return onEvent(target, observer, ObserveEvent.Type.VANISH);
// }
//
// /**
// *INTERNAL USE ONLY: for use with scripting API bridges
// * @param threshold min pixel size - 0 = ObserveMinChangedPixels
// * @param observer ObserverCallBack
// * @return the event's name
// */
// public String onChangeJ(int threshold, Object observer) {
// return onEvent( (threshold > 0 ? threshold : Settings.ObserveMinChangedPixels),
// observer, ObserveEvent.Type.CHANGE);
// }
//
//</editor-fold>
public String onChangeDo(int threshold, Object observer) {
String name = Observing.add(this, (ObserverCallBack) observer, ObserveEvent.Type.CHANGE, threshold);
log(lvl, "%s: onChange%s: %s minSize: %d", toStringShort(),
(observer == null ? "" : " with callback"), name, threshold);
return name;
}
/**
* start an observer in this region that runs forever (use stopObserving() in handler)
* for details about the observe event handler: {@link ObserverCallBack}
* for details about APPEAR/VANISH/CHANGE events: {@link ObserveEvent}
* @return false if not possible, true if events have happened
*/
public boolean observe() {
return observe(Float.POSITIVE_INFINITY);
}
/**
* start an observer in this region for the given time
* for details about the observe event handler: {@link ObserverCallBack}
* for details about APPEAR/VANISH/CHANGE events: {@link ObserveEvent}
* @param secs time in seconds the observer should run
* @return false if not possible, true if events have happened
*/
public boolean observe(double secs) {
return observeDo(secs);
}
/**
*INTERNAL USE ONLY: for use with scripting API bridges
* @param secs time in seconds the observer should run
* @param bg run in background true/false
* @return false if not possible, true if events have happened
*/
public boolean observeJ(double secs, boolean bg) {
if (bg) {
return observeInBackground(secs);
} else {
return observeDo(secs);
}
}
private boolean observeDo(double secs) {
if (regionObserver == null) {
Debug.error("Region: observe: Nothing to observe (Region might be invalid): " + this.toStringShort());
return false;
}
if (observing) {
Debug.error("Region: observe: already running for this region. Only one allowed!");
return false;
}
log(lvl, "observe: starting in " + this.toStringShort() + " for " + secs + " seconds");
int MaxTimePerScan = (int) (1000.0 / observeScanRate);
long begin_t = (new Date()).getTime();
long stop_t;
if (secs > Long.MAX_VALUE) {
stop_t = Long.MAX_VALUE;
} else {
stop_t = begin_t + (long) (secs * 1000);
}
regionObserver.initialize();
observing = true;
Observing.addRunningObserver(this);
while (observing && stop_t > (new Date()).getTime()) {
long before_find = (new Date()).getTime();
ScreenImage simg = getScreen().capture(x, y, w, h);
if (!regionObserver.update(simg)) {
observing = false;
break;
}
if (!observing) {
break;
}
long after_find = (new Date()).getTime();
try {
if (after_find - before_find < MaxTimePerScan) {
Thread.sleep((int) (MaxTimePerScan - (after_find - before_find)));
}
} catch (Exception e) {
}
}
boolean observeSuccess = false;
if (observing) {
observing = false;
log(lvl, "observe: stopped due to timeout in "
+ this.toStringShort() + " for " + secs + " seconds");
} else {
log(lvl, "observe: ended successfully: " + this.toStringShort());
observeSuccess = Observing.hasEvents(this);
}
return observeSuccess;
}
/**
* start an observer in this region for the given time that runs in background
* for details about the observe event handler: {@link ObserverCallBack}
* for details about APPEAR/VANISH/CHANGE events: {@link ObserveEvent}
* @param secs time in seconds the observer should run
* @return false if not possible, true otherwise
*/
public boolean observeInBackground(double secs) {
if (observing) {
Debug.error("Region: observeInBackground: already running for this region. Only one allowed!");
return false;
}
log(lvl, "entering observeInBackground for %f secs", secs);
Thread observeThread = new Thread(new ObserverThread(secs));
observeThread.start();
log(lvl, "observeInBackground now running");
return true;
}
private class ObserverThread implements Runnable {
private double time;
ObserverThread(double time) {
this.time = time;
}
@Override
public void run() {
observe(time);
}
}
/**
* stops a running observer
*/
public void stopObserver() {
log(lvl, "observe: request to stop observer for " + this.toStringShort());
observing = false;
}
/**
* stops a running observer printing an info message
* @param message text
*/
public void stopObserver(String message) {
Debug.info(message);
stopObserver();
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Mouse actions - clicking">
public Location checkMatch() {
if (lastMatch != null) {
return lastMatch.getTarget();
}
return getTarget();
}
/**
* move the mouse pointer to region's last successful match <br>use center if no lastMatch <br>
* if region is a match: move to targetOffset <br>same as mouseMove
*
* @return 1 if possible, 0 otherwise
*/
public int hover() {
try { // needed to cut throw chain for FindFailed
return hover(checkMatch());
} catch (FindFailed ex) {
}
return 0;
}
/**
* move the mouse pointer to the given target location<br> same as mouseMove<br> Pattern or Filename - do a find
* before and use the match<br> Region - position at center<br> Match - position at match's targetOffset<br> Location
* - position at that point<br>
*
* @param <PFRML> to search: Pattern, Filename, Text, Region, Match or Location
* @param target Pattern, Filename, Text, Region, Match or Location
* @return 1 if possible, 0 otherwise
* @throws FindFailed for Pattern or Filename
*/
public <PFRML> int hover(PFRML target) throws FindFailed {
log(lvl, "hover: " + target);
return mouseMove(target);
}
/**
* left click at the region's last successful match <br>use center if no lastMatch <br>if region is a match: click
* targetOffset
*
* @return 1 if possible, 0 otherwise
*/
public int click() {
try { // needed to cut throw chain for FindFailed
return click(checkMatch(), 0);
} catch (FindFailed ex) {
return 0;
}
}
/**
* left click at the given target location<br> Pattern or Filename - do a find before and use the match<br> Region -
* position at center<br> Match - position at match's targetOffset<br>
* Location - position at that point<br>
*
* @param <PFRML> to search: Pattern, Filename, Text, Region, Match or Location
* @param target Pattern, Filename, Text, Region, Match or Location
* @return 1 if possible, 0 otherwise
* @throws FindFailed for Pattern or Filename
*/
public <PFRML> int click(PFRML target) throws FindFailed {
return click(target, 0);
}
/**
* left click at the given target location<br> holding down the given modifier keys<br>
* Pattern or Filename - do a find before and use the match<br> Region - position at center<br>
* Match - position at match's targetOffset<br> Location - position at that point<br>
*
* @param <PFRML> to search: Pattern, Filename, Text, Region, Match or Location
* @param target Pattern, Filename, Text, Region, Match or Location
* @param modifiers the value of the resulting bitmask (see KeyModifier)
* @return 1 if possible, 0 otherwise
* @throws FindFailed for Pattern or Filename
*/
public <PFRML> int click(PFRML target, Integer modifiers) throws FindFailed {
Location loc = getLocationFromTarget(target);
int ret = Mouse.click(loc, InputEvent.BUTTON1_MASK, modifiers, false, this);
//TODO SikuliActionManager.getInstance().clickTarget(this, target, _lastScreenImage, _lastMatch);
return ret;
}
/**
* double click at the region's last successful match <br>use center if no lastMatch <br>if region is a match: click
* targetOffset
*
* @return 1 if possible, 0 otherwise
*/
public int doubleClick() {
try { // needed to cut throw chain for FindFailed
return doubleClick(checkMatch(), 0);
} catch (FindFailed ex) {
return 0;
}
}
/**
* double click at the given target location<br> Pattern or Filename - do a find before and use the match<br> Region -
* position at center<br> Match - position at match's targetOffset<br>
* Location - position at that point<br>
*
* @param <PFRML> Pattern, Filename, Text, Region, Match or Location
* @param target Pattern, Filename, Text, Region, Match or Location
* @return 1 if possible, 0 otherwise
* @throws FindFailed for Pattern or Filename
*/
public <PFRML> int doubleClick(PFRML target) throws FindFailed {
return doubleClick(target, 0);
}
/**
* double click at the given target location<br> holding down the given modifier keys<br>
* Pattern or Filename - do a find before and use the match<br> Region - position at center<br > Match - position at
* match's targetOffset<br> Location - position at that point<br>
*
* @param <PFRML> Pattern, Filename, Text, Region, Match or Location
* @param target Pattern, Filename, Text, Region, Match or Location
* @param modifiers the value of the resulting bitmask (see KeyModifier)
* @return 1 if possible, 0 otherwise
* @throws FindFailed for Pattern or Filename
*/
public <PFRML> int doubleClick(PFRML target, Integer modifiers) throws FindFailed {
Location loc = getLocationFromTarget(target);
int ret = Mouse.click(loc, InputEvent.BUTTON1_MASK, modifiers, true, this);
//TODO SikuliActionManager.getInstance().doubleClickTarget(this, target, _lastScreenImage, _lastMatch);
return ret;
}
/**
* right click at the region's last successful match <br>use center if no lastMatch <br>if region is a match: click
* targetOffset
*
* @return 1 if possible, 0 otherwise
*/
public int rightClick() {
try { // needed to cut throw chain for FindFailed
return rightClick(checkMatch(), 0);
} catch (FindFailed ex) {
return 0;
}
}
/**
* right click at the given target location<br> Pattern or Filename - do a find before and use the match<br> Region -
* position at center<br> Match - position at match's targetOffset<br > Location - position at that point<br>
*
* @param <PFRML> Pattern, Filename, Text, Region, Match or Location
* @param target Pattern, Filename, Text, Region, Match or Location
* @return 1 if possible, 0 otherwise
* @throws FindFailed for Pattern or Filename
*/
public <PFRML> int rightClick(PFRML target) throws FindFailed {
return rightClick(target, 0);
}
/**
* right click at the given target location<br> holding down the given modifier keys<br>
* Pattern or Filename - do a find before and use the match<br> Region - position at center<br > Match - position at
* match's targetOffset<br> Location - position at that point<br>
*
* @param <PFRML> Pattern, Filename, Text, Region, Match or Location
* @param target Pattern, Filename, Text, Region, Match or Location
* @param modifiers the value of the resulting bitmask (see KeyModifier)
* @return 1 if possible, 0 otherwise
* @throws FindFailed for Pattern or Filename
*/
public <PFRML> int rightClick(PFRML target, Integer modifiers) throws FindFailed {
Location loc = getLocationFromTarget(target);
int ret = Mouse.click(loc, InputEvent.BUTTON3_MASK, modifiers, false, this);
//TODO SikuliActionManager.getInstance().rightClickTarget(this, target, _lastScreenImage, _lastMatch);
return ret;
}
/**
* time in milliseconds to delay between button down/up at next click only (max 1000)
*
* @param millisecs value
*/
public void delayClick(int millisecs) {
Settings.ClickDelay = millisecs;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Mouse actions - drag & drop">
/**
* Drag from region's last match and drop at given target <br>applying Settings.DelayAfterDrag and DelayBeforeDrop
* <br> using left mouse button
*
* @param <PFRML> Pattern, Filename, Text, Region, Match or Location
* @param target Pattern, Filename, Text, Region, Match or Location
* @return 1 if possible, 0 otherwise
* @throws FindFailed if the Find operation failed
*/
public <PFRML> int dragDrop(PFRML target) throws FindFailed {
return dragDrop(lastMatch, target);
}
/**
* Drag from a position and drop to another using left mouse button<br>applying Settings.DelayAfterDrag and
* DelayBeforeDrop
*
* @param <PFRML> Pattern, Filename, Text, Region, Match or Location
* @param t1 source position
* @param t2 destination position
* @return 1 if possible, 0 otherwise
* @throws FindFailed if the Find operation failed
*/
public <PFRML> int dragDrop(PFRML t1, PFRML t2) throws FindFailed {
Location loc1 = getLocationFromTarget(t1);
Location loc2 = getLocationFromTarget(t2);
int retVal = 0;
if (loc1 != null && loc2 != null) {
IRobot r1 = loc1.getRobotForPoint("drag");
IRobot r2 = loc2.getRobotForPoint("drop");
if (r1 != null && r2 != null) {
Mouse.use(this);
r1.smoothMove(loc1);
r1.delay((int) (Settings.DelayBeforeMouseDown * 1000));
r1.mouseDown(InputEvent.BUTTON1_MASK);
double DelayBeforeDrag = Settings.DelayBeforeDrag;
if (DelayBeforeDrag < 0.0) {
DelayBeforeDrag = Settings.DelayAfterDrag;
}
r1.delay((int) (DelayBeforeDrag * 1000));
r2.smoothMove(loc2);
r2.delay((int) (Settings.DelayBeforeDrop * 1000));
r2.mouseUp(InputEvent.BUTTON1_MASK);
Mouse.let(this);
retVal = 1;
}
}
Settings.DelayBeforeMouseDown = Settings.DelayValue;
Settings.DelayAfterDrag = Settings.DelayValue;
Settings.DelayBeforeDrag = -Settings.DelayValue;
Settings.DelayBeforeDrop = Settings.DelayValue;
return retVal;
}
/**
* Prepare a drag action: move mouse to given target <br>press and hold left mouse button <br >wait
* Settings.DelayAfterDrag
*
* @param <PFRML> Pattern, Filename, Text, Region, Match or Location
* @param target Pattern, Filename, Text, Region, Match or Location
* @return 1 if possible, 0 otherwise
* @throws FindFailed if not found
*/
public <PFRML> int drag(PFRML target) throws FindFailed {
Location loc = getLocationFromTarget(target);
int retVal = 0;
if (loc != null) {
IRobot r = loc.getRobotForPoint("drag");
if (r != null) {
Mouse.use(this);
r.smoothMove(loc);
r.delay((int) (Settings.DelayBeforeMouseDown * 1000));
r.mouseDown(InputEvent.BUTTON1_MASK);
double DelayBeforeDrag = Settings.DelayBeforeDrag;
if (DelayBeforeDrag < 0.0) {
DelayBeforeDrag = Settings.DelayAfterDrag;
}
r.delay((int) (DelayBeforeDrag * 1000));
r.waitForIdle();
Mouse.let(this);
retVal = 1;
}
}
Settings.DelayBeforeMouseDown = Settings.DelayValue;
Settings.DelayAfterDrag = Settings.DelayValue;
Settings.DelayBeforeDrag = -Settings.DelayValue;
Settings.DelayBeforeDrop = Settings.DelayValue;
return retVal;
}
/**
* finalize a drag action with a drop: move mouse to given target <br>
* wait Settings.DelayBeforeDrop <br>
* before releasing the left mouse button
*
* @param <PFRML> Pattern, Filename, Text, Region, Match or Location
* @param target Pattern, Filename, Text, Region, Match or Location
* @return 1 if possible, 0 otherwise
* @throws FindFailed if not found
*/
public <PFRML> int dropAt(PFRML target) throws FindFailed {
Location loc = getLocationFromTarget(target);
int retVal = 0;
if (loc != null) {
IRobot r = loc.getRobotForPoint("drag");
if (r != null) {
Mouse.use(this);
r.smoothMove(loc);
r.delay((int) (Settings.DelayBeforeDrop * 1000));
r.mouseUp(InputEvent.BUTTON1_MASK);
r.waitForIdle();
Mouse.let(this);
retVal = 1;
}
}
Settings.DelayBeforeMouseDown = Settings.DelayValue;
Settings.DelayAfterDrag = Settings.DelayValue;
Settings.DelayBeforeDrag = -Settings.DelayValue;
Settings.DelayBeforeDrop = Settings.DelayValue;
return retVal;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Mouse actions - low level + Wheel">
/**
* press and hold the specified buttons - use + to combine Button.LEFT left mouse button Button.MIDDLE middle mouse
* button Button.RIGHT right mouse button
*
* @param buttons spec
*/
public void mouseDown(int buttons) {
Mouse.down(buttons, this);
}
/**
* release all currently held buttons
*/
public void mouseUp() {
Mouse.up(0, this);
}
/**
* release the specified mouse buttons (see mouseDown) if buttons==0, all currently held buttons are released
*
* @param buttons spec
*/
public void mouseUp(int buttons) {
Mouse.up(buttons, this);
}
/**
* move the mouse pointer to the region's last successful match<br>same as hover<br>
*
* @return 1 if possible, 0 otherwise
*/
public int mouseMove() {
if (lastMatch != null) {
try {
return mouseMove(lastMatch);
} catch (FindFailed ex) {
return 0;
}
}
return 0;
}
/**
* move the mouse pointer to the given target location<br> same as hover<br> Pattern or Filename - do a find before
* and use the match<br> Region - position at center<br> Match - position at match's targetOffset<br>
* Location - position at that point<br>
*
* @param <PFRML> Pattern, Filename, Text, Region, Match or Location
* @param target Pattern, Filename, Text, Region, Match or Location
* @return 1 if possible, 0 otherwise
* @throws FindFailed for Pattern or Filename
*/
public <PFRML> int mouseMove(PFRML target) throws FindFailed {
Location loc = getLocationFromTarget(target);
return Mouse.move(loc, this);
}
/**
* move the mouse from the current position to the offset position given by the parameters
* @param xoff horizontal offset (< 0 left, > 0 right)
* @param yoff vertical offset (< 0 up, > 0 down)
* @return 1 if possible, 0 otherwise
*/
public int mouseMove(int xoff, int yoff) {
try {
return mouseMove(Mouse.at().offset(xoff, yoff));
} catch (Exception ex) {
return 0;
}
}
/**
* Move the wheel at the current mouse position<br> the given steps in the given direction: <br >Button.WHEEL_DOWN,
* Button.WHEEL_UP
*
* @param direction to move the wheel
* @param steps the number of steps
* @return 1 in any case
*/
public int wheel(int direction, int steps) {
Mouse.wheel(direction, steps, this);
return 1;
}
/**
* move the mouse pointer to the given target location<br> and move the wheel the given steps in the given direction:
* <br>Button.WHEEL_DOWN, Button.WHEEL_UP
*
* @param <PFRML> Pattern, Filename, Text, Region, Match or Location target
* @param target Pattern, Filename, Text, Region, Match or Location
* @param direction to move the wheel
* @param steps the number of steps
* @return 1 if possible, 0 otherwise
* @throws FindFailed if the Find operation failed
*/
public <PFRML> int wheel(PFRML target, int direction, int steps) throws FindFailed {
return wheel(target, direction, steps, Mouse.WHEEL_STEP_DELAY);
}
/**
* move the mouse pointer to the given target location<br> and move the wheel the given steps in the given direction:
* <br>Button.WHEEL_DOWN, Button.WHEEL_UP
*
* @param <PFRML> Pattern, Filename, Text, Region, Match or Location target
* @param target Pattern, Filename, Text, Region, Match or Location
* @param direction to move the wheel
* @param steps the number of steps
* @param stepDelay number of miliseconds to wait when incrementing the step value
* @return 1 if possible, 0 otherwise
* @throws FindFailed if the Find operation failed
*/
public <PFRML> int wheel(PFRML target, int direction, int steps, int stepDelay) throws FindFailed {
Location loc = getLocationFromTarget(target);
if (loc != null) {
Mouse.use(this);
Mouse.keep(this);
Mouse.move(loc, this);
Mouse.wheel(direction, steps, this, stepDelay);
Mouse.let(this);
return 1;
}
return 0;
}
/**
*
* @return current location of mouse pointer
* @deprecated use {@link Mouse#at()} instead
*/
@Deprecated
public static Location atMouse() {
return Mouse.at();
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Keyboard actions + paste">
/**
* press and hold the given key use a constant from java.awt.event.KeyEvent which might be special in the current
* machine/system environment
*
* @param keycode Java KeyCode
*/
public void keyDown(int keycode) {
getRobotForRegion().keyDown(keycode);
}
/**
* press and hold the given keys including modifier keys <br>use the key constants defined in class Key, <br>which
* only provides a subset of a US-QWERTY PC keyboard layout <br>might be mixed with simple characters
* <br>use + to concatenate Key constants
*
* @param keys valid keys
*/
public void keyDown(String keys) {
getRobotForRegion().keyDown(keys);
}
/**
* release all currently pressed keys
*/
public void keyUp() {
getRobotForRegion().keyUp();
}
/**
* release the given keys (see keyDown(keycode) )
*
* @param keycode Java KeyCode
*/
public void keyUp(int keycode) {
getRobotForRegion().keyUp(keycode);
}
/**
* release the given keys (see keyDown(keys) )
*
* @param keys valid keys
*/
public void keyUp(String keys) {
getRobotForRegion().keyUp(keys);
}
/**
* Compact alternative for type() with more options <br>
* - special keys and options are coded as #XN. or #X+ or #X- <br>
* where X is a refrence for a special key and N is an optional repeat factor <br>
* A modifier key as #X. modifies the next following key<br>
* the trailing . ends the special key, the + (press and hold) or - (release) does the same, <br>
* but signals press-and-hold or release additionally.<br>
* except #W / #w all special keys are not case-sensitive<br>
* a #wn. inserts a wait of n millisecs or n secs if n less than 60 <br>
* a #Wn. sets the type delay for the following keys (must be > 60 and denotes millisecs)
* - otherwise taken as normal wait<br>
* Example: wait 2 secs then type CMD/CTRL - N then wait 1 sec then type DOWN 3 times<br>
* Windows/Linux: write("#w2.#C.n#W1.#d3.")<br>
* Mac: write("#w2.#M.n#W1.#D3.")<br>
* for more details about the special key codes and examples consult the docs <br>
* @param text a coded text interpreted as a series of key actions (press/hold/release)
* @return 0 for success 1 otherwise
*/
public int write(String text) {
Debug.info("Write: " + text);
char c;
String token, tokenSave;
String modifier = "";
int k;
IRobot robot = getRobotForRegion();
int pause = 20 + (Settings.TypeDelay > 1 ? 1000 : (int) (Settings.TypeDelay * 1000));
Settings.TypeDelay = 0.0;
robot.typeStarts();
for (int i = 0; i < text.length(); i++) {
log(lvl + 1, "write: (%d) %s", i, text.substring(i));
c = text.charAt(i);
token = null;
boolean isModifier = false;
if (c == '#') {
if (text.charAt(i + 1) == '#') {
log(3, "write at: %d: %s", i, c);
i += 1;
continue;
}
if (text.charAt(i + 2) == '+' || text.charAt(i + 2) == '-') {
token = text.substring(i, i + 3);
isModifier = true;
} else if (-1 < (k = text.indexOf('.', i))) {
if (k > -1) {
token = text.substring(i, k + 1);
if (token.length() > Key.keyMaxLength || token.substring(1).contains("#")) {
token = null;
}
}
}
}
Integer key = -1;
if (token == null) {
log(lvl + 1, "write: %d: %s", i, c);
} else {
log(lvl + 1, "write: token at %d: %s", i, token);
int repeat = 0;
if (token.toUpperCase().startsWith("#W")) {
if (token.length() > 3) {
i += token.length() - 1;
int t = 0;
try {
t = Integer.parseInt(token.substring(2, token.length() - 1));
} catch (NumberFormatException ex) {
}
if ((token.startsWith("#w") && t > 60)) {
pause = 20 + (t > 1000 ? 1000 : t);
log(lvl + 1, "write: type delay: " + t);
} else {
log(lvl + 1, "write: wait: " + t);
robot.delay((t < 60 ? t * 1000 : t));
}
continue;
}
}
tokenSave = token;
token = token.substring(0, 2).toUpperCase() + ".";
if (Key.isRepeatable(token)) {
try {
repeat = Integer.parseInt(tokenSave.substring(2, tokenSave.length() - 1));
} catch (NumberFormatException ex) {
token = tokenSave;
}
} else if (tokenSave.length() == 3 && Key.isModifier(tokenSave.toUpperCase())) {
i += tokenSave.length() - 1;
modifier += tokenSave.substring(1, 2).toUpperCase();
continue;
} else {
token = tokenSave;
}
if (-1 < (key = Key.toJavaKeyCodeFromText(token))) {
if (repeat > 0) {
log(lvl + 1, "write: %s Repeating: %d", token, repeat);
} else {
log(lvl + 1, "write: %s", tokenSave);
repeat = 1;
}
i += tokenSave.length() - 1;
if (isModifier) {
if (tokenSave.endsWith("+")) {
robot.keyDown(key);
} else {
robot.keyUp(key);
}
continue;
}
if (repeat > 1) {
for (int n = 0; n < repeat; n++) {
robot.typeKey(key.intValue());
}
continue;
}
}
}
if (!modifier.isEmpty()) {
log(lvl + 1, "write: modifier + " + modifier);
for (int n = 0; n < modifier.length(); n++) {
robot.keyDown(Key.toJavaKeyCodeFromText(String.format("#%s.", modifier.substring(n, n + 1))));
}
}
if (key > -1) {
robot.typeKey(key.intValue());
} else {
robot.typeChar(c, IRobot.KeyMode.PRESS_RELEASE);
}
if (!modifier.isEmpty()) {
log(lvl + 1, "write: modifier - " + modifier);
for (int n = 0; n < modifier.length(); n++) {
robot.keyUp(Key.toJavaKeyCodeFromText(String.format("#%s.", modifier.substring(n, n + 1))));
}
}
robot.delay(pause);
modifier = "";
}
robot.typeEnds();
robot.waitForIdle();
return 0;
}
/**
* enters the given text one character/key after another using keyDown/keyUp
* <br>about the usable Key constants see keyDown(keys) <br>Class Key only provides a subset of a US-QWERTY PC
* keyboard layout<br>the text is entered at the current position of the focus/carret
*
* @param text containing characters and/or Key constants
* @return 1 if possible, 0 otherwise
*/
public int type(String text) {
try {
return keyin(null, text, 0);
} catch (FindFailed ex) {
return 0;
}
}
/**
* enters the given text one character/key after another using keyDown/keyUp<br>while holding down the given modifier
* keys <br>about the usable Key constants see keyDown(keys) <br>Class Key only provides a subset of a US-QWERTY PC
* keyboard layout<br>the text is entered at the current position of the focus/carret
*
* @param text containing characters and/or Key constants
* @param modifiers constants according to class KeyModifiers
* @return 1 if possible, 0 otherwise
*/
public int type(String text, int modifiers) {
try {
return keyin(null, text, modifiers);
} catch (FindFailed findFailed) {
return 0;
}
}
/**
* enters the given text one character/key after another using
*
* keyDown/keyUp<br>while holding down the given modifier keys <br>about the usable Key constants see keyDown(keys)
* <br>Class Key only provides a subset of a US-QWERTY PC keyboard layout<br>the text is entered at the current
* position of the focus/carret
*
*
* @param text containing characters and/or Key constants
* @param modifiers constants according to class Key - combine using +
* @return 1 if possible, 0 otherwise
*/
public int type(String text, String modifiers) {
String target = null;
int modifiersNew = Key.convertModifiers(modifiers);
if (modifiersNew == 0) {
target = text;
text = modifiers;
}
try {
return keyin(target, text, modifiersNew);
} catch (FindFailed findFailed) {
return 0;
}
}
/**
* first does a click(target) at the given target position to gain focus/carret <br>enters the given text one
* character/key after another using keyDown/keyUp <br>about the usable Key constants see keyDown(keys)
* <br>Class Key only provides a subset of a US-QWERTY PC keyboard layout
*
* @param <PFRML> Pattern, Filename, Text, Region, Match or Location
* @param target Pattern, Filename, Text, Region, Match or Location
* @param text containing characters and/or Key constants
* @return 1 if possible, 0 otherwise
* @throws FindFailed if not found
*/
public <PFRML> int type(PFRML target, String text) throws FindFailed {
return keyin(target, text, 0);
}
/**
* first does a click(target) at the given target position to gain focus/carret <br>enters the given text one
* character/key after another using keyDown/keyUp <br>while holding down the given modifier keys<br>about the usable
* Key constants see keyDown(keys) <br>Class Key only provides a subset of a US-QWERTY PC keyboard layout
*
* @param <PFRML> Pattern, Filename, Text, Region, Match or Location
* @param target Pattern, Filename, Text, Region, Match or Location
* @param text containing characters and/or Key constants
* @param modifiers constants according to class KeyModifiers
* @return 1 if possible, 0 otherwise
* @throws FindFailed if not found
*/
public <PFRML> int type(PFRML target, String text, int modifiers) throws FindFailed {
return keyin(target, text, modifiers);
}
/**
* first does a click(target) at the given target position to gain focus/carret <br>enters the given text one
* character/key after another using keyDown/keyUp <br>while holding down the given modifier keys<br>about the usable
* Key constants see keyDown(keys) <br>Class Key only provides a subset of a US-QWERTY PC keyboard layout
*
* @param <PFRML> Pattern, Filename, Text, Region, Match or Location
* @param target Pattern, Filename, Text, Region, Match or Location
* @param text containing characters and/or Key constants
* @param modifiers constants according to class Key - combine using +
* @return 1 if possible, 0 otherwise
* @throws FindFailed if not found
*/
public <PFRML> int type(PFRML target, String text, String modifiers) throws FindFailed {
int modifiersNew = Key.convertModifiers(modifiers);
return keyin(target, text, modifiersNew);
}
private <PFRML> int keyin(PFRML target, String text, int modifiers)
throws FindFailed {
if (target != null && 0 == click(target, 0)) {
return 0;
}
Debug profiler = Debug.startTimer("Region.type");
if (text != null && !"".equals(text)) {
String showText = "";
for (int i = 0; i < text.length(); i++) {
showText += Key.toJavaKeyCodeText(text.charAt(i));
}
String modText = "";
String modWindows = null;
if ((modifiers & KeyModifier.WIN) != 0) {
modifiers -= KeyModifier.WIN;
modifiers |= KeyModifier.META;
log(lvl, "Key.WIN as modifier");
modWindows = "Windows";
}
if (modifiers != 0) {
modText = String.format("( %s ) ", KeyEvent.getKeyModifiersText(modifiers));
if (modWindows != null) {
modText = modText.replace("Meta", modWindows);
}
}
Debug.action("%s TYPE \"%s\"", modText, showText);
log(lvl, "%s TYPE \"%s\"", modText, showText);
profiler.lap("before getting Robot");
IRobot r = getRobotForRegion();
int pause = 20 + (Settings.TypeDelay > 1 ? 1000 : (int) (Settings.TypeDelay * 1000));
Settings.TypeDelay = 0.0;
profiler.lap("before typing");
r.typeStarts();
for (int i = 0; i < text.length(); i++) {
r.pressModifiers(modifiers);
r.typeChar(text.charAt(i), IRobot.KeyMode.PRESS_RELEASE);
r.releaseModifiers(modifiers);
r.delay(pause);
}
r.typeEnds();
profiler.lap("after typing, before waitForIdle");
r.waitForIdle();
profiler.end();
return 1;
}
return 0;
}
/**
* time in milliseconds to delay between each character at next type only (max 1000)
*
* @param millisecs value
*/
public void delayType(int millisecs) {
Settings.TypeDelay = millisecs;
}
/**
* pastes the text at the current position of the focus/carret <br>using the clipboard and strg/ctrl/cmd-v (paste
* keyboard shortcut)
*
* @param text a string, which might contain unicode characters
* @return 0 if possible, 1 otherwise
*/
public int paste(String text) {
try {
return paste(null, text);
} catch (FindFailed ex) {
return 1;
}
}
/**
* first does a click(target) at the given target position to gain focus/carret <br> and then pastes the text <br>
* using the clipboard and strg/ctrl/cmd-v (paste keyboard shortcut)
*
* @param <PFRML> Pattern, Filename, Text, Region, Match or Location target
* @param target Pattern, Filename, Text, Region, Match or Location
* @param text a string, which might contain unicode characters
* @return 0 if possible, 1 otherwise
* @throws FindFailed if not found
*/
public <PFRML> int paste(PFRML target, String text) throws FindFailed {
if (target != null) {
click(target, 0);
}
if (text != null) {
App.setClipboard(text);
int mod = Key.getHotkeyModifier();
IRobot r = getRobotForRegion();
r.keyDown(mod);
r.keyDown(KeyEvent.VK_V);
r.keyUp(KeyEvent.VK_V);
r.keyUp(mod);
return 1;
}
return 0;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="OCR - read text from Screen">
/**
* STILL EXPERIMENTAL: tries to read the text in this region<br> might contain misread characters, NL characters and
* other stuff, when interpreting contained grafics as text<br>
* Best results: one line of text with no grafics in the line
*
* @return the text read (utf8 encoded)
*/
public String text() {
if (Settings.OcrTextRead) {
ScreenImage simg = getScreen().capture(x, y, w, h);
TextRecognizer tr = TextRecognizer.getInstance();
if (tr == null) {
Debug.error("text: text recognition is now switched off");
return "--- no text ---";
}
String textRead = tr.recognize(simg);
log(lvl, "text: #(" + textRead + ")#");
return textRead;
}
Debug.error("text: text recognition is currently switched off");
return "--- no text ---";
}
/**
* VERY EXPERIMENTAL: returns a list of matches, that represent single words, that have been found in this region<br>
* the match's x,y,w,h the region of the word<br> Match.getText() returns the word (utf8) at this match<br>
* Match.getScore() returns a value between 0 ... 1, that represents some OCR-confidence value<br > (the higher, the
* better the OCR engine thinks the result is)
*
* @return a list of matches
*/
public List<Match> listText() {
if (Settings.OcrTextRead) {
ScreenImage simg = getScreen().capture(x, y, w, h);
TextRecognizer tr = TextRecognizer.getInstance();
if (tr == null) {
Debug.error("text: text recognition is now switched off");
return null;
}
log(lvl, "listText: scanning %s", this);
return tr.listText(simg, this);
}
Debug.error("text: text recognition is currently switched off");
return null;
}
//</editor-fold>
public String saveScreenCapture() {
return getScreen().capture(this).save();
}
public String saveScreenCapture(String path) {
return getScreen().capture(this).save(path);
}
public String saveScreenCapture(String path, String name) {
return getScreen().capture(this).save(path, name);
}
}
|