1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 11154 11155 11156 11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366 11367 11368 11369 11370 11371 11372 11373 11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392 11393 11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442 11443 11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457 11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483 11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500 11501 11502 11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517 11518 11519 11520 11521 11522 11523 11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 11551 11552 11553 11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564 11565 11566 11567 11568 11569 11570 11571 11572 11573 11574 11575 11576 11577 11578 11579 11580 11581 11582 11583 11584 11585 11586 11587 11588 11589 11590 11591 11592 11593 11594 11595 11596 11597 11598 11599 11600 11601 11602 11603 11604 11605 11606 11607 11608 11609 11610 11611 11612 11613 11614 11615 11616 11617 11618 11619 11620 11621 11622 11623 11624 11625 11626 11627 11628 11629 11630 11631 11632 11633 11634 11635 11636 11637 11638 11639 11640 11641 11642 11643 11644 11645 11646 11647 11648 11649 11650 11651 11652 11653 11654 11655 11656 11657 11658 11659 11660 11661 11662 11663 11664 11665 11666 11667 11668 11669 11670 11671 11672 11673 11674 11675 11676 11677 11678 11679 11680 11681 11682 11683 11684 11685 11686 11687 11688 11689 11690 11691 11692 11693 11694 11695 11696 11697 11698 11699 11700 11701 11702 11703 11704 11705 11706 11707 11708 11709 11710 11711 11712 11713 11714 11715 11716 11717 11718 11719 11720 11721 11722 11723 11724 11725 11726 11727 11728 11729 11730 11731 11732 11733 11734 11735 11736 11737 11738 11739 11740 11741 11742 11743 11744 11745 11746 11747 11748 11749 11750 11751 11752 11753 11754 11755 11756 11757 11758 11759 11760 11761 11762 11763 11764 11765 11766 11767 11768 11769 11770 11771 11772 11773 11774 11775 11776 11777 11778 11779 11780 11781 11782 11783 11784 11785 11786 11787 11788 11789 11790 11791 11792 11793 11794 11795 11796 11797 11798 11799 11800 11801 11802 11803 11804 11805 11806 11807 11808 11809 11810 11811 11812 11813 11814 11815 11816 11817 11818 11819 11820 11821 11822 11823 11824 11825 11826 11827 11828 11829 11830 11831 11832 11833 11834 11835 11836 11837 11838 11839 11840 11841 11842 11843 11844 11845 11846 11847 11848 11849 11850 11851 11852 11853 11854 11855 11856 11857 11858 11859 11860 11861 11862 11863 11864 11865 11866 11867 11868 11869 11870 11871 11872 11873 11874 11875 11876 11877 11878 11879 11880 11881 11882 11883 11884 11885 11886 11887 11888 11889 11890 11891 11892 11893 11894 11895 11896 11897 11898 11899 11900 11901 11902 11903 11904 11905 11906 11907 11908 11909 11910 11911 11912 11913 11914 11915 11916 11917 11918 11919 11920 11921 11922 11923 11924 11925 11926 11927 11928 11929 11930 11931 11932 11933 11934 11935 11936 11937 11938 11939 11940 11941 11942 11943 11944 11945 11946 11947 11948 11949 11950 11951 11952 11953 11954 11955 11956 11957 11958 11959 11960 11961 11962 11963 11964 11965 11966 11967 11968 11969 11970 11971 11972 11973 11974 11975 11976 11977 11978 11979 11980 11981 11982 11983 11984 11985 11986 11987 11988 11989 11990 11991 11992 11993 11994 11995 11996 11997 11998 11999 12000 12001 12002 12003 12004 12005 12006 12007 12008 12009 12010 12011 12012 12013 12014 12015 12016 12017 12018 12019 12020 12021 12022 12023 12024 12025 12026 12027 12028 12029 12030 12031 12032 12033 12034 12035 12036 12037 12038 12039 12040 12041 12042 12043 12044 12045 12046 12047 12048 12049 12050 12051 12052 12053 12054 12055 12056 12057 12058 12059 12060 12061 12062 12063 12064 12065 12066 12067 12068 12069 12070 12071 12072 12073 12074 12075 12076 12077 12078 12079 12080 12081 12082 12083 12084 12085 12086 12087 12088 12089 12090 12091 12092 12093 12094 12095 12096 12097 12098 12099 12100 12101 12102 12103 12104 12105 12106 12107 12108 12109 12110 12111 12112 12113 12114 12115 12116 12117 12118 12119 12120 12121 12122 12123 12124 12125 12126 12127 12128 12129 12130 12131 12132 12133 12134 12135 12136 12137 12138 12139 12140 12141 12142 12143 12144 12145 12146 12147 12148 12149 12150 12151 12152 12153 12154 12155 12156 12157 12158 12159 12160 12161 12162 12163 12164 12165 12166 12167 12168 12169 12170 12171 12172 12173 12174 12175 12176 12177 12178 12179 12180 12181 12182 12183 12184 12185 12186 12187 12188 12189 12190 12191 12192 12193 12194 12195 12196 12197 12198 12199 12200 12201 12202 12203 12204 12205 12206 12207 12208 12209 12210 12211 12212 12213 12214 12215 12216 12217 12218 12219 12220 12221 12222 12223 12224 12225 12226 12227 12228 12229 12230 12231 12232 12233 12234 12235 12236 12237 12238 12239 12240 12241 12242 12243 12244 12245 12246 12247 12248 12249 12250 12251 12252 12253 12254 12255 12256 12257 12258 12259 12260 12261 12262 12263 12264 12265 12266 12267 12268 12269 12270 12271 12272 12273 12274 12275 12276 12277 12278 12279 12280 12281 12282 12283 12284 12285 12286 12287 12288 12289 12290 12291 12292 12293 12294 12295 12296 12297 12298 12299 12300 12301 12302 12303 12304 12305 12306 12307 12308 12309 12310 12311 12312 12313 12314 12315 12316 12317 12318 12319 12320 12321 12322 12323 12324 12325 12326 12327 12328 12329 12330 12331 12332 12333 12334 12335 12336 12337 12338 12339 12340 12341 12342 12343 12344 12345 12346 12347 12348 12349 12350 12351 12352 12353 12354 12355 12356 12357 12358 12359 12360 12361 12362 12363 12364 12365 12366 12367 12368 12369 12370 12371 12372 12373 12374 12375 12376 12377 12378 12379 12380 12381 12382 12383 12384 12385 12386 12387 12388 12389 12390 12391 12392 12393 12394 12395 12396 12397 12398 12399 12400 12401 12402 12403 12404 12405 12406 12407 12408 12409 12410 12411 12412 12413 12414 12415 12416 12417 12418 12419 12420 12421 12422 12423 12424 12425 12426 12427 12428 12429 12430 12431 12432 12433 12434 12435 12436 12437 12438 12439 12440 12441 12442 12443 12444 12445 12446 12447 12448 12449 12450 12451 12452 12453 12454 12455 12456 12457 12458 12459 12460 12461 12462 12463 12464 12465 12466 12467 12468 12469 12470 12471 12472 12473 12474 12475 12476 12477 12478 12479 12480 12481 12482 12483 12484 12485 12486 12487 12488 12489 12490 12491 12492 12493 12494 12495 12496 12497 12498 12499 12500 12501 12502 12503 12504 12505 12506 12507 12508 12509 12510 12511 12512 12513 12514 12515 12516 12517 12518 12519 12520 12521 12522 12523 12524 12525 12526 12527 12528 12529 12530 12531 12532 12533 12534 12535 12536 12537 12538 12539 12540 12541 12542 12543 12544 12545 12546 12547 12548 12549 12550 12551 12552 12553 12554 12555 12556 12557 12558 12559 12560 12561 12562 12563 12564 12565 12566 12567 12568 12569 12570 12571 12572 12573 12574 12575 12576 12577 12578 12579 12580 12581 12582 12583 12584 12585 12586 12587 12588 12589 12590 12591 12592 12593 12594 12595 12596 12597 12598 12599 12600 12601 12602 12603 12604 12605 12606 12607 12608 12609 12610 12611 12612 12613 12614 12615 12616 12617 12618 12619 12620 12621 12622 12623 12624 12625 12626 12627 12628 12629 12630 12631 12632 12633 12634 12635 12636 12637 12638 12639 12640 12641 12642 12643 12644 12645 12646 12647 12648 12649 12650 12651 12652 12653 12654 12655 12656 12657 12658 12659 12660 12661 12662 12663 12664 12665 12666 12667 12668 12669 12670 12671 12672 12673 12674 12675 12676 12677 12678 12679 12680 12681 12682 12683 12684 12685 12686 12687 12688 12689 12690 12691 12692 12693 12694 12695 12696 12697 12698 12699 12700 12701 12702 12703 12704 12705 12706 12707 12708 12709 12710 12711 12712 12713 12714 12715 12716 12717 12718 12719 12720 12721 12722 12723 12724 12725 12726 12727 12728 12729 12730 12731 12732 12733 12734 12735 12736 12737 12738 12739 12740 12741 12742 12743 12744 12745 12746 12747 12748 12749 12750 12751 12752 12753 12754 12755 12756 12757 12758 12759 12760 12761 12762 12763 12764 12765 12766 12767 12768 12769 12770 12771 12772 12773 12774 12775 12776 12777 12778 12779 12780 12781 12782 12783 12784 12785 12786 12787 12788 12789 12790 12791 12792 12793 12794 12795 12796 12797 12798 12799 12800 12801 12802 12803 12804 12805 12806 12807 12808 12809 12810 12811 12812 12813 12814 12815 12816 12817 12818 12819 12820 12821 12822 12823 12824 12825 12826 12827 12828 12829 12830 12831 12832 12833 12834 12835 12836 12837 12838 12839 12840 12841 12842 12843 12844 12845 12846 12847 12848 12849 12850 12851 12852 12853 12854 12855 12856 12857 12858 12859 12860 12861 12862 12863 12864 12865 12866 12867 12868 12869 12870 12871 12872 12873 12874 12875 12876 12877 12878 12879 12880 12881 12882 12883 12884 12885 12886 12887 12888 12889 12890 12891 12892 12893 12894 12895 12896 12897 12898 12899 12900 12901 12902 12903 12904 12905 12906 12907 12908 12909 12910 12911 12912 12913 12914 12915 12916 12917 12918 12919 12920 12921 12922 12923 12924 12925 12926 12927 12928 12929 12930 12931 12932 12933 12934 12935 12936 12937 12938 12939 12940 12941 12942 12943 12944 12945 12946 12947 12948 12949 12950 12951 12952 12953 12954 12955 12956 12957 12958 12959 12960 12961 12962 12963 12964 12965 12966 12967 12968 12969 12970 12971 12972 12973 12974 12975 12976 12977 12978 12979 12980 12981 12982 12983 12984 12985 12986 12987 12988 12989 12990 12991 12992 12993 12994 12995 12996 12997 12998 12999 13000 13001 13002 13003 13004 13005 13006 13007 13008 13009 13010 13011 13012 13013 13014 13015 13016 13017 13018 13019 13020 13021 13022 13023 13024 13025 13026 13027 13028 13029 13030 13031 13032 13033 13034 13035 13036 13037 13038 13039 13040 13041 13042 13043 13044 13045 13046 13047 13048 13049 13050 13051 13052 13053 13054 13055 13056 13057 13058 13059 13060 13061 13062 13063 13064 13065 13066 13067 13068 13069 13070 13071 13072 13073 13074 13075 13076 13077 13078 13079 13080 13081 13082 13083 13084 13085 13086 13087 13088 13089 13090 13091 13092 13093 13094 13095 13096 13097 13098 13099 13100 13101 13102 13103 13104 13105 13106 13107 13108 13109 13110 13111 13112 13113 13114 13115 13116 13117 13118 13119 13120 13121 13122 13123 13124 13125 13126 13127 13128 13129 13130 13131 13132 13133 13134 13135 13136 13137 13138 13139 13140 13141 13142 13143 13144 13145 13146 13147 13148 13149 13150 13151 13152 13153 13154 13155 13156 13157 13158 13159 13160 13161 13162 13163 13164 13165 13166 13167 13168 13169 13170 13171 13172 13173 13174 13175 13176 13177 13178 13179 13180 13181 13182 13183 13184 13185 13186 13187 13188 13189 13190 13191 13192 13193 13194 13195 13196 13197 13198 13199 13200 13201 13202 13203 13204 13205 13206 13207 13208 13209 13210 13211 13212 13213 13214 13215 13216 13217 13218 13219 13220 13221 13222 13223 13224 13225 13226 13227 13228 13229 13230 13231 13232 13233 13234 13235 13236 13237 13238 13239 13240 13241 13242 13243 13244 13245 13246 13247 13248 13249 13250 13251 13252 13253 13254 13255 13256 13257 13258 13259 13260 13261 13262 13263 13264 13265 13266 13267 13268 13269 13270 13271 13272 13273 13274 13275 13276 13277 13278 13279 13280 13281 13282 13283 13284 13285 13286 13287 13288 13289 13290 13291 13292 13293 13294 13295 13296 13297 13298 13299 13300 13301 13302 13303 13304 13305 13306 13307 13308 13309 13310 13311 13312 13313 13314 13315 13316 13317 13318 13319 13320 13321 13322 13323 13324 13325 13326 13327 13328 13329 13330 13331 13332 13333 13334 13335 13336 13337 13338 13339 13340 13341 13342 13343 13344 13345 13346 13347 13348 13349 13350 13351 13352 13353 13354 13355 13356 13357 13358 13359 13360 13361 13362 13363 13364 13365 13366 13367 13368 13369 13370 13371 13372 13373 13374 13375 13376 13377 13378 13379 13380 13381 13382 13383 13384 13385 13386 13387 13388 13389 13390 13391 13392 13393 13394 13395 13396 13397 13398 13399 13400 13401 13402 13403 13404 13405 13406 13407 13408 13409 13410 13411 13412 13413 13414 13415 13416 13417 13418 13419 13420 13421 13422 13423 13424 13425 13426 13427 13428 13429 13430 13431 13432 13433 13434 13435 13436 13437 13438 13439 13440 13441 13442 13443 13444 13445 13446 13447 13448 13449 13450 13451 13452 13453 13454 13455 13456 13457 13458 13459 13460 13461 13462 13463 13464 13465 13466 13467 13468 13469 13470 13471 13472 13473 13474 13475 13476 13477 13478 13479 13480 13481 13482 13483 13484 13485 13486 13487 13488 13489 13490 13491 13492 13493 13494 13495 13496 13497 13498 13499 13500 13501 13502 13503 13504 13505 13506 13507 13508 13509 13510 13511 13512 13513 13514 13515 13516 13517 13518 13519 13520 13521 13522 13523 13524 13525 13526 13527 13528 13529 13530 13531 13532 13533 13534 13535 13536 13537 13538 13539 13540 13541 13542 13543 13544 13545 13546 13547 13548 13549 13550 13551 13552 13553 13554 13555 13556 13557 13558 13559 13560 13561 13562 13563 13564 13565 13566 13567 13568 13569 13570 13571 13572 13573 13574 13575 13576 13577 13578 13579 13580 13581 13582 13583 13584 13585 13586 13587 13588 13589 13590 13591 13592 13593 13594 13595 13596 13597 13598 13599 13600 13601 13602 13603 13604 13605 13606 13607 13608 13609 13610 13611 13612 13613 13614 13615 13616 13617 13618 13619 13620 13621 13622 13623 13624 13625 13626 13627 13628 13629 13630 13631 13632 13633 13634 13635 13636 13637 13638 13639 13640 13641 13642 13643 13644 13645 13646 13647 13648 13649 13650 13651 13652 13653 13654 13655 13656 13657 13658 13659 13660 13661 13662 13663 13664 13665 13666 13667 13668 13669 13670 13671 13672 13673 13674 13675 13676 13677 13678 13679 13680 13681 13682 13683 13684 13685 13686 13687 13688 13689 13690 13691 13692 13693 13694 13695 13696 13697 13698 13699 13700 13701 13702 13703 13704 13705 13706 13707 13708 13709 13710 13711 13712 13713 13714 13715 13716 13717 13718 13719 13720 13721 13722 13723 13724 13725 13726 13727 13728 13729 13730 13731 13732 13733 13734 13735 13736 13737 13738 13739 13740 13741 13742 13743 13744 13745 13746 13747 13748 13749 13750 13751 13752 13753 13754 13755 13756 13757 13758 13759 13760 13761 13762 13763 13764 13765 13766 13767 13768 13769 13770 13771 13772 13773 13774 13775 13776 13777 13778 13779 13780 13781 13782 13783 13784 13785 13786 13787 13788 13789 13790 13791 13792 13793 13794 13795 13796 13797 13798 13799 13800 13801 13802 13803 13804 13805 13806 13807 13808 13809 13810 13811 13812 13813 13814 13815 13816 13817 13818 13819 13820 13821 13822 13823 13824 13825 13826 13827 13828 13829 13830 13831 13832 13833 13834 13835 13836 13837 13838 13839 13840 13841 13842 13843 13844 13845 13846 13847 13848 13849 13850 13851 13852 13853 13854 13855 13856 13857 13858 13859 13860 13861 13862 13863 13864 13865 13866 13867 13868 13869 13870 13871 13872 13873 13874 13875 13876 13877 13878 13879 13880 13881 13882 13883 13884 13885 13886 13887 13888 13889 13890 13891 13892 13893 13894 13895 13896 13897 13898 13899 13900 13901 13902 13903 13904 13905 13906 13907 13908 13909 13910 13911 13912 13913 13914 13915 13916 13917 13918 13919 13920 13921 13922 13923 13924 13925 13926 13927 13928 13929 13930 13931 13932 13933 13934 13935 13936 13937 13938 13939 13940 13941 13942 13943 13944 13945 13946 13947 13948 13949 13950 13951 13952 13953 13954 13955 13956 13957 13958 13959 13960 13961 13962 13963 13964 13965 13966 13967 13968 13969 13970 13971 13972 13973 13974 13975 13976 13977 13978 13979 13980 13981 13982 13983 13984 13985 13986 13987 13988 13989 13990 13991 13992 13993 13994 13995 13996 13997 13998 13999 14000 14001 14002 14003 14004 14005 14006 14007 14008 14009 14010 14011 14012 14013 14014 14015 14016 14017 14018 14019 14020 14021 14022 14023 14024 14025 14026 14027 14028 14029 14030 14031 14032 14033 14034 14035 14036 14037 14038 14039 14040 14041 14042 14043 14044 14045 14046 14047 14048 14049 14050 14051 14052 14053 14054 14055 14056 14057 14058 14059 14060 14061 14062 14063 14064 14065 14066 14067 14068 14069 14070 14071 14072 14073 14074 14075 14076 14077 14078 14079 14080 14081 14082 14083 14084 14085 14086 14087 14088 14089 14090 14091 14092 14093 14094 14095 14096 14097 14098 14099 14100 14101 14102 14103 14104 14105 14106 14107 14108 14109 14110 14111 14112 14113 14114 14115 14116 14117 14118 14119 14120 14121 14122 14123 14124 14125 14126 14127 14128 14129 14130 14131 14132 14133 14134 14135 14136 14137 14138 14139 14140 14141 14142 14143 14144 14145 14146 14147 14148 14149 14150 14151 14152 14153 14154 14155 14156 14157 14158 14159 14160 14161 14162 14163 14164 14165 14166 14167 14168 14169 14170 14171 14172 14173 14174 14175 14176 14177 14178 14179 14180 14181 14182 14183 14184 14185 14186 14187 14188 14189 14190 14191 14192 14193 14194 14195 14196 14197 14198 14199 14200 14201 14202 14203 14204 14205 14206 14207 14208 14209 14210 14211 14212 14213 14214 14215 14216 14217 14218 14219 14220 14221 14222 14223 14224 14225 14226 14227 14228 14229 14230 14231 14232 14233 14234 14235 14236 14237 14238 14239 14240 14241 14242 14243 14244 14245 14246 14247 14248 14249 14250 14251 14252 14253 14254 14255 14256 14257 14258 14259 14260 14261 14262 14263 14264 14265 14266 14267 14268 14269 14270 14271 14272 14273 14274 14275 14276 14277 14278 14279 14280 14281 14282 14283 14284 14285 14286 14287 14288 14289 14290 14291 14292 14293 14294 14295 14296 14297 14298 14299 14300 14301 14302 14303 14304 14305 14306 14307 14308 14309 14310 14311 14312 14313 14314 14315 14316 14317 14318 14319 14320 14321 14322 14323 14324 14325 14326 14327 14328 14329 14330 14331 14332 14333 14334 14335 14336 14337 14338 14339 14340 14341 14342 14343 14344 14345 14346 14347 14348 14349 14350 14351 14352 14353 14354 14355 14356 14357 14358 14359 14360 14361 14362 14363 14364 14365 14366 14367 14368 14369 14370 14371 14372 14373 14374 14375 14376 14377 14378 14379 14380 14381 14382 14383 14384 14385 14386 14387 14388 14389 14390 14391 14392 14393 14394 14395 14396 14397 14398 14399 14400 14401 14402 14403 14404 14405 14406 14407 14408 14409 14410 14411 14412 14413 14414 14415 14416 14417 14418 14419 14420 14421 14422 14423 14424 14425 14426 14427 14428 14429 14430 14431 14432 14433 14434 14435 14436 14437 14438 14439 14440 14441 14442 14443 14444 14445 14446 14447 14448 14449 14450 14451 14452 14453 14454 14455 14456 14457 14458 14459 14460 14461 14462 14463 14464 14465 14466 14467 14468 14469 14470 14471 14472 14473 14474 14475 14476 14477 14478 14479 14480 14481 14482 14483 14484 14485 14486 14487 14488 14489 14490 14491 14492 14493 14494 14495 14496 14497 14498 14499 14500 14501 14502 14503 14504 14505 14506 14507 14508 14509 14510 14511 14512 14513 14514 14515 14516 14517 14518 14519 14520 14521 14522 14523 14524 14525 14526 14527 14528 14529 14530 14531 14532 14533 14534 14535 14536 14537 14538 14539 14540 14541 14542 14543 14544 14545 14546 14547 14548 14549 14550 14551 14552 14553 14554 14555 14556 14557 14558 14559 14560 14561 14562 14563 14564 14565 14566 14567 14568 14569 14570 14571 14572 14573 14574 14575 14576 14577 14578 14579 14580 14581 14582 14583 14584 14585 14586 14587 14588 14589 14590 14591 14592 14593 14594 14595 14596 14597 14598 14599 14600 14601 14602 14603 14604 14605 14606 14607 14608 14609 14610 14611 14612 14613 14614 14615 14616 14617 14618 14619 14620 14621 14622 14623 14624 14625 14626 14627 14628 14629 14630 14631 14632 14633 14634 14635 14636 14637 14638 14639 14640 14641 14642 14643 14644 14645 14646 14647 14648 14649 14650 14651 14652 14653 14654 14655 14656 14657 14658 14659 14660 14661 14662 14663 14664 14665 14666 14667 14668 14669 14670 14671 14672 14673 14674 14675 14676 14677 14678 14679 14680 14681 14682 14683 14684 14685 14686 14687 14688 14689 14690 14691 14692 14693 14694 14695 14696 14697 14698 14699 14700 14701 14702 14703 14704 14705 14706 14707 14708 14709 14710 14711 14712 14713 14714 14715 14716 14717 14718 14719 14720 14721 14722 14723 14724 14725 14726 14727 14728 14729 14730 14731 14732 14733 14734 14735 14736 14737 14738 14739 14740 14741 14742 14743 14744 14745 14746 14747 14748 14749 14750 14751 14752 14753 14754 14755 14756 14757 14758 14759 14760 14761 14762 14763 14764 14765 14766 14767 14768 14769 14770 14771 14772 14773 14774 14775 14776 14777 14778 14779 14780 14781 14782 14783 14784 14785 14786 14787 14788 14789 14790 14791 14792 14793 14794 14795 14796 14797 14798 14799 14800 14801 14802 14803 14804 14805 14806 14807 14808 14809 14810 14811 14812 14813 14814 14815 14816 14817 14818 14819 14820 14821 14822 14823 14824 14825 14826 14827 14828 14829 14830 14831 14832 14833 14834 14835 14836 14837 14838 14839 14840 14841 14842 14843 14844 14845 14846 14847 14848 14849 14850 14851 14852 14853 14854 14855 14856 14857 14858 14859 14860 14861 14862 14863 14864 14865 14866 14867 14868 14869 14870 14871 14872 14873 14874 14875 14876 14877 14878 14879 14880 14881 14882 14883 14884 14885 14886 14887 14888 14889 14890 14891 14892 14893 14894 14895 14896 14897 14898 14899 14900 14901 14902 14903 14904 14905 14906 14907 14908 14909 14910 14911 14912 14913 14914 14915 14916 14917 14918 14919 14920 14921 14922 14923 14924 14925 14926 14927 14928 14929 14930 14931 14932 14933 14934 14935 14936 14937 14938 14939 14940 14941 14942 14943 14944 14945 14946 14947 14948 14949 14950 14951 14952 14953 14954 14955 14956 14957 14958 14959 14960 14961 14962 14963 14964 14965 14966 14967 14968 14969 14970 14971 14972 14973 14974 14975 14976 14977 14978 14979 14980 14981 14982 14983 14984 14985 14986 14987 14988 14989 14990 14991 14992 14993 14994 14995 14996 14997 14998 14999 15000 15001 15002 15003 15004 15005 15006 15007 15008 15009 15010 15011 15012 15013 15014 15015 15016 15017 15018 15019 15020 15021 15022 15023 15024 15025 15026 15027 15028 15029 15030 15031 15032 15033 15034 15035 15036 15037 15038 15039 15040 15041 15042 15043 15044 15045 15046 15047 15048 15049 15050 15051 15052 15053 15054 15055 15056 15057 15058 15059 15060 15061 15062 15063 15064 15065 15066 15067 15068 15069 15070 15071 15072 15073 15074 15075 15076 15077 15078 15079 15080 15081 15082 15083 15084 15085 15086 15087 15088 15089 15090 15091 15092 15093 15094 15095 15096 15097 15098 15099 15100 15101 15102 15103 15104 15105 15106 15107 15108 15109 15110 15111 15112 15113 15114 15115 15116 15117 15118 15119 15120 15121 15122 15123 15124 15125 15126 15127 15128 15129 15130 15131 15132 15133 15134 15135 15136 15137 15138 15139 15140 15141 15142 15143 15144 15145 15146 15147 15148 15149 15150 15151 15152 15153 15154 15155 15156 15157 15158 15159 15160 15161 15162 15163 15164 15165 15166 15167 15168 15169 15170 15171 15172 15173 15174 15175 15176 15177 15178 15179 15180 15181 15182 15183 15184 15185 15186 15187 15188 15189 15190 15191 15192 15193 15194 15195 15196 15197 15198 15199 15200 15201 15202 15203 15204 15205 15206 15207 15208 15209 15210 15211 15212 15213 15214 15215 15216 15217 15218 15219 15220 15221 15222 15223 15224 15225 15226 15227 15228 15229 15230 15231 15232 15233 15234 15235 15236 15237 15238 15239 15240 15241 15242 15243 15244 15245 15246 15247 15248 15249 15250 15251 15252 15253 15254 15255 15256 15257 15258 15259 15260 15261 15262 15263 15264 15265 15266 15267 15268 15269 15270 15271 15272 15273 15274 15275 15276 15277 15278 15279 15280 15281 15282 15283 15284 15285 15286 15287 15288 15289 15290 15291 15292 15293 15294 15295 15296 15297 15298 15299 15300 15301 15302 15303 15304 15305 15306 15307 15308 15309 15310 15311 15312 15313 15314 15315 15316 15317 15318 15319 15320 15321 15322 15323 15324 15325 15326 15327 15328 15329 15330 15331 15332 15333 15334 15335 15336 15337 15338 15339 15340 15341 15342 15343 15344 15345 15346 15347 15348 15349 15350 15351 15352 15353 15354 15355 15356 15357 15358 15359 15360 15361 15362 15363 15364 15365 15366 15367 15368 15369 15370 15371 15372 15373 15374 15375 15376 15377 15378 15379 15380 15381 15382 15383 15384 15385 15386 15387 15388 15389 15390 15391 15392 15393 15394 15395 15396 15397 15398 15399 15400 15401 15402 15403 15404 15405 15406 15407 15408 15409 15410 15411 15412 15413 15414 15415 15416 15417 15418 15419 15420 15421 15422 15423 15424 15425 15426 15427 15428 15429 15430 15431 15432 15433 15434 15435 15436 15437 15438 15439 15440 15441 15442 15443 15444 15445 15446 15447 15448 15449 15450 15451 15452 15453 15454 15455 15456 15457 15458 15459 15460 15461 15462 15463 15464 15465 15466 15467 15468 15469 15470 15471 15472 15473 15474 15475 15476 15477 15478 15479 15480 15481 15482 15483 15484 15485 15486 15487 15488 15489 15490 15491 15492 15493 15494 15495 15496 15497 15498 15499 15500 15501 15502 15503 15504 15505 15506 15507 15508 15509 15510 15511 15512 15513 15514 15515 15516 15517 15518 15519 15520 15521 15522 15523 15524 15525 15526 15527 15528 15529 15530 15531 15532 15533 15534 15535 15536 15537 15538 15539 15540 15541 15542 15543 15544 15545 15546 15547 15548 15549 15550 15551 15552 15553 15554 15555 15556 15557 15558 15559 15560 15561 15562 15563 15564 15565 15566 15567 15568 15569 15570 15571 15572 15573 15574 15575 15576 15577 15578 15579 15580 15581 15582 15583 15584 15585 15586 15587 15588 15589 15590 15591 15592 15593 15594 15595 15596 15597 15598 15599 15600 15601 15602 15603 15604 15605 15606 15607 15608 15609 15610 15611 15612 15613 15614 15615 15616 15617 15618 15619 15620 15621 15622 15623 15624 15625 15626 15627 15628 15629 15630 15631 15632 15633 15634 15635 15636 15637 15638 15639 15640 15641 15642 15643 15644 15645 15646 15647 15648 15649 15650 15651 15652 15653 15654 15655 15656 15657 15658 15659 15660 15661 15662 15663 15664 15665 15666 15667 15668 15669 15670 15671 15672 15673 15674 15675 15676 15677 15678 15679 15680 15681 15682 15683 15684 15685 15686 15687 15688 15689 15690 15691 15692 15693 15694 15695 15696 15697 15698 15699 15700 15701 15702 15703 15704 15705 15706 15707 15708 15709 15710 15711 15712 15713 15714 15715 15716 15717 15718 15719 15720 15721 15722 15723 15724 15725 15726 15727 15728 15729 15730 15731 15732 15733 15734 15735 15736 15737 15738 15739 15740 15741 15742 15743 15744 15745 15746 15747 15748 15749 15750 15751 15752 15753 15754 15755 15756 15757 15758 15759 15760 15761 15762 15763 15764 15765 15766 15767 15768 15769 15770 15771 15772 15773 15774 15775 15776 15777 15778 15779 15780 15781 15782 15783 15784 15785 15786 15787 15788 15789 15790 15791 15792 15793 15794 15795 15796 15797 15798 15799 15800 15801 15802 15803 15804 15805 15806 15807 15808 15809 15810 15811 15812 15813 15814 15815 15816 15817 15818 15819 15820 15821 15822 15823 15824 15825 15826 15827 15828 15829 15830 15831 15832 15833 15834 15835 15836 15837 15838 15839 15840 15841 15842 15843 15844 15845 15846 15847 15848 15849 15850 15851 15852 15853 15854 15855 15856 15857 15858 15859 15860 15861 15862 15863 15864 15865 15866 15867 15868 15869 15870 15871 15872 15873 15874 15875 15876 15877 15878 15879 15880 15881 15882 15883 15884 15885 15886 15887 15888 15889 15890 15891 15892 15893 15894 15895 15896 15897 15898 15899 15900 15901 15902 15903 15904 15905 15906 15907 15908 15909 15910 15911 15912 15913 15914 15915 15916 15917 15918 15919 15920 15921 15922 15923 15924 15925 15926 15927 15928 15929 15930 15931 15932 15933 15934 15935 15936 15937 15938 15939 15940 15941 15942 15943 15944 15945 15946 15947 15948 15949 15950 15951 15952 15953 15954 15955 15956 15957 15958 15959 15960 15961 15962 15963 15964 15965 15966 15967 15968 15969 15970 15971 15972 15973 15974 15975 15976 15977 15978 15979 15980 15981 15982 15983 15984 15985 15986 15987 15988 15989 15990 15991 15992 15993 15994 15995 15996 15997 15998 15999 16000 16001 16002 16003 16004 16005 16006 16007 16008 16009 16010 16011 16012 16013 16014 16015 16016 16017 16018 16019 16020 16021 16022 16023 16024 16025 16026 16027 16028 16029 16030 16031 16032 16033 16034 16035 16036 16037 16038 16039 16040 16041 16042 16043 16044 16045 16046 16047 16048 16049 16050 16051 16052 16053 16054 16055 16056 16057 16058 16059 16060 16061 16062 16063 16064 16065 16066 16067 16068 16069 16070 16071 16072 16073 16074 16075 16076 16077 16078 16079 16080 16081 16082 16083 16084 16085 16086 16087 16088 16089 16090 16091 16092 16093 16094 16095 16096 16097 16098 16099 16100 16101 16102 16103 16104 16105 16106 16107 16108 16109 16110 16111 16112 16113 16114 16115 16116 16117 16118 16119 16120 16121 16122 16123 16124 16125 16126 16127 16128 16129 16130 16131 16132 16133 16134 16135 16136 16137 16138 16139 16140 16141 16142 16143 16144 16145 16146 16147 16148 16149 16150 16151 16152 16153 16154 16155 16156 16157 16158 16159 16160 16161 16162 16163 16164 16165 16166 16167 16168 16169 16170 16171 16172 16173 16174 16175 16176 16177 16178 16179 16180 16181 16182 16183 16184 16185 16186 16187 16188 16189 16190 16191 16192 16193 16194 16195 16196 16197 16198 16199 16200 16201 16202 16203 16204 16205 16206 16207 16208 16209 16210 16211 16212 16213 16214 16215 16216 16217 16218 16219 16220 16221 16222 16223 16224 16225 16226 16227 16228 16229 16230 16231 16232 16233 16234 16235 16236 16237 16238 16239 16240 16241 16242 16243 16244 16245 16246 16247 16248 16249 16250 16251 16252 16253 16254 16255 16256 16257 16258 16259 16260 16261 16262 16263 16264 16265 16266 16267 16268 16269 16270 16271 16272 16273 16274 16275 16276 16277 16278 16279 16280 16281 16282 16283 16284 16285 16286 16287 16288 16289 16290 16291 16292 16293 16294 16295 16296 16297 16298 16299 16300 16301 16302 16303 16304 16305 16306 16307 16308 16309 16310 16311 16312 16313 16314 16315 16316 16317 16318 16319 16320 16321 16322 16323 16324 16325 16326 16327 16328 16329 16330 16331 16332 16333 16334 16335 16336 16337 16338 16339 16340 16341 16342 16343 16344 16345 16346 16347 16348 16349 16350 16351 16352 16353 16354 16355 16356 16357 16358 16359 16360 16361 16362 16363 16364 16365 16366 16367 16368 16369 16370 16371 16372 16373 16374 16375 16376 16377 16378 16379 16380 16381 16382 16383 16384 16385 16386 16387 16388 16389 16390 16391 16392 16393 16394 16395 16396 16397 16398 16399 16400 16401 16402 16403 16404 16405 16406 16407 16408 16409 16410 16411 16412 16413 16414 16415 16416 16417 16418 16419 16420 16421 16422 16423 16424 16425 16426 16427 16428 16429 16430 16431 16432 16433 16434 16435 16436 16437 16438 16439 16440 16441 16442 16443 16444 16445 16446 16447 16448 16449 16450 16451 16452 16453 16454 16455 16456 16457 16458 16459 16460 16461 16462 16463 16464 16465 16466 16467 16468 16469 16470 16471 16472 16473 16474 16475 16476 16477 16478 16479 16480 16481 16482 16483 16484 16485 16486 16487 16488 16489 16490 16491 16492 16493 16494 16495 16496 16497 16498 16499 16500 16501 16502 16503 16504 16505 16506 16507 16508 16509 16510 16511 16512 16513 16514 16515 16516 16517 16518 16519 16520 16521 16522 16523 16524 16525 16526 16527 16528 16529 16530 16531 16532 16533 16534 16535 16536 16537 16538 16539 16540 16541 16542 16543 16544 16545 16546 16547 16548 16549 16550 16551 16552 16553 16554 16555 16556 16557 16558 16559 16560 16561 16562 16563 16564 16565 16566 16567 16568 16569 16570 16571 16572 16573 16574 16575 16576 16577 16578 16579 16580 16581 16582 16583 16584 16585 16586 16587 16588 16589 16590 16591 16592 16593 16594 16595 16596 16597 16598 16599 16600 16601 16602 16603 16604 16605 16606 16607 16608 16609 16610 16611 16612 16613 16614 16615 16616 16617 16618 16619 16620 16621 16622 16623 16624 16625 16626 16627 16628 16629 16630 16631 16632 16633 16634 16635 16636 16637 16638 16639 16640 16641 16642 16643 16644 16645 16646 16647 16648 16649 16650 16651 16652 16653 16654 16655 16656 16657 16658 16659 16660 16661 16662 16663 16664 16665 16666 16667 16668 16669 16670 16671 16672 16673 16674 16675 16676 16677 16678 16679 16680 16681 16682 16683 16684 16685 16686 16687 16688 16689 16690 16691 16692 16693 16694 16695 16696 16697 16698 16699 16700 16701 16702 16703 16704 16705 16706 16707 16708 16709 16710 16711 16712 16713 16714 16715 16716 16717 16718 16719 16720 16721 16722 16723 16724 16725 16726 16727 16728 16729 16730 16731 16732 16733 16734 16735 16736 16737 16738 16739 16740 16741 16742 16743 16744 16745 16746 16747 16748 16749 16750 16751 16752 16753 16754 16755 16756 16757 16758 16759 16760 16761 16762 16763 16764 16765 16766 16767 16768 16769 16770 16771 16772 16773 16774 16775 16776 16777 16778 16779 16780 16781 16782 16783 16784 16785 16786 16787 16788 16789 16790 16791 16792 16793 16794 16795 16796 16797 16798 16799 16800 16801 16802 16803 16804 16805 16806 16807 16808 16809 16810 16811 16812 16813 16814 16815 16816 16817 16818 16819 16820 16821 16822 16823 16824 16825 16826 16827 16828 16829 16830 16831 16832 16833 16834 16835 16836 16837 16838 16839 16840 16841 16842 16843 16844 16845 16846 16847 16848 16849 16850 16851 16852 16853 16854 16855 16856 16857 16858 16859 16860 16861 16862 16863 16864 16865 16866 16867 16868 16869 16870 16871 16872 16873 16874 16875 16876 16877 16878 16879 16880 16881 16882 16883 16884 16885 16886 16887 16888 16889 16890 16891 16892 16893 16894 16895 16896 16897 16898 16899 16900 16901 16902 16903 16904 16905 16906 16907 16908 16909 16910 16911 16912 16913 16914 16915 16916 16917 16918 16919 16920 16921 16922 16923 16924 16925 16926 16927 16928 16929 16930 16931 16932 16933 16934 16935 16936 16937 16938 16939 16940 16941 16942 16943 16944 16945 16946 16947 16948 16949 16950 16951 16952 16953 16954 16955 16956 16957 16958 16959 16960 16961 16962 16963 16964 16965 16966 16967 16968 16969 16970 16971 16972 16973 16974 16975 16976 16977 16978 16979 16980 16981 16982 16983 16984 16985 16986 16987 16988 16989 16990 16991 16992 16993 16994 16995 16996 16997 16998 16999 17000 17001 17002 17003 17004 17005 17006 17007 17008 17009 17010 17011 17012 17013 17014 17015 17016 17017 17018 17019 17020 17021 17022 17023 17024 17025 17026 17027 17028 17029 17030 17031 17032 17033 17034 17035 17036 17037 17038 17039 17040 17041 17042 17043 17044 17045 17046 17047 17048 17049 17050 17051 17052 17053 17054 17055 17056 17057 17058 17059 17060 17061 17062 17063 17064 17065 17066 17067 17068 17069 17070 17071 17072 17073 17074 17075 17076 17077 17078 17079 17080 17081 17082 17083 17084 17085 17086 17087 17088 17089 17090 17091 17092 17093 17094 17095 17096 17097 17098 17099 17100 17101 17102 17103 17104 17105 17106 17107 17108 17109 17110 17111 17112 17113 17114 17115 17116 17117 17118 17119 17120 17121 17122 17123 17124 17125 17126 17127 17128 17129 17130 17131 17132 17133 17134 17135 17136 17137 17138 17139 17140 17141 17142 17143 17144 17145 17146 17147 17148 17149 17150 17151 17152 17153 17154 17155 17156 17157 17158 17159 17160 17161 17162 17163 17164 17165 17166 17167 17168 17169 17170 17171 17172 17173 17174 17175 17176 17177 17178 17179 17180 17181 17182 17183 17184 17185 17186 17187 17188 17189 17190 17191 17192 17193 17194 17195 17196 17197 17198 17199 17200 17201 17202 17203 17204 17205 17206 17207 17208 17209 17210 17211 17212 17213 17214 17215 17216 17217 17218 17219 17220 17221 17222 17223 17224 17225 17226 17227 17228 17229 17230 17231 17232 17233 17234 17235 17236 17237 17238 17239 17240 17241 17242 17243 17244 17245 17246 17247 17248 17249 17250 17251 17252 17253 17254 17255 17256 17257 17258 17259 17260 17261 17262 17263 17264 17265 17266 17267 17268 17269 17270 17271 17272 17273 17274 17275 17276 17277 17278 17279 17280 17281 17282 17283 17284 17285 17286 17287 17288 17289 17290 17291 17292 17293 17294 17295 17296 17297 17298 17299 17300 17301 17302 17303 17304 17305 17306 17307 17308 17309 17310 17311 17312 17313 17314 17315 17316 17317 17318 17319 17320 17321 17322 17323 17324 17325 17326 17327 17328 17329 17330 17331 17332 17333 17334 17335 17336 17337 17338 17339 17340 17341 17342 17343 17344 17345 17346 17347 17348 17349 17350 17351 17352 17353 17354 17355 17356 17357 17358 17359 17360 17361 17362 17363 17364 17365 17366 17367 17368 17369 17370 17371 17372 17373 17374 17375 17376 17377 17378 17379 17380 17381 17382 17383 17384 17385 17386 17387 17388 17389 17390 17391 17392 17393 17394 17395 17396 17397 17398 17399 17400 17401 17402 17403 17404 17405 17406 17407 17408 17409 17410 17411 17412 17413 17414 17415 17416 17417 17418 17419 17420 17421 17422 17423 17424 17425 17426 17427 17428 17429 17430 17431 17432 17433 17434 17435 17436 17437 17438 17439 17440 17441 17442 17443 17444 17445 17446 17447 17448 17449 17450 17451 17452 17453 17454 17455 17456 17457 17458 17459 17460 17461 17462 17463 17464 17465 17466 17467 17468 17469 17470 17471 17472 17473 17474 17475 17476 17477 17478 17479 17480 17481 17482 17483 17484 17485 17486 17487 17488 17489 17490 17491 17492 17493 17494 17495 17496 17497 17498 17499 17500 17501 17502 17503 17504 17505 17506 17507 17508 17509 17510 17511 17512 17513 17514 17515 17516 17517 17518 17519 17520 17521 17522 17523 17524 17525 17526 17527 17528 17529 17530 17531 17532 17533 17534 17535 17536 17537 17538 17539 17540 17541 17542 17543 17544 17545 17546 17547 17548 17549 17550 17551 17552 17553 17554 17555 17556 17557 17558 17559 17560 17561 17562 17563 17564 17565 17566 17567 17568 17569 17570 17571 17572 17573 17574 17575 17576 17577 17578 17579 17580 17581 17582 17583 17584 17585 17586 17587 17588 17589 17590 17591 17592 17593 17594 17595 17596 17597 17598 17599 17600 17601 17602 17603 17604 17605 17606 17607 17608 17609 17610 17611 17612 17613 17614 17615 17616 17617 17618 17619 17620 17621 17622 17623 17624 17625 17626 17627 17628 17629 17630 17631 17632 17633 17634 17635 17636 17637 17638 17639 17640 17641 17642 17643 17644 17645 17646 17647 17648 17649 17650 17651 17652 17653 17654 17655 17656 17657 17658 17659 17660 17661 17662 17663 17664 17665 17666 17667 17668 17669 17670 17671 17672 17673 17674 17675 17676 17677 17678 17679 17680 17681 17682 17683 17684 17685 17686 17687 17688 17689 17690 17691 17692 17693 17694 17695 17696 17697 17698 17699 17700 17701 17702 17703 17704 17705 17706 17707 17708 17709 17710 17711 17712 17713 17714 17715 17716 17717 17718 17719 17720 17721 17722 17723 17724 17725 17726 17727 17728 17729 17730 17731 17732 17733 17734 17735 17736 17737 17738 17739 17740 17741 17742 17743 17744 17745 17746 17747 17748 17749 17750 17751 17752 17753 17754 17755 17756 17757 17758 17759 17760 17761 17762 17763 17764 17765 17766 17767 17768 17769 17770 17771 17772 17773 17774 17775 17776 17777 17778 17779 17780 17781 17782 17783 17784 17785 17786 17787 17788 17789 17790 17791 17792 17793 17794 17795 17796 17797 17798 17799 17800 17801 17802 17803 17804 17805 17806 17807 17808 17809 17810 17811 17812 17813 17814 17815 17816 17817 17818 17819 17820 17821 17822 17823 17824 17825 17826 17827 17828 17829 17830 17831 17832 17833 17834 17835 17836 17837 17838 17839 17840 17841 17842 17843 17844 17845 17846 17847 17848 17849 17850 17851 17852 17853 17854 17855 17856 17857 17858 17859 17860 17861 17862 17863 17864 17865 17866 17867 17868 17869 17870 17871 17872 17873 17874 17875 17876 17877 17878 17879 17880 17881 17882 17883 17884 17885 17886 17887 17888 17889 17890 17891 17892 17893 17894 17895 17896 17897 17898 17899 17900 17901 17902 17903 17904 17905 17906 17907 17908 17909 17910 17911 17912 17913 17914 17915 17916 17917 17918 17919 17920 17921 17922 17923 17924 17925 17926 17927 17928 17929 17930 17931 17932 17933 17934 17935 17936 17937 17938 17939 17940 17941 17942 17943 17944 17945 17946 17947 17948 17949 17950 17951 17952 17953 17954 17955 17956 17957 17958 17959 17960 17961 17962 17963 17964 17965 17966 17967 17968 17969 17970 17971 17972 17973 17974 17975 17976 17977 17978 17979 17980 17981 17982 17983 17984 17985 17986 17987 17988 17989 17990 17991 17992 17993 17994 17995 17996 17997 17998 17999 18000 18001 18002 18003 18004 18005 18006 18007 18008 18009 18010 18011 18012 18013 18014 18015 18016 18017 18018 18019 18020 18021 18022 18023 18024 18025 18026 18027 18028 18029 18030 18031 18032 18033 18034 18035 18036 18037 18038 18039 18040 18041 18042 18043 18044 18045 18046 18047 18048 18049 18050 18051 18052 18053 18054 18055 18056 18057 18058 18059 18060 18061 18062 18063 18064 18065 18066 18067 18068 18069 18070 18071 18072 18073 18074 18075 18076 18077 18078 18079 18080 18081 18082 18083 18084 18085 18086 18087 18088 18089 18090 18091 18092 18093 18094 18095 18096 18097 18098 18099 18100 18101 18102 18103 18104 18105 18106 18107 18108 18109 18110 18111 18112 18113 18114 18115 18116 18117 18118 18119 18120 18121 18122 18123 18124 18125 18126 18127 18128 18129 18130 18131 18132 18133 18134 18135 18136 18137 18138 18139 18140 18141 18142 18143 18144 18145 18146 18147 18148 18149 18150 18151 18152 18153 18154 18155 18156 18157 18158 18159 18160 18161 18162 18163 18164 18165 18166 18167 18168 18169 18170 18171 18172 18173 18174 18175 18176 18177 18178 18179 18180 18181 18182 18183 18184 18185 18186 18187 18188 18189 18190 18191 18192 18193 18194 18195 18196 18197 18198 18199 18200 18201 18202 18203 18204 18205 18206 18207 18208 18209 18210 18211 18212 18213 18214 18215 18216 18217 18218 18219 18220 18221 18222 18223 18224 18225 18226 18227 18228 18229 18230 18231 18232 18233 18234 18235 18236 18237 18238 18239 18240 18241 18242 18243 18244 18245 18246 18247 18248 18249 18250 18251 18252 18253 18254 18255 18256 18257 18258 18259 18260 18261 18262 18263 18264 18265 18266 18267 18268 18269 18270 18271 18272 18273 18274 18275 18276 18277 18278 18279 18280 18281 18282 18283 18284 18285 18286 18287 18288 18289 18290 18291 18292 18293 18294 18295 18296 18297 18298 18299 18300 18301 18302 18303 18304 18305 18306 18307 18308 18309 18310 18311 18312 18313 18314 18315 18316 18317 18318 18319 18320 18321 18322 18323 18324 18325 18326 18327 18328 18329 18330 18331 18332 18333 18334 18335 18336 18337 18338 18339 18340 18341 18342 18343 18344 18345 18346 18347 18348 18349 18350 18351 18352 18353 18354 18355 18356 18357 18358 18359 18360 18361 18362 18363 18364 18365 18366 18367 18368 18369 18370 18371 18372 18373 18374 18375 18376 18377 18378 18379 18380 18381 18382 18383 18384 18385 18386 18387 18388 18389 18390 18391 18392 18393 18394 18395 18396 18397 18398 18399 18400 18401 18402 18403 18404 18405 18406 18407 18408 18409 18410 18411 18412 18413 18414 18415 18416 18417 18418 18419 18420 18421 18422 18423 18424 18425 18426 18427 18428 18429 18430 18431 18432 18433 18434 18435 18436 18437 18438 18439 18440 18441 18442 18443 18444 18445 18446 18447 18448 18449 18450 18451 18452 18453 18454 18455 18456 18457 18458 18459 18460 18461 18462 18463 18464 18465 18466 18467 18468 18469 18470 18471 18472 18473 18474 18475 18476 18477 18478 18479 18480 18481 18482 18483 18484 18485 18486 18487 18488 18489 18490 18491 18492 18493 18494 18495 18496 18497 18498 18499 18500 18501 18502 18503 18504 18505 18506 18507 18508 18509 18510 18511 18512 18513 18514 18515 18516 18517 18518 18519 18520 18521 18522 18523 18524 18525 18526 18527 18528 18529 18530 18531 18532 18533 18534 18535 18536 18537 18538 18539 18540 18541 18542 18543 18544 18545 18546 18547 18548 18549 18550 18551 18552 18553 18554 18555 18556 18557 18558 18559 18560 18561 18562 18563 18564 18565 18566 18567 18568 18569 18570 18571 18572 18573 18574 18575 18576 18577 18578 18579 18580 18581 18582 18583 18584 18585 18586 18587 18588 18589 18590 18591 18592 18593 18594 18595 18596 18597 18598 18599 18600 18601 18602 18603 18604 18605 18606 18607 18608 18609 18610 18611 18612 18613 18614 18615 18616 18617 18618 18619 18620 18621 18622 18623 18624 18625 18626 18627 18628 18629 18630 18631 18632 18633 18634 18635 18636 18637 18638 18639 18640 18641 18642 18643 18644 18645 18646 18647 18648 18649 18650 18651 18652 18653 18654 18655 18656 18657 18658 18659 18660 18661 18662 18663 18664 18665 18666 18667 18668 18669 18670 18671 18672 18673 18674 18675 18676 18677 18678 18679 18680 18681 18682 18683 18684 18685 18686 18687 18688 18689 18690 18691 18692 18693 18694 18695 18696 18697 18698 18699 18700 18701 18702 18703 18704 18705 18706 18707 18708 18709 18710 18711 18712 18713 18714 18715 18716 18717 18718 18719 18720 18721 18722 18723 18724 18725 18726 18727 18728 18729 18730 18731 18732 18733 18734 18735 18736 18737 18738 18739 18740 18741 18742 18743 18744 18745 18746 18747 18748 18749 18750 18751 18752 18753 18754 18755 18756 18757 18758 18759 18760 18761 18762 18763 18764 18765 18766 18767 18768 18769 18770 18771 18772 18773 18774 18775 18776 18777 18778 18779 18780 18781 18782 18783 18784 18785 18786 18787 18788 18789 18790 18791 18792 18793 18794 18795 18796 18797 18798 18799 18800 18801 18802 18803 18804 18805 18806 18807 18808 18809 18810 18811 18812 18813 18814 18815 18816 18817 18818 18819 18820 18821 18822 18823 18824 18825 18826 18827 18828 18829 18830 18831 18832 18833 18834 18835 18836 18837 18838 18839 18840 18841 18842 18843 18844 18845 18846 18847 18848 18849 18850 18851 18852 18853 18854 18855 18856 18857 18858 18859 18860 18861 18862 18863 18864 18865 18866 18867 18868 18869 18870 18871 18872 18873 18874 18875 18876 18877 18878 18879 18880 18881 18882 18883 18884 18885 18886 18887 18888 18889 18890 18891 18892 18893 18894 18895 18896 18897 18898 18899 18900 18901 18902 18903 18904 18905 18906 18907 18908 18909 18910 18911 18912 18913 18914 18915 18916 18917 18918 18919 18920 18921 18922 18923 18924 18925 18926 18927 18928 18929 18930 18931 18932 18933 18934 18935 18936 18937 18938 18939 18940 18941 18942 18943 18944 18945 18946 18947 18948 18949 18950 18951 18952 18953 18954 18955 18956 18957 18958 18959 18960 18961 18962 18963 18964 18965 18966 18967 18968 18969 18970 18971 18972 18973 18974 18975 18976 18977 18978 18979 18980 18981 18982 18983 18984 18985 18986 18987 18988 18989 18990 18991 18992 18993 18994 18995 18996 18997 18998 18999 19000 19001 19002 19003 19004 19005 19006 19007 19008 19009 19010 19011 19012 19013 19014 19015 19016 19017 19018 19019 19020 19021 19022 19023 19024 19025 19026 19027 19028 19029 19030 19031 19032 19033 19034 19035 19036 19037 19038 19039 19040 19041 19042 19043 19044 19045 19046 19047 19048 19049 19050 19051 19052 19053 19054 19055 19056 19057 19058 19059 19060 19061 19062 19063 19064 19065 19066 19067 19068 19069 19070 19071 19072 19073 19074 19075 19076 19077 19078 19079 19080 19081 19082 19083 19084 19085 19086 19087 19088 19089 19090 19091 19092 19093 19094 19095 19096 19097 19098 19099 19100 19101 19102 19103 19104 19105 19106 19107 19108 19109 19110 19111 19112 19113 19114 19115 19116 19117 19118 19119 19120 19121 19122 19123 19124 19125 19126 19127 19128 19129 19130 19131 19132 19133 19134 19135 19136 19137 19138 19139 19140 19141 19142 19143 19144 19145 19146 19147 19148 19149 19150 19151 19152 19153 19154 19155 19156 19157 19158 19159 19160 19161 19162 19163 19164 19165 19166 19167 19168 19169 19170 19171 19172 19173 19174 19175 19176 19177 19178 19179 19180 19181 19182 19183 19184 19185 19186 19187 19188 19189 19190 19191 19192 19193 19194 19195 19196 19197 19198 19199 19200 19201 19202 19203 19204 19205 19206 19207 19208 19209 19210 19211 19212 19213 19214 19215 19216 19217 19218 19219 19220 19221 19222 19223 19224 19225 19226 19227 19228 19229 19230 19231 19232 19233 19234 19235 19236 19237 19238 19239 19240 19241 19242 19243 19244 19245 19246 19247 19248 19249 19250 19251 19252 19253 19254 19255 19256 19257 19258 19259 19260 19261 19262 19263 19264 19265 19266 19267 19268 19269 19270 19271 19272 19273 19274 19275 19276 19277 19278 19279 19280 19281 19282 19283 19284 19285 19286 19287 19288 19289 19290 19291 19292 19293 19294 19295 19296 19297 19298 19299 19300 19301 19302 19303 19304 19305 19306 19307 19308 19309 19310 19311 19312 19313 19314 19315 19316 19317 19318 19319 19320 19321 19322 19323 19324 19325 19326 19327 19328 19329 19330 19331 19332 19333 19334 19335 19336 19337 19338 19339 19340 19341 19342 19343 19344 19345 19346 19347 19348 19349 19350 19351 19352 19353 19354 19355 19356 19357 19358 19359 19360 19361 19362 19363 19364 19365 19366 19367 19368 19369 19370 19371 19372 19373 19374 19375 19376 19377 19378 19379 19380 19381 19382 19383 19384 19385 19386 19387 19388 19389 19390 19391 19392 19393 19394 19395 19396 19397 19398 19399 19400 19401 19402 19403 19404 19405 19406 19407 19408 19409 19410 19411 19412 19413 19414 19415 19416 19417 19418 19419 19420 19421 19422 19423 19424 19425 19426 19427 19428 19429 19430 19431 19432 19433 19434 19435 19436 19437 19438 19439 19440 19441 19442 19443 19444 19445 19446 19447 19448 19449 19450 19451 19452 19453 19454 19455 19456 19457 19458 19459 19460 19461 19462 19463 19464 19465 19466 19467 19468 19469 19470 19471 19472 19473 19474 19475 19476 19477 19478 19479 19480 19481 19482 19483 19484 19485 19486 19487 19488 19489 19490 19491 19492 19493 19494 19495 19496 19497 19498 19499 19500 19501 19502 19503 19504 19505 19506 19507 19508 19509 19510 19511 19512 19513 19514 19515 19516 19517 19518 19519 19520 19521 19522 19523 19524 19525 19526 19527 19528 19529 19530 19531 19532 19533 19534 19535 19536 19537 19538 19539 19540 19541 19542 19543 19544 19545 19546 19547 19548 19549 19550 19551 19552 19553 19554 19555 19556 19557 19558 19559 19560 19561 19562 19563 19564 19565 19566 19567 19568 19569 19570 19571 19572 19573 19574 19575 19576 19577 19578 19579 19580 19581 19582 19583 19584 19585 19586 19587 19588 19589 19590 19591 19592 19593 19594 19595 19596 19597 19598 19599 19600 19601 19602 19603 19604 19605 19606 19607 19608 19609 19610 19611 19612 19613 19614 19615 19616 19617 19618 19619 19620 19621 19622 19623 19624 19625 19626 19627 19628 19629 19630 19631 19632 19633 19634 19635 19636 19637 19638 19639 19640 19641 19642 19643 19644 19645 19646 19647 19648 19649 19650 19651 19652 19653 19654 19655 19656 19657 19658 19659 19660 19661 19662 19663 19664 19665 19666 19667 19668 19669 19670 19671 19672 19673 19674 19675 19676 19677 19678 19679 19680 19681 19682 19683 19684 19685 19686 19687 19688 19689 19690 19691 19692 19693 19694 19695 19696 19697 19698 19699 19700 19701 19702 19703 19704 19705 19706 19707 19708 19709 19710 19711 19712 19713 19714 19715 19716 19717 19718 19719 19720 19721 19722 19723 19724 19725 19726 19727 19728 19729 19730 19731 19732 19733 19734 19735 19736 19737 19738 19739 19740 19741 19742 19743 19744 19745 19746 19747 19748 19749 19750 19751 19752 19753 19754 19755 19756 19757 19758 19759 19760 19761 19762 19763 19764 19765 19766 19767 19768 19769 19770 19771 19772 19773 19774 19775 19776 19777 19778 19779 19780 19781 19782 19783 19784 19785 19786 19787 19788 19789 19790 19791 19792 19793 19794 19795 19796 19797 19798 19799 19800 19801 19802 19803 19804 19805 19806 19807 19808 19809 19810 19811 19812 19813 19814 19815 19816 19817 19818 19819 19820 19821 19822 19823 19824 19825 19826 19827 19828 19829 19830 19831 19832 19833 19834 19835 19836 19837 19838 19839 19840 19841 19842 19843 19844 19845 19846 19847 19848 19849 19850 19851 19852 19853 19854 19855 19856 19857 19858 19859 19860 19861 19862 19863 19864 19865 19866 19867 19868 19869 19870 19871 19872 19873 19874 19875 19876 19877 19878 19879 19880 19881 19882 19883 19884 19885 19886 19887 19888 19889 19890 19891 19892 19893 19894 19895 19896 19897 19898 19899 19900 19901 19902 19903 19904 19905 19906 19907 19908 19909 19910 19911 19912 19913 19914 19915 19916 19917 19918 19919 19920 19921 19922 19923 19924 19925 19926 19927 19928 19929 19930 19931 19932 19933 19934 19935 19936 19937 19938 19939 19940 19941 19942 19943 19944 19945 19946 19947 19948 19949 19950 19951 19952 19953 19954 19955 19956 19957 19958 19959 19960 19961 19962 19963 19964 19965 19966 19967 19968 19969 19970 19971 19972 19973 19974 19975 19976 19977 19978 19979 19980 19981 19982 19983 19984 19985 19986 19987 19988 19989 19990 19991 19992 19993 19994 19995 19996 19997 19998 19999 20000 20001 20002 20003 20004 20005 20006 20007 20008 20009 20010 20011 20012 20013 20014 20015 20016 20017 20018 20019 20020 20021 20022 20023 20024 20025 20026 20027 20028 20029 20030 20031 20032 20033 20034 20035 20036 20037 20038 20039 20040 20041 20042 20043 20044 20045 20046 20047 20048 20049 20050 20051 20052 20053 20054 20055 20056 20057 20058 20059 20060 20061 20062 20063 20064 20065 20066 20067 20068 20069 20070 20071 20072 20073 20074 20075 20076 20077 20078 20079 20080 20081 20082 20083 20084 20085 20086 20087 20088 20089 20090 20091 20092 20093 20094 20095 20096 20097 20098 20099 20100 20101 20102 20103 20104 20105 20106 20107 20108 20109 20110 20111 20112 20113 20114 20115 20116 20117 20118 20119 20120 20121 20122 20123 20124 20125 20126 20127 20128 20129 20130 20131 20132 20133 20134 20135 20136 20137 20138 20139 20140 20141 20142 20143 20144 20145 20146 20147 20148 20149 20150 20151 20152 20153 20154 20155 20156 20157 20158 20159 20160 20161 20162 20163 20164 20165 20166 20167 20168 20169 20170 20171 20172 20173 20174 20175 20176 20177 20178 20179 20180 20181 20182 20183 20184 20185 20186 20187 20188 20189 20190 20191 20192 20193 20194 20195 20196 20197 20198 20199 20200 20201 20202 20203 20204 20205 20206 20207 20208 20209 20210 20211 20212 20213 20214 20215 20216 20217 20218 20219 20220 20221 20222 20223 20224 20225 20226 20227 20228 20229 20230 20231 20232 20233 20234 20235 20236 20237 20238 20239 20240 20241 20242 20243 20244 20245 20246 20247 20248 20249 20250 20251 20252 20253 20254 20255 20256 20257 20258 20259 20260 20261 20262 20263 20264 20265 20266 20267 20268 20269 20270 20271 20272 20273 20274 20275 20276 20277 20278 20279 20280 20281 20282 20283 20284 20285 20286 20287 20288 20289 20290 20291 20292 20293 20294 20295 20296 20297 20298 20299 20300 20301 20302 20303 20304 20305 20306 20307 20308 20309 20310 20311 20312 20313 20314 20315 20316 20317 20318 20319 20320 20321 20322 20323 20324 20325 20326 20327 20328 20329 20330 20331 20332 20333 20334 20335 20336 20337 20338 20339 20340 20341 20342 20343 20344 20345 20346 20347 20348 20349 20350 20351 20352 20353 20354 20355 20356 20357 20358 20359 20360 20361 20362 20363 20364 20365 20366 20367 20368 20369 20370 20371 20372 20373 20374 20375 20376 20377 20378 20379 20380 20381 20382 20383 20384 20385 20386 20387 20388 20389 20390 20391 20392 20393 20394 20395 20396 20397 20398 20399 20400 20401 20402 20403 20404 20405 20406 20407 20408 20409 20410 20411 20412 20413 20414 20415 20416 20417 20418 20419 20420 20421 20422 20423 20424 20425 20426 20427 20428 20429 20430 20431 20432 20433 20434 20435 20436 20437 20438 20439 20440 20441 20442 20443 20444 20445 20446 20447 20448 20449 20450 20451 20452 20453 20454 20455 20456 20457 20458 20459 20460 20461 20462 20463 20464 20465 20466 20467 20468 20469 20470 20471 20472 20473 20474 20475 20476 20477 20478 20479 20480 20481 20482 20483 20484 20485 20486 20487 20488 20489 20490 20491 20492 20493 20494 20495 20496 20497 20498 20499 20500 20501 20502 20503 20504 20505 20506 20507 20508 20509 20510 20511 20512 20513 20514 20515 20516 20517 20518 20519 20520 20521 20522 20523 20524 20525 20526 20527 20528 20529 20530 20531 20532 20533 20534 20535 20536 20537 20538 20539 20540 20541 20542 20543 20544 20545 20546 20547 20548 20549 20550 20551 20552 20553 20554 20555 20556 20557 20558 20559 20560 20561 20562 20563 20564 20565 20566 20567 20568 20569 20570 20571 20572 20573 20574 20575 20576 20577 20578 20579 20580 20581 20582 20583 20584 20585 20586 20587 20588 20589 20590 20591 20592 20593 20594 20595 20596 20597 20598 20599 20600 20601 20602 20603 20604 20605 20606 20607 20608 20609 20610 20611 20612 20613 20614 20615 20616 20617 20618 20619 20620 20621 20622 20623 20624 20625 20626 20627 20628 20629 20630 20631 20632 20633 20634 20635 20636 20637 20638 20639 20640 20641 20642 20643 20644 20645 20646 20647 20648 20649 20650 20651 20652 20653 20654 20655 20656 20657 20658 20659 20660 20661 20662 20663 20664 20665 20666 20667 20668 20669 20670 20671 20672 20673 20674 20675 20676 20677 20678 20679 20680 20681 20682 20683 20684 20685 20686 20687 20688 20689 20690 20691 20692 20693 20694 20695 20696 20697 20698 20699 20700 20701 20702 20703 20704 20705 20706 20707 20708 20709 20710 20711 20712 20713 20714 20715 20716 20717 20718 20719 20720 20721 20722 20723 20724 20725 20726 20727 20728 20729 20730 20731 20732 20733 20734 20735 20736 20737 20738 20739 20740 20741 20742 20743 20744 20745 20746 20747 20748 20749 20750 20751 20752 20753 20754 20755 20756 20757 20758 20759 20760 20761 20762 20763 20764 20765 20766 20767 20768 20769 20770 20771 20772 20773 20774 20775 20776 20777 20778 20779 20780 20781 20782 20783 20784 20785 20786 20787 20788 20789 20790 20791 20792 20793 20794 20795 20796 20797 20798 20799 20800 20801 20802 20803 20804 20805 20806 20807 20808 20809 20810 20811 20812 20813 20814 20815 20816 20817 20818 20819 20820 20821 20822 20823 20824 20825 20826 20827 20828 20829 20830 20831 20832 20833 20834 20835 20836 20837 20838 20839 20840 20841 20842 20843 20844 20845 20846 20847 20848 20849 20850 20851 20852 20853 20854 20855 20856 20857 20858 20859 20860 20861 20862 20863 20864 20865 20866 20867 20868 20869 20870 20871 20872 20873 20874 20875 20876 20877 20878 20879 20880 20881 20882 20883 20884 20885 20886 20887 20888 20889 20890 20891 20892 20893 20894 20895 20896 20897 20898 20899 20900 20901 20902 20903 20904 20905 20906 20907 20908 20909 20910 20911 20912 20913 20914 20915 20916 20917 20918 20919 20920 20921 20922 20923 20924 20925 20926 20927 20928 20929 20930 20931 20932 20933 20934 20935 20936 20937 20938 20939 20940 20941 20942 20943 20944 20945 20946 20947 20948 20949 20950 20951 20952 20953 20954 20955 20956 20957 20958 20959 20960 20961 20962 20963 20964 20965 20966 20967 20968 20969 20970 20971 20972 20973 20974 20975 20976 20977 20978 20979 20980 20981 20982 20983 20984 20985 20986 20987 20988 20989 20990 20991 20992 20993 20994 20995 20996 20997 20998 20999 21000 21001 21002 21003 21004 21005 21006 21007 21008 21009 21010 21011 21012 21013 21014 21015 21016 21017 21018 21019 21020 21021 21022 21023 21024 21025 21026 21027 21028 21029 21030 21031 21032 21033 21034 21035 21036 21037 21038 21039 21040 21041 21042 21043 21044 21045 21046 21047 21048 21049 21050 21051 21052 21053 21054 21055 21056 21057 21058 21059 21060 21061 21062 21063 21064 21065 21066 21067 21068 21069 21070 21071 21072 21073 21074 21075 21076 21077 21078 21079 21080 21081 21082 21083 21084 21085 21086 21087 21088 21089 21090 21091 21092 21093 21094 21095 21096 21097 21098 21099 21100 21101 21102 21103 21104 21105 21106 21107 21108 21109 21110 21111 21112 21113 21114 21115 21116 21117 21118 21119 21120 21121 21122 21123 21124 21125 21126 21127 21128 21129 21130 21131 21132 21133 21134 21135 21136 21137 21138 21139 21140 21141 21142 21143 21144 21145 21146 21147 21148 21149 21150 21151 21152 21153 21154 21155 21156 21157 21158 21159 21160 21161 21162 21163 21164 21165 21166 21167 21168 21169 21170 21171 21172 21173 21174 21175 21176 21177 21178 21179 21180 21181 21182 21183 21184 21185 21186 21187 21188 21189 21190 21191 21192 21193 21194 21195 21196 21197 21198 21199 21200 21201 21202 21203 21204 21205 21206 21207 21208 21209 21210 21211 21212 21213 21214 21215 21216 21217 21218 21219 21220 21221 21222 21223 21224 21225 21226 21227 21228 21229 21230 21231 21232 21233 21234 21235 21236 21237 21238 21239 21240 21241 21242 21243 21244 21245 21246 21247 21248 21249 21250 21251 21252 21253 21254 21255 21256 21257 21258 21259 21260 21261 21262 21263 21264 21265 21266 21267 21268 21269 21270 21271 21272 21273 21274 21275 21276 21277 21278 21279 21280 21281 21282 21283 21284 21285 21286 21287 21288 21289 21290 21291 21292 21293 21294 21295 21296 21297 21298 21299 21300 21301 21302 21303 21304 21305 21306 21307 21308 21309 21310 21311 21312 21313 21314 21315 21316 21317 21318 21319 21320 21321 21322 21323 21324 21325 21326 21327 21328 21329 21330 21331 21332 21333 21334 21335 21336 21337 21338 21339 21340 21341 21342 21343 21344 21345 21346 21347 21348 21349 21350 21351 21352 21353 21354 21355 21356 21357 21358 21359 21360 21361 21362 21363 21364 21365 21366 21367 21368 21369 21370 21371 21372 21373 21374 21375 21376 21377 21378 21379 21380 21381 21382 21383 21384 21385 21386 21387 21388 21389 21390 21391 21392 21393 21394 21395 21396 21397 21398 21399 21400 21401 21402 21403 21404 21405 21406 21407 21408 21409 21410 21411 21412 21413 21414 21415 21416 21417 21418 21419 21420 21421 21422 21423 21424 21425 21426 21427 21428 21429 21430 21431 21432 21433 21434 21435 21436 21437 21438 21439 21440 21441 21442 21443 21444 21445 21446 21447 21448 21449 21450 21451 21452 21453 21454 21455 21456 21457 21458 21459 21460 21461 21462 21463 21464 21465 21466 21467 21468 21469 21470 21471 21472 21473 21474 21475 21476 21477 21478 21479 21480 21481 21482 21483 21484 21485 21486 21487 21488 21489 21490 21491 21492 21493 21494 21495 21496 21497 21498 21499 21500 21501 21502 21503 21504 21505 21506 21507 21508 21509 21510 21511 21512 21513 21514 21515 21516 21517 21518 21519 21520 21521 21522 21523 21524 21525 21526 21527 21528 21529 21530 21531 21532 21533 21534 21535 21536 21537 21538 21539 21540 21541 21542 21543 21544 21545 21546 21547 21548 21549 21550 21551 21552 21553 21554 21555 21556 21557 21558 21559 21560 21561 21562 21563 21564 21565 21566 21567 21568 21569 21570 21571 21572 21573 21574 21575 21576 21577 21578 21579 21580 21581 21582 21583 21584 21585 21586 21587 21588 21589 21590 21591 21592 21593 21594 21595 21596 21597 21598 21599 21600 21601 21602 21603 21604 21605 21606 21607 21608 21609 21610 21611 21612 21613 21614 21615 21616 21617 21618 21619 21620 21621 21622 21623 21624 21625 21626 21627 21628 21629 21630 21631 21632 21633 21634 21635 21636 21637 21638 21639 21640 21641 21642 21643 21644 21645 21646 21647 21648 21649 21650 21651 21652 21653 21654 21655 21656 21657 21658 21659 21660 21661 21662 21663 21664 21665 21666 21667 21668 21669 21670 21671 21672 21673 21674 21675 21676 21677 21678 21679 21680 21681 21682 21683 21684 21685 21686 21687 21688 21689 21690 21691 21692 21693 21694 21695 21696 21697 21698 21699 21700 21701 21702 21703 21704 21705 21706 21707 21708 21709 21710 21711 21712 21713 21714 21715 21716 21717 21718 21719 21720 21721 21722 21723 21724 21725 21726 21727 21728 21729 21730 21731 21732 21733 21734 21735 21736 21737 21738 21739 21740 21741 21742 21743 21744 21745 21746 21747 21748 21749 21750 21751 21752 21753 21754 21755 21756 21757 21758 21759 21760 21761 21762 21763 21764 21765 21766 21767 21768 21769 21770 21771 21772 21773 21774 21775 21776 21777 21778 21779 21780 21781 21782 21783 21784 21785 21786 21787 21788 21789 21790 21791 21792 21793 21794 21795 21796 21797 21798 21799 21800 21801 21802 21803 21804 21805 21806 21807 21808 21809 21810 21811 21812 21813 21814 21815 21816 21817 21818 21819 21820 21821 21822 21823 21824 21825 21826 21827 21828 21829 21830 21831 21832 21833 21834 21835 21836 21837 21838 21839 21840 21841 21842 21843 21844 21845 21846 21847 21848 21849 21850 21851 21852 21853 21854 21855 21856 21857 21858 21859 21860 21861 21862 21863 21864 21865 21866 21867 21868 21869 21870 21871 21872 21873 21874 21875 21876 21877 21878 21879 21880 21881 21882 21883 21884 21885 21886 21887 21888 21889 21890 21891 21892 21893 21894 21895 21896 21897 21898 21899 21900 21901 21902 21903 21904 21905 21906 21907 21908 21909 21910 21911 21912 21913 21914 21915 21916 21917 21918 21919 21920 21921 21922 21923 21924 21925 21926 21927 21928 21929 21930 21931 21932 21933 21934 21935 21936 21937 21938 21939 21940 21941 21942 21943 21944 21945 21946 21947 21948 21949 21950 21951 21952 21953 21954 21955 21956 21957 21958 21959 21960 21961 21962 21963 21964 21965 21966 21967 21968 21969 21970 21971 21972 21973 21974 21975 21976 21977 21978 21979 21980 21981 21982 21983 21984 21985 21986 21987 21988 21989 21990 21991 21992 21993 21994 21995 21996 21997 21998 21999 22000 22001 22002 22003 22004 22005 22006 22007 22008 22009 22010 22011 22012 22013 22014 22015 22016 22017 22018 22019 22020 22021 22022 22023 22024 22025 22026 22027 22028 22029 22030 22031 22032 22033 22034 22035 22036 22037 22038 22039 22040 22041 22042 22043 22044 22045 22046 22047 22048 22049 22050 22051 22052 22053 22054 22055 22056 22057 22058 22059 22060 22061 22062 22063 22064 22065 22066 22067 22068 22069 22070 22071 22072 22073 22074 22075 22076 22077 22078 22079 22080 22081 22082 22083 22084 22085 22086 22087 22088 22089 22090 22091 22092 22093 22094 22095 22096 22097 22098 22099 22100 22101 22102 22103 22104 22105 22106 22107 22108 22109 22110 22111 22112 22113 22114 22115 22116 22117 22118 22119 22120 22121 22122 22123 22124 22125 22126 22127 22128 22129 22130 22131 22132 22133 22134 22135 22136 22137 22138 22139 22140 22141 22142 22143 22144 22145 22146 22147 22148 22149 22150 22151 22152 22153 22154 22155 22156 22157 22158 22159 22160 22161 22162 22163 22164 22165 22166 22167 22168 22169 22170 22171 22172 22173 22174 22175 22176 22177 22178 22179 22180 22181 22182 22183 22184 22185 22186 22187 22188 22189 22190 22191 22192 22193 22194 22195 22196 22197 22198 22199 22200 22201 22202 22203 22204 22205 22206 22207 22208 22209 22210 22211 22212 22213 22214 22215 22216 22217 22218 22219 22220 22221 22222 22223 22224 22225 22226 22227 22228 22229 22230 22231 22232 22233 22234 22235 22236 22237 22238 22239 22240 22241 22242 22243 22244 22245 22246 22247 22248 22249 22250 22251 22252 22253 22254 22255 22256 22257 22258 22259 22260 22261 22262 22263 22264 22265 22266 22267 22268 22269 22270 22271 22272 22273 22274 22275 22276 22277 22278 22279 22280 22281 22282 22283 22284 22285 22286 22287 22288 22289 22290 22291 22292 22293 22294 22295 22296 22297 22298 22299 22300 22301 22302 22303 22304 22305 22306 22307 22308 22309 22310 22311 22312 22313 22314 22315 22316 22317 22318 22319 22320 22321 22322 22323 22324 22325 22326 22327 22328 22329 22330 22331 22332 22333 22334 22335 22336 22337 22338 22339 22340 22341 22342 22343 22344 22345 22346 22347 22348 22349 22350 22351 22352 22353 22354 22355 22356 22357 22358 22359 22360 22361 22362 22363 22364 22365 22366 22367 22368 22369 22370 22371 22372 22373 22374 22375 22376 22377 22378 22379 22380 22381 22382 22383 22384 22385 22386 22387 22388 22389 22390 22391 22392 22393 22394 22395 22396 22397 22398 22399 22400 22401 22402 22403 22404 22405 22406 22407 22408 22409 22410 22411 22412 22413 22414 22415 22416 22417 22418 22419 22420 22421 22422 22423 22424 22425 22426 22427 22428 22429 22430 22431 22432 22433 22434 22435 22436 22437 22438 22439 22440 22441 22442 22443 22444 22445 22446 22447 22448 22449 22450 22451 22452 22453 22454 22455 22456 22457 22458 22459 22460 22461 22462 22463 22464 22465 22466 22467 22468 22469 22470 22471 22472 22473 22474 22475 22476 22477 22478 22479 22480 22481 22482 22483 22484 22485 22486 22487 22488 22489 22490 22491 22492 22493 22494 22495 22496 22497 22498 22499 22500 22501 22502 22503 22504 22505 22506 22507 22508 22509 22510 22511 22512 22513 22514 22515 22516 22517 22518 22519 22520 22521 22522 22523 22524 22525 22526 22527 22528 22529 22530 22531 22532 22533 22534 22535 22536 22537 22538 22539 22540 22541 22542 22543 22544 22545 22546 22547 22548 22549 22550 22551 22552 22553 22554 22555 22556 22557 22558 22559 22560 22561 22562 22563 22564 22565 22566 22567 22568 22569 22570 22571 22572 22573 22574 22575 22576 22577 22578 22579 22580 22581 22582 22583 22584 22585 22586 22587 22588 22589 22590 22591 22592 22593 22594 22595 22596 22597 22598 22599 22600 22601 22602 22603 22604 22605 22606 22607 22608 22609 22610 22611 22612 22613 22614 22615 22616 22617 22618 22619 22620 22621 22622 22623 22624 22625 22626 22627 22628 22629 22630 22631 22632 22633 22634 22635 22636 22637 22638 22639 22640 22641 22642 22643 22644 22645 22646 22647 22648 22649 22650 22651 22652 22653 22654 22655 22656 22657 22658 22659 22660 22661 22662 22663 22664 22665 22666 22667 22668 22669 22670 22671 22672 22673 22674 22675 22676 22677 22678 22679 22680 22681 22682 22683 22684 22685 22686 22687 22688 22689 22690 22691 22692 22693 22694 22695 22696 22697 22698 22699 22700 22701 22702 22703 22704 22705 22706 22707 22708 22709 22710 22711 22712 22713 22714 22715 22716 22717 22718 22719 22720 22721 22722 22723 22724 22725 22726 22727 22728 22729 22730 22731 22732 22733 22734 22735 22736 22737 22738 22739 22740 22741 22742 22743 22744 22745 22746 22747 22748 22749 22750 22751 22752 22753 22754 22755 22756 22757 22758 22759 22760 22761 22762 22763 22764 22765 22766 22767 22768 22769 22770 22771 22772 22773 22774 22775 22776 22777 22778 22779 22780 22781 22782 22783 22784 22785 22786 22787 22788 22789 22790 22791 22792 22793 22794 22795 22796 22797 22798 22799 22800 22801 22802 22803 22804 22805 22806 22807 22808 22809 22810 22811 22812 22813 22814 22815 22816 22817 22818 22819 22820 22821 22822 22823 22824 22825 22826 22827 22828 22829 22830 22831 22832 22833 22834 22835 22836 22837 22838 22839 22840 22841 22842 22843 22844 22845 22846 22847 22848 22849 22850 22851 22852 22853 22854 22855 22856 22857 22858 22859 22860 22861 22862 22863 22864 22865 22866 22867 22868 22869 22870 22871 22872 22873 22874 22875 22876 22877 22878 22879 22880 22881 22882 22883 22884 22885 22886 22887 22888 22889 22890 22891 22892 22893 22894 22895 22896 22897 22898 22899 22900 22901 22902 22903 22904 22905 22906 22907 22908 22909 22910 22911 22912 22913 22914 22915 22916 22917 22918 22919 22920 22921 22922 22923 22924 22925 22926 22927 22928 22929 22930 22931 22932 22933 22934 22935 22936 22937 22938 22939 22940 22941 22942 22943 22944 22945 22946 22947 22948 22949 22950 22951 22952 22953 22954 22955 22956 22957 22958 22959 22960 22961 22962 22963 22964 22965 22966 22967 22968 22969 22970 22971 22972 22973 22974 22975 22976 22977 22978 22979 22980 22981 22982 22983 22984 22985 22986 22987 22988 22989 22990 22991 22992 22993 22994 22995 22996 22997 22998 22999 23000 23001 23002 23003 23004 23005 23006 23007 23008 23009 23010 23011 23012 23013 23014 23015 23016 23017 23018 23019 23020 23021 23022 23023 23024 23025 23026 23027 23028 23029 23030 23031 23032 23033 23034 23035 23036 23037 23038 23039 23040 23041 23042 23043 23044 23045 23046 23047 23048 23049 23050 23051 23052 23053 23054 23055 23056 23057 23058 23059 23060 23061 23062 23063 23064 23065 23066 23067 23068 23069 23070 23071 23072 23073 23074 23075 23076 23077 23078 23079 23080 23081 23082 23083 23084 23085 23086 23087 23088 23089 23090 23091 23092 23093 23094 23095 23096 23097 23098 23099 23100 23101 23102 23103 23104 23105 23106 23107 23108 23109 23110 23111 23112 23113 23114 23115 23116 23117 23118 23119 23120 23121 23122 23123 23124 23125 23126 23127 23128 23129 23130 23131 23132 23133 23134 23135 23136 23137 23138 23139 23140 23141 23142 23143 23144 23145 23146 23147 23148 23149 23150 23151 23152 23153 23154 23155 23156 23157 23158 23159 23160 23161 23162 23163 23164 23165 23166 23167 23168 23169 23170 23171 23172 23173 23174 23175 23176 23177 23178 23179 23180 23181 23182 23183 23184 23185 23186 23187 23188 23189 23190 23191 23192 23193 23194 23195 23196 23197 23198 23199 23200 23201 23202 23203 23204 23205 23206 23207 23208 23209 23210 23211 23212 23213 23214 23215 23216 23217 23218 23219 23220 23221 23222 23223 23224 23225 23226 23227 23228 23229 23230 23231 23232 23233 23234 23235 23236 23237 23238 23239 23240 23241 23242 23243 23244 23245 23246 23247 23248 23249 23250 23251 23252 23253 23254 23255 23256 23257 23258 23259 23260 23261 23262 23263 23264 23265 23266 23267 23268 23269 23270 23271 23272 23273 23274 23275 23276 23277 23278 23279 23280 23281 23282 23283 23284 23285 23286 23287 23288 23289 23290 23291 23292 23293 23294 23295 23296 23297 23298 23299 23300 23301 23302 23303 23304 23305 23306 23307 23308 23309 23310 23311 23312 23313 23314 23315 23316 23317 23318 23319 23320 23321 23322 23323 23324 23325 23326 23327 23328 23329 23330 23331 23332 23333 23334 23335 23336 23337 23338 23339 23340 23341 23342 23343 23344 23345 23346 23347 23348 23349 23350 23351 23352 23353 23354 23355 23356 23357 23358 23359 23360 23361 23362 23363 23364 23365 23366 23367 23368 23369 23370 23371 23372 23373 23374 23375 23376 23377 23378 23379 23380 23381 23382 23383 23384 23385 23386 23387 23388 23389 23390 23391 23392 23393 23394 23395 23396 23397 23398 23399 23400 23401 23402 23403 23404 23405 23406 23407 23408 23409 23410 23411 23412 23413 23414 23415 23416 23417 23418 23419 23420 23421 23422 23423 23424 23425 23426 23427 23428 23429 23430 23431 23432 23433 23434 23435 23436 23437 23438 23439 23440 23441 23442 23443 23444 23445 23446 23447 23448 23449 23450 23451 23452 23453 23454 23455 23456 23457 23458 23459 23460 23461 23462 23463 23464 23465 23466 23467 23468 23469 23470 23471 23472 23473 23474 23475 23476 23477 23478 23479 23480 23481 23482 23483 23484 23485 23486 23487 23488 23489 23490 23491 23492 23493 23494 23495 23496 23497 23498 23499 23500 23501 23502 23503 23504 23505 23506 23507 23508 23509 23510 23511 23512 23513 23514 23515 23516 23517 23518 23519 23520 23521 23522 23523 23524 23525 23526 23527 23528 23529 23530 23531 23532 23533 23534 23535 23536 23537 23538 23539 23540 23541 23542 23543 23544 23545 23546 23547 23548 23549 23550 23551 23552 23553 23554 23555 23556 23557 23558 23559 23560 23561 23562 23563 23564 23565 23566 23567 23568 23569 23570 23571 23572 23573 23574 23575 23576 23577 23578 23579 23580 23581 23582 23583 23584 23585 23586 23587 23588 23589 23590 23591 23592 23593 23594 23595 23596 23597 23598 23599 23600 23601 23602 23603 23604 23605 23606 23607 23608 23609 23610 23611 23612 23613 23614 23615 23616 23617 23618 23619 23620 23621 23622 23623 23624 23625 23626 23627 23628 23629 23630 23631 23632 23633 23634 23635 23636 23637 23638 23639 23640 23641 23642 23643 23644 23645 23646 23647 23648 23649 23650 23651 23652 23653 23654 23655 23656 23657 23658 23659 23660 23661 23662 23663 23664 23665 23666 23667 23668 23669 23670 23671 23672 23673 23674 23675 23676 23677 23678 23679 23680 23681 23682 23683 23684 23685 23686 23687 23688 23689 23690 23691 23692 23693 23694 23695 23696 23697 23698 23699 23700 23701 23702 23703 23704 23705 23706 23707 23708 23709 23710 23711 23712 23713 23714 23715 23716 23717 23718 23719 23720 23721 23722 23723 23724 23725 23726 23727 23728 23729 23730 23731 23732 23733 23734 23735 23736 23737 23738 23739 23740 23741 23742 23743 23744 23745 23746 23747 23748 23749 23750 23751 23752 23753 23754 23755 23756 23757 23758 23759 23760 23761 23762 23763 23764 23765 23766 23767 23768 23769 23770 23771 23772 23773 23774 23775 23776 23777 23778 23779 23780 23781 23782 23783 23784 23785 23786 23787 23788 23789 23790 23791 23792 23793 23794 23795 23796 23797 23798 23799 23800 23801 23802 23803 23804 23805 23806 23807 23808 23809 23810 23811 23812 23813 23814 23815 23816 23817 23818 23819 23820 23821 23822 23823 23824 23825 23826 23827 23828 23829 23830 23831 23832 23833 23834 23835 23836 23837 23838 23839 23840 23841 23842 23843 23844 23845 23846 23847 23848 23849 23850 23851 23852 23853 23854 23855 23856 23857 23858 23859 23860 23861 23862 23863 23864 23865 23866 23867 23868 23869 23870 23871 23872 23873 23874 23875 23876 23877 23878 23879 23880 23881 23882 23883 23884 23885 23886 23887 23888 23889 23890 23891 23892 23893 23894 23895 23896 23897 23898 23899 23900 23901 23902 23903 23904 23905 23906 23907 23908 23909 23910 23911 23912 23913 23914 23915 23916 23917 23918 23919 23920 23921 23922 23923 23924 23925 23926 23927 23928 23929 23930 23931 23932 23933 23934 23935 23936 23937 23938 23939 23940 23941 23942 23943 23944 23945 23946 23947 23948 23949 23950 23951 23952 23953 23954 23955 23956 23957 23958 23959 23960 23961 23962 23963 23964 23965 23966 23967 23968 23969 23970 23971 23972 23973 23974 23975 23976 23977 23978 23979 23980 23981 23982 23983 23984 23985 23986 23987 23988 23989 23990 23991 23992 23993 23994 23995 23996 23997 23998 23999 24000 24001 24002 24003 24004 24005 24006 24007 24008 24009 24010 24011 24012 24013 24014 24015 24016 24017 24018 24019 24020 24021 24022 24023 24024 24025 24026 24027 24028 24029 24030 24031 24032 24033 24034 24035 24036 24037 24038 24039 24040 24041 24042 24043 24044 24045 24046 24047 24048 24049 24050 24051 24052 24053 24054 24055 24056 24057 24058 24059 24060 24061 24062 24063 24064 24065 24066 24067 24068 24069 24070 24071 24072 24073 24074 24075 24076 24077 24078 24079 24080 24081 24082 24083 24084 24085 24086 24087 24088 24089 24090 24091 24092 24093 24094 24095 24096 24097 24098 24099 24100 24101 24102 24103 24104 24105 24106 24107 24108 24109 24110 24111 24112 24113 24114 24115 24116 24117 24118 24119 24120 24121 24122 24123 24124 24125 24126 24127 24128 24129 24130 24131 24132 24133 24134 24135 24136 24137 24138 24139 24140 24141 24142 24143 24144 24145 24146 24147 24148 24149 24150 24151 24152 24153 24154 24155 24156 24157 24158 24159 24160 24161 24162 24163 24164 24165 24166 24167 24168 24169 24170 24171 24172 24173 24174 24175 24176 24177 24178 24179 24180 24181 24182 24183 24184 24185 24186 24187 24188 24189 24190 24191 24192 24193 24194 24195 24196 24197 24198 24199 24200 24201 24202 24203 24204 24205 24206 24207 24208 24209 24210 24211 24212 24213 24214 24215 24216 24217 24218 24219 24220 24221 24222 24223 24224 24225 24226 24227 24228 24229 24230 24231 24232 24233 24234 24235 24236 24237 24238 24239 24240 24241 24242 24243 24244 24245 24246 24247 24248 24249 24250 24251 24252 24253 24254 24255 24256 24257 24258 24259 24260 24261 24262 24263 24264 24265 24266 24267 24268 24269 24270 24271 24272 24273 24274 24275 24276 24277 24278 24279 24280 24281 24282 24283 24284 24285 24286 24287 24288 24289 24290 24291 24292 24293 24294 24295 24296 24297 24298 24299 24300 24301 24302 24303 24304 24305 24306 24307 24308 24309 24310 24311 24312 24313 24314 24315 24316 24317 24318 24319 24320 24321 24322 24323 24324 24325 24326 24327 24328 24329 24330 24331 24332 24333 24334 24335 24336 24337 24338 24339 24340 24341 24342 24343 24344 24345 24346 24347 24348 24349 24350 24351 24352 24353 24354 24355 24356 24357 24358 24359 24360 24361 24362 24363 24364 24365 24366 24367 24368 24369 24370 24371 24372 24373 24374 24375 24376 24377 24378 24379 24380 24381 24382 24383 24384 24385 24386 24387 24388 24389 24390 24391 24392 24393 24394 24395 24396 24397 24398 24399 24400 24401 24402 24403 24404 24405 24406 24407 24408 24409 24410 24411 24412 24413 24414 24415 24416 24417 24418 24419 24420 24421 24422 24423 24424 24425 24426 24427 24428 24429 24430 24431 24432 24433 24434 24435 24436 24437 24438 24439 24440 24441 24442 24443 24444 24445 24446 24447 24448 24449 24450 24451 24452 24453 24454 24455 24456 24457 24458 24459 24460 24461 24462 24463 24464 24465 24466 24467 24468 24469 24470 24471 24472 24473 24474 24475 24476 24477 24478 24479 24480 24481 24482 24483 24484 24485 24486 24487 24488 24489 24490 24491 24492 24493 24494 24495 24496 24497 24498 24499 24500 24501 24502 24503 24504 24505 24506 24507 24508 24509 24510 24511 24512 24513 24514 24515 24516 24517 24518 24519 24520 24521 24522 24523 24524 24525 24526 24527 24528 24529 24530 24531 24532 24533 24534 24535 24536 24537 24538 24539 24540 24541 24542 24543 24544 24545 24546 24547 24548 24549 24550 24551 24552 24553 24554 24555 24556 24557 24558 24559 24560 24561 24562 24563 24564 24565 24566 24567 24568 24569 24570 24571 24572 24573 24574 24575 24576 24577 24578 24579 24580 24581 24582 24583 24584 24585 24586 24587 24588 24589 24590 24591 24592 24593 24594 24595 24596 24597 24598 24599 24600 24601 24602 24603 24604 24605 24606 24607 24608 24609 24610 24611 24612 24613 24614 24615 24616 24617 24618 24619 24620 24621 24622 24623 24624 24625 24626 24627 24628 24629 24630 24631 24632 24633 24634 24635 24636 24637 24638 24639 24640 24641 24642 24643 24644 24645 24646 24647 24648 24649 24650 24651 24652 24653 24654 24655 24656 24657 24658 24659 24660 24661 24662 24663 24664 24665 24666 24667 24668 24669 24670 24671 24672 24673 24674 24675 24676 24677 24678 24679 24680 24681 24682 24683 24684 24685 24686 24687 24688 24689 24690 24691 24692 24693 24694 24695 24696 24697 24698 24699 24700 24701 24702 24703 24704 24705 24706 24707 24708 24709 24710 24711 24712 24713 24714 24715 24716 24717 24718 24719 24720 24721 24722 24723 24724 24725 24726 24727 24728 24729 24730 24731 24732 24733 24734 24735 24736 24737 24738 24739 24740 24741 24742 24743 24744 24745 24746 24747 24748 24749 24750 24751 24752 24753 24754 24755 24756 24757 24758 24759 24760 24761 24762 24763 24764 24765 24766 24767 24768 24769 24770 24771 24772 24773 24774 24775 24776 24777 24778 24779 24780 24781 24782 24783 24784 24785 24786 24787 24788 24789 24790 24791 24792 24793 24794 24795 24796 24797 24798 24799 24800 24801 24802 24803 24804 24805 24806 24807 24808 24809 24810 24811 24812 24813 24814 24815 24816 24817 24818 24819 24820 24821 24822 24823 24824 24825 24826 24827 24828 24829 24830 24831 24832 24833 24834 24835 24836 24837 24838 24839 24840 24841 24842 24843 24844 24845 24846 24847 24848 24849 24850 24851 24852 24853 24854 24855 24856 24857 24858 24859 24860 24861 24862 24863 24864 24865 24866 24867 24868 24869 24870 24871 24872 24873 24874 24875 24876 24877 24878 24879 24880 24881 24882 24883 24884 24885 24886 24887 24888 24889 24890 24891 24892 24893 24894 24895 24896 24897 24898 24899 24900 24901 24902 24903 24904 24905 24906 24907 24908 24909 24910 24911 24912 24913 24914 24915 24916 24917 24918 24919 24920 24921 24922 24923 24924 24925 24926 24927 24928 24929 24930 24931 24932 24933 24934 24935 24936 24937 24938 24939 24940 24941 24942 24943 24944 24945 24946 24947 24948 24949 24950 24951 24952 24953 24954 24955 24956 24957 24958 24959 24960 24961 24962 24963 24964 24965 24966 24967 24968 24969 24970 24971 24972 24973 24974 24975 24976 24977 24978 24979 24980 24981 24982 24983 24984 24985 24986 24987 24988 24989 24990 24991 24992 24993 24994 24995 24996 24997 24998 24999 25000 25001 25002 25003 25004 25005 25006 25007 25008 25009 25010 25011 25012 25013 25014 25015 25016 25017 25018 25019 25020 25021 25022 25023 25024 25025 25026 25027 25028 25029 25030 25031 25032 25033 25034 25035 25036 25037 25038 25039 25040 25041 25042 25043 25044 25045 25046 25047 25048 25049 25050 25051 25052 25053 25054 25055 25056 25057 25058 25059 25060 25061 25062 25063 25064 25065 25066 25067 25068 25069 25070 25071 25072 25073 25074 25075 25076 25077 25078 25079 25080 25081 25082 25083 25084 25085 25086 25087 25088 25089 25090 25091 25092 25093 25094 25095 25096 25097 25098 25099 25100 25101 25102 25103 25104 25105 25106 25107 25108 25109 25110 25111 25112 25113 25114 25115 25116 25117 25118 25119 25120 25121 25122 25123 25124 25125 25126 25127 25128 25129 25130 25131 25132 25133 25134 25135 25136 25137 25138 25139 25140 25141 25142 25143 25144 25145 25146 25147 25148 25149 25150 25151 25152 25153 25154 25155 25156 25157 25158 25159 25160 25161 25162 25163 25164 25165 25166 25167 25168 25169 25170 25171 25172 25173 25174 25175 25176 25177 25178 25179 25180 25181 25182 25183 25184 25185 25186 25187 25188 25189 25190 25191 25192 25193 25194 25195 25196 25197 25198 25199 25200 25201 25202 25203 25204 25205 25206 25207 25208 25209 25210 25211 25212 25213 25214 25215 25216 25217 25218 25219 25220 25221 25222 25223 25224 25225 25226 25227 25228 25229 25230 25231 25232 25233 25234 25235 25236 25237 25238 25239 25240 25241 25242 25243 25244 25245 25246 25247 25248 25249 25250 25251 25252 25253 25254 25255 25256 25257 25258 25259 25260 25261 25262 25263 25264 25265 25266 25267 25268 25269 25270 25271 25272 25273 25274 25275 25276 25277 25278 25279 25280 25281 25282 25283 25284 25285 25286 25287 25288 25289 25290 25291 25292 25293 25294 25295 25296 25297 25298 25299 25300 25301 25302 25303 25304 25305 25306 25307 25308 25309 25310 25311 25312 25313 25314 25315 25316 25317 25318 25319 25320 25321 25322 25323 25324 25325 25326 25327 25328 25329 25330 25331 25332 25333 25334 25335 25336 25337 25338 25339 25340 25341 25342 25343 25344 25345 25346 25347 25348 25349 25350 25351 25352 25353 25354 25355 25356 25357 25358 25359 25360 25361 25362 25363 25364 25365 25366 25367 25368 25369 25370 25371 25372 25373 25374 25375 25376 25377 25378 25379 25380 25381 25382 25383 25384 25385 25386 25387 25388 25389 25390 25391 25392 25393 25394 25395 25396 25397 25398 25399 25400 25401 25402 25403 25404 25405 25406 25407 25408 25409 25410 25411 25412 25413 25414 25415 25416 25417 25418 25419 25420 25421 25422 25423 25424 25425 25426 25427 25428 25429 25430 25431 25432 25433 25434 25435 25436 25437 25438 25439 25440 25441 25442 25443 25444 25445 25446 25447 25448 25449 25450 25451 25452 25453 25454 25455 25456 25457 25458 25459 25460 25461 25462 25463 25464 25465 25466 25467 25468 25469 25470 25471 25472 25473 25474 25475 25476 25477 25478 25479 25480 25481 25482 25483 25484 25485 25486 25487 25488 25489 25490 25491 25492 25493 25494 25495 25496 25497 25498 25499 25500 25501 25502 25503 25504 25505 25506 25507 25508 25509 25510 25511 25512 25513 25514 25515 25516 25517 25518 25519 25520 25521 25522 25523 25524 25525 25526 25527 25528 25529 25530 25531 25532 25533 25534 25535 25536 25537 25538 25539 25540 25541 25542 25543 25544 25545 25546 25547 25548 25549 25550 25551 25552 25553 25554 25555 25556 25557 25558 25559 25560 25561 25562 25563 25564 25565 25566 25567 25568 25569 25570 25571 25572 25573 25574 25575 25576 25577 25578 25579 25580 25581 25582 25583 25584 25585 25586 25587 25588 25589 25590 25591 25592 25593 25594 25595 25596 25597 25598 25599 25600 25601 25602 25603 25604 25605 25606 25607 25608 25609 25610 25611 25612 25613 25614 25615 25616 25617 25618 25619 25620 25621 25622 25623 25624 25625 25626 25627 25628 25629 25630 25631 25632 25633 25634 25635 25636 25637 25638 25639 25640 25641 25642 25643 25644 25645 25646 25647 25648 25649 25650 25651 25652 25653 25654 25655 25656 25657 25658 25659 25660 25661 25662 25663 25664 25665 25666 25667 25668 25669 25670 25671 25672 25673 25674 25675 25676 25677 25678 25679 25680 25681 25682 25683 25684 25685 25686 25687 25688 25689 25690 25691 25692 25693 25694 25695 25696 25697 25698 25699 25700 25701 25702 25703 25704 25705 25706 25707 25708 25709 25710 25711 25712 25713 25714 25715 25716 25717 25718 25719 25720 25721 25722 25723 25724 25725 25726 25727 25728 25729 25730 25731 25732 25733 25734 25735 25736 25737 25738 25739 25740 25741 25742 25743 25744 25745 25746 25747 25748 25749 25750 25751 25752 25753 25754 25755 25756 25757 25758 25759 25760 25761 25762 25763 25764 25765 25766 25767 25768 25769 25770 25771 25772 25773 25774 25775 25776 25777 25778 25779 25780 25781 25782 25783 25784 25785 25786 25787 25788 25789 25790 25791 25792 25793 25794 25795 25796 25797 25798 25799 25800 25801 25802 25803 25804 25805 25806 25807 25808 25809 25810 25811 25812 25813 25814 25815 25816 25817 25818 25819 25820 25821 25822 25823 25824 25825 25826 25827 25828 25829 25830 25831 25832 25833 25834 25835 25836 25837 25838 25839 25840 25841 25842 25843 25844 25845 25846 25847 25848 25849 25850 25851 25852 25853 25854 25855 25856 25857 25858 25859 25860 25861 25862 25863 25864 25865 25866 25867 25868 25869 25870 25871 25872 25873 25874 25875 25876 25877 25878 25879 25880 25881 25882 25883 25884 25885 25886 25887 25888 25889 25890 25891 25892 25893 25894 25895 25896 25897 25898 25899 25900 25901 25902 25903 25904 25905 25906 25907 25908 25909 25910 25911 25912 25913 25914 25915 25916 25917 25918 25919 25920 25921 25922 25923 25924 25925 25926 25927 25928 25929 25930 25931 25932 25933 25934 25935 25936 25937 25938 25939 25940 25941 25942 25943 25944 25945 25946 25947 25948 25949 25950 25951 25952 25953 25954 25955 25956 25957 25958 25959 25960 25961 25962 25963 25964 25965 25966 25967 25968 25969 25970 25971 25972 25973 25974 25975 25976 25977 25978 25979 25980 25981 25982 25983 25984 25985 25986 25987 25988 25989 25990 25991 25992 25993 25994 25995 25996 25997 25998 25999 26000 26001 26002 26003 26004 26005 26006 26007 26008 26009 26010 26011 26012 26013 26014 26015 26016 26017 26018 26019 26020 26021 26022 26023 26024 26025 26026 26027 26028 26029 26030 26031 26032 26033 26034 26035 26036 26037 26038 26039 26040 26041 26042 26043 26044 26045 26046 26047 26048 26049 26050 26051 26052 26053 26054 26055 26056 26057 26058 26059 26060 26061 26062 26063 26064 26065 26066 26067 26068 26069 26070 26071 26072 26073 26074 26075 26076 26077 26078 26079 26080 26081 26082 26083 26084 26085 26086 26087 26088 26089 26090 26091 26092 26093 26094 26095 26096 26097 26098 26099 26100 26101 26102 26103 26104 26105 26106 26107 26108 26109 26110 26111 26112 26113 26114 26115 26116 26117 26118 26119 26120 26121 26122 26123 26124 26125 26126 26127 26128 26129 26130 26131 26132 26133 26134 26135 26136 26137 26138 26139 26140 26141 26142 26143 26144 26145 26146 26147 26148 26149 26150 26151 26152 26153 26154 26155 26156 26157 26158 26159 26160 26161 26162 26163 26164 26165 26166 26167 26168 26169 26170 26171 26172 26173 26174 26175 26176 26177 26178 26179 26180 26181 26182 26183 26184 26185 26186 26187 26188 26189 26190 26191 26192 26193 26194 26195 26196 26197 26198 26199 26200 26201 26202 26203 26204 26205 26206 26207 26208 26209 26210 26211 26212 26213 26214 26215 26216 26217 26218 26219 26220 26221 26222 26223 26224 26225 26226 26227 26228 26229 26230 26231 26232 26233 26234 26235 26236 26237 26238 26239 26240 26241 26242 26243 26244 26245 26246 26247 26248 26249 26250 26251 26252 26253 26254 26255 26256 26257 26258 26259 26260 26261 26262 26263 26264 26265 26266 26267 26268 26269 26270 26271 26272 26273 26274 26275 26276 26277 26278 26279 26280 26281 26282 26283 26284 26285 26286 26287 26288 26289 26290 26291 26292 26293 26294 26295 26296 26297 26298 26299 26300 26301 26302 26303 26304 26305 26306 26307 26308 26309 26310 26311 26312 26313 26314 26315 26316 26317 26318 26319 26320 26321 26322 26323 26324 26325 26326 26327 26328 26329 26330 26331 26332 26333 26334 26335 26336 26337 26338 26339 26340 26341 26342 26343 26344 26345 26346 26347 26348 26349 26350 26351 26352 26353 26354 26355 26356 26357 26358 26359 26360 26361 26362 26363 26364 26365 26366 26367 26368 26369 26370 26371 26372 26373 26374 26375 26376 26377 26378 26379 26380 26381 26382 26383 26384 26385 26386 26387 26388 26389 26390 26391 26392 26393 26394 26395 26396 26397 26398 26399 26400 26401 26402 26403 26404 26405 26406 26407 26408 26409 26410 26411 26412 26413 26414 26415 26416 26417 26418 26419 26420 26421 26422 26423 26424 26425 26426 26427 26428 26429 26430 26431 26432 26433 26434 26435 26436 26437 26438 26439 26440 26441 26442 26443 26444 26445 26446 26447 26448 26449 26450 26451 26452 26453 26454 26455 26456 26457 26458 26459 26460 26461 26462 26463 26464 26465 26466 26467 26468 26469 26470 26471 26472 26473 26474 26475 26476 26477 26478 26479 26480 26481 26482 26483 26484 26485 26486 26487 26488 26489 26490 26491 26492 26493 26494 26495 26496 26497 26498 26499 26500 26501 26502 26503 26504 26505 26506 26507 26508 26509 26510 26511 26512 26513 26514 26515 26516 26517 26518 26519 26520 26521 26522 26523 26524 26525 26526 26527 26528 26529 26530 26531 26532 26533 26534 26535 26536 26537 26538 26539 26540 26541 26542 26543 26544 26545 26546 26547 26548 26549 26550 26551 26552 26553 26554 26555 26556 26557 26558 26559 26560 26561 26562 26563 26564 26565 26566 26567 26568 26569 26570 26571 26572 26573 26574 26575 26576 26577 26578 26579 26580 26581 26582 26583 26584 26585 26586 26587 26588 26589 26590 26591 26592 26593 26594 26595 26596 26597 26598 26599 26600 26601 26602 26603 26604 26605 26606 26607 26608 26609 26610 26611 26612 26613 26614 26615 26616 26617 26618 26619 26620 26621 26622 26623 26624 26625 26626 26627 26628 26629 26630 26631 26632 26633 26634 26635 26636 26637 26638 26639 26640 26641 26642 26643 26644 26645 26646 26647 26648 26649 26650 26651 26652 26653 26654 26655 26656 26657 26658 26659 26660 26661 26662 26663 26664 26665 26666 26667 26668 26669 26670 26671 26672 26673 26674 26675 26676 26677 26678 26679 26680 26681 26682 26683 26684 26685 26686 26687 26688 26689 26690 26691 26692 26693 26694 26695 26696 26697 26698 26699 26700 26701 26702 26703 26704 26705 26706 26707 26708 26709 26710 26711 26712 26713 26714 26715 26716 26717 26718 26719 26720 26721 26722 26723 26724 26725 26726 26727 26728 26729 26730 26731 26732 26733 26734 26735 26736 26737 26738 26739 26740 26741 26742 26743 26744 26745 26746 26747 26748 26749 26750 26751 26752 26753 26754 26755 26756 26757 26758 26759 26760 26761 26762 26763 26764 26765 26766 26767 26768 26769 26770 26771 26772 26773 26774 26775 26776 26777 26778 26779 26780 26781 26782 26783 26784 26785 26786 26787 26788 26789 26790 26791 26792 26793 26794 26795 26796 26797 26798 26799 26800 26801 26802 26803 26804 26805 26806 26807 26808 26809 26810 26811 26812 26813 26814 26815 26816 26817 26818 26819 26820 26821 26822 26823 26824 26825 26826 26827 26828 26829 26830 26831 26832 26833 26834 26835 26836 26837 26838 26839 26840 26841 26842 26843 26844 26845 26846 26847 26848 26849 26850 26851 26852 26853 26854 26855 26856 26857 26858 26859 26860 26861 26862 26863 26864 26865 26866 26867 26868 26869 26870 26871 26872 26873 26874 26875 26876 26877 26878 26879 26880 26881 26882 26883 26884 26885 26886 26887 26888 26889 26890 26891 26892 26893 26894 26895 26896 26897 26898 26899 26900 26901 26902 26903 26904 26905 26906 26907 26908 26909 26910 26911 26912 26913 26914 26915 26916 26917 26918 26919 26920 26921 26922 26923 26924 26925 26926 26927 26928 26929 26930 26931 26932 26933 26934 26935 26936 26937 26938 26939 26940 26941 26942 26943 26944 26945 26946 26947 26948 26949 26950 26951 26952 26953 26954 26955 26956 26957 26958 26959 26960 26961 26962 26963 26964 26965 26966 26967 26968 26969 26970 26971 26972 26973 26974 26975 26976 26977 26978 26979 26980 26981 26982 26983 26984 26985 26986 26987 26988 26989 26990 26991 26992 26993 26994 26995 26996 26997 26998 26999 27000 27001 27002 27003 27004 27005 27006 27007 27008 27009 27010 27011 27012 27013 27014 27015 27016 27017 27018 27019 27020 27021 27022 27023 27024 27025 27026 27027 27028 27029 27030 27031 27032 27033 27034 27035 27036 27037 27038 27039 27040 27041 27042 27043 27044 27045 27046 27047 27048 27049 27050 27051 27052 27053 27054 27055 27056 27057 27058 27059 27060 27061 27062 27063 27064 27065 27066 27067 27068 27069 27070 27071 27072 27073 27074 27075 27076 27077 27078 27079 27080 27081 27082 27083 27084 27085 27086 27087 27088 27089 27090 27091 27092 27093 27094 27095 27096 27097 27098 27099 27100 27101 27102 27103 27104 27105 27106 27107 27108 27109 27110 27111 27112 27113 27114 27115 27116 27117 27118 27119 27120 27121 27122 27123 27124 27125 27126 27127 27128 27129 27130 27131 27132 27133 27134 27135 27136 27137 27138 27139 27140 27141 27142 27143 27144 27145 27146 27147 27148 27149 27150 27151 27152 27153 27154 27155 27156 27157 27158 27159 27160 27161 27162 27163 27164 27165 27166 27167 27168 27169 27170 27171 27172 27173 27174 27175 27176 27177 27178 27179 27180 27181 27182 27183 27184 27185 27186 27187 27188 27189 27190 27191 27192 27193 27194 27195 27196 27197 27198 27199 27200 27201 27202 27203 27204 27205 27206 27207 27208 27209 27210 27211 27212 27213 27214 27215 27216 27217 27218 27219 27220 27221 27222 27223 27224 27225 27226 27227 27228 27229 27230 27231 27232 27233 27234 27235 27236 27237 27238 27239 27240 27241 27242 27243 27244 27245 27246 27247 27248 27249 27250 27251 27252 27253 27254 27255 27256 27257 27258 27259 27260 27261 27262 27263 27264 27265 27266 27267 27268 27269 27270 27271 27272 27273 27274 27275 27276 27277 27278 27279 27280 27281 27282 27283 27284 27285 27286 27287 27288 27289 27290 27291 27292 27293 27294 27295 27296 27297 27298 27299 27300 27301 27302 27303 27304 27305 27306 27307 27308 27309 27310 27311 27312 27313 27314 27315 27316 27317 27318 27319 27320 27321 27322 27323 27324 27325 27326 27327 27328 27329 27330 27331 27332 27333 27334 27335 27336 27337 27338 27339 27340 27341 27342 27343 27344 27345 27346 27347 27348 27349 27350 27351 27352 27353 27354 27355 27356 27357 27358 27359 27360 27361 27362 27363 27364 27365 27366 27367 27368 27369 27370 27371 27372 27373 27374 27375 27376 27377 27378 27379 27380 27381 27382 27383 27384 27385 27386 27387 27388 27389 27390 27391 27392 27393 27394 27395 27396 27397 27398 27399 27400 27401 27402 27403 27404 27405 27406 27407 27408 27409 27410 27411 27412 27413 27414 27415 27416 27417 27418 27419 27420 27421 27422 27423 27424 27425 27426 27427 27428 27429 27430 27431 27432 27433 27434 27435 27436 27437 27438 27439 27440 27441 27442 27443 27444 27445 27446 27447 27448 27449 27450 27451 27452 27453 27454 27455 27456 27457 27458 27459 27460
|
#!/usr/bin/perl
# the line above could be the first line for a typical UNIX systems
# you can find perl on your system by using "which perl" in the shell
# to build an exectuable for windows use this PAR call:
# pp -M Tk::DragDrop::Win32Site -o mapivi.exe mapivi
# to build an exectuable for Linux use this PAR call:
# pp -M Tk::DragDrop::XDNDSite -M Tk::DragDrop::SunSite -M PerlIO -o mapivi.exe mapivi
# include perl packages
use strict;
use Encode::Unicode; # needed according to the PAR FAQ (for perl apps on Microsoft Windows)
use warnings;
#use diagnostics;
# pod (to view the formated document try "perldoc mapivi" in the shell
=head1 NAME
MaPiVi - Picture Viewer and Organizer
MaPiVi means Martin's Picture Viewer
=head1 DESCRIPTION
JPEG picture viewer / image management system with meta info support
written in Perl/Tk for UNIX, Mac OS X and Windows.
I wrote mapivi just for me, because I needed a image viewer which is
also able to display and edit meta infos of JPEG pictures, like EXIF,
JPEG comments and IPTC/IIM infos.
As hobby photographer I am mostly interested in the EXIF infos (like timestamp,
camera model, focal length, exposure time, aperture, etc.) and the
possibility to add and edit IPTC infos and JPEG comments.
But I also want to rename pictures according to their internal date/time
and to do lossless rotation, lossless cropping and other stuff.
mapivi can be found here:
http://mapivi.de.vu (link to the mapivi site)
or if this won't work:
http://herrmanns-stern.de (real site)
http://sourceforge.net/projects/mapivi (download)
I would be happy to receive some feedback (e.g. on which os mapivi
works), bugfixes, patches or suggestions about mapivi.
Copyright (c) 2002, 2003, 2004, 2005, 2006 Martin Herrmann
All rights reserved.
Feel free to redistribute. Enjoy!
=head1 USAGE
mapivi [file|directory]
to display a certain picture use:
mapivi picture.jpg
mapivi will generate and display all pictures in the directory
as thumbnails. The given picture will be displayed in
original size or zoomed to fit the window (picture frame).
to view a directory containing pictures use:
mapivi ~/pics/
mapivi will generate and display all pictures in the given directory
as thumbnails.
=head1 KEYS
mapivi is controlled by the following keys:
see also menu Help->Keys (the list is generated from the source
code and is always actual.)
=over 4
=item Space, Page-Down
Show the next picture in directory
=item BackSpace, Page-Up
Show the previous picture in directory
=item Escape
Iconify MaPiVi (Boss-Key :)
=item Cursor-up, -down, -left, -right
Scroll the picture, if it's bigger than the Canvas
=item Shift-Cursor-up, -down, -left, -right
Move to the border of the picture, if it's bigger than the Canvas
=item q
Quit MaPiVi
For all other key bindings, see the menu Help->Keys
=back
=head1 MOUSE
Try the right mouse button in the thumbnail picture list for a popup menu to copy, move, rename, rotate or delete pictures, to open a new directory, to add or remove comments or to exit MaPiVi.
Use the buttons to add, edit or remove JPG comments, or to display all EXIF infos.
If you hold the mouse over the buttons or labels a help message will pop up (or at least at most of them :).
=cut
my $EvilOS = 0; # boolean, if we run on Windows this is 1
my $MacOSX = 0; # boolean, if we run on Mac OS X this is 1
if ($^O =~ m/win/i) {
$EvilOS = 1;
}
if ($^O =~ m/darwin/i) { # Mac OS X is not evil, but unfortunately contains the string "win"!
$MacOSX = 1;
$EvilOS = 0;
}
my $home = glob("~");
use Env;
if ($EvilOS) {
$home = $ENV{HOME} if defined $ENV{HOME};
$home = $ENV{HOMEDRIVE}.$ENV{HOMEPATH} if (!-d $home and (defined $ENV{HOMEDRIVE} and defined $ENV{HOMEPATH}));
$home = "C:/" if (!-d $home);
die "mapivi can not find a home dir" if (!-d $home);
}
my $maprogsdir = "$home/.maprogs"; # the main config dir for my programms
if (($EvilOS) and (defined $ENV{APPDATA}) and ($maprogsdir ne $ENV{APPDATA}."/maprogs")) {
# migration from the old config dir to the new only for windows
if (-d "$maprogsdir/mapivi") {
my $olddir = "$maprogsdir/mapivi";
my $newdir = $ENV{APPDATA}."/maprogs/mapivi";
warn "\nMapivi 0.3.6: Error!\n\nYou still have the old Mapivi config directory:\n$olddir,\n\n1) please create a new directory for the configuration here:\n $newdir,\n2) copy all directories and files from the old directory to the new one\n3) delete the old directory and then\n4) restart Mapivi.\n\nKindly excuse this inconvenience! (will exit in 30 seconds)\n";
sleep 30;
exit;
}
}
# for windows we use this path
$maprogsdir = $ENV{APPDATA}."/maprogs" if defined $ENV{APPDATA};
my $configdir = "$maprogsdir/mapivi"; # the configuration dir
my $splashAvail = (eval "require Tk::Splash") ? 1 : 0 ;
my $splash;
my $logo = "$configdir/logo.jpg";
if ($splashAvail and -f $logo) {
# Splash->Show parameters: $image, $width, $height, $title, $overrideredirect
$splash = Tk::Splash->Show($logo, 844, 259, "", 1);
}
use File::Basename;
use POSIX qw(ceil);
use Cwd qw(cwd abs_path);
my $verbose = 0; # boolean (1 = print debug infos, 0 = be quiet)
# get version from RCS version
my @RCSVersion = split / /, '$Revision: 9.1 $';
my $version = "0.".$RCSVersion[1];
my $mapiviInfo = "<a href=\"http://mapivi.de.vu\" title=\"gallery produced by mapivi $version\">mapivi</a>";
showCopyright();
#use Encode qw(is_utf8 encode decode);
#use encoding "utf8"
use File::Copy;
use File::Find;
use File::Path; # for rmtree, mkpath
use Text::Wrap;
use Tk;
use Tk::JPEG;
use Tk::PNG;
use Tk::HList;
use Tk::ItemStyle;
use Tk::ROText;
use Tk::ProgressBar;
use Tk::IO;
use Tk::ErrorDialog;
use Tk::Balloon;
use Tk::DirTree;
use Tk::Font;
use Tk::Pane;
use Tk::Tiler;
use Tk::NoteBook;
use Tk::FileSelect;
use Image::Info qw(image_info dim);
use Storable qw(store retrieve dclone);
use Tk::Adjuster;
use Tk::DragDrop;
use Tk::DropSite;
# this will be used in future to provide a multilanguage mapivi
# keywords: i18n, gettext
#use Locale::TextDomain ('mapivi', $configdir."/locale");
#use POSIX qw(locale_h);
#setlocale (LC_MESSAGES, '');
use Image::MetaData::JPEG;
# disable warnings from this module
$Image::MetaData::JPEG::show_warnings = 0; # todo: use metadatawarn to switch this
my $metadataVersionNeeded = 0.14;
my $metadataVersion = $Image::MetaData::JPEG::VERSION;
$metadataVersion =~ s/[a-zA-Z]//g;
die "Aborting, because Mapivi needs at least version $metadataVersionNeeded of perl module Image::MetaData::JPEG!\n(installed version: $metadataVersion)\n" if ($metadataVersion < $metadataVersionNeeded);
use Time::Local; # timelocal()
#use Tk::Date; # not in the Tk distro
# This should prevent opening DOS boxes on windows when doing background tasks, but does not work. ToDo
#my $win32Avail = (eval "require Win32") ? 1 : 0;
#SetChildShowWindow() if ($EvilOS and $win32Avail);
#use Data::Dumper;
#use Tk::DirSelect;
#use Tk::ColorEditor;
# optional modules
# seems not to work so I comment it out for a test in the future:
#my $win32FOAvail = (eval "require Win32::FileOp") ? 1 : 0;
my $win32FOAvail = 0;
my $resizeAvail = (eval "require Tk::ResizeButton") ? 1 : 0;
my $filespecAvail = (eval "require File::Spec") ? 1 : 0;
use constant Win32ProcAvail => eval { require Win32::Process; 1 };
use constant MatchEntryAvail => eval { require Tk::MatchEntry; 1 };
#use Time::HiRes qw(gettimeofday tv_interval); # needed just for debugging
#my $hiresstart;
# constants
use constant WITH_PATH => 1;
use constant JUST_FILE => 0;
use constant LONG => 1;
use constant SHORT => 0;
use constant WRAP => 1;
use constant NO_WRAP => 0;
use constant FORMAT => 1;
use constant NO_FORMAT => 0;
use constant NUMERIC => 1;
use constant STRING => 0;
use constant WAIT => 1;
use constant NO_WAIT => 0;
use constant TOUCH => 1;
use constant NO_TOUCH => 0;
use constant OVERWRITE => 1;
use constant ASK_OVERWRITE => 0;
use constant ASK => 1;
use constant NO_ASK => 0;
use constant PREVIEW => 1;
use constant NO_PREVIEW => 0;
use constant SHOW => 1;
use constant NO_SHOW => 0;
use constant COPY => 0;
use constant BACKUP => 1;
use constant TRASH => 0;
use constant REMOVE => 1;
use constant OK => 1;
use constant CANCEL => 0;
use constant ADD => 1;
use constant RESET => 0;
# function prototypes
sub progressWinInit($$);
sub progressWinCheck($);
sub progressWinUpdate($$$$);
sub progressWinEnd($);
sub updateOneRow($$);
sub insertPic($$);
sub checkDateFormat($);
sub checkGeometry($);
sub checkTempFile($);
sub checkWriteable($);
sub getRealFile($);
sub getThumbFileName($);
sub addComment($);
sub addCommentToPic($$$);
sub buildBackupName($);
sub makeBackup($);
sub getIPTCByLine($);
sub doubleList($$$$);
sub overwrite($$);
sub copyPicsDialog($$);
sub getDirDialog($);
sub is_a_JPEG($);
sub setProperty($$$);
# globals
my @dirHist; # directory history - stores the last directories visited
my @cachedPics; # a list of all cached pictures
my @savedselection;
my @savedselection2;
# search database: hash to store all the data of all pictures in the visited directories (comments, EXIF, IPTC)
my %searchDB;
# directory checklist: hash to store properties of directories (key: dir value: hash SORT, META, PRIO, COMM)
my %dirProperties;
# hash to store all loaded photo objects (real size or zoomed) key = path/file name, value = photo object
my %photos;
# hash to store all loaded thumbnail photo objects key = path/file name, value = photo object
my %thumbs;
my %searchthumbs;# hash containing all thumbnails of the search dialog, for memory clean up
my %light_table_thumbs;# hash containing all thumbnails of the light table, for memory clean up
my %thumbDBhash; # store the thumb dirs for one session: dir -> thumbdir
my %dirHotlist; # often visited dirs
# minimum set of the hot dirs
foreach my $dir ("/", $home, cwd()) {
$dirHotlist{$dir} = 1 unless (defined $dirHotlist{$dir});
}
my %quickSortHash;
my %quickSortHashSize;
my %quickSortHashPixel;
my %quickSortHashBitsPixel;
my $quickSortSwitch = 0;
my $actpic = ""; # the path and file name of the actual picture
my $actdir = ""; # the actual directory
my $widthheight = "";
my $loadtime = "";
my $size = "";
my $zoomFactorStr = "";
my $urgencyStr = "-";
my $urgencyScale = 0;
my $nrof = "";
my $exif = "";
my $userinfo = "";
my $otherFiles = "";
my $proccount = 0;
my $nrToConvert = 0;
my $maxCommentLength = 2**16 - 3; # a comment block may have max 64kB
my $trashdir = "$configdir/trash"; # the trashcan
my $plugindir = "$configdir/PlugIns"; # the mapivi plugin dir
my $iptcdir = "$configdir/IPTC_templates"; # the IPTC templates directory
my $configFile = "$configdir/mapivirc"; # the configuration file
my $file_Entry_values = "$configdir/Entry_values";
my $exifdirname = ".exif"; # the subdir to store exif infos
my $thumbdirname = ".thumbs"; # the subdir to store thumbnails
my $xvpicsdirname = ".xvpics"; # a subdir from GIMP we usualy ignore
my $thumbExample = "$configdir/thumbExample.jpg";
my $nonJPEGsuffixes = "gif|png|tif|tiff|bmp|ppm|ps"; # xcf works, but makes problems with layers
my $cameraJunkSuffixes = "ctg"; # uninteresting files created by cameras
my $copyright_year = (localtime(time()))[5] + 1900; # the actual year, for the copyright notice
my $HTMLPicDir = "pics"; # this is the name of the subdir for pics when building html pages
my $HTMLThumbDir = "thumbs"; # this is the name of the subdir for thumbs when building HTML pages
my $cropPreviewSize = 400; # canvas size in x and y direction of the crop preview
my $slideshow = 0; # start/stop flag for slideshow
my $showPicInAction = 0; # bool = 1 while loading picture
my $mapiviURL = "http://mapivi.de.vu";
my %topFullSceenConf;
my $topFullScreen = 0;
my %winapps; # used for sub findApp()
my $defaultthumbP;
my $clocktimer;
my $time;
my $date;
my $clockL;
my $scsw;
my $wizW;
my $impW;
my $interpW;
my $fuzzybw; # fuzzy border dialod window
my $ll_b_w; # lossless border dialod window
my $ow; # options window, see sub options()
my $sw; # the search window, see searchMetaInfo()
my $dpw; # the dir properties window, see showDirProperties()
my $dsw; # the dir size window
my $ltw; # the light table window for slideshows
my @light_table_list; # the light table slideshow pic list
my $ddw; # dirDiffWindow widget
my $catw; # the IPTC categories window, see editIPTCCategories()
my $keyw; # the IPTC keywords window, see editIPTCKeywords()
my $keycw; # the comment keywords window, see editCommentKeywords()
my $dupw; # the duplicate search window, see sub finddups()
my $filterW; # the filter window
my $menubar; # handle for menubar of main window
my $balloon; # balloon handle
my $dirMenu; # context menu for dirs
my $thumbMenu; # context menu for thumbnails
my $picMenu; # context menu for picture
my $copyEXIFDataSource; # global variable of sub copyEXIFData()
my $copyCommentSource; # global variable of sub copyComment()
my $iptcCopy; # global hash ref for copyIPTC()
my ($idx, $idy); # coordinates of actual item when clicked on or moved
my ($width, $height);
my %nonJPEGdirNoAskAgain; # hash to store the dirs with non-JPEG files not to convert (valid for one session)
#my $stopButStop = 0; # stop actual action if 1
my $cleanDirNoAsk = 0; # needed in sub cleanDir()
my $cleanDirLevel = 0; # needed in sub cleanDir()
my $keyXBut; # close button of IPTC keyword window
# some example hierarchical categories
my @precats = sort qw(Nature Nature/Flower Nature/Landscape Nature/Macro Nature/Animal Nature/Animal/Fish Nature/Animal/Cat Nature/Animal/Insect Nature/Animal/Insect/Ant People People/Portrait People/Wedding Architecture Architecture/Tower Architecture/Bridge Architecture/Church Technology Technology/Car Technology/Train Technology/Computer);
# overwrite them, when some stored categories are available
@precats = readArrayFromFile("$configdir/categories") if (-f "$configdir/categories");
uniqueArray(\@precats); # remove double entries
foreach (@precats) { $_ =~ s|^/||; } # cut leading slash
@precats = qw(Nature) unless (@precats); # add a starting point if array is empty
# some example hierarchical keywords
my @prekeys = qw(Family Family/Einstein Family/Einstein/Albert Family/Einstein/Hermann Family/Einstein/Pauline Family/Planck Family/Planck/Max Family/Planck/Johann Family/Planck/Marie Family/Planck/Karl Family/Planck/Grete Family/Planck/Emma Family/Planck/Erwin Family/Planck/Hermann Friend Friend/Bundy Friend/Bundy/Al Friend/Bundy/Bud Friend/Bundy/Kelly Friend/Bundy/Peggy);
# overwrite them, when some stored keywords are available
@prekeys = readArrayFromFile("$configdir/keywords") if (-f "$configdir/keywords");
uniqueArray(\@prekeys); # remove double entries
foreach (@prekeys) { $_ =~ s|^/||; } # cut leading slash
@prekeys = qw(Family) unless (@prekeys); # add a starting point if array is empty
# global hash for new keywords found in displayed pictures
my %new_keywords;
# global hash to store keywords, which should be ignored (e.g. nature.animal.dog)
my %ignore_keywords;
# external programs used by mapivi
my %exprogs = qw/convert 0 composite 0 jhead 0 jpegtran 0 jpegpixi 0 mogrify 0 gimp-remote 0 gimp-win-remote 0 montage 0 xwd 0 identify 0 thunderbird 0 exiftool 0/;
# short comment about the usage of the external programs
my %exprogscom = (
"convert" => "build thumbnails",
"composite" => "combine pictures e.g. thumbnails with a background",
"jhead" => "handle EXIF infos and embedded thumbnail pictures",
"jpegtran" => "do lossless rotation of pictures",
"jpegpixi" => "do nearly lossless interpolation (remove dead pixels)",
"mogrify" => "change the size/quality of pictures",
"montage" => "combine pictures to e.g. index prints",
"gimp-remote" => "edit pictures with The GIMP (only UNIX)",
"gimp-win-remote"=> "edit pictures with The GIMP (only windows)",
"xwd" => "make a screenshot of a window or desktop",
"identify" => "describe the format and characteristics of a picture",
"thunderbird" => "send pictures via email",
"exiftool" => "Read/write meta information in image files",
);
# where to find the external programs (resources)
my %exprogsres = (
"convert" => "Image Magick http://www.imagemagick.org",
"composite" => "Image Magick http://www.imagemagick.org",
"jhead" => "http://www.sentex.net/~mwandel/jhead/",
"jpegtran" => "libjpeg http://www.ijg.org",
"jpegpixi" => "http://www.zero-based.org/software/jpegpixi/",
"mogrify" => "Image Magick http://www.imagemagick.org",
"montage" => "Image Magick http://www.imagemagick.org",
"gimp-remote" => "The GIMP http://www.gimp.org",
"gimp-win-remote"=> "gimp-win-remote http://sourceforge.net/projects/gimp-win-remote/",
"identify" => "Image Magick http://www.imagemagick.org",
"thunderbird" => "http://www.mozilla.org/projects/thunderbird/",
"exiftool" => "http://owl.phy.queensu.ca/~phil/exiftool/",
);
# hash to replace (german) umlaute by corresponding letters
my %umlaute = qw( ae Ae oe Oe ue Ue ss);
my $umlaute = join "", keys(%umlaute);
# hash to replace (german) umlaute by corresponding HTML-tags
my %umlauteHTML = qw( ä Ä ö Ö ü Ü ß);
my $umlauteHTML = join "", keys(%umlauteHTML);
# hash to escape special HTML characters
my %htmlChars = (
"<" => "<",
">" => ">",
"&" => "&",
"\"" => """,
"'" => "'",
);
my $htmlChars = join "", keys(%htmlChars);
# config hash
# insert here all default configurations
# these configurations will be overwritten by $configFile
# at startup
my %config = (
"Geometry" => "790x560+1+1", # fit on a 800x600 screen
"SearchGeometry" => "790x560+1+1", # fit on a 800x600 screen
"KeyGeometry" => "250x500+50+50", # fit on a 800x600 screen
"LtwGeometry" => "700x500+10+10", # fit on a 800x600 screen
"FontSize" => 12,
"FontFamily" => "itc avant garde",
"ColorFG" => "black",
"ColorBG" => "#efefef",
"ColorMenuBG" => "LightGoldenrod3",
"ColorMenuFG" => "black",
"ColorBG2" => "#e5e5e5",
"ColorBGCanvas" => "#efefef",
"ColorHlBG" => "#eeeeee",
"ColorActBG" => "LightGoldenrod1",
"ColorEntry" => "gray90",
"ColorSel" => "LightGoldenrod2",
"ColorSelBut" => "red3",
"ColorSelFG" => "black",
"ColorName" => "black",
"ColorComm" => "black",
"ColorIPTC" => "black",
"ColorEXIF" => "black",
"ColorFile" => "black",
"ColorDir" => "black",
"ColorThumbBG" => "azure3",
"ColorProgress" => "#106dba",
"ColorPicker" => "red", # last color selected with color picker
"DefaultThumb" => "$configdir/EmptyThumb.jpg",
"Copyright" => "copyright (c) $copyright_year Herrmann",
"Comment" => "This picture was taken in south africa ...",
"MaxProcs" => 1,
"MaxCachedPics" => 3,
"NrOfRuns" => 0, # count how often mapivi was started
"ShowPic" => 1, # boolean (1 = show pic, 0 = do not show pic)
"ShowThumbs" => 1, # boolean (1 = show thumbs, 0 = show default thumb)
"UseDefaultThumb" => 1, # boolean (1 = show def thumb if no thumb is shown, 0 = show nothing at all)
"ThumbCapt" => "none", # thumbnail caption
"ThumbCaptFontSize" => 10, # todo add to options dialog
"ShowDirTree" => 1, # boolean (1 = show dir tree, 0 = hide)
"ShowInfoFrame" => 1, # boolean (1 = show info frame, 0 = hide)
"ShowThumbFrame" => 1, # boolean (1 = show thumb frame, 0 = hide)
"ShowPicFrame" => 1, # boolean (1 = show pic frame, 0 = hide)
"ShowComment" => 1, # boolean (1 = show comment, 0 = hide comment in thumbnail view)
"ShowCommentField"=> 1, # boolean (1 = show comment, 0 = hide comment in picture view)
"ShowEXIF" => 1, # boolean (1 = show EXIF, 0 = hide EXIF in thumbnail view)
"ShowEXIFField" => 1, # boolean (1 = show EXIF, 0 = hide EXIF in picture view)
"ShowIPTC" => 1, # boolean (1 = show IPTC, 0 = hide IPTC in thumbnail view)
"ShowFile" => 1, # boolean (1 = show Size, 0 = hide Size in thumbnail view)
"ShowDirectory" => 1, # boolean (1 = show directory, 0 = hide dir in thumbnail view)
"ShowMenu" => 1, # boolean (1 = show menu, 0 = hide the menu bar)
"ShowHiddenDirs" => 0, # boolean (1 = show hidden dirs (starting with .), 0 = hide them)
"Overrideredirect"=> 0, # boolean (1 = no window frame, 0 = window frame)
"PicQuality" => 95, # quality of jpg picture (in %)
"PicSharpen" => 5, # sharpness of picture
"PicBlur" => 0, # blur the pictur
"PicGamma" => 1.0,# gamma value of picture
"PicBrightness" => 100,# Brightnes of picture (in %)
"PicSaturation" => 100,# Saturation of picture (in %)
"PicHue" => 100,# Hue of picture (in %)
"PicStrip" => 0, # boolean (1 = strip all meta info when resizing pic)
"ThumbQuality" => 85, # quality of thumbnail jpg picture
"SortBy" => "name",
"SortReverse" => 0,
"LastDir" => $home,
"FileNameFormat" => "%y%m%d-%h%M%s", # the actual file name format when renaming
"FileNameFormatDef"=> "%y%m%d-%h%M%s", # the default file name format when renaming
"ThumbSharpen" => 1,
"ThumbSize" => 100,
"ThumbBorder" => 4,
"HTMLaddComment" => 1,
"HTMLaddEXIF" => 1,
"HTMLaddIPTC" => 0,
"HTMLcols" => 2,
"HTMLTargetDir" => $home,
"HTMLGalleryIndex"=> "../galleries.html",
"HTMLGalleryTitle"=> "My gallery",
"HTMLHomepage" => "../../index.shtml",
"HTMLTemplate" => "$configdir/pagetemplate.html",
"HTMLFooter" => "© <a href=\"http://herrmanns-stern.de\">Martin Herrmann</a> <a href=\"mailto:Martin-Herrmann\@gmx.de\"><Martin-Herrmann\@gmx.de></a>",
"HTMLBGcolor" => "white",
"HTMLPicSize" => 500,
"HTMLPicSharpen" => 1,
"HTMLPicCopyright"=> 0, # bool - add a visible copyright info into the picture
"HTMLPicQuality" => 75, # quality of html jpg pictures
"HTMLPicEXIF" => 1, # bool - 1 = copy the EXIF infos to the converted HTML pics
"HTMLnoPicChange" => 0, # bool - 1 = no pic changes (no resize etc ...)
"AutoZoom" => 1, # boolean - zoom big pictures to fill the canvas
"UseEXIFThumb" => 0, # boolean - use EXIF Thumbnails if available
"AskGenerateThumb"=> 1, # ask before generating thumbnails
"AskDeleteThumb" => 1, # ask before deleting thumbnails
"AskMakeDir" => 1, # ask before makeing a directory (e.g. .thumbs or .exif)
"MaxTrashSize" => 50, # MB - a warning will appear if the trash contains more than this
"BitsPixel" => 1, # boolean - show bits per pixel info
"AspectRatio" => 1, # boolean - show image aspect ratio e.g. 4:3 or 3:2
"NameComment" => 0, # boolean - 1 = add file name to comment, when importing pics
"NameComRmSuffix" => 1, # boolean - 1 = remove file suffix when adding filename to comment
"ShowClock" => 1, # boolean - 1 = show actual time
"SaveDatabase" => 1, # boolean - 1 = save dir info to a file
"UseThumbShadow" => 0,
"MakeBackup" => 1, # make a backup of the original file, before appling a filter
"PicListFile" => "$home/filelist",
"XMLFile" => "$home/IPTCinfo.xml",
"saveEXIFforEdit" => 1, # save the EXIF info before editing the picture with GIMP (needed for GIMP version 1.3.15 and lower)
"indexRows" => 2, # indexPrint
"indexCols" => 2, # indexPrint
"indexPicX" => 500, # indexPrint
"indexPicY" => 500, # indexPrint
"indexDisX" => 10, # indexPrint
"indexDisY" => 10, # indexPrint
"indexBG" => "white", # indexPrint background color
"indexLabel" => 1, # indexPrint
"indexLabelStr" => "%f (%wx%h, %b)", # indexPrint
"WarnBeforeResize"=> 1, # warn before using mogrify in resize
"ShowMoreEXIF" => 1, # show more EXIF infos: contrast sharpness saturation metering wb in thumbnail list ...
"IPTCoverwrite" => 0, # overwrite IPTC attributes, when editing multiple pictures
"IPTCmergeCatKey" => 1, # merge categories and keywords, when editing multiple pictures
"IPTCdateEXIF" => 0, # use EXIF date as creation date
"IPTCtimeEXIF" => 0, # use EXIF time as creation time
"IPTCbylineEXIF" => 0, # use EXIF owner as ByLine
"IPTCaddMapivi" => 0, # add Mapivi infos to IPTC
"IPTC_action" => 'UPDATE', # ADD UPDATE or REPLACE
"CheckForNonJPEGs"=> 1, # check if there are non JPEGs in the dir and ask to convert them
"ShowPicInfo" => 1, # show a balloon info box with EXIF, comment, ... for the actual picture
"SearchPattern" => "", # the search pattern
"SearchExPattern" => "", # the search exclude pattern
"SearchCom" => 1, # search in the picture comments
"SearchExif" => 1, # search in the picture EXIF info
"SearchIptc" => 1, # search in the picture IPTC info
"SearchKeys" => 1, # search in the picture keywords
"SearchName" => 1, # search in the picture file name
"SearchDir" => 1, # search in the picture path
"SearchCase" => 0, # search case sensitive
"SearchWord" => 0, # 1 = search only complete words 0 = match also parts
"SearchType" => 'exactly', # search type: "exactly", "all" or "any"
"SearchOnlyInDir" => 0, # search only in dirs matching the actual/selected dir
"SearchUrgencyOn" => 0, # search for pictures with a certain IPTC urgency level
"SearchUrgency" => 0, # search only for pictures with this IPTC urgency level
"SearchUrgencyRel"=> '<=',# <=, ==, >=
"SearchPixelOn" => 0, # search for pictures with a certain pixel size
"SearchPixel" => 0, #
"SearchPixelRel" => '<=', # <=, ==, >=
"SearchPopOn" => 0, # search for pic with a certain number of views
"SearchPopRel" => 0, # <=, ==, >=
"SearchPop" => 0, # search for pic with a certein numer of views
"SearchJoin" => 0, # join comment, EXIF, IPTC and filename before searching
"SearchDate" => 0, # search pics by date
"SearchDateStart" => "01.01.1970", # start date
"SearchDateEnd" => "25.08.2010", # end date
"SearchMore" => 0, # show more search options in search window
"SearchDBOnlyNew" => 0, # add only new pics when building DB
"CopyPosition" => 'SouthEast', # position of the visible copyright info
"CopyX" => 20, # x offset of the visible copyright info
"CopyY" => 20, # Y offset of the visible copyright info
"CopyAdd" => 0, # bool - add a visible copyright info
"CopyFontFamily" => "Courier", # font family of the embedded copyright info
"CopyFontSize" => 12, # font size of the embedded copyright info
"CopyFontColFG" => "white", # foreground color of the embedded copyright info font
"CopyFontColBG" => "black", # background color of the embedded copyright info font
"CopyFontShadow" => 1, # bool - add a shadow to the copyright text
"CopyrightLogo" => "$configdir/MapiviIcon.gif",
"CopyTextOrLogo" => "text",
"BorderWidth1x" => 10, # border 1 width in x direction
"BorderWidth1y" => 10, # border 1 width in y direction
"BorderColor1" => "white", # border 1 color
"BorderWidth2x" => 0, # border 2 width in x direction
"BorderWidth2y" => 0, # border 2 width in y direction
"BorderColor2" => "black", # border 2 color
"BorderWidth3x" => 0, # border 3 width in x direction
"BorderWidth3y" => 0, # border 3 width in y direction
"BorderColor3" => "white", # border 3 color
"BorderWidth4x" => 0, # border 4 width in x direction
"BorderWidth4y" => 0, # border 4 width in y direction
"BorderColor4" => "gray80",# border 4 color
"BorderAdd" => 0, # bool - add a border
"DropShadow" => 0, # bool - add a drop shadow
"DropShadowWidth" => 5, # the width of the drop shadow
"DropShadowBlur" => 3, # the blur sigma factor of the drop shadow
"DropShadowBGColor" => "white", # the background color of the drop shadow
"jpegtranTrim" => 0, # bool - use the -trim switch of jpegtran
"SlideShowTime" => 4, # pause between picture loading im sec
"CropAspect" => 3/2, # 0 for no aspect ratio, 3/2 for 3:2 1 for 1:1 4/3 for 4:3
"AspectSloppyFactor" => 2.0, # delta factor for aspect ratio calculation in %
"FilterDeco" => 0, # add a border or a text to the pictures when filtering
"FilterPrevSize" => 200, # filter preview size (100% zoom crop of the picture)
"EXIFshowApp" => 1, # show App*-Info and MakerNotes and ColorComponents in EXIF info
"AddMapiviComment"=> 0, # add a comment to pictures created/processed by mapivi
"Layout" => 0, # layout of the dir, thumb and picture frame
"Layout0dirX" => 25, # default percentual width of the different layouts
"Layout0thumbX" => 30, # ""
"Layout1dirX" => 20, # ""
"Layout3thumbX" => 20, # ""
"Layout5dirX" => 20, # ""
"CommentHeight" => 2, # height of the comment text frame above the picture
"Gamma" => 1.0, # the gamma value, when displaying pictures
"ShowFileDate" => 0, # show the file date in the size coloumn
"Unsharp" => 0, # bool unsharp mask operation on/off
"UnsharpRadius" => 0, # unsharp mask radius (blur)
"UnsharpSigma" => 1.0, # unsharp mask sigma (blur)
"UnsharpAmount" => 1.0, # unsharp mask amount
"UnsharpThreshold"=> 0.05,# unsharp mask threshold
"ResizeFilter" => "Lanczos",
"RenameBackup" => 1, # bool, if 1 a backup file will be renamed if the file is renamed
"ThumbMaxLimit" => 200, # maximum number of displayed thumbnails
"Level" => 0, # level a picture
"LevelBlack" => 8, # level a picture black point (%)
"LevelWhite" => 92, # level a picture white point (%)
"LevelGamma" => 1.0, # level a picture mid point (gamma value)
"indexBorder" => 0, # bool add a border around the index print
"indexBorderWidth"=> 50,
"indexBorderColor"=> 'white',
"indexInnerBorder" => 0, # bool add a border around the each picture
"indexInnerBorderWidth"=> 2,
"indexInnerBorderColor"=> 'black',
"indexFontSize" => 10, # the font size of the index labels (0 = automatic)
"CheckForLinks" => 1, # bool - check if a file is a link before processing it
"ColorAdj" => 0, # bool - do some color adjustments when filtering a pic
"LineLimit" => 6, # max nr of lines in the thumbnail table e.g. for comments
"LineLength" => 30, # length of one line in the thumbnail table e.g. for comments
"ExtViewer" => 'display', # name of external picture viewer
"ExtViewerMulti" => 0, # bool
"ExtBGApp" => "wmsetbg -a", # name of external app to set desktop background (with options)
"ConvertUmlaut" => 1, # convert german umlaute (e.g. -> ae etc.)
"ShowUrgency" => 1, # show the rating/IPTC urgency in the status bar
"DeadPixelStr" => "1300,846,3 85,411,3 7,365,3 1529,185,3 1593,201,3 1387,1003,3 1957,1057,3 50,1043,2 615,935,3", # info about the dead pixels of your camera see: http://www.zero-based.org/software/jpegpixi/
"DeadPixelMethod" => "linear",
"ShowCoordinates" => 0,
"ImportSource" => "/mnt/usb/DCIM/DIMG",
"ImportSubdirs" => 0, # bool - import also from all subdirs
"ImportTargetFix" => "$home/pictures",
"ImportTargetVar" => "2006/200602/20060214_Birthday_Sam",
"ImportDeadPixel" => 1,
"ImportRotate" => 1,
"ImportRename" => 1,
"ImportDeleteCameraJunk" => 0,
"ImportDelete" => 1,
"ImportUnmount" => 1,
"ImportMount" => 1,
"ImportDevice" => "/mnt/usb",
"ImportShowPics" => 1,
"ImportAddCom" => 0,
"ImportAddComment"=> "(c) $copyright_year Martin Herrmann",
"ImportAddIPTC" => 0,
"ImportIPTCTempl" => 'template.iptc2',
"Borderwidth" => 1, # border width of GUI elements (widgets)
"PrintBaseDir" => "$home/pictures/print",
"PrintVarDir" => "3_times_13x18",
"PrintTimes" => "1",
"PrintTimesStr" => "times",
"PrintSize" => "10x15",
"CenterThumb" => 0, # move the thumbnails up or down, so that the next e.g. previous thumb is also visible
"ShowNextPicAfterDel" => 0, # open and display next pic after a delete
"BeepWhenLooping" => 1, # play a beep when looping to the first e.g. last picture
"SlowButMoreFeatures" => 0, # enable some features slowing down mapivi
"setEXIFDateAskAgain" => 0, # show/don't show ask dialog
"EXIFDateAbs" => "2006:02:20-18:51:45",
"EXIFPlusMin" => "+", # used in setEXIFdate
"EXIFAbsRel" => "abs", # used in setEXIFdate
"EXIFyears" => 0, # used in setEXIFdate
"EXIFdays" => 0, # used in setEXIFdate
"EXIFhours" => 0, # used in setEXIFdate
"EXIFmin" => 0, # used in setEXIFdate
"EXIFsec" => 0, # used in setEXIFdate
"RotateThumb" => 1, # bool - rotate thumb when rotating the pic
"ToggleBorder" => 0, # bool - switch window decoration on/off in fullscreen mode
"CentralThumbDB" => 0, # bool - 1 = central thumb DB, 0 = decentral .thumbs dirs
"IPTCLastPad" => "cap", # remember the NoteBook page on the IPTC dialog
"OptionsLastPad" => "gen", # remember the NoteBook page on the IPTC dialog
"MetadataWarn" => 0, # print a warning to stdout if some strange metadata is found (e.g. in EXIF)
"dirDiffDirA" => $home,
"dirDiffDirB" => $home,
"dirDiffSize" => 1,
"dirDiffPixel" => 1,
"dirDiffComment" => 1,
"dirDiffEXIF" => 1,
"dirDiffIPTC" => 1,
"MailPicNoChange" => 0,
"MailPicMaxLength"=> 800,
"MailPicQuality" => 75,
"winDirRequesterAskAgain" => 1,
"FuzzyBorderWidth"=> 10,
"FuzzyBorderBlur" => 10,
"FuzzyBorderColor"=> "black",
"ShowInfoInCanvas"=> 0,
"llBorderWidth" => 16,
"llBorderWidthI" => 1,
"llBorderColor" => "white",
"llBorderColorI" => "black",
"supportOtherPictureFormats" => 0,
"CategoriesAll" => 1,
"KeywordsAll" => 1,
"Version" => '000',
"ShowUnfinishedDirs" => 1,
"ShowFinishedDirs" => 1,
"trackPopularity" => 1,
"ChannelRed" => 100,
"ChannelGreen" => 100,
"ChannelBlue" => 100,
"ChannelDeco" => 0,
"ChannelBright" => 1,
'SlideShowDir' => $home, # settings for slideshows
'relative_path' => 1, # settings for xnview slideshows
'xnview_loop' => 1, # settings for xnview slideshows
'xnview_fullscreen' => 1, # settings for xnview slideshows
'xnview_filename' => 0, # settings for xnview slideshows
'xnview_random' => 0, # settings for xnview slideshows
'xnview_mouse' => 0, # settings for xnview slideshows
'xnview_title' => 0, # settings for xnview slideshows
'PicWinBalloon' => 1, # boolean -1 show balloon info in pic window
'IPTCProfessional'=> 1, # boolean - 1 = professional IPTC, 0 = simple dialog
'CheckNewKeywords'=> 1,
'KeywordMore' => 0, # boolean 1 = show more options in keyword search window
'KeywordExclude' => '', # space separated list of keywords to exclude
'KeywordLimit' => 0, # boolean 1 = limit number of displayed keywords
'UrgencyChangeWarning' => 1, # boolean 1 = show a warning when urgency changed
);
# some platform specific default settings
# for windows
if ($EvilOS) {
$config{ExtViewer} = 'C:\Program Files\IrfanView\iview_32.exe';
}
# for Mac OS X
if ($MacOSX) {
$config{ExtViewer} = "macosx-preview";
$config{ExtViewerMulti} = 1;
}
my @IPTCAttributes = (
"Urgency",
"Keywords",
"Headline",
"Caption/Abstract",
"SubLocation",
"City",
"Province/State",
"Country/PrimaryLocationCode",
"Country/PrimaryLocationName",
"Writer/Editor",
"ObjectName",
"CopyrightNotice",
"Category",
"Source",
"EditStatus",
"OriginatingProgram",
"ProgramVersion",
"EditorialUpdate",
"ObjectCycle",
"ByLine",
"ByLineTitle",
"FixtureIdentifier",
"ContentLocationName",
"ContentLocationCode",
"ReleaseDate",
"ReleaseTime",
"OriginalTransmissionReference",
"ExpirationDate",
"ExpirationTime",
"Credit",
"SpecialInstructions",
"ActionAdvised",
"Contact",
#"ReferenceService", # only usefull for multiple objects
#"ReferenceDate", # only usefull for multiple objects
#"ReferenceNumber", # only usefull for multiple objects
"DateCreated",
"TimeCreated",
"ImageType",
"ImageOrientation",
"DigitalCreationDate",
"DigitalCreationTime",
"LanguageIdentifier",
#"RecordVersion", # binary
"ObjectTypeReference",
"ObjectAttributeReference",
"SubjectReference",
"SupplementalCategory",
#"RasterizedCaption", # binary
# Audio... and ObjDataPreview... left out by now ...
);
my %iptcHelp = (
"ByLine" => "Contains name of the creator of the objectdata, e.g. writer, photographer or graphic artist. Examples: Robert Capa, Ernest Hemingway, Pablo Picasso (max. 32 chars)",
"ByLineTitle" => "A ByLineTitle is the title of the creator or creators of an objectdata. Where used, a by-line title should follow the ByLine it modifies. Examples: Staff Photographer, Corresponsal, Envoye Special (max. 32 chars)",
"Caption/Abstract" => "The Caption field is the text that accompanies the photo, containing the who, what, when, where and why information (max. 2000 chars)",
"CaptionWriter" => "The Caption Writer field lists the initials of all the people who wrote or edited the caption, header fields or image file. This includes toning and pixel editing",
"Category" => "Identifies the subject of the objectdata in the opinion of the provider. A list of categories will be maintained by a regional registry, where available, otherwise by the provider. Note: Use of this DataSet is Deprecated. It is likely that this DataSet will not be included in further versions of the IIM. The Category field lists codes that aid in a more detailed search. (max. 3 chars)",
"SubLocation" => "Identifies the location within a city. Examples: Capitol Hill, Maple Leaf Gardens, Strandgateparken (max. 32 chars)",
"City" => "The City field lists where the photo was originally made. For file photos, do not use the transmission point's city (max. 32 chars)",
"Country/PrimaryLocationCode" => "The Country field lists the three-letter country code where the photo was originally made. For file photos, do not put the transmission points country. Examples: USA (United States), GER (Germany), FRA (France), XUN (United Nations) (max. 3 chars)",
"Country/PrimaryLocationName" => "Provides full, publishable, name of the country/primary location where the intellectual property of the objectdata was created, according to guidelines of the provider. (max. 64 chars)",
"DateCreated" => "The Create Date field is the date the photo was originally made. For file photos, use the date the photo was originally made, if known. If the complete date is not known, leaf the field blank. The field will not accept a partial date. (8 chars CCYYMMDD)",
"TimeCreated" => "Represented in the form HHMMSS+HHMM (or -HHMM) to designate the time the intellectual content of the objectdata current source material was created rather than the creation of the physical representation. Follows ISO 8601 standard. Where the time cannot be precisely determined, the closest approximation should be used. Example: 133015+0100 indicates that the object intellectual content was created at 1:30 p.m. and 15 seconds Frankfurt time, one hour ahead of UTC. (11 chars HHMMSS+HHMM)",
"Credit" => "Identifies the provider of the objectdata, not necessarily the owner/creator. (The Credit field is the name of the service transmitting the photo) (max. 32 chars)",
"Headline" => "The Headline field lists keywords to aid in a more detailed search for a photo. Example: Lindbergh Lands In Paris (max. 256 chars)",
"SpecialInstructions" => "The Instructions field lists special notations that apply uniquely to a photo, such as file photo, correction, advance or outs Examples: SECOND OF FOUR STORIES, 3 Pictures follow, Argentina OUT (max. 256 chars)",
"ObjectName" => "Used as a shorthand reference for the object. Changes to existing data, such as updated stories or new crops on photos, should be identified in Edit Status. Examples: Wall St., Ferry Sinks. The Object Name field lists the story slug associated with a photo. For photos without a story, Associated Press photographers or photo editors will make up a logical slug to aid in a search and note it as a stand alone photo in the INSTRUCTIONS field of the NAA/IPTC header. If a related story moves on Data-Stream, the photo will be retransmitted with the appropriate OBJECT NAME to match the story. (max. 64 chars)",
"Source" => "Identifies the original owner of the intellectual content of the objectdata. This could be an agency, a member of an agency or an individual. (The Source field lists who is the original provider of a photo, such as: AP, an AP member, pool photo provider or handout photo provider.) (max. 32 chars)",
"Province/State" => "The State field lists the state where the photo was originally made. Use U.S. postal code abbreviations. For file photos, do not use the transmission point's state. Examples: WA, Sussex, Baden-Wuerttenberg (max. 32 chars)",
"SupplementalCategory" => "The Supplemental Categories field lists codes that aid in a more detailed search for a photo.",
"OriginalTransmissionReference" => "A code representing the location of original transmission according to practices of the provider. Examples: BER-5, PAR-12-11-01. (The Trans Reference field lists a call letter/number combination associated with a photo. It includes an originating transmit points call letters and picture number from that point's sequence of offerings for a given day. Example: NY105.) (max. 32 chars)",
"Urgency" => "priority 0 meaning None, 1 meaning High to 8 meaning Low",
"CopyrightNotice" => "Contains any necessary copyright notice. (max. 128 chars)",
"ExpirationTime" => "Designates in the form HHMMSS+HHMM (or -HHMM) the latest time the provider or owner intends the objectdata to be used. Follows ISO 8601 standard. Example: 090000-0500 indicates an objectdata that should not be used after 0900 in New York (five hours behind UTC).",
"ExpirationDate" => "Designates in the form CCYYMMDD the latest date the provider or owner intends the objectdata to be used. Follows ISO 8601 standard. Example: 19940317 indicates an objectdata that should not be used after 17 March 1994.",
"ReleaseTime" => "Designates in the form HHMMSS+HHMM (or -HHMM) the earliest time the provider intends the object to be used. Follows ISO 8601 standard. Example: 090000-0500 indicates object for use after 0900 in New York (five hours behind UTC)",
"ReleaseDate" => "Designates in the form CCYYMMDD the earliest date the provider intends the object to be used. Follows ISO 8601 standard. Example: 19890317 indicates data for release on 17 March 1989. (8 chars)",
"FixtureIdentifier" => "Identifies objectdata that recurs often and predictably. Enables users to immediately find or recall such an object. Example: EUROWEATHER",
"EditStatus" => "Status of the objectdata, according to the practice of the provider. Examples: Lead, CORRECTION (max. 64 chars)",
"Writer/Editor" => "Identification of the name of the person involved in the writing, editing or correcting the objectdata or caption/abstract. (max. 32 chars)",
"LanguageIdentifier" => "Describes the major national language of the object, according to the 2-letter codes of ISO 639:1988. Does not define or imply
any coded character set, but is used for internal routing, e.g. to various editorial desks. Example: en (english), de (german) (2 or 3 chars)",
"ObjectCycle" => "Where: a = morning, p = evening, b = both. Virtually only used in North America. (1 char)",
"Contact" => "Identifies the person or organisation which can provide further background information on the objectdata. (max. 128 chars)"
);
# store all values which were entered in the labeled entry widgets
# key = label of entry, value = reference to array containing all unique values
my %entryHistory;
my @allcolors = qw/black gray10 gray20 gray30 gray40 gray50 gray60 gray70 gray80 gray85 gray90
gray95 white snow2 snow3 snow4 seashell1 seashell2 seashell3 seashell4
AntiqueWhite1 AntiqueWhite2 AntiqueWhite3 AntiqueWhite4 bisque1
bisque2 bisque3 bisque4 PeachPuff1 PeachPuff2 PeachPuff3 PeachPuff4
NavajoWhite1 NavajoWhite2 NavajoWhite3 NavajoWhite4 LemonChiffon1
LemonChiffon2 LemonChiffon3 LemonChiffon4 cornsilk1 cornsilk2
cornsilk3 cornsilk4 ivory1 ivory2 ivory3 ivory4 honeydew1 honeydew2
honeydew3 honeydew4 LavenderBlush1 LavenderBlush2 LavenderBlush3
LavenderBlush4 MistyRose1 MistyRose2 MistyRose3 MistyRose4 azure1
azure2 azure3 azure4 SlateBlue1 SlateBlue2 SlateBlue3 SlateBlue4
RoyalBlue1 RoyalBlue2 RoyalBlue3 RoyalBlue4 blue1 blue2 blue3 blue4
DodgerBlue1 DodgerBlue2 DodgerBlue3 DodgerBlue4 SteelBlue1 SteelBlue2
SteelBlue3 SteelBlue4 DeepSkyBlue1 DeepSkyBlue2 DeepSkyBlue3
DeepSkyBlue4 SkyBlue1 SkyBlue2 SkyBlue3 SkyBlue4 LightSkyBlue1
LightSkyBlue2 LightSkyBlue3 LightSkyBlue4 SlateGray1 SlateGray2
SlateGray3 SlateGray4 LightSteelBlue1 LightSteelBlue2 LightSteelBlue3
LightSteelBlue4 LightBlue1 LightBlue2 LightBlue3 LightBlue4 LightCyan1
LightCyan2 LightCyan3 LightCyan4 PaleTurquoise1 PaleTurquoise2
PaleTurquoise3 PaleTurquoise4 CadetBlue1 CadetBlue2 CadetBlue3
CadetBlue4 turquoise1 turquoise2 turquoise3 turquoise4 cyan1 cyan2
cyan3 cyan4 DarkSlateGray1 DarkSlateGray2 DarkSlateGray3
DarkSlateGray4 aquamarine1 aquamarine2 aquamarine3 aquamarine4
DarkSeaGreen1 DarkSeaGreen2 DarkSeaGreen3 DarkSeaGreen4 SeaGreen1
SeaGreen2 SeaGreen3 SeaGreen4 PaleGreen1 PaleGreen2 PaleGreen3
PaleGreen4 SpringGreen1 SpringGreen2 SpringGreen3 SpringGreen4 green1
green2 green3 green4 chartreuse1 chartreuse2 chartreuse3 chartreuse4
OliveDrab1 OliveDrab2 OliveDrab3 OliveDrab4 DarkOliveGreen1
DarkOliveGreen2 DarkOliveGreen3 DarkOliveGreen4 khaki1 khaki2 khaki3
khaki4 LightGoldenrod1 LightGoldenrod2 LightGoldenrod3 LightGoldenrod4
LightYellow1 LightYellow2 LightYellow3 LightYellow4 yellow1 yellow2
yellow3 yellow4 gold1 gold2 gold3 gold4 goldenrod1 goldenrod2
goldenrod3 goldenrod4 DarkGoldenrod1 DarkGoldenrod2 DarkGoldenrod3
DarkGoldenrod4 RosyBrown1 RosyBrown2 RosyBrown3 RosyBrown4 IndianRed1
IndianRed2 IndianRed3 IndianRed4 sienna1 sienna2 sienna3 sienna4
burlywood1 burlywood2 burlywood3 burlywood4 wheat1 wheat2 wheat3
wheat4 tan1 tan2 tan3 tan4 chocolate1 chocolate2 chocolate3 chocolate4
firebrick1 firebrick2 firebrick3 firebrick4 brown1 brown2 brown3
brown4 salmon1 salmon2 salmon3 salmon4 LightSalmon1 LightSalmon2
LightSalmon3 LightSalmon4 orange1 orange2 orange3 orange4 DarkOrange1
DarkOrange2 DarkOrange3 DarkOrange4 coral1 coral2 coral3 coral4
tomato1 tomato2 tomato3 tomato4 OrangeRed1 OrangeRed2 OrangeRed3
OrangeRed4 red1 red2 red3 red4 DeepPink1 DeepPink2 DeepPink3 DeepPink4
HotPink1 HotPink2 HotPink3 HotPink4 pink1 pink2 pink3 pink4 LightPink1
LightPink2 LightPink3 LightPink4 PaleVioletRed1 PaleVioletRed2
PaleVioletRed3 PaleVioletRed4 maroon1 maroon2 maroon3 maroon4
VioletRed1 VioletRed2 VioletRed3 VioletRed4 magenta1 magenta2 magenta3
magenta4 orchid1 orchid2 orchid3 orchid4 plum1 plum2 plum3 plum4
MediumOrchid1 MediumOrchid2 MediumOrchid3 MediumOrchid4 DarkOrchid1
DarkOrchid2 DarkOrchid3 DarkOrchid4 purple1 purple2 purple3 purple4
MediumPurple1 MediumPurple2 MediumPurple3 MediumPurple4 thistle1
thistle2 thistle3 thistle4/;
# get the configurations from the rc file if the configdir exists
readConfig($configFile, \%config) if (-d $configdir);
# check if this is the first start of a new Mapivi version
mapiviUpdate() if (($config{Version} eq '000') or ($version ne $config{Version}));
$config{Version} = $version;
processARGV(); # process the command line arguments as early as possible to give a fast feedback
my $layoutOld = $config{Layout}; # this must be done after readConfig!
# for zoom and subsample of Tk::Photo objects
# the higher the zoom value the longer the time to zoom
# subsample is quite fast, so the first number (zoom) should not be bigger than 4
# the second (subsample) may be bigger
my @frac;
if ($config{SlowButMoreFeatures}) {
@frac = (10,1, 6,1, 4,1, 3,1, 2,1, 3,2, 4,3, 1,1, 4,5, 3,4, 2,3, 3,5, 1,2, 2,5, 1,3, 1,4, 1,5, 1,6, 1,7, 1,8, 1,10, 1,12, 1,16, 1,25, 1,50);
}
else {
@frac = (10,1, 6,1, 4,1, 3,1, 2,1, 3,2, 4,3, 1,1, 4,5, 3,4, 2,3, 1,2, 1,3, 1,4, 1,5, 1,6, 1,7, 1,8, 1,10, 1,12, 1,16, 1,25, 1,50);
}
# open main window
my $top = MainWindow->new;
# hide it, while building up
$top->withdraw;
# set the window size
checkGeometry(\$config{Geometry});
$top->geometry($config{Geometry});
# add a window and icon picture
my $mapiviiconfile = "$configdir/MapiviIcon.gif";
$mapiviiconfile = "$configdir/MapiviIcon32.gif" if $EvilOS;
my $mapiviicon = $top->Photo(-file => $mapiviiconfile) if (-f $mapiviiconfile);
$top->idletasks if $EvilOS; # this line is crucial (at least on windows)
$top->iconimage($mapiviicon) if $mapiviicon;
my $dragAndDrop1 = "$configdir/MiniPic.jpg";
my $dragAndDrop2 = "$configdir/MiniPicMulti.jpg";
my $dragAndDropIcon1 = $top->Photo(-file => $dragAndDrop1) if (-f $dragAndDrop1);
my $dragAndDropIcon2 = $top->Photo(-file => $dragAndDrop2) if (-f $dragAndDrop2);
# button bitmap needed for color buttons
my $mcbut = pack("b8" x 8,
".......",
".......",
".......",
".......",
".......",
".......",
".......",
".......");
$top->DefineBitmap('mcbut' => 8, 8, $mcbut);
# button bitmap needed for + buttons
my $plusbut = pack("b5" x 5,
"..1..",
"..1..",
"11111",
"..1..",
"..1..",);
$top->DefineBitmap('plusbut' => 5, 5, $plusbut);
# button bitmap needed for - buttons
my $minusbut = pack("b5" x 5,
".....",
".....",
"11111",
".....",
".....",);
$top->DefineBitmap('minusbut' => 5, 5, $minusbut);
# pseudo transpartent bitmap for cropDialog
my $transbits = pack("b4" x 4,
"11..",
"11..",
"..11",
"..11");
$top->DefineBitmap('transp' => 4, 4, $transbits);
# pseudo transpartent bitmap for cropDialog
my $transbits2 = pack("b1" x 3,
"1",
"1",
".");
$top->DefineBitmap('transp2' => 1, 3, $transbits2);
# pseudo transpartent bitmap for cropDialog
my $transbits3 = pack("b1" x 3,
"1",
".",
"1");
$top->DefineBitmap('transp3' => 1, 3, $transbits3);
# set title and icon
$top->title("MaPiVi $version");
$top->iconname("MaPiVi");
# set options
my $ScW = 10;
$ScW = 14 if $EvilOS; # the small scrollbars look ugly under windows
for (qw(Scale Scrollbar)) {
$top->optionAdd("*$_.width", $ScW, "userDefault");
}
# override -takefocus for frames and scrollbars
$top->optionAdd('*Frame.TakeFocus','0');
$top->optionAdd('*Scrollbar.TakeFocus','0');
$top->optionAdd('*ResizeButton.TakeFocus','0');
# change menu style to compact
$top->optionAdd('*Menu.borderWidth' => 1);
$top->optionAdd('*Menu.activeBorderWidth' => 0);
$top->optionAdd('*Menu.borderWidth' => 1);
$top->optionAdd('*selectForeground', $config{ColorSelFG}, 'userDefault');
$top->optionAdd('*selectBackground', $config{ColorSel}, 'userDefault');
$top->optionAdd("*highlightColor", $config{ColorSel}, 'userDefault');
$top->optionAdd("*highlightBackground", $config{ColorHlBG}, 'userDefault');
$top->optionAdd("*background", $config{ColorBG}, 'userDefault');
$top->optionAdd("*activeBackground", $config{ColorActBG}, 'userDefault');
# must be after the *background optionAdd call
$top->optionAdd("*Menu.background", $config{ColorMenuBG}, 'userDefault');
for (qw(foreground)) {
$top->optionAdd("*$_", $config{ColorFG}, 'userDefault');
}
# must be after the *foreground and *background optionAdd call
$top->optionAdd("*Menu.background", $config{ColorMenuBG}, 'userDefault');
$top->optionAdd("*Menu.foreground", $config{ColorMenuFG}, 'userDefault');
for (qw(Scale Scrollbar Adjuster)) {
$top->optionAdd("*$_.troughColor", $config{ColorEntry}, "userDefault");
}
$top->optionAdd("*ProgressBar.troughColor", $config{ColorBG}, "userDefault");
$top->optionAdd("*Label.background", $config{ColorBG}, "userDefault");
for (qw(Entry NumEntry Listbox KListbox K2Listbox TixHList HList ROText Text
BrowseEntry.Entry NoteBook)) {
$top->optionAdd("*$_.background", $config{ColorEntry}, "userDefault");
}
for (qw(Button Checkbutton Radiobutton Menubutton
FlatCheckbox FireButton Menu)) {
$top->optionAdd("*$_.cursor", "hand2", "userDefault");
}
$top->optionAdd("*Radiobutton.selectColor", $config{ColorSelBut}, "userDefault");
$top->optionAdd("*Checkbutton.selectColor", $config{ColorSelBut}, "userDefault");
$top->optionAdd("*Menu.selectColor", $config{ColorSelBut}, "userDefault");
my $font = $top->Font(-family => $config{FontFamily},
-size => $config{FontSize},
#-weight => "normal,-slant,roman,-underline,0,-overstrike,0
);
my $small_font = $top->Font(-family => $config{FontFamily}, -size => 8);
$top->optionAdd("*font", $font, "userDefault");
# slick scrollbars
$top->optionAdd('*Scrollbar.borderWidth' => $config{Borderwidth});
$top->optionAdd('*Adjuster.borderWidth' => $config{Borderwidth});
$top->optionAdd('*Button.borderWidth' => $config{Borderwidth});
$top->optionAdd('*ResizeButton.borderWidth' => $config{Borderwidth});
$top->optionAdd('*Entry.borderWidth' => $config{Borderwidth});
$top->optionAdd('*Scale.borderWidth' => $config{Borderwidth});
$top->optionAdd('*Slider.borderWidth' => $config{Borderwidth});
$top->optionAdd('*NoteBook.borderWidth' => $config{Borderwidth});
$top->optionAdd('*Frame.borderWidth' => $config{Borderwidth});
$top->optionAdd('*NoteBook.Frame.borderWidth' => 0);
$top->optionAdd('*checkbutton.borderWidth' => $config{Borderwidth});
$top->optionAdd('*Checkbutton.borderWidth' => $config{Borderwidth});
$top->optionAdd('*Radiobutton.borderWidth' => $config{Borderwidth});
$top->optionAdd('*radiobutton.borderWidth' => $config{Borderwidth});
$top->optionAdd('*separator.borderWidth' => $config{Borderwidth});
$top->optionAdd('*Menu.borderWidth' => $config{Borderwidth});
$top->optionAdd('*Cascade.borderWidth' => $config{Borderwidth});
$top->optionAdd('*Label.borderWidth' => $config{Borderwidth});
$top->optionAdd('*Canvas.borderWidth' => $config{Borderwidth});
$top->optionAdd('*ROText.borderWidth' => $config{Borderwidth});
$top->optionAdd('*Optionmenu.borderWidth' => $config{Borderwidth});
$top->optionAdd('*DirTree.borderWidth' => $config{Borderwidth});
$top->optionAdd('*HList.borderWidth' => $config{Borderwidth});
# call quitMain when the window is closed by the window manager
$top->protocol("WM_DELETE_WINDOW" => sub { quitMain(); });
# init stuff
$balloon = $top->Balloon(-bg => $config{ColorSel}, -initwait => 1000);
$balloon->Subwidget("message")->configure(-justify => "left");
$top->fontCreate(qw/C_big -family courier -size 14 -weight bold/);
#createMenubar();
my $infoF = $top->Frame(-relief => "raised");
# $subF contains the 3 frames: dirtree ($dirF), thumbnails ($thumbF) and picture ($mainF)
my $subF = $top->Frame();
my $dirF = $subF->Frame();
my $dirA = $subF->Adjuster();
my $thumbF = $subF->Frame();
my $thumbA = $subF->Adjuster();
my $mainF = $subF->Frame();
my $exifF = $mainF->Frame(-relief => "raised");
my $iptcB = makeButton($exifF, "left", "IPTC", "iptc.gif", 'displayIPTCData($picLB)');
$balloon->attach($iptcB, -msg => "Show all IPTC Information of displayed picture");
my $exifB = makeButton($exifF, "left", "EXIF", "exif.gif", 'displayEXIFData($picLB)');
$balloon->attach($exifB, -msg => "Show all EXIF Information of displayed picture");
my $exifL = $exifF->Label(-textvariable => \$exif, -anchor => 'w', -justify => "left", -relief => "sunken")->pack(-side => "left", -fill => 'both', -expand => 1);
$balloon->attach($exifL, -msg => "EXIF Information of displayed picture");
my $comF = $mainF->Frame(-relief => "raised");
my $comBF = $comF->Frame()->pack(-side => "left", -expand => 1, -fill => "both", -anchor=>"nw", -padx => 0, -pady => 0);
my $nrofL = $infoF->Label(-justify => "left",-textvariable => \$nrof, -relief => "sunken", -anchor => 'w'
)->pack(-side => "left", -expand => 0, -fill => "y");
$balloon->attach($nrofL, -msg => "x/y (z, s) = first selected picture is number x\nfrom y pictures in the actual directory\nz pictures are selected\ns is the size of all selected pictures");
my $dirtreedir;
# if the actual dir should be displayed in the dir frame, just change $thumbF to $dirF in the line below
my $actdirF = $thumbF->Frame()->pack(-expand => 1, -fill => 'x', -padx => 2, -pady => 1);
my $actdirL = $actdirF->Label(-textvariable => \$actdir, -width => 10, -anchor => "e", -relief => "sunken", -bd => $config{Borderwidth})->pack(-side => "left", -expand => 1, -fill => 'x');
$balloon->attach($actdirL, -msg => "actual directory\nClick here to open a simple directory requester.");
$actdirL->bind("<Button-1>", sub { getDirAndOpen(); });
my $otherFilesL = $actdirF->Label(-textvariable => \$otherFiles, -relief => "sunken", -bd => $config{Borderwidth})->pack(-side => "left");
$balloon->attach($otherFilesL, -msg => "number of non-JPEG files in the actual directory");
my $otherFilesB = $actdirF->Button(-text => "i", -command => sub {showNonJPEGS();}, -padx => 1, -pady => 0)->pack(-side => "left");
$balloon->attach($otherFilesB, -msg => "show non-JPEG files in the actual directory");
my $parentDirB = $actdirF->Button(-text => "..", -command => sub {
my $parentdir = dirname($actdir);
print "changing to $parentdir (was: $actdir)\n" if $verbose;
openDirPost($parentdir);
}, -padx => 0, -pady => 0)->pack(-side => "left");
$balloon->attach($parentDirB, -msg => "open parent directory");
my $dirPropSORT = 0;
my $dirPropMETA = 0;
my $dirPropPRIO = 0;
$actdirF->{cbSORT} = $actdirF->Checkbutton(-variable => \$dirPropSORT, -command => sub { $dirProperties{$actdir}{SORT} = $dirPropSORT; }, -padx => 0)->pack(-side => 'left', -anchor=>'w');
$actdirF->{cbMETA} = $actdirF->Checkbutton(-variable => \$dirPropMETA, -command => sub { $dirProperties{$actdir}{META} = $dirPropMETA; }, -padx => 0)->pack(-side => 'left', -anchor=>'w');
$actdirF->{cbPRIO} = $actdirF->Checkbutton(-variable => \$dirPropPRIO, -command => sub { $dirProperties{$actdir}{PRIO} = $dirPropPRIO; }, -padx => 0)->pack(-side => 'left', -anchor=>'w');
$balloon->attach($actdirF->{cbSORT}, -msg => "Sort:\nCheck this button, if the pictures\nin this directory are sorted out.");
$balloon->attach($actdirF->{cbMETA}, -msg => "Meta:\nCheck this button, if all needed meta infos\n(comments, IPTC) of the pictures in this directory are added.");
$balloon->attach($actdirF->{cbPRIO}, -msg => "Prio:\nCheck this button, if the pictures in this\ndirectory are rated with a IPTC urgency flag.");
my $dirtree;
$dirtree = $dirF->Scrolled('DirTree',
-scrollbars => 'osoe',
# -width => $config{AdjusterDir},
-width => 30,
-height => 200,
-showhidden => $config{ShowHiddenDirs},
-selectmode => 'browse',
#-selectmode => 'extended', # todo: usefull?
-exportselection => 1,
-browsecmd => sub {
# this function will show all subdirs when clicking on the + sign of a dir
$dirtreedir = shift;
return if (@_ >= 1);
if (!-d $dirtreedir) { print "$dirtreedir does not exists!\n"; return; }
$top->Busy;
my @dirs = getDirs($dirtreedir);
$top->Unbusy;
return if (@dirs < 1);
$top->Busy;
my $lastdir = $dirtreedir."/".$dirs[-1];
if ($dirtree->info("exists", "$lastdir")) {
$dirtree->see($lastdir) if (-d $lastdir);
}
$top->Unbusy;
},
-command => sub { openDirPost($dirtreedir); },
)->pack(-fill => "both", -expand => 1);
# Set the initial directory
exists &Tk::DirTree::chdir ? $dirtree->chdir($actdir) : $dirtree->set_dir($actdir);
bindMouseWheel($dirtree);
$dirtree->bind('<Enter>', sub { $dirtree->focus; } ) unless $EvilOS;
$dirtree->bind('<ButtonPress-3>', sub {
$dirMenu->Popup(-popover => "cursor", -popanchor => "nw");
} );
my $dtr = $dirtree->Subwidget("scrolled");
# change the binding order of the dirtree
$dtr->bindtags([$dtr,ref $dtr,$dtr->toplevel,'all']);
# stop the execution of the scape key
$dtr->bind('<Key-space>', sub { Tk->break; } );
my $c = $mainF->Scrolled('Canvas',
-scrollbars => 'osoe',
-width => 2000,
-height => 2000,
-relief => "flat",
-borderwidth => 0,
-highlightthickness => 0,
-bg => $config{ColorBGCanvas},
);
$c->configure(-scrollregion => [0, 0, 100, 100]);
my $whL = $infoF->Label(-textvariable => \$widthheight, -relief => "sunken")->pack(-side => "left", -expand => 0, -fill => "y");
$balloon->attach($whL, -msg => "width and height of displayed picture in pixels");
my $sizeL = $infoF->Label(-textvariable => \$size, -relief => "sunken")->pack(-side => "left", -fill => "y");
$balloon->attach($sizeL, -msg => "file size of displayed picture in kByte");
my $zoomL = $infoF->Label(-textvariable => \$zoomFactorStr, -relief => "sunken")->pack(-side => "left", -fill => "y");
$balloon->attach($zoomL, -msg => "zoom factor of the actual picture");
if ($config{ShowUrgency}) {
my $urgF = $infoF->Frame(-relief => "sunken")->pack(-side => "left", -fill => "y");
my $urgL = $urgF->Label(-textvariable => \$urgencyStr)->pack(-side => "left", -fill => "y");
$balloon->attach($urgF, -msg => "the rating (IPTC urgency) of the actual picture\n0 or - meaning None, 1 meaning High to 8 meaning Low");
my $urgAnchor = 's'; $urgAnchor = 'n' if ($Tk::VERSION < 804); # the anchor behavior has changed
my $urgencyBar =
$urgF->ProgressBar(-takefocus => 0,
-borderwidth => 0,
-width => 12,
-length => (2*$config{FontSize}), # try to guess the height of the labels
-padx => 0,
-pady => 0,
-variable => \$urgencyScale,
-colors => [0, $top->Darken($config{ColorSel}, 30), 1, $top->Darken($config{ColorSel}, 40), 2, $top->Darken($config{ColorSel}, 50), 3, $top->Darken($config{ColorSel}, 60), 4, $top->Darken($config{ColorSel}, 70), 5, $top->Darken($config{ColorSel}, 80), 6, $top->Darken($config{ColorSel}, 90), 7, $config{ColorSel} ],
-troughcolor => $config{ColorBG},
-resolution => 1,
-blocks => 0,
-gap => 0,
-anchor => $urgAnchor,
-from => 0,
-to => 8
)->pack(-side => 'left', -fill => 'both', -expand => 0, -padx => 0, -pady => 0);
}
my $userInfoL = $infoF->Label(-textvariable => \$userinfo, -relief => "sunken")->pack(-side => "left", -fill => 'both', -expand => 1);
my $userInfoMsg;
$balloon->attach($userInfoL, -postcommand => sub { $userInfoMsg = "information about what's going on"; $userInfoMsg .= "\n(actual directory: $actdir)"}, -msg => \$userInfoMsg);
my $colorPickerInfo = $infoF->Label(-text => ' ', -background => $config{ColorPicker}, -relief => "sunken")->pack(-side => "left", -fill => 'both', -expand => 0);
$balloon->attach($colorPickerInfo, -msg => "Color picker: last color picked by clicking\non the picture in the main window.\nPlease click to clear.");
$colorPickerInfo->bind('<ButtonRelease-1>', sub {
$config{ColorPicker} = $config{ColorBG};
$colorPickerInfo->configure(-background => $config{ColorPicker}); });
#my $stopB = makeButton($infoF, "left", "STOP", "StopPic.gif", 'stopButStop()');
#$balloon->attach($stopB, -msg => "Stop actual action.\nThis may take a while, pressing the button once is enough,\neven if no immidiate feedback is visible.");
#stopButEnd();
my $nrTCL = $infoF->Label(-textvariable => \$nrToConvert, -relief => "sunken")->pack(-side => "left", -expand => 0, -fill => "y");
$balloon->attach($nrTCL, -msg => "Number of thumbnails to generate/refresh");
my $progressBar =
$infoF->ProgressBar(-takefocus => 0,
-borderwidth => 1,
-relief => 'sunken',
-width => (2*$config{FontSize}), # try to guess the height of the labels
-length => 30,
-padx => 0,
-pady => 0,
-variable => \$proccount,
-colors => [0 => $config{ColorProgress}],
-resolution => 1,
-blocks => $config{MaxProcs},
-anchor => 'w',
-from => 0,
-to => $config{MaxProcs}
)->pack(-side => 'left', -fill => 'both', -expand => 0, -padx => 0, -pady => 0);
$clockL = $infoF->Label(-textvariable => \$time, -relief => "sunken")->pack(-side => "left", -fill => "y");
$balloon->attach($clockL, -msg => \$date);
my $commentText = $comF->Scrolled("ROText",
-scrollbars => 'oe',
-wrap => 'word',
-width => 200,
-height => $config{CommentHeight},
)->pack(-side => "left", -fill => 'both', -expand => "1", -padx => 0, -pady => 0);
$balloon->attach($commentText, -msg => "Comment(s) of displayed picture");
my $addB = makeButton($comBF, "left", "add", "add.gif", 'addComment($picLB)');
$balloon->attach($addB, -msg => "Add a comment");
my $editB = makeButton($comBF, "left", "edit", "edit.gif", 'editComment($picLB)');
$balloon->attach($editB, -msg => "Edit a comment");
my $remB = makeButton($comBF, "left", "del", "delete.gif", 'removeComment()');
$balloon->attach($remB, -msg => "Remove comment(s)");
$balloon->attach($progressBar, -msg => "info about the number of background processes\n(generating thumbnail pictures)");
my $picLB = makeThumbListbox($thumbF);
$picLB->bind('<Enter>', sub { $picLB->focus; } ) unless $EvilOS;
# item styles for the thumbnail view
my $thumbCaptionFont = $top->Font(-family => $config{FontFamily},
-size => $config{ThumbCaptFontSize});
my $thumbS = $picLB->ItemStyle('imagetext', -anchor => 'w', -textanchor => 's', -foreground=>$config{ColorFG}, -background=>$config{ColorBG}, -font => $thumbCaptionFont);
my $fileS = $picLB->ItemStyle('text', -anchor=>'nw', -foreground=>$config{ColorFile}, -background=>$config{ColorBG});
my $iptcS = $picLB->ItemStyle('text', -anchor=>'nw', -foreground=>$config{ColorIPTC}, -background=>$config{ColorBG});
my $comS = $picLB->ItemStyle('text', -anchor=>'nw', -foreground=>$config{ColorComm}, -background=>$config{ColorBG2});
my $exifS = $picLB->ItemStyle('text', -anchor=>'nw', -foreground=>$config{ColorEXIF}, -background=>$config{ColorBG2});
my $dirS = $picLB->ItemStyle('text', -anchor=>'nw', -foreground=>$config{ColorDir}, -background=>$config{ColorBG2});
toggleHeaders();
# mouse and button bindings
# key-desc,double click,show picture in own window
#$picLB->bind('<Double-Button-1>', sub { showPicInOwnWin(); } ); # does not always work ???
# key-desc,MiddleMouseButton,show picture in own window
$picLB->bind('<ButtonPress-2>', sub {
return if (!$picLB->info('children'));
showPicInOwnWin(getNearestItem($picLB));
} );
# experimental stuff
#$top->bind('<ButtonPress-4>', sub { print "Mouse Press But 4\n"; } );
#$top->bind('<ButtonPress-5>', sub { print "Mouse Press But 5\n"; } );
# Define the source for drags.
# Drags are started while pressing the Ctrl key and the left mouse button and moving the
# mouse. Then the StartDrag callback is executed.
my $token;
# key-desc,S-C-LeftBut,(Shift-Ctrl-LeftMouseButton) drag and drop pictures to a dir
$token = $picLB->DragDrop
(-event => '<Shift-Control-B1-Motion>',
-sitetypes => 'Local',
-startcommand => sub { dragFromPicLB($token) },
);
# Define the target for drops.
$dirtree->DropSite
(-droptypes => 'Local',
-dropcommand => sub { dropToDirTree(); },
);
$picLB->bind('<ButtonPress-1>', sub {
# saved here for undo function
@savedselection2 = @savedselection;
@savedselection = $picLB->info('selection');
} );
$picLB->bind('<ButtonRelease-1>', sub { showSelectedPic(); } );
$picLB->bind('<ButtonPress-3>', sub {
if ($slideshow == 1) { $slideshow = 0; slideshow(); } # switch slideshow off
$thumbMenu->Popup(-popover => "cursor", -popanchor => "nw");
} );
$c->CanvasBind('<ButtonPress-3>', sub {
if ($slideshow == 1) { $slideshow = 0; slideshow(); } # switch slideshow off
$picMenu->Popup(-popover => "cursor", -popanchor => "nw");
} );
# key-desc,b,show backup picture (if available)
$top->bind('<Key-b>', sub { showBackup(); });
# key-desc,w,show window list
$top->bind('<Key-w>', sub { showWindowList(); });
# key-desc,Ctrl-r,rebuild selected thumbnails
$top->bind('<Control-r>', sub { rebuildThumbs(); } );
# key-desc,Ctrl-s,search database
$top->bind('<Control-s>', sub { searchMetaInfo(); } );
# key-desc,o,open a new directory
$top->bind('<Key-o>', sub { openDir(); } );
# key-desc,h,show hot directories
$top->bind('<Key-h>', sub { $dirMenu->Popup(-popover => "cursor", -popanchor => "nw"); } );
# key-desc,u,update (reread directory and Image)
$top->bind('<Key-u>', sub { updateThumbsPlus(); } );
# key-desc,F05,smart update (add new and remove deleted images)
$top->bind('<Key-F5>', sub { smart_update(); } );
# key-desc,U,update image
$top->bind('<Key-U>', sub {
deleteCachedPics($actpic);
showPic($actpic);
} );
# layouts
# key-desc,l,cycle layout of directory thumbnail and picture frame
$top->bind('<Key-l>', sub { $config{Layout}++; layout(1); } );
# key-desc,F01,toggle show menu bar
$top->bind('<Key-F1>', sub { $config{ShowMenu} = $config{ShowMenu} ? 0 : 1; showHideFrames(); } );
# key-desc,F02,toggle show status bar
$top->bind('<Key-F2>', sub { $config{ShowInfoFrame} = $config{ShowInfoFrame} ? 0 : 1; showHideFrames(); } );
# key-desc,F03,toggle show EXIF box
$top->bind('<Key-F3>', sub { $config{ShowEXIFField} = $config{ShowEXIFField} ? 0 : 1; showHideFrames(); } );
# key-desc,F04,toggle show comment box
$top->bind('<Key-F4>', sub { $config{ShowCommentField} = $config{ShowCommentField} ? 0 : 1; showHideFrames(); } );
# key-desc,F06,layout 0: directories-thumbnails-picture (25-30-45)
$top->bind('<Key-F6>', sub { $config{Layout} = 0 ; layout(1);} );
# key-desc,F07,layout 1: directories-thumbnails (20-80-0)
$top->bind('<Key-F7>', sub { $config{Layout} = 1 ; layout(1);} );
# key-desc,F08,layout 2: thumbnails (0-100-0)
$top->bind('<Key-F8>', sub { $config{Layout} = 2 ; layout(1);} );
# key-desc,F09,layout 3: thumbnails-picture (0-50-50)
$top->bind('<Key-F9>', sub { $config{Layout} = 3 ; layout(1);} );
# key-desc,F10,layout 4: picture (0-0-100)
$top->bind('<Key-F10>', sub { $config{Layout} = 4 ; layout(1); Tk->break; # stop default binding of this key
} );
# key-desc,F11,fullscreen mode
$top->bind('<Key-F11>', sub { topFullScreen(); });
addCommonKeyBindings($top, $picLB);
# key-desc,Delete,delete selected pictures to trash
$top->bind('<Key-Delete>', sub { deletePics($picLB, TRASH); } );
# key-desc,Shift-Delete,remove selected pictures
$top->bind('<Shift-Delete>', sub { deletePics($picLB, REMOVE); } );
# key-desc,q,quit mapivi
$top->bind('<Key-q>', sub { quitMain(); } );
# key-desc,R,smart rename selected pictures (e.g to EXIF date)
$top->bind('<Key-R>', sub { renameSmart($picLB); } );
# key-desc,F12,quit mapivi
$top->bind('<Key-F12>', sub { quitMain(); } );
# show picture, EXIF, Comment and IPTC info
# key-desc,c,display JPEG comment
$top->bind('<Key-c>', sub { showComment(); } );
# key-desc,t,display embedded EXIF thumbnail
$top->bind('<Key-t>', sub { showEXIFThumb(); } );
# key-desc,Ctrl-v,toggle verbose output
$top->bind('<Control-v>', sub { toggle(\$verbose); $userinfo = "verbose switched to $verbose"; $userInfoL->update;
} );
# key-desc,Ctrl-c,crop (lossless)
$top->bind('<Control-c>', sub { crop($picLB); } );
# key-desc,Ctrl-b,add border and/or copyright
$top->bind('<Control-b>', sub { addDecoration(); } );
# key-desc,Ctrl-q,change size/quality
$top->bind('<Control-q>', sub { changeSizeQuality(); } );
# key-desc,Ctrl-o,open options dialog
$top->bind('<Control-o>', sub { options(); } );
# key-desc,d,display picture in own window
#$picLB->bind('<Key-d>', sub { showPicInOwnWin(); } );
$picLB->bind('<Key-d>', sub {
my @sellist = getSelection($picLB);
return unless checkSelection($top, 1, 0, \@sellist);
show_multiple_pics(\@sellist, 0); # todo : get nearset pic instead of first (0)
} );
$dirtree->bind('<Key-d>', sub {
my $dir = getRightDir();
my @list = getPics($dir, WITH_PATH);
sortPics($config{SortBy}, $config{SortReverse}, \@list);
showThumbList(\@list, $dir); });
$dirtree->bind('<ButtonPress-2>', sub {
$dirtree->selectionClear();
$dirtree->selectionSet(getNearestItem($dirtree));
my $dir = getRightDir();
my @list = getPics($dir, WITH_PATH);
sortPics($config{SortBy}, $config{SortReverse}, \@list);
showThumbList(\@list, $dir); });
# key-desc,Ctrl-e,edit picture in GIMP
$top->bind('<Control-e>', sub { GIMPedit(); } );
# key-desc,Ctrl-f,apply a filter to the picture
$top->bind('<Control-f>', sub { filterPic(); } );
# key-desc,Ctrl-h,display picture in original size (100% zoom)
$top->bind('<Control-h>', sub { zoom100(); });
# key-desc,H,display picture histogram
$top->bind('<H>', sub { showHistogram($picLB); });
# key-desc,z,display picture in original size (100% zoom)
$top->bind('<Key-z>', sub { zoom100(); });
# key-desc,9,rotate picture(s) 90 degrees clockwise
$top->bind('<Key-9>', sub { rotate(90); });
# key-desc,8,rotate picture(s) 180 degrees clockwise
$top->bind('<Key-8>', sub { rotate(180); });
# key-desc,7,rotate picture(s) 270 degrees clockwise
$top->bind('<Key-7>', sub { rotate(270); });
# key-desc,0,auto rotate picture(s) (EXIF orientation)
$top->bind('<Key-0>', sub { rotate("auto"); });
# key-desc,f,fit picture in canvas (auto zoom)
$top->bind('<Key-f>', sub { fitPicture(); });
# key-desc,Escape,iconify the main window/close any other window
$top->bind('<Key-Escape>', sub { $top->iconify; } );
# thumbnail navigation
# key-desc,Space,display the next picture
$top->bind('<Key-space>', sub {
return if (stillBusy()); # block, until last picture is loaded
if ($slideshow == 1) { $slideshow = 0; slideshow(); } # switch slideshow off
showPic(nextPic($actpic));
} );
# key-desc,S,display the next selected picture
$top->bind('<S>', sub {
return if (stillBusy()); # block, until last picture is loaded
if ($slideshow == 1) { $slideshow = 0; slideshow(); } # switch slideshow off
my @sellist = $picLB->info('selection');
showPic(nextSelectedPic($actpic));
reselect($picLB, @sellist);
} );
# key-desc,Page-Down,display the next picture
$top->bind('<Key-Next>', sub {
return if (stillBusy()); # block, until last picture is loaded
if ($slideshow == 1) { $slideshow = 0; slideshow(); } # switch slideshow off
showPic(nextPic($actpic));} );
# key-desc,Backspace,display the previous picture
$top->bind('<Key-BackSpace>', sub {
return if (stillBusy()); # block, until last picture is loaded
if ($slideshow == 1) { $slideshow = 0; slideshow(); } # switch slideshow off
showPic(prevPic($actpic));} );
# key-desc,Page-Up,display the previous picture
$top->bind('<Key-Prior>', sub {
return if (stillBusy()); # block, until last picture is loaded
if ($slideshow == 1) { $slideshow = 0; slideshow(); } # switch slideshow off
showPic(prevPic($actpic));} );
# key-desc,Home,display the first picture
$top->bind('<Key-Home>', sub {
return if (stillBusy()); # block, until last picture is loaded
if ($slideshow == 1) { $slideshow = 0; slideshow(); } # switch slideshow off
my @childs = $picLB->info('children');
return unless (@childs);
showPic($childs[0]); } );
# key-desc,End,display the last picture
$top->bind('<Key-End>', sub {
return if (stillBusy()); # block, until last picture is loaded
if ($slideshow == 1) { $slideshow = 0; slideshow(); } # switch slideshow off
my @childs = $picLB->info('children');
return unless (@childs);
showPic($childs[-1]);
});
# key-desc,Ctrl-g,goto picture
$top->bind('<Control-g>', sub { gotoPic($picLB); } );
# key-desc,Return,display the selected picture
$picLB->bind('<Key-Return>', sub { showSelectedPic(); } );
# key-desc,s,start/stop slideshow
$top->bind('<Key-s>', sub {
if ($slideshow == 0) { $slideshow = 1; } else { $slideshow = 0; }
slideshow();
} );
# key-desc,-,zoom out or faster slideshow
$top->bind('<Key-minus>', sub {
if ($slideshow) {
$config{SlideShowTime}-- if ($config{SlideShowTime} >= 1);
$userinfo = "slideshow time: ".$config{SlideShowTime}." sec"; $userInfoL->update;
}
else {
zoomStep(-1);
}
} );
# key-desc,+,zoom in or slideshow slower
$top->bind('<Key-plus>', sub {
if ($slideshow) {
$config{SlideShowTime}++ if ($config{SlideShowTime} < 30);
$userinfo = "slideshow time: ".$config{SlideShowTime}." sec"; $userInfoL->update;
}
else {
zoomStep(1);
}
});
# support drag and drop from extern
# this enables dropping pictures and directories on the mapivi window
if ($Tk::VERSION < 804) {
$top->DropSite
(-dropcommand => \&dragAndDropExtern,
-droptypes => ($^O eq 'MSWin32' ? 'Win32' : ['KDE', 'XDND', 'Sun'])
);
}
else {
$top->DropSite
(#-entercommand => sub { print "DragAndDrop - Entercommand\n";},
-dropcommand => \&dragAndDropExtern,
-droptypes => ($^O eq 'MSWin32' ? 'Win32' : ['XDND', 'Sun']) # KDEsite was removed in Tk804.026
);
}
startup();
# show all types of images supported by Tk::Image
#my @types = $top->imageTypes;printlist(@types);
# Perl/Tk-Mainloop
$top->MainLoop;
# override the Motion sub of listbox (extended selection mode)
# seems not to help with the drag and drop problem
#sub Tk::HList::Motion {
#sub Tk::Listbox::Motion {
# return;
#}
##############################################################
# stillBusy - block some keys, untill loading of pictures is finished
##############################################################
sub stillBusy {
if ($showPicInAction) {
beep();
$userinfo = "busy (loading pic), please retry later"; $userInfoL->update;
return 1;
}
return 0;
}
##############################################################
# makeThumbListbox - create a scrolled HList for thumbnail display
##############################################################
sub makeThumbListbox {
my $widget = shift;
my $lb = $widget->Scrolled('HList',
-header => 1,
-separator => ';', # todo here we hope that ; will never be in a directory or file name
-pady => 0,
-columns => 6,
-scrollbars => 'osoe',
-selectmode => 'extended',
-background => $config{ColorBG},
-width => 30,
-height => 200,
)->pack(-expand => 1, -fill => 'both');
bindMouseWheel($lb);
my $colNr = 0;
if ($resizeAvail) {
my $thumbH = $lb->ResizeButton(-text => 'Thumbnail',
-relief => 'flat', -pady => 0,-anchor => 'w',
-widget => \$lb, -column => $colNr);
$lb->{thumbcol} = $colNr;
$lb->header('create', $colNr++, -itemtype => 'window', -widget => $thumbH, -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
my $sizeH = $lb->ResizeButton(-text => 'File',
-relief => 'flat', -pady => 0,-anchor => 'w',
-command => sub {
return unless ($lb == $picLB);
if ($config{SortBy} eq 'name') {
toggle(\$config{SortReverse});
} else {
$config{SortReverse} = 0;
}
$config{SortBy} = 'name';
updateThumbsPlus(); },
-widget => \$lb, -column => $colNr);
$lb->{filecol} = $colNr;
$lb->header('create', $colNr++, -itemtype => 'window', -widget => $sizeH, -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
my $iptcH = $lb->ResizeButton(-text => 'IPTC',
-relief => 'flat', -pady => 0,-anchor => 'w',
-command => sub {
return unless ($lb == $picLB);
if ($config{SortBy} eq 'urgency') {
toggle(\$config{SortReverse});
} else {
$config{SortReverse} = 0;
}
$config{SortBy} = 'urgency';
updateThumbsPlus(); },
-widget => \$lb, -column => $colNr);
$lb->{iptccol} = $colNr;
$lb->header('create', $colNr++, -itemtype => 'window', -widget => $iptcH, -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
my $comH = $lb->ResizeButton(-text => 'Comments',
-relief => 'flat', -pady => 0,-anchor => 'w',
-widget => \$lb, -column => $colNr);
$lb->{comcol} = $colNr;
$lb->header('create', $colNr++, -itemtype => 'window', -widget => $comH, -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
my $exifH = $lb->ResizeButton(-text => 'EXIF',
-relief => 'flat', -pady => 0,-anchor => 'w',
-command => sub {
return unless ($lb == $picLB);
$config{SortBy} = 'exifdate';
toggle(\$config{SortReverse});
updateThumbsPlus(); },
-widget => \$lb, -column => $colNr);
$lb->{exifcol} = $colNr;
$lb->header('create', $colNr++, -itemtype => 'window', -widget => $exifH, -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
my $dirH = $lb->ResizeButton(-text => 'Folder',
-relief => 'flat', -pady => 0,-anchor => 'w',
-command => sub {
return unless ($lb == $picLB);
if ($config{SortBy} eq 'name') {
toggle(\$config{SortReverse});
} else {
$config{SortReverse} = 0;
}
$config{SortBy} = 'name';
updateThumbsPlus(); },
-widget => \$lb, -column => $colNr);
$lb->{dircol} = $colNr;
$lb->header('create', $colNr, -itemtype => 'window', -widget => $dirH, -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
}
else { # no resizeAvail
$lb->{thumbcol} = $colNr;
$lb->header('create', $colNr++, -text => 'Thumbnail', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
#$lb->{namecol} = $colNr;
#$lb->header('create', $colNr++, -text => 'Name', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
$lb->{filecol} = $colNr;
$lb->header('create', $colNr++, -text => 'File', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
$lb->{iptccol} = $colNr;
$lb->header('create', $colNr++, -text => 'IPTC', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
$lb->{comcol} = $colNr;
$lb->header('create', $colNr++, -text => 'Comments', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
$lb->{exifcol} = $colNr;
$lb->header('create', $colNr++, -text => 'EXIF', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
$lb->{dircol} = $colNr;
$lb->header('create', $colNr, -text => 'Folder', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
}
return $lb;
}
##############################################################
# addCommonKeyBindings - add key shortcuts to a widget
##############################################################
sub addCommonKeyBindings {
my $bind_w = shift; # widget to bind keys to
my $lb_w = shift; # thumbnail listbox to use
# key-desc,a,add a JPEG comment
$bind_w->bind('<Key-a>', sub { addComment($lb_w); } );
# key-desc,e,edit a JPEG comment
$bind_w->bind('<Key-e>', sub { editComment($lb_w); } );
# key-desc,v,open picture in external viewer
$bind_w->bind('<Key-v>', sub { openPicInViewer($lb_w); } );
# key-desc,r,rename selected pictures
$bind_w->bind('<Key-r>', sub { renamePic($lb_w); } );
# key-desc,x,display embedded EXIF data
$bind_w->bind('<Key-x>', sub { displayEXIFData($lb_w); } );
# key-desc,Ctrl-a,select all pictures
$bind_w->bind('<Control-a>', sub { selectAll($lb_w); } );
# key-desc,i,display IPTC data
$bind_w->bind('<Key-i>', sub { displayIPTCData($lb_w); } );
# key-desc,Ctrl-i,edit IPTC data
$bind_w->bind('<Control-i>', sub { editIPTC($lb_w); } );
# key-desc,Ctrl-p,copy to print
$bind_w->bind('<Control-p>', sub { copyToPrint($lb_w); } );
# key-desc,Ctrl-l,show selected thumbnails on light table
$bind_w->bind('<Control-l>', sub { light_table_add_from_lb($lb_w); } );
# key-desc,Ctrl-t,add/remove categories
$bind_w->bind('<Control-t>', sub { editIPTCCategories($lb_w); } );
# key-desc,Ctrl-k,add/remove keywords
$bind_w->bind('<Control-k>', sub { editIPTCKeywords($lb_w); } );
# key-desc,Ctrl-F01,set IPTC urgency to 1 - high
$bind_w->bind('<Control-F1>', sub { setIPTCurgency($lb_w, 1); } );
# key-desc,Ctrl-F02,set IPTC urgency to 2
$bind_w->bind('<Control-F2>', sub { setIPTCurgency($lb_w, 2); } );
# key-desc,Ctrl-F03,set IPTC urgency to 3
$bind_w->bind('<Control-F3>', sub { setIPTCurgency($lb_w, 3); } );
# key-desc,Ctrl-F04,set IPTC urgency to 4
$bind_w->bind('<Control-F4>', sub { setIPTCurgency($lb_w, 4); } );
# key-desc,Ctrl-F05,set IPTC urgency to 5 - normal
$bind_w->bind('<Control-F5>', sub { setIPTCurgency($lb_w, 5); } );
# key-desc,Ctrl-F06,set IPTC urgency to 6
$bind_w->bind('<Control-F6>', sub { setIPTCurgency($lb_w, 6); } );
# key-desc,Ctrl-F07,set IPTC urgency to 7
$bind_w->bind('<Control-F7>', sub { setIPTCurgency($lb_w, 7); } );
# key-desc,Ctrl-F08,set IPTC urgency to 8 - low
$bind_w->bind('<Control-F8>', sub { setIPTCurgency($lb_w, 8); } );
# key-desc,Ctrl-F09,set IPTC urgency to 0 - none
$bind_w->bind('<Control-F9>', sub { setIPTCurgency($lb_w, 0); } );
# key-desc,Ctrl-F10,remove IPTC urgency flag
$bind_w->bind('<Control-F10>', sub { setIPTCurgency($lb_w, 9); } );
}
##############################################################
# startup - shows the given pic in the canvas
##############################################################
sub startup {
$picLB->focus;
if ($config{NrOfRuns} == 0) {
#whereIsPerl();
makeConfigDir();
copyConfigPics();
copyOtherStuff();
copyPlugIns();
}
$config{NrOfRuns}++;
gratulation() if (($config{NrOfRuns} % 1000 == 0) and ($config{NrOfRuns} > 0)); # modulo
# create menus
createMenubar();
createDirMenu();
createThumbMenu();
createPicMenu();
checkSystem();
startStopClock();
# migrate from the old file name "dirInfo" to "SearchDataBase"
if (-f "$configdir/dirInfo") {
if (-f "$configdir/SearchDataBase") {
warn "Mapivi: there is something wrong! I found a file \"dirInfo\" and \"SearchDataBase\" in $configdir\n";
}
else {
if (rename("$configdir/dirInfo", "$configdir/SearchDataBase")) {
print "Mapivi: I have renamed the file \"dirInfo\" to \"SearchDataBase\" in $configdir\n";
}
else {
warn "Mapivi: error renaming \"dirInfo\" to \"SearchDataBase\" in $configdir: $!\n";
}
}
}
# try to get the saved database (meta info hash)
if ($config{SaveDatabase} and -f "$configdir/SearchDataBase") {
my $hashRef = retrieve("$configdir/SearchDataBase");
warn "could not retrieve searchDB" unless defined $hashRef;
%searchDB = %{$hashRef};
}
# try to get the saved hotlist directories
if (-f "$configdir/hotlist") {
my $hashRef = retrieve("$configdir/hotlist");
warn "could not retrieve hotlist" unless defined $hashRef;
%dirHotlist = %{$hashRef};
}
# try to get the saved directory properties
if (-f "$configdir/dirProperties") {
my $hashRef = retrieve("$configdir/dirProperties");
warn "could not retrieve dirProperties" unless defined $hashRef;
%dirProperties = %{$hashRef};
}
# try to get the saved ignore keywords
if (-f "$configdir/keywords_ignore") {
my $hashRef = retrieve("$configdir/keywords_ignore");
warn "could not retrieve keywords_ignore" unless defined $hashRef;
%ignore_keywords = %{$hashRef};
}
if (MatchEntryAvail) {
# try to get the saved entry values
if (-f $file_Entry_values) {
my $hashRef = retrieve($file_Entry_values);
warn "could not retrieve $file_Entry_values" unless defined $hashRef;
%entryHistory = %{$hashRef};
}
}
updateDirMenu();
if (-f $config{DefaultThumb}) {
$defaultthumbP = $picLB->Photo(-format => "jpeg", -file => $config{DefaultThumb}, -gamma => $config{Gamma});
}
else {
warn "Mapivi info: no file ".$config{DefaultThumb}." found! (Please copy any thumbnail to this folder and rename it ".basename($config{DefaultThumb}).")\n";
undef $defaultthumbP;
}
layout(0);
# remove splash screen
$splash->Destroy if $splash;
# show main window
$top->deiconify;
$top->raise;
setDirProperties();
updateThumbs();
setAdjusterPos();
showPic($actpic) if (defined $actpic and $actpic ne "");
selectDirInTree($actdir);
checkTrash();
if ($EvilOS) {
warn "Win32::Process module not available\n" unless (Win32ProcAvail);
}
$top->update();
}
##############################################################
# testSuite - automated regression tests for mapivi
##############################################################
sub testSuite {
my @childs = $picLB->info('children');
if (@childs < 2) {
$top->messageBox(-icon => 'error', -message => "test suite must be started in a directory with at least two picture!",
-title => "test suite", -type => 'OK');
return;
}
my $startdir = dirname($childs[0]);
my $rc = $top->messageBox(-icon => 'question', -message => "Start some internal test with ".scalar @childs." pictures in $actdir.\nTest results will go to STDOUT (shell/DOS-box where you've started Mapivi).\nOk to go on?",
-title => "Start test suite?", -type => 'OKCancel');
return unless ($rc =~ m/Ok/i);
# test single selection
print "testSuite: testing single selection\n";
foreach (@childs) {
selectThumb($picLB, $_);
my @sel = $picLB->info('selection');
print "testSuite: *** wrong selection\n" if (@sel != 1);
print "testSuite: *** wrong selection\n" if ($sel[0] ne $_);
}
# test all selection
print "testSuite: testing all selection\n";
selectAll($picLB);
my @sel = $picLB->info('selection');
print "testSuite: *** wrong selection\n" if (@sel != @childs);
my $dir1 = "$trashdir/testdir1";
my $dir2 = "$trashdir/testdir2";
# cleanup
foreach ($dir1, $dir2) {
print "testSuite: removing temp dir $_\n";
rmtree($_, 0, 1) if (-d $_); # dir, 0 = no message for each file, 1 = skip write protected files
}
foreach ($dir1, $dir2) { unless (makeDir($_, NO_ASK)) { print "testSuite: could not create $_\n"; } }
print "testSuite: temp dirs created\n";
foreach ($dir1, $dir2) { unless (-d $_) { warn "testSuite: *** $_ not found!\n"; return; } }
# test copy actdir -> dir1
print "testSuite: testing copy all\n";
selectAll($picLB);
copyPics($dir1, COPY, $picLB, @childs);
openDirPost($dir1);
my @childs1 = $picLB->info('children');
if (@childs1 != @childs) {
warn "testSuite: *** copy error ".scalar @childs1." ne ".scalar @childs."\n";
}
foreach my $i (0 .. $#childs1) {
# todo this will fail, if files are sorted by file date (copy date)
if (basename($childs[$i]) ne basename($childs1[$i])) {
warn "testSuite: *** copy error $childs[$i] ne $childs1[$i]\n";
}
}
# copy first pic dir1 -> dir2
print "testSuite: testing copy first\n";
selectThumb($picLB, $childs1[0]);
@sel = $picLB->info('selection');
if (@sel ne 1) {
warn "testSuite: *** sel error ".scalar @sel." ne 1\n";
}
copyPics($dir2, COPY, $picLB, @sel);
openDirPost($dir2);
my @childs2 = $picLB->info('children');
if (@childs2 ne 1) {
warn "testSuite: *** copy error ".scalar @childs2." ne 0\n";
}
if (basename($childs1[0]) ne basename($childs2[0])) {
warn "testSuite: *** copy error $childs[0] ne $childs1[0]\n";
}
# clean dir2
selectAll($picLB);
deletePics($picLB, TRASH);
# copy last pic dir1 -> dir2
print "testSuite: testing copy last\n";
openDirPost($dir1);
selectThumb($picLB, $childs1[-1]);
@sel = $picLB->info('selection');
if (@sel ne 1) {
warn "testSuite: *** sel error ".scalar @sel." ne 1\n";
}
copyPics($dir2, COPY, $picLB, @sel);
openDirPost($dir2);
@childs2 = $picLB->info('children');
if (@childs2 ne 1) {
warn "testSuite: *** copy error ".scalar @childs2." ne 0\n";
}
if (basename($childs1[-1]) ne basename($childs2[-1])) {
warn "testSuite: *** copy error $childs[-1] ne $childs1[-1]\n";
}
# clean dir2
print "testSuite: cleaning dir\n";
selectAll($picLB);
deletePics($picLB, TRASH);
# move all pics dir1 -> dir2
print "testSuite: testing move all\n";
openDirPost($dir1);
selectAll($picLB);
@sel = $picLB->info('selection');
movePics($dir2, $picLB, @sel);
openDirPost($dir2);
@childs2 = $picLB->info('children');
if (@childs2 != @childs1) {
warn "testSuite: *** move error ".scalar @childs2." ne ".scalar @childs1."\n";
}
# move first and last pics dir2 -> dir1
print "testSuite: testing move first and last\n";
selectThumb($picLB, $childs2[0]);
@sel = $picLB->info('selection');
movePics($dir1, $picLB, @sel);
selectThumb($picLB, $childs2[-1]);
@sel = $picLB->info('selection');
movePics($dir1, $picLB, @sel);
openDirPost($dir1);
@childs1 = $picLB->info('children');
if (@childs1 != 2) {
warn "testSuite: *** move error ".scalar @childs1." ne 2\n";
}
# test backup dir1
print "testSuite: testing backup all\n";
selectAll($picLB);
@sel = $picLB->info('selection');
copyPics($dir1, BACKUP, $picLB, @sel);
@childs1 = $picLB->info('children');
if (@childs1 != 4) {
warn "testSuite: *** backup error ".scalar @childs1." ne 4\n";
}
# test delete backups dir1
selectBak();
@sel = $picLB->info('selection');
warn "testSuite: *** sel error ".scalar @sel." ne 2\n" if (@sel != 2);
deletePics($picLB, TRASH);
@childs1 = $picLB->info('children');
warn "testSuite: *** delete backup error ".scalar @childs1." ne 2\n" if (@childs1 != 2);
# move the two pics back dir1 -> dir2
print "testSuite: testing move back\n";
selectAll($picLB);
@sel = $picLB->info('selection');
warn "testSuite: *** sel error ".scalar @sel." ne 2\n" if (@sel != 2);
movePics($dir2, $picLB, @sel);
@childs1 = $picLB->info('children');
if (@childs1 != 0) {
warn "testSuite: *** delete backup error ".scalar @childs1." ne 0\n";
}
# check if nothing is lost
openDirPost($dir2);
@childs2 = $picLB->info('children');
warn "testSuite: *** we lost some pics ".scalar @childs2." ne ".scalar @childs."\n" if (@childs2 != @childs);
warn "testSuite: move ".scalar @childs2." = ".scalar @childs."?\n";
# link all pics dir2 -> dir1
print "testSuite: testing link all\n";
openDirPost($dir2);
@childs2 = $picLB->info('children');
selectAll($picLB);
@sel = $picLB->info('selection');
linkPics($dir1, @sel);
@childs2 = $picLB->info('children');
openDirPost($dir1);
@childs1 = $picLB->info('children');
warn "testSuite: link ".scalar @childs2." = ".scalar @childs1."?\n";
if (@childs2 != @childs1) {
warn "testSuite: *** link error ".scalar @childs2." ne ".scalar @childs1."\n";
}
# clean dir1
print "testSuite: cleaning dir\n";
selectAll($picLB);
deletePics($picLB, TRASH);
# test comments first pic
print "testSuite: testing comment single\n";
my $testcom = "xxxcccxxx1234ABC";
openDirPost($dir2);
@childs2 = $picLB->info('children');
selectThumb($picLB, $childs2[0]);
@sel = $picLB->info('selection');
addCommentToPic($testcom, $sel[0], TOUCH);
my $com = getComment($sel[0], LONG);
if ($com !~ m/.*$testcom.*/) {
warn "testSuite: *** comment $com does not contain $testcom\n";
}
# test comments join
print "testSuite: testing comments remove and join\n";
# add a comment to all pics
selectAll($picLB);
@sel = $picLB->info('selection');
addCommentToPic($testcom, $_, TOUCH) foreach (@sel);
# remove the comments from the last pic, so we have at least one example for no comment
selectThumb($picLB, $childs2[-1]);
removeAllComments(NO_ASK);
warn "testSuite: *** remove comment error\n" if (scalar getComments($childs2[-1]) != 0);
selectAll($picLB);
my %comNr; # hash: key:dpic value:nr of comments
foreach (@childs2) {
my @com = getComments($_);
$comNr{$_} = scalar @com;
}
joinComments(NO_ASK);
foreach (@childs2) {
my @com = getComments($_);
my $nr = $comNr{$_};
$nr = 1 if ($nr >= 2);
print $comNr{$_}." -> $nr act: ".scalar @com."($#com)\n" if $verbose;
warn "testSuite: *** comment join error\n" if ($nr != @com);
}
# test rotate
print "testSuite: testing rotate single\n";
selectThumb($picLB, $childs2[0]);
rotate(90);
rotate(270);
my $size = getFileSize($childs2[0]);
rotate(90);
rotate(270);
warn "testSuite: *** rotate single file mismatch!\n" if ($size != getFileSize($childs2[0]));
@childs2 = $picLB->info('children');
warn "testSuite: *** rotate all 90 ".scalar @childs2." ne ".scalar @childs."\n" if (@childs2 != @childs);
##################################################
print "testSuite: going back to start dir\n";
openDirPost($startdir);
changeDir($startdir); # linking files changes the cwd so we must move back before we try to remove the dirs
# end
$top->messageBox(-icon => 'info', -message => "test suite finished",
-title => "test suite", -type => 'OK');
# cleanup
foreach ($dir1, $dir2) {
print "testSuite: removing temp dir $_\n";
rmtree($_, 0, 1) if (-d $_); # dir, 0 = no message for each file, 1 = skip write protected files
}
}
##############################################################
# whereIsPerl - adjust the first line of this program according
# to the path to perl
# start mapivi the first time with:
# > perl mapivi
# and then just a:
# > mapivi
# will do it.
##############################################################
sub whereIsPerl {
return if $EvilOS;
# look for perl
my $rc = `which perl`; # run shell command which
chomp $rc;
print "whereIsPerl: which perl: $rc\n" if $verbose;
if ($rc =~ m/^(no perl)/i) {
warn "whereIsPerl: no perl found!";
return;
}
unless (-w $0) {
warn "whereIsPerl: could not open $0 for write access!";
return;
}
my $file;
# look what's in the first line of this program
if (!open($file, "<$0")) {
warn "whereIsPerl: could not open $0 for read access!: $!";
return;
}
my @lines = <$file>; # read the complete into the array lines
close $file;
my $firstline = "#!$rc -w\n"; # this should be the first line
print "whereIsPerl: first line: --".$lines[0]."--\n" if $verbose; # this is the first line
if ($lines[0] ne $firstline) { # compare them
$lines[0] = $firstline;
} else {
print "whereIsPerl: nothing to do, first line is ok!" if $verbose;
return;
}
# first line has changed
if (!open($file, ">$0")) {
warn "whereIsPerl: could not open $0 for write access!: $!";
return;
}
print $file @lines; # write everything back
close $file;
}
##############################################################
# addToCachedPics - add a image (path and file name) to
# the cachedPics list
# if it is already in the list, move it to
# the end
##############################################################
sub addToCachedPics {
my $dpic = shift;
for my $t ( 0 .. $#cachedPics ) {
if ($cachedPics[$t] eq $dpic) {
splice @cachedPics, $t, 1; # remove it from list
last;
}
}
push @cachedPics, $dpic; # add item to the list
print "addToCachedPics: $dpic list:$#cachedPics\n" if $verbose;
checkCachedPics();
}
##############################################################
# checkCachedPics - check if the cachedPics list contains more
# images than allowed, remove the oldest
# if necessary
##############################################################
sub checkCachedPics {
# first check if all entries are valid pictures
my @rm_list;
for my $t ( 0 .. $#cachedPics ) {
push @rm_list, $t unless (-f $cachedPics[$t]);
}
# remove the invalid pictures
for my $t (reverse @rm_list) {
my $dpic = $cachedPics[$t];
next unless ($dpic);
print "checkCachedPics: removing not existing $dpic\n" if $verbose;
$c->delete('withtag', $dpic); # remove it from the canvas
$photos{$dpic}->delete if $photos{$dpic}; # delete the photo object
delete $photos{$dpic}; # delete the hash item
splice @cachedPics, $t, 1; # remove not existing pictures it from list
}
# short the list, if it is to long
while (@cachedPics > $config{MaxCachedPics}) {
if ($actpic eq $cachedPics[0]) {
print "this is the aktual pic - skipping!\n" if $verbose;
next; # todo this was last. what is right???
}
my $dpic = shift @cachedPics; # get the oldest
print "checkCachedPics: removing old $dpic list:$#cachedPics\n" if $verbose;
$c->delete('withtag', $dpic); # remove it from the canvas
$photos{$dpic}->delete if $photos{$dpic}; # delete the photo object
delete $photos{$dpic}; # delete the hash item
}
#printlist(@cachedPics);
# just for safety
warn "*** checkCachedPics: photos hash contains more than MaxCachedPics pics (".scalar @cachedPics."(".scalar(keys(%photos)).") > ".$config{MaxCachedPics}.")" if (keys %photos > $config{MaxCachedPics});
}
##############################################################
# renameCachedPic - rename a list item
##############################################################
sub renameCachedPic($$) {
my $old = shift;
my $new = shift;
return unless (defined $photos{$old});
# open new photo object
$photos{$new} = $top->Photo;
$photos{$new}->blank;
$photos{$new}->copy($photos{$old});
$c->delete('withtag', $old); # remove it from the canvas
$photos{$old}->delete if $photos{$old}; # delete the photo object
delete $photos{$old}; # delete the hash item
my $xoffset = 0; my $yoffset = 0;
$xoffset = int(($c->width - $photos{$new}->width) /2) if ($c->width > $photos{$new}->width);
$yoffset = int(($c->height - $photos{$new}->height)/2) if ($c->height > $photos{$new}->height);
# hide all items on the canvas
canvasHide();
# insert pic
my $id = $c->createImage($xoffset, $yoffset, -image => $photos{$new}, -tag => ["pic", $new], -anchor => "nw");
bindItem($id);
for my $t ( 0 .. $#cachedPics ) {
if ($cachedPics[$t] eq $old) {
$cachedPics[$t] = $new; # rename list item
}
}
print "renameCachedPic: $old -> $new\n" if $verbose;
checkCachedPics();
}
##############################################################
# deleteCachedPics - delete all or just one element(s)
# and photo objects of the cachedPics list
##############################################################
sub deleteCachedPics {
my $dpic = shift; # optional, if available this picture will be removed from the cachedPics list,
# if not available all elements will be deleted
if (defined($dpic) and isInList($dpic, \@cachedPics)) {
print "deleteCachedPics: delete single pic $dpic (".scalar @cachedPics.")\n" if $verbose;
$c->delete('withtag', $dpic); # remove it from the canvas
$photos{$dpic}->delete if $photos{$dpic}; # delete the photo object
delete $photos{$dpic}; # delete the hash item
#printlist(@cachedPics);
my @list = @cachedPics; # copy list
@cachedPics = (); # empty list
foreach my $i (reverse 0 .. $#list) {
unless ($list[$i] eq $dpic) {
print "deleteCachedPics: adding $list[$i]\n" if $verbose;
push @cachedPics, $list[$i];
}
}
}
else {
print "deleteCachedPics: delete all (".scalar @cachedPics.")\n" if $verbose;
foreach (@cachedPics) {
$c->delete('withtag', $_); # remove it from the canvas
$photos{$_}->delete if $photos{$_}; # delete the photo object
delete $photos{$_}; # delete the hash item
print "deleteCachedPics: deleting pic $_\n" if $verbose;
}
@cachedPics = (); # empty list
}
}
##############################################################
# showSelectedPic - displays the original picture of the
# selected thumbnail
##############################################################
sub showSelectedPic {
return if (stillBusy()); # block, until last picture is loaded
my @sellist = $picLB->info('selection');
# show index number in window
showNrOf();
return unless ($picLB->info('children'));
return if (@sellist > 1);
showPic($sellist[0]);
}
##############################################################
# showNrOf
##############################################################
sub showNrOf {
my @pics = $picLB->info('children');
my @sellist = $picLB->info('selection');
my $index = 0;
my $size = 0;
my $sizeStr = "";
if (@sellist >= 1) { # selection available
foreach (@pics) {
$index++;
last if ($_ eq $sellist[0]);
}
}
if (@sellist >= 2) { # more than one selected
foreach (@sellist) {
$size += getFileSize($_, NO_FORMAT);
}
$sizeStr = computeUnit($size) if $size;
$sizeStr = ", $sizeStr" if ($sizeStr ne "");
}
# show index number in window
$nrof = "$index/".@pics." (".@sellist."$sizeStr)";
}
##############################################################
# computeUnit - do a byte to kB or MB conversion
##############################################################
sub computeUnit {
my $size = shift;
my $sizeStr;
$size = int($size/1024);
if ($size > 1024) { # MegaByte
if ($size < (1024*100)) { # less than 100MB
$size = int($size*10/1024)/10; # e.g. 6.9MB or 23.4MB
}
else {
$size = int($size/1024); # e.g. 104MB
}
$sizeStr = "${size}MB";
}
else {
$sizeStr = "${size}kB";
}
return $sizeStr;
}
##############################################################
# showPic - displays the picture with the given index $i
##############################################################
sub showPic {
my $dpic = shift;
my @pics = $picLB->info('children');
return if ((!defined $dpic) or (!@pics));
if (@pics < 1) {
warn "no pictures in picLB!" if $verbose;
$userinfo = "no JPEG pictures in dir $actdir"; $userInfoL->update;
return;
}
$actpic = $dpic;
return if ((!defined $actpic) or ($actpic eq ""));
setTitle();
# show EXIF info and comment
showImageInfo($dpic);
my $pic = basename($dpic);
# select thumb in list even if picture is not shown (see "ShowPic" below)
selectThumb($picLB, $dpic);
return if (!$config{ShowPic});
# we are still not able to display RAW pictures (nefextract may be a solution for NEFs)
return if ($dpic =~ m/.*\.(nef)|(raw)$/i);
# do not show a picture if there is no picture frame
if (!$config{ShowPicFrame}) {
$userinfo = "$pic not displayed - no picture frame (hint: try F9 or F11)"; $userInfoL->update;
return;
}
# do not show a picture if the frame is very small
if ($mainF->width < 200) {
$userinfo = "$pic not displayed (picture frame too small)"; $userInfoL->update;
return;
}
$showPicInAction = 1;
$balloon->detach($c); # clear the balloon info for the actual pic (right frame of main window)
$userinfo = "loading $pic ..."; $userInfoL->update;
my @ids = $c->find('withtag', $dpic);
my $id;
if (@ids > 0) { # pic is already loaded
print "showPic: using cached pic $dpic\n" if $verbose;
# hide all items on the canvas
canvasHide();
$c->itemconfigure($ids[0], -state => 'normal');
$id = $ids[0];
$top->update();
}
else {
print "showPic: loading pic $dpic\n" if $verbose;
if (-f $dpic) { # load pic
$top->Busy();
#my $dpic_jpg = "";
#if ($dpic =~ m/(.*)\.nef$/i) {
# $dpic_jpg = $1.".jpg";
# print "$dpic is a NEF -> $dpic_jpg\n";
# my $command = "nefextract \"$dpic\" > \"$dpic_jpg\" ";
# execute($command);
#}
#if (-f $dpic_jpg) {
# load pic
# $photos{$dpic} = $top->Photo(-file => $dpic_jpg, -gamma => $config{Gamma});
# zoom pic
# autoZoom(\$photos{$dpic}, $dpic_jpg, $c->width, $c->height);
#}
#else {
# load pic
$photos{$dpic} = $top->Photo(-file => $dpic, -gamma => $config{Gamma});
# zoom pic
autoZoom(\$photos{$dpic}, $dpic, $c->width, $c->height) if (exists $photos{$dpic} and $config{AutoZoom});
#}
if (exists $photos{$dpic}) {
# center pic in canvas, only when it's smaller
my $xoffset = 0; my $yoffset = 0;
$xoffset = int(($c->width - $photos{$dpic}->width) /2) if ($c->width > $photos{$dpic}->width);
$yoffset = int(($c->height - $photos{$dpic}->height)/2) if ($c->height > $photos{$dpic}->height);
# hide all items on the canvas
canvasHide();
# insert pic
$id = $c->createImage($xoffset, $yoffset, -image => $photos{$dpic}, -tag => ['pic',"$dpic"], -anchor => 'nw');
bindItem($id);
addToCachedPics($dpic);
}
else {
$userinfo = "error loading $actpic"; $userInfoL->update;
warn "showPic: error loading $actpic!" if $verbose;
}
$top->Unbusy();
addToCachedPics($dpic);
}
else {
canvasHide();
warn "showPic: error $actpic not available!" if $verbose;
}
}
# show zoom info
showZoomInfo($dpic, $id);
showImageInfoCanvas($dpic);
increasePicPopularity($dpic);
updateOneRow($dpic, $picLB) if ($config{trackPopularity});
if ($config{ShowPicInfo}) {
# balloon info for displayed picture (right frame of the main window)
my $balloonmsg = makeBalloonMsg($dpic);
# bind the balloon to the canvas
$balloon->attach($c->Subwidget('canvas'), -balloonposition => 'mouse', -msg => {"pic" => $balloonmsg} );
}
else { $balloon->detach($c->Subwidget('canvas')); }
$userinfo = "$pic"; $userInfoL->update;
# adjust the canvas scrollbars
my ($x1, $y1, $x2, $y2) = $c->bbox($id);
if (defined($x1) and defined($x2) and defined($y1) and defined($y2)) {
$c->configure(-scrollregion => [0, 0, $x2-$x1, $y2-$y1]);
}
$top->Unbusy();
$showPicInAction = 0;
}
##############################################################
# canvasHide
##############################################################
sub canvasHide {
# hide all items on the canvas
$c->update();
#$c->itemconfigure('all', -state => 'hidden');
#$c->itemconfigure('withtag', 'pic', -state => 'hidden');
foreach ($c->find('withtag', 'pic')) {
$c->itemconfigure($_, -state => 'hidden');
}
}
##############################################################
# setTitle - set the window title and the userinfo to the
# actual pic
##############################################################
sub setTitle {
my $title = "";
$title = basename($actpic)." - " if ((defined $actpic) and ($actpic ne "") and (-f $actpic));
$title .= "MaPiVi $version";
# just a little gag
my (undef,undef,undef,$d,$m,$y,undef,undef, undef,undef) = localtime(time());
$y += 1900; $m++;
$title .= " - Happy new year $y!" if ($d == 1 and $m == 1);
$top->title($title);
$userinfo = basename($actpic); $userInfoL->update;
}
##############################################################
# increasePicPopularity
##############################################################
sub increasePicPopularity {
return unless ($config{trackPopularity});
my $dpic = shift;
if (defined $searchDB{$dpic}{POP}) {
$searchDB{$dpic}{POP}++;
}
else {
$searchDB{$dpic}{POP} = 1;
}
print "$dpic has been shown $searchDB{$dpic}{POP} times.\n" if $verbose;
}
##############################################################
# showMostPopularPics - display the Top50 of the most viewed pics
##############################################################
sub showMostPopularPics {
# open window
my $win = $top->Toplevel();
$win->title('Most popular pictures - TOP50');
$win->iconimage($mapiviicon) if $mapiviicon;
my $text = "searching ...";
$win->Label(-textvariable => \$text)->pack(-expand => 0, -fill => 'x');
my $tlb = $win->Scrolled("HList",
-header => 1,
-separator => ';', # todo here we hope that ; will never be in a directory or file name
-pady => 0,
-columns => 3,
-scrollbars => 'osoe',
-selectmode => 'extended',
-background => $config{ColorBG}, #8fa8bf
-width => 100,
-height => 60,
)->pack(-expand => 1, -fill => "both");
bindMouseWheel($tlb);
$tlb->header('create', 0, -text => 'Place', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
$tlb->header('create', 1, -text => 'Thumbnail', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
$tlb->header('create', 2, -text => 'Info', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
my $butF = $win->Frame()->pack(-fill =>'x', -padx => 3, -pady => 3);
my $Xbut = $butF->Button(-text => 'Close',
-command => sub {
$win->destroy();
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$win->bind('<Control-q>', sub { $Xbut->invoke; });
$win->bind('<Key-Escape>', sub { $Xbut->invoke; });
$win->bind('<Control-a>', sub { selectAll($tlb); } );
$win->bind('<ButtonPress-2>', sub {
return if (!$tlb->info('children'));
my $dpic = getNearestItem($tlb);
showPicInOwnWin($dpic); });
$win->Popup(-popover => 'cursor');
repositionWindow($win);
my @populatity_list = sort {
my $popa = 0;
$popa = $searchDB{$a}{POP} if (defined $searchDB{$a}{POP});
my $popb = 0;
$popb = $searchDB{$b}{POP} if (defined $searchDB{$b}{POP});
$popb <=> $popa;
} keys %searchDB;
$win->update();
$text = "loading ...";
my %thumbs;
foreach my $nr (0 .. 49) {
my $dpic = $populatity_list[$nr];
my $num = $nr + 1;
my $pic = basename($dpic);
my $path = dirname($dpic);
my $thumb = getThumbFileName($dpic);
$tlb->add($dpic);
$text = "loading $num ...";
$tlb->itemCreate($dpic, 0, -text => $num, -style => $comS);
if (-f $thumb) {
$thumbs{$thumb} = $top->Photo(-file => $thumb, -gamma => $config{Gamma});
if (defined $thumbs{$thumb}) {
$tlb->itemCreate($dpic, 1, -image => $thumbs{$thumb}, -itemtype => 'imagetext', -style => $thumbS);
}
}
my $pop = 0;
$pop = $searchDB{$dpic}{POP} if (defined $searchDB{$dpic}{POP});
$tlb->itemCreate($dpic, 2, -text => "$pic\n$path\nViewed $pop times", -style => $fileS);
}
$text = "Ready";
$win->waitWindow;
foreach (keys %thumbs) { $thumbs{$_}->delete if (defined $thumbs{$_}); } # free memory
}
##############################################################
# stopWatchStart
##############################################################
my $stopWatchTime;
sub stopWatchStart {
$stopWatchTime = Tk::timeofday();
}
##############################################################
# stopWatchStop
##############################################################
sub stopWatchStop {
my $text = '';
$text = shift;
printf "stopWatch: %.5f secs ($text)\n", (Tk::timeofday() - $stopWatchTime);
}
##############################################################
# selectThumb
##############################################################
sub selectThumb {
my $lb = shift;
my $index = shift;
$lb->selectionClear();
return unless (defined $index);
unless ($lb->info("exists", $index)) {
warn "selectThumb: $index is not availabel!" if $verbose;
return;
}
$lb->selectionSet($index);
$lb->anchorSet($index);
$lb->see($index);
$lb->update;
if ($config{CenterThumb}) {
my $next = $lb->info('next', $index);
my $prev = $lb->info('prev', $index);
$lb->see($prev) if ($prev);
$lb->update;
$lb->see($next) if ($next);
}
showNrOf();
}
##############################################################
# selectAll
##############################################################
sub selectAll {
my $lb = shift;
my @pics = $lb->info('children');
return unless (@pics);
$lb->selectionSet($pics[0], $pics[-1]);
showNrOf() if ($lb == $picLB);
}
##############################################################
# selectBak
##############################################################
sub selectBak {
$picLB->selectionClear();
my @pics = $picLB->info('children');
foreach (@pics) {
if ($_ =~ m/.*-bak\.jp(g|eg)$/i) {
$picLB->selectionSet($_);
}
}
showNrOf();
if (!defined $picLB->info('selection')) {
$top->messageBox(-icon => 'info', -message => "Nothing selected!\nThere are no file names matching the pattern: \"*-bak.jp(e)g\".",
-title => "No backups", -type => 'OK');
}
}
##############################################################
# selectInv
##############################################################
sub selectInv {
my @sellist = $picLB->info('selection');
$picLB->selectionClear();
my @pics = $picLB->info('children');
foreach (@pics) {
if (!isInList($_, \@sellist)) {
$picLB->selectionSet($_);
}
}
showNrOf();
}
##############################################################
# getThumbFileName - return the location of the corresponding
# thumbnail file (full path)
##############################################################
sub getThumbFileName($) {
my $dpic = shift;
my $dir = dirname( $dpic);
my $pic = basename($dpic);
# normalize the path
$dir =~ s!\\!\/!g; # replace Windows path delimiter with UNIX style \ -> /
#$dir =~ s/\\/\//g; # replace Windows path delimiter with UNIX style \ -> /
if (defined $thumbDBhash{$dir}) {
return $thumbDBhash{$dir}."/$pic";
}
#$dir =~ s!^([a-z]:)/!$1\\!i if $EvilOS; # replace E:/ with E:\ else Win will fire an error message that E: is not mounted
my @thumbDirNoNos = qw( /mnt/cdrom /mnt/dvd ); # todo
my $thumbDB = "$configdir/thumbDB";
my $thumbdir = "$dir/$thumbdirname";
# central thumbDB
if (($config{CentralThumbDB}) or # config option set to central thumbdir
(!-d $dir) or # if the directory is not mounted/available
((-d $thumbdir) and (!-w $thumbdir)) or # or .thumbdir exists but is write protected
(-f "$dir/.nothumbs") or # or file .nothumbs is found
((!-w $dir) and (!-d $thumbdir))) { # or dir is write protected but there is no .thumbdir
if ($EvilOS) { # in windows we have to get rid of the device names (C:\ d:/ etc.)
print "getThumbFileName: $dir " if $verbose;
$dir =~ s!^[a-z]:/!!i; # for slash
$dir =~ s!^[a-z]:\\!!i; # for backslash
print "-> $dir\n" if $verbose;
}
else { # for other OS (Linux etc.) we cut off special parts
foreach (@thumbDirNoNos) {
if ($dir =~ /^$_/) {
print "getThumbFileName: $dir " if $verbose;
$dir =~ s/^$_//; # cut off unwanted dir part e.g. /mnt/cdrom
print "-> $dir\n" if $verbose;
last; # one is enough
}
}
}
$thumbdir = "$thumbDB/$dir";
$thumbdir =~ s/\/+/\//g; # replace multiple slashes with one // -> /
}
$thumbDBhash{$dir} = $thumbdir; # store for quicker response
my $thumb = "$thumbdir/$pic"; # add the pic name
return $thumb;
}
##############################################################
# generateThumbs - generate thumbnails for each picture
# remove outdated thumbs
##############################################################
sub generateThumbs {
print "generateThumbs\n" if $verbose;
my $ask = shift; # ASK = ask the user befor making a thumbnail dir, NO_ASK
my $show = shift; # SHOW = show the generated thumbs in $picLB, NO_SHOW
my $getpics = shift; # optional bool, get the pics with getpics not from the listbox
my ($pic, $dpic, $lpic, $thumb, $string);
my $nrofprocs = 0;
my @pics;
if ((defined $getpics) and ($getpics == 1)) {
@pics = getPics($actdir, WITH_PATH);
# if the thumbs won't be shown, no need to sort
sortPics($config{SortBy}, $config{SortReverse}, \@pics) if ($show == SHOW);
}
else {
@pics = $picLB->info('children'); # this should be much faster than getPics($actdir);
}
# remove outdated thumbs and exif data
cleanSubDirs($actdir);
return if (@pics <= 0);
my $thumbdir = dirname(getThumbFileName("$actdir/dummy.jpg"));
return if (!makeDir("$thumbdir", $ask));
# if thumb dir is not writeable
if (!-w $thumbdir) {
$top->messageBox(-icon => 'warning', -message => "$thumbdir is not writeable, so mapivi is not able to generate thumbnails", -title => "No write access", -type => 'OK');
return;
}
# look what's to do
$nrToConvert = 0;
foreach $lpic (@pics) {
$dpic = $lpic;
next if (!getRealFile(\$dpic));
$thumb = getThumbFileName($lpic);
if (aNewerThanb($dpic, $thumb)) {
$nrToConvert++; # count the nr of thumbs to generate/refresh
}
}
return if ($nrToConvert == 0); # nothing to do
# ask the user, if he wants to update the thumbs now
if ($config{AskGenerateThumb}) {
my $rc = checkDialog("Generate thumbnails?",
"There are $nrToConvert thumbnails to generate.\nShall I do this now?",
\$config{AskGenerateThumb},
"ask every time",
"",
'OK', 'Cancel');
return if ($rc ne 'OK');
}
my $pre = makeCommandString(\%config);
# generate thumbs
my $i = 0; # pic list index
foreach $lpic (@pics) {
$dpic = $lpic;
next if (!getRealFile(\$dpic));
$pic = basename($dpic);
$thumb = getThumbFileName($lpic);
if (!aNewerThanb($dpic, $thumb)) {
$i++;
next;
}
if (-z $dpic) { # file is empty (size zero)
$top->messageBox(-icon => 'warning', -message => "$pic is an empty file. Skipping.",
-title => 'Error', -type => 'OK');
$i++;
next;
}
removeFile($thumb);
# try to get the EXIF thumbnail
if ($config{UseEXIFThumb}) {
my $errors = "";
extractThumb($dpic, $thumb, \$errors);
}
# found a EXIF thumbnail -> show it
if (-f $thumb) {
# here we increase the process counter, just because ...
proccount(1);
# ... in updateOneThumb it will be decreased
updateOneThumb($thumb, $lpic, $show);
$i++;
next;
}
# thumbnail is always in JPEG format, but the suffix of the picture is not changed
$string = "$pre \"$dpic\" JPEG:\"$thumb\" ";
print "command: $string\n" if $verbose;
if (!$EvilOS) { # running on a "good" OS like Linux we can use background processes :)
# start a background process for each pic
my $fh = Tk::IO->new(-linecommand => \&nop, -childcommand => [\&updateOneThumb, $thumb, $dpic, $show]);
#$hiresstart = [gettimeofday]; # hires - measure the loading time
$fh->exec($string);
proccount(1); # count processes
$nrofprocs = proccount();
if ($nrofprocs >= $config{MaxProcs}) {
# waiting for current process to finish
$fh->wait();
}
}
else { # we run on a evil OS like windows - no threading :(
# todo added for vinci
#my $thumbdir = dirname($thumb);
#print "*** no thumb dir: $thumbdir\n" unless (-d $thumbdir);
#my $picdir = dirname($dpic);
#print "*** no pic dir: $picdir\n" unless (-d $picdir);
#print "*** no source pic: $dpic\n" unless (-f $dpic);
proccount(1); # count processes
(system "$string") == 0 or warn "$string failed: $!";
updateOneThumb($thumb, $lpic, $show);
}
$i++;
}
print "...done\n" if $verbose;
}
##############################################################
# generateOneThumb
##############################################################
sub generateOneThumb {
my $dpic = shift;
my $pre = makeCommandString(\%config);
my $thumb = getThumbFileName($dpic);
my $string = "$pre \"$dpic\" JPEG:\"$thumb\" ";
execute($string);
}
##############################################################
# cleanSubDirs - remove thumbs and exif infos without a
# corresponding picture
##############################################################
sub cleanSubDirs {
my $dir = shift;
my $thumbdir = dirname(getThumbFileName("$dir/dummy.jpg"));
my $exifdir = "$dir/$exifdirname";
my $pic;
return if (!-d $dir);
# clean thumb and exif dir
foreach my $subdir ($thumbdir, $exifdir) {
if (-d $subdir) {
my @subpics = getPics($subdir, JUST_FILE); # no sort needed
foreach $pic (@subpics) {
if (!-f "$dir/$pic") {
removeFile("$subdir/$pic");
}
}
}
}
}
##############################################################
# makeCommandString - build up the command string for the
# generation of thumbnails depending on
# the settings in the given config hash
##############################################################
sub makeCommandString {
my $conf = shift;
my $pre = "";
$pre = " montage -size $conf->{'ThumbSize'}x$conf->{'ThumbSize'} -geometry $conf->{'ThumbSize'}x$conf->{'ThumbSize'}+$conf->{'ThumbBorder'}+$conf->{'ThumbBorder'} -quality $conf->{'ThumbQuality'} -background \"$conf->{'ColorThumbBG'}\" ";
#$pre .= "-frame $conf->{'ThumbBorder'}x$conf->{'ThumbBorder'} " if $conf->{UseThumbFrame};
$pre .= "-shadow " if $conf->{UseThumbShadow};
# ! Sharpen is the most time consuming option, when building thumbnails!
if ($conf->{ThumbSharpen} > 0) {
$pre .= "-sharpen $conf->{'ThumbSharpen'} " # the higher the value the slower
}
return $pre;
}
##############################################################
# light_table_open_window
##############################################################
sub light_table_open_window {
if (Exists($ltw)) {
$ltw->deiconify;
$ltw->raise;
$ltw->focus;
return;
}
# open window
$ltw = $top->Toplevel();
$ltw->title('Mapivi Light table');
$ltw->iconimage($mapiviicon) if $mapiviicon;
$ltw->bind('<Key-Escape>', sub {light_table_close(ASK);});
$ltw->bind('<Key-q>', sub {light_table_close(ASK);});
$ltw->bind('<Control-a>', sub {light_table_select_all();});
# window resize event
$ltw->bind("<Configure>" => sub {
# if there is a timer running cancel it
$ltw->{LAST_RESIZE_TIMER_MH}->cancel if ($ltw->{LAST_RESIZE_TIMER_MH});
$ltw->{LAST_RESIZE_MH} = Tk::timeofday;
# after 200 msec we reorder the thumbnails according to the new geometry to give a preview
$ltw->{LAST_RESIZE_TIMER_MH} = $ltw->after(200, sub {
light_table_reorder();
});
});
# call quitMain when the window is closed by the window manager
$ltw->protocol("WM_DELETE_WINDOW" => sub { light_table_close(ASK); });
$ltw->{menu} = $ltw->Menu;
$ltw->configure(-menu => $ltw->{menu});
my $file_menu = $ltw->{menu}->cascade(-label => "Slideshow");
$file_menu->cget(-menu)->configure(-title => "Slideshow menu");
#$file_menu->command(-label => "Rename pics ...", -command => sub { rename_pics(); });
$file_menu->command(-label => "Open ...", -command => sub { light_table_open(RESET); });
$file_menu->command(-label => "Show selected pictures", -command => sub { my @sel = getSelection($ltw->{canvas}); show_multiple_pics(\@sel, 0);});
$file_menu->command(-label => "Add list ...", -command => sub { light_table_open(ADD); });
$file_menu->command(-label => "Save", -command => sub {
if ((defined $ltw->{file}) and (-f $ltw->{file})) {
light_table_save($ltw->{file});
}
});
$file_menu->command(-label => "Save as ...", -command => sub { light_table_save_as(); });
$file_menu->command(-label => "Clear", -command => sub { undef @light_table_list; light_table_clear(); });
$file_menu->command(-label => "Update", -command => sub { light_table_reorder(); });
$file_menu->command(-label => "Close", -command => sub { light_table_close(NO_ASK); });
my $sort_menu = $ltw->{menu}->cascade(-label => 'Sort');
$sort_menu->command(-label => 'file name (A - Z)',
-command => sub {
$ltw->Busy;
sortPics('name', 0, \@light_table_list);
$ltw->Unbusy;
light_table_reorder();
});
$sort_menu->command(-label => 'file name (Z - A)',
-command => sub {
$ltw->Busy;
sortPics('name', 1, \@light_table_list);
$ltw->Unbusy;
light_table_reorder();
});
$sort_menu->command(-label => 'EXIF date (new first)',
-command => sub {
$ltw->Busy;
sortPics('exifdate', 0, \@light_table_list);
$ltw->Unbusy;
light_table_reorder();
});
$sort_menu->command(-label => 'EXIF date (old first)',
-command => sub {
$ltw->Busy;
sortPics('exifdate', 1, \@light_table_list);
$ltw->Unbusy;
light_table_reorder();
});
$sort_menu->command(-label => 'IPTC urgency/rating (high first)',
-command => sub {
$ltw->Busy;
sortPics('urgency', 0, \@light_table_list);
$ltw->Unbusy;
light_table_reorder();
});
$sort_menu->command(-label => 'IPTC urgency (low first)',
-command => sub {
$ltw->Busy;
sortPics('urgency', 1, \@light_table_list);
$ltw->Unbusy;
light_table_reorder();
});
my $opt_menu = $ltw->{menu}->cascade(-label => "Options");
$ltw->{show_balloon} = 1; # todo: move to config hash
$ltw->{show_status} = 1; # todo: move to config hash
$opt_menu->checkbutton(-label => "show balloon info", -variable => \$ltw->{show_balloon}, -command => sub { light_table_balloon();});
$opt_menu->checkbutton(-label => "show status line", -variable => \$ltw->{show_status}, -command => sub { light_table_status();});
$ltw->{status_line} = $ltw->Label(-textvariable => \$ltw->{label});
$ltw->{frame} = $ltw->Scrolled('Canvas',
-scrollbars => 'oe',
-confine => 1,
-xscrollincrement => 117,
-yscrollincrement => 117,
-height => 570,
-width => 370,
-relief => 'flat',
-borderwidth => 0,
-highlightthickness => 0,
)->pack(-fill =>'both', -expand => 1, -padx => 3, -pady => 3);
#bindMouseWheel($ltw->{frame});
light_table_status();
$ltw->{canvas} = $ltw->{frame}->Subwidget('canvas');
my $context_menu = $ltw->Menu(-title => "Context Menu");
$ltw->bind('<ButtonPress-3>', sub {
$context_menu->Popup(-popover => "cursor", -popanchor => "nw");
} );
$ltw->bind('<Key-Delete>', sub {light_table_delete(); });
$context_menu->command(-label => 'Move selected to top',
-command => sub { light_table_shift('top'); });
$context_menu->command(-label => 'Move selected to bottom',
-command => sub { light_table_shift('bottom'); });
$context_menu->command(-label => 'Delete selected',
-accelerator => "<Delete>",
-command => sub { light_table_delete(); });
$context_menu->command(-label => 'Copy and rename selected',
-command => sub { light_table_copy_rename(); });
$context_menu->command(-label => 'montage/index print ...',
-command => sub { my @pics = getSelection($ltw->{canvas}); indexPrint(\@pics); });
$context_menu->command(-label => 'Show in viewer',
-command => sub { openPicInViewer($ltw->{canvas}); });
#$context_menu->command(-label => 'Show in external viewer',
# -command => sub { openPicInViewer($ltw);(); });
$context_menu->separator;
#$context_menu->command(-label => 'Add pics', -command => sub { add_pics(); });
$ltw->{thumb_distance} = 5; # in pixels
$ltw->{thumb_size} = 108; # in pixels todo
$ltw->Popup;
checkGeometry(\$config{LtwGeometry});
$ltw->geometry($config{LtwGeometry});
}
##############################################################
# light_table_status
##############################################################
sub light_table_status {
if ($ltw->{show_status}) {
$ltw->{status_line}->pack(-before => $ltw->{frame} ,-fill => 'x');
}
else {
$ltw->{status_line}->packForget;
}
}
##############################################################
# light_table_open
##############################################################
sub light_table_open {
my $mode = shift; # must be ADD or RESET
my $text = 'Open';
$text = 'Add to' if ($mode == ADD);
my $fileSelect = $ltw->FileSelect(-title => "$text slideshow",
-initialfile => "slideshow.sld",
-create => 0,
-directory => $config{SlideShowDir},
-width => 30, -height => 30);
my $file = $fileSelect->Show;
return unless (defined $file);
return if ($file eq '');
return unless (-f $file);
unless (-T $file) {
$ltw->messageBox(-icon => 'warning',
-message => 'Please select a valid slideshow (ASCII) file.',
-title => 'Wrong file type',
-type => 'OK');
return;
}
$config{SlideShowDir} = dirname($file) if (-d dirname($file));
my $fh;
if (!open($fh, "<$file")) {
warn "open slideshow: Couldn't open $file: $!";
return;
}
if ($mode == RESET) {
# reset list and clean up canvas
undef @light_table_list;
light_table_clear();
}
my @pics;
my $pic_number = 0;
my $errors = '';
my $double = '';
my $double_count = 0;
while (<$fh>) {
chomp; # no newline
if ($_ =~ m|\"(.*)\"|) { # match just quoted lines
$pic_number++;
my $dpic;
# $dpic may also have a relative path!
if ($filespecAvail) {
$dpic = File::Spec->rel2abs($1, dirname($file));
}
print "found $dpic - " if $verbose;
if (-f $dpic) {
print "file\n" if $verbose;
if (isInList($dpic, \@light_table_list)) {
$double .= "$dpic\n";
$double_count++;
}
else {
push @pics, $dpic;
}
}
else {
print "no file\n" if $verbose;
$errors .= "error: $dpic not found! (number: $pic_number)\n";
}
}
else { $errors .= "info: ignoring line $_\n"; }
}
close $fh;
$errors .= "\nadded ".scalar @pics." of $pic_number pictures!\n";
# add pics to end of global list
push @light_table_list, @pics;
# add new pictures to light table
light_table_add_list(\@pics);
$ltw->{label} = scalar @light_table_list.' pictures';
if (($errors ne '') or ($double_count > 0)) {
my $text;
$text = "These $double_count pictures are already in the slideshow and have been skipped:\n$double\n\n" if ($double_count > 0);
$text .= "Information and errors while reading $file:\n$errors" if ($errors ne '');
showText("Information and Errors", $text, NO_WAIT);
}
if ($mode == RESET) {
$ltw->title('Light table: '.basename($file));
$ltw->{file} = $file;
}
}
##############################################################
# light_table_save_as
##############################################################
sub light_table_save_as {
my $fileSelect = $ltw->FileSelect(-title => "Save as (use .sld suffix)",
-initialfile => "slideshow.sld",
-create => 1,
-directory => $config{SlideShowDir},
-width => 30, -height => 30);
my $file = $fileSelect->Show;
return unless (defined $file);
return if ($file eq '');
$config{SlideShowDir} = dirname($file) if (-d dirname($file));
if (-f $file) {
my $rc = $ltw->messageBox(-icon => 'warning', -message => "Slideshow file $file exist.\nOk to overwrite?",
-title => "Overwrite slideshow?", -type => "OKCancel");
return if ($rc !~ m/Ok/i);
}
my $rc = 0;
# open window
my $win = $top->Toplevel();
$win->title('Save slideshow options');
$win->iconimage($mapiviicon) if $mapiviicon;
$win->Checkbutton(-variable => \$config{relative_path}, -text => "Use relative file paths")->pack(-anchor=>'w');
$win->Checkbutton(-variable => \$config{xnview_loop}, -text => "Loop slide show")->pack(-anchor=>'w');
$win->Checkbutton(-variable => \$config{xnview_fullscreen}, -text => "Full screen display")->pack(-anchor=>'w');
$win->Checkbutton(-variable => \$config{xnview_title}, -text => "Show title bar")->pack(-anchor=>'w');
$win->Checkbutton(-variable => \$config{xnview_filename}, -text => "Show file name")->pack(-anchor=>'w');
$win->Checkbutton(-variable => \$config{xnview_mouse}, -text => "Hide mouse")->pack(-anchor=>'w');
$win->Checkbutton(-variable => \$config{xnview_random}, -text => "Random order")->pack(-anchor=>'w');
my $but_frame =
$win->Frame()->pack(-fill =>'x');
my $ok_but =
$but_frame->Button(-text => 'OK',
-command => sub {
$rc = 1;
$win->withdraw();
$win->destroy();
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 2, -pady => 3);
my $x_but =
$but_frame->Button(-text => 'Cancel',
-command => sub {
$win->withdraw();
$win->destroy();
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 2, -pady => 3);
$win->Popup(-popover => 'cursor');
repositionWindow($win);
$win->waitWindow;
return unless ($rc);
light_table_save($file);
}
##############################################################
# light_table_save
##############################################################
sub light_table_save {
my $file = shift;
print "writing slideshow to $file\n" if $verbose;
my $fh;
if (!open($fh, ">$file")) {
print "could not open $file for write access!: $!\n";
return;
}
my $xnview_slideshow_header =
'# Slide Show Sequence
View = 1
CenterWindow = 0
ReadErrors = 1
BackgroundColor = 0';
print $fh "$xnview_slideshow_header\n";
print $fh "Loop = $config{xnview_loop}\n";
print $fh "FullScreen = $config{xnview_fullscreen}\n";
print $fh "TitleBar = $config{xnview_title}\n";
print $fh "HideMouse = $config{xnview_mouse}\n";
print $fh "RandomOrder = $config{xnview_random}\n";
print $fh "ShowFilename = $config{xnview_filename}\n";
foreach my $dpic (@light_table_list) {
my $rel = $dpic;
if ($filespecAvail and $config{relative_path}) {
$rel = File::Spec->abs2rel($dpic, dirname($file));
}
print $fh "\"$rel\"\n";
print "\"$rel\"\n" if $verbose;
}
close $fh;
$ltw->{label} = "wrote slideshow: ".basename($file);
$ltw->title('Light table: '.basename($file));
$ltw->{file} = $file;
}
##############################################################
# light_table_close
##############################################################
sub light_table_close {
my $ask = shift;
if ((defined $ask) and ($ask == ASK)) {
my $rc = $ltw->messageBox(-icon => 'question',
-message => "The slideshow will not be saved automatically.\nReally quit?",
-title => "Close light table?", -type => 'OKCancel');
return unless ($rc =~ m/Ok/i);
}
undef @light_table_list;
light_table_clear();
$config{LtwGeometry} = $ltw->geometry;
$ltw->destroy();
}
##############################################################
# light_table_clear
##############################################################
sub light_table_clear {
$ltw->{canvas}->delete('all');
# delete all photo objects (thumbnnails)
foreach (keys %light_table_thumbs) {
$light_table_thumbs{$_}->delete if (defined $light_table_thumbs{$_}); # delete photo object
delete $light_table_thumbs{$_}; # delete hash entry
}
$ltw->{label} = scalar @light_table_list.' pictures';
$ltw->title('Mapivi Light table');
}
##############################################################
# light_table_add_from_lb
##############################################################
sub light_table_add_from_lb {
my $lb = shift;
my @sellist = $lb->info('selection');
light_table_add(\@sellist);
}
##############################################################
# light_table_add
##############################################################
sub light_table_add {
my $list_ref = shift;
return unless checkSelection($top, 1, 0, $list_ref);
# open light table window if needed
light_table_open_window() unless (Exists($ltw));
my $error = '';
my $error_count = 0;
my @list;
# check for double pictures (not yet supported)
foreach my $dpic (@$list_ref) {
if (isInList($dpic, \@light_table_list)) {
$error .= "$dpic\n";
$error_count++;
}
else {
push @list, $dpic;
}
}
if ($error ne '') {
$error = "These $error_count pictures are already in the slideshow and have been skipped:\n\n".$error;
showText('Ignored pictures', $error, NO_WAIT);
}
return unless (@list);
# add selected pictures at end of slideshow list
push @light_table_list, @list;
# add selected pictures to light table
light_table_add_list(\@list);
}
##############################################################
# light_table_add_list
##############################################################
sub light_table_add_list {
my $list_ref = shift; # list of JPEG pics with full path
return if (@$list_ref < 1); # no pics to add
# get thumb size info from first thumbnail in list (this may be wrong)
my ($tw, $th) = getSize(getThumbFileName($$list_ref[0]));
$ltw->{thumb_size} = $tw if ($tw > 1);
my $i = 0;
my $pw = progressWinInit($ltw, "Add pictures to light table");
foreach my $dpic (@$list_ref) {
my $thumb = getThumbFileName($dpic);
last if progressWinCheck($pw);
$i++;
progressWinUpdate($pw, "adding picture ($i/".scalar @$list_ref.") ...", $i, scalar @$list_ref);
if (-f $thumb) {
# save all thumb photo objects in global hash %light_table_thumbs
# to delete them later
$light_table_thumbs{$dpic} = $ltw->Photo(-file => $thumb);
}
else {
if ($config{UseDefaultThumb} and $defaultthumbP) {
$light_table_thumbs{$dpic} = $defaultthumbP;
}
}
if ($light_table_thumbs{$dpic}) {
my $id = $ltw->{canvas}->createImage(0, 0,
-image => $light_table_thumbs{$dpic},
-tag => ['THUMB_MH',$dpic],
-anchor => 'nw');
# add bindings
$ltw->{canvas}->bind($id,'<ButtonPress-1>',
sub { light_table_select($id); });
$ltw->{canvas}->bind($id,'<Shift-ButtonPress-1>',
sub {$ltw->{LOCK_MH} = 1; light_table_select_range();});
$ltw->{canvas}->bind($id,'<Control-ButtonPress-1>',
sub {$ltw->{LOCK_MH} = 1; light_table_select_add($id); });
$ltw->{canvas}->bind($id,'<B1-Motion>',
sub { light_table_move($id); });
$ltw->{canvas}->bind($id,'<ButtonRelease-1>',
sub { return if ($ltw->{LOCK_MH}); light_table_drop($id); });
$ltw->{canvas}->bind($id,'<Shift-ButtonRelease-1>',
sub { $ltw->{LOCK_MH} = 0; });
$ltw->{canvas}->bind($id,'<Control-ButtonRelease-1>',
sub { $ltw->{LOCK_MH} = 0; });
$ltw->{canvas}->bind($id,'<ButtonPress-2>',
sub { showPicInOwnWin($dpic); });
#sub { show_multiple_pics($list_ref, 0); });
}
}
progressWinEnd($pw);
light_table_reorder();
$ltw->{canvas}->yviewMoveto(1);
$ltw->{label} = scalar @light_table_list.' pictures';
}
##############################################################
# light_table_balloon
##############################################################
sub light_table_balloon {
if ($ltw->{show_balloon}) {
my $msg;
# the balloon message is generated on demand later, to speed up the loading of the thumbs
$balloon->attach($ltw->{canvas},
-postcommand => sub {
my @curr = $ltw->{canvas}->find('withtag', 'current');
my $dpic = get_path_from_id($curr[0]);
$msg = makeBalloonMsg($dpic);
},
-balloonposition => 'mouse',
-msg => \$msg);
}
else {
$balloon->detach($ltw->{canvas});
}
}
##############################################################
# light_table_reorder
##############################################################
sub light_table_reorder {
$ltw->update;
#$ltw->Busy; # resizing the window does not work under windows if Busy is used
my $dis = $ltw->{thumb_size} + $ltw->{thumb_distance};
# get canvas size
my $cx = $ltw->{canvas}->width;
my $cy = $ltw->{canvas}->height;
# calc visible columns and rows
my $c_cols = int($cx/$dis);
$c_cols = 1 if ($c_cols < 1); # avoid division by zero
my $c_rows = int($cy/$dis);
# how many rows are needed for all pics?
my $all_rows = int(@light_table_list / $c_cols);
$all_rows++ if ((@light_table_list % $c_cols) != 0);
# adjust scrollbar
$ltw->{canvas}->configure(-scrollregion => [0, 0, $c_cols*$dis + $ltw->{thumb_distance}, $all_rows*$dis + $ltw->{thumb_distance}]);
my $index = 0;
foreach my $dpic (@light_table_list) {
my $row = int ($index / $c_cols);
my $col = $index % $c_cols; # modulo
#print "reorder: $index col:$col row:$row $dpic\n";
# we move the thumbs by tag which is the path+file name
# this excludes the possibility to have a pic twice in the list
$ltw->{canvas}->coords($dpic, $col*$dis+$ltw->{thumb_distance}, $row*$dis+$ltw->{thumb_distance});
$index++;
}
light_table_update_selection();
$ltw->{label} = scalar @light_table_list.' pictures';
#$ltw->Unbusy; # resizing the window does not work under windows if Busy is used
}
##############################################################
# get_path_from_id
##############################################################
sub get_path_from_id {
my $id = shift;
my @tags = $ltw->{canvas}->gettags($id);
my $dpic = '';
foreach (@tags) {
next if ($_ eq 'current');
next if ($_ =~ m/.*_MH/); # all my thumb tags are ending with _MH
$dpic = $_; # so this must be the path with file name
}
if ($dpic eq '') {
print "Error could not find path from item: ";
print "$_ " foreach (@tags);
print "\n";
}
return $dpic;
}
##############################################################
# light_table_copy_rename
##############################################################
sub light_table_copy_rename {
# find all selected thumbs
my @sel = $ltw->{canvas}->find('withtag', 'THUMBSELECT_MH');
return unless checkSelection($top, 1, 0, \@sel);
my $rc = $ltw->messageBox(-icon => 'warning', -message => "Copy and rename the ".scalar @sel." selected pictures.\nThe pictures will be renamed by adding a leading number according to the current order.\npic.jpg will for example be renamed to: 000-pic.jpg.\n\nOk to proceed?",
-title => "Copy and rename", -type => "OKCancel");
return if ($rc !~ m/Ok/i);
my $targetdir = getDirDialog("Copy pictures to");
return if ($targetdir eq "");
return unless (-d $targetdir);
makeDir(dirname(getThumbFileName("$targetdir/dummy.jpg")), ASK);
my $i = 0;
$rc = 1;
my $digits = 3;
my $pw = progressWinInit($ltw, "Copy and rename pictures");
foreach my $id (@sel) {
my $dpic = get_path_from_id($id);
last if progressWinCheck($pw);
my $pic = basename($dpic);
my $tpic = $targetdir.'/'.sprintf "%0*d-$pic", $digits, $i;
my $thumbpic = getThumbFileName($dpic);
my $thumbtpic = getThumbFileName($tpic);
$i++;
progressWinUpdate($pw, "copy and rename picture ($i/".scalar @sel.") ...", $i, scalar @sel);
$rc = overwritePic($tpic, $dpic, (scalar(@sel) - $i + 1)) if ($rc != 2);
next if ($rc == 0);
last if ($rc == -1);
if (mycopy ($dpic, $tpic, OVERWRITE)) {
if ((-d dirname($thumbtpic)) and (-f $thumbpic)) {
mycopy ("$thumbpic","$thumbtpic", OVERWRITE)
}
$searchDB{$tpic} = $searchDB{$dpic}; # copy meta info in search database
}
} # foreach - end
progressWinEnd($pw);
}
##############################################################
# light_table_drop
##############################################################
sub light_table_drop {
# where the drop happened
my $x = $ltw->{canvas}->canvasx($Tk::event->x());
my $y = $ltw->{canvas}->canvasy($Tk::event->y());
# distance between upper left corner of thumbs
my $dis = $ltw->{thumb_size} + $ltw->{thumb_distance};
$dis = 1 if ($dis == 0); # avoid division by zero
# drop position in cols/rows
my $col = sprintf "%0d", ($x / $dis);
my $row = sprintf "%0d", ($y / $dis);
print "drop at x=$x y=$y col=$col row=$row\n";
# get size of canvas in cols/rows
my $cx = $ltw->{canvas}->width;
my $cy = $ltw->{canvas}->height;
my $c_cols = int($cx/$dis);
my $c_rows = int($cy/$dis);
# new position in list
my $to_index = $row * $c_cols + $col;
my $to_dpic = $light_table_list[$to_index];
# find all selected thumbs
my @sel = $ltw->{canvas}->find('withtag', 'THUMBSELECT_MH');
my @sel_dpics;
# remove selected pics from the pic list
foreach my $id (@sel) {
my $dpic = get_path_from_id($id);
my $index = index_in_list($dpic, \@light_table_list);
#print "drop: removing index $index ($dpic)\n";
# remove this pic from the list
push @sel_dpics, splice @light_table_list, $index, 1;
}
# add the removed pics at the right place again
foreach my $dpic (@sel_dpics) {
#print "drop: adding at $to_index $dpic\n";
# add it at the right position
splice @light_table_list, $to_index, 0, $dpic;
}
#print "the list has now ".scalar @light_table_list." items\n";
light_table_reorder();
light_table_update_selection();
}
##############################################################
# index_in_list - returns the index of an element in a list
# return -1 if not found
##############################################################
sub index_in_list {
my $e = shift;
my $listRef = shift;
my $index = 0;
foreach (@$listRef) {
last if ($e eq $_);
$index++;
}
if ($index > @$listRef) {
print "$index is bigger than @$listRef\n";
$index = -1;
}
return $index;
}
##############################################################
# light_table_select - select a thumbnail, remove all other selections
##############################################################
sub light_table_select {
my $id = shift;
# remember the current selection
my @sel_IDs = $ltw->{canvas}->find('withtag', 'THUMBSELECT_MH');
$ltw->{sel_IDs} = \@sel_IDs;
$ltw->{sel_time} = Tk::timeofday();
# delete all selection frames
print "light_table_select\n";
remove_tag_from_all('THUMBSELECT_MH');
remove_tag_from_all('ANCHOR_MH');
# select just the current thumb
$ltw->{canvas}->addtag('THUMBSELECT_MH', 'withtag', 'current');
# this is the new anchor
$ltw->{canvas}->addtag('ANCHOR_MH', 'withtag', 'current');
# update the selection frames
light_table_update_selection();
}
##############################################################
# remove_tag_from_all - delete a certain tag from all elements
# in the canvas
##############################################################
sub remove_tag_from_all {
my $tag = shift;
#print "remove_tag_from_all: $tag\n";
# build a list of all thumbs with this tag
#my @sel = $ltw->{canvas}->find( qw|withtag $tag| );
my @sel = $ltw->{canvas}->find('withtag', $tag);
# remove the tag from these thumbs
foreach my $id (@sel) {
#print "remove_tag_from_all: removing $tag\n";
$ltw->{canvas}->dtag($id, $tag);
}
}
##############################################################
# light_table_select_add - toggle selection of single thumbnail
##############################################################
sub light_table_select_add {
my @tags = $ltw->{canvas}->gettags('current');
if (isInList('THUMBSELECT_MH', \@tags)) {
$ltw->{canvas}->dtag('current', 'THUMBSELECT_MH');
}
else {
$ltw->{canvas}->addtag('THUMBSELECT_MH', 'withtag', 'current');
}
light_table_update_selection();
}
##############################################################
# light_table_select_all - select all thumbnail
##############################################################
sub light_table_select_all {
remove_tag_from_all('THUMBSELECT_MH');
my @all = $ltw->{canvas}->find('all');
foreach my $id (@all) {
$ltw->{canvas}->addtag('THUMBSELECT_MH', 'withtag', $id);
}
light_table_update_selection();
}
##############################################################
# light_table_select_range - select range of thumbnail
##############################################################
sub light_table_select_range {
# build a list of all thumbs with tag ANCHOR_MH
my @sel = $ltw->{canvas}->find('withtag', 'ANCHOR_MH');
if (@sel < 1) {
print "no anchor found!\n";
return;
}
if (@sel > 1) {
print "error ".scalar @sel." anchors found! - removing anchors\n";
remove_tag_from_all('ANCHOR_MH');
return;
}
my $start_id = $sel[0];
my $start_dpic = get_path_from_id($start_id);
my $start_index = index_in_list($start_dpic, \@light_table_list);
@sel = $ltw->{canvas}->find('withtag', 'current');
my $end_id = $sel[0];
my $end_dpic = get_path_from_id($end_id);
my $end_index = index_in_list($end_dpic, \@light_table_list);
print "light_table_select_range: select from $start_dpic ($start_index) to $end_dpic ($end_index)\n";
# do we need to swap?
if ($end_index < $start_index) {
my $tmp = $start_index;
$start_index = $end_index;
$end_index = $tmp;
}
foreach ($start_index .. $end_index) {
$ltw->{canvas}->addtag('THUMBSELECT_MH', 'withtag', $light_table_list[$_]);
}
#$ltw->{canvas}->addtag('THUMBSELECT_MH', 'withtag', 'current');
#$ltw->{canvas}->dtag($id, 'THUMBSELECT_MH');
light_table_update_selection();
}
##############################################################
# light_table_update_selection - draw a frame around each selected
# thumbnail (with tag THUMBSELECT_MH)
##############################################################
sub light_table_update_selection {
# first we remove all frames
$ltw->{canvas}->delete('withtag', 'FRAME');
# find all selected thumbs
my @sel = $ltw->{canvas}->find('withtag', 'THUMBSELECT_MH');
# draw a frame
foreach my $thumb (@sel) {
my ($x, $y) = $ltw->{canvas}->coords( $thumb );
$ltw->{canvas}->createRectangle( $x, $y, $x+$ltw->{thumb_size}+1, $y+$ltw->{thumb_size}+1,
-tags => ['FRAME'],
-outline => $config{ColorSel},
-width => 3,
);
}
$ltw->{label} = scalar @light_table_list.' pictures, '.scalar @sel.' selected';
}
##############################################################
# light_table_delete - remove the selected thumbs from the list
# will - of course - not remove the files!!!
##############################################################
sub light_table_delete {
# find all selected thumbs
my @sel = $ltw->{canvas}->find('withtag', 'THUMBSELECT_MH');
# remove them from the list and the canvas
foreach my $id (@sel) {
my $dpic = get_path_from_id($id);
my $index = index_in_list($dpic, \@light_table_list);
print "deleting index $index ($dpic)\n";
# remove this pic from the list
splice @light_table_list, $index, 1;
# delete item from canvas
$ltw->{canvas}->delete($id);
$light_table_thumbs{$dpic}->delete if (defined $light_table_thumbs{$dpic}); # delete photo object
delete $light_table_thumbs{$dpic}; # delete hash entry
}
light_table_reorder();
light_table_update_selection();
}
##############################################################
# light_table_shift - move the selected thumbs to the top or
# bottom of the list
##############################################################
sub light_table_shift {
my $where = shift; # must be 'top' or 'bottom'
return unless (defined $where);
return if (($where ne 'top') and ($where ne 'bottom'));
# find all selected thumbs
my @sel = $ltw->{canvas}->find('withtag', 'THUMBSELECT_MH');
my @shift_pics; # pics to move
# remove them from the list
foreach my $id (@sel) {
my $dpic = get_path_from_id($id);
my $index = index_in_list($dpic, \@light_table_list);
# remove this pic from the list and add it to @shift_pics
push @shift_pics, splice @light_table_list, $index, 1;
}
if ($where eq 'top') {
unshift @light_table_list, @shift_pics; # add them at the start of the list
}
elsif ($where eq 'bottom') {
push @light_table_list, @shift_pics; # add them to the end of the list
}
else {
warn "light_table_shift: should not be reached where = $where";
}
light_table_reorder();
light_table_update_selection();
}
##############################################################
# light_table_move - called if a thumbnail is dragged inside the light table
##############################################################
sub light_table_move {
# stop repeat timer
$ltw->{SCROLL_MH}->cancel if $ltw->{SCROLL_MH};
my $id = shift;
# if the last selection happened just 400ms ago and the clicked
# thumb was inside the last selection, we reselect the last selection
if (((Tk::timeofday() - $ltw->{sel_time}) < 0.4) and isInList($id, $ltw->{sel_IDs})) {
# reset time
$ltw->{sel_time} = 0;
# first remove the tags
remove_tag_from_all('THUMBSELECT_MH');
# then add the selection from the saved list
foreach my $id (@{$ltw->{sel_IDs}}) {
my $dpic = get_path_from_id($id);
$ltw->{canvas}->addtag('THUMBSELECT_MH', 'withtag', $dpic);
}
light_table_update_selection();
}
$ltw->{canvas}->raise($id);
# get mouse coordinates
my $ex = $Tk::event->x();
my $ey = $Tk::event->y();
my $x = $ltw->{canvas}->canvasx($ex);
my $y = $ltw->{canvas}->canvasy($ey);
my $offset = int($ltw->{thumb_size}/2);
# move thumb to mouse position
$ltw->{canvas}->coords($id, $x-$offset, $y-$offset);
# autoscroll: scroll up or down if needed
# get actual scroll state
my ($y1,$y2) = $ltw->{canvas}->yview;
my $cy = $Tk::event->y;
print "light_table_move cy:$cy\n" if $verbose;
# everything is visible no scrolling needed
return if ($y1 == 0 and $y2 == 1);
my $c_h = $ltw->{canvas}->height; # the visible height
#my @sr = $ltw->{canvas}->cget(-scrollregion);
#my @sr = $ltw->{frame}->cget(-scrollregion);
#my $c_h_all = $sr[3] - $sr[1]; # the height of the scrollregion
# scroll up if mouse is less then a half thumbnailsize away from the upper border
# and there is still room to scroll ($y1 > 0) and no button release has happened
if (($cy < $offset) and ($y1 > 0)) {
$ltw->{SCROLL_MH} = $ltw->repeat(100, sub {
print "scroll up\n";
$ltw->{canvas}->yview('scroll',-1,'units');
# move thumb to mouse position
my $x = $ltw->{canvas}->canvasx($ex);
my $y = $ltw->{canvas}->canvasy($ey);
$ltw->{canvas}->coords($id, $x-$offset, $y-$offset);
$ltw->idletasks; });
}
# scroll down if mouse is less then a half thumbnailsize away from the lower border
# and there is still room to scroll ($y2 < 1) and no button release has happened
if (($cy > $c_h - $offset) and ($y2 < 1)) {
$ltw->{SCROLL_MH} = $ltw->repeat(100, sub {
print "scroll down\n";
$ltw->{canvas}->yview('scroll',1,'units');
# move thumb to mouse position
my $x = $ltw->{canvas}->canvasx($ex);
my $y = $ltw->{canvas}->canvasy($ey);
$ltw->{canvas}->coords($id, $x-$offset, $y-$offset);
$ltw->idletasks; });
}
}
##############################################################
# nop - a do nothing function, needed from Tk::IO
##############################################################
sub nop { return; }
##############################################################
# getThumbCaption - return the appropriate caption for the
# thumbnail of a picture, possibly empty
##############################################################
sub getThumbCaption {
my $dpic = shift;
if (($config{ThumbCapt} eq '') or ($config{ThumbCapt} eq 'none')) {
return '';
}
elsif ($config{ThumbCapt} eq 'filename') {
my $capt = basename($dpic);
$capt =~ s/(.*)\.jp(g|eg)$/$1/i; # remove suffix
return $capt;
}
elsif ($config{ThumbCapt} eq 'filenameSuffix') {
my $capt = basename($dpic);
return $capt;
}
elsif ($config{ThumbCapt} eq 'objectname') {
return getIPTCObjectName($dpic);
}
else {
warn 'getThumbCaption: ThumbCapt has unexpected value: "'.$config{ThumbCapt}.'"';
return "";
}
}
##############################################################
# updateOneThumb - this function is called when a convert
# process is finished; replaces the default
# thumbnail with the actual thumbnail
##############################################################
sub updateOneThumb {
my $thumb = shift;
my $dpic = shift; # the index (entrypath) of the hlist element
my $show = shift; # SHOW, NO_SHOW
proccount(-1);
$nrToConvert--; $nrToConvert = 0 if ($nrToConvert < 0);
# check if we are still in the same dir
if (dirname($thumb) ne dirname(getThumbFileName("$actdir/dummy.jpg"))) {
return; # no, we are not so do not display the generated thumbs
}
if (($show == SHOW) and (-f $thumb)) {
$thumbs{$thumb} = $picLB->Photo(-format => "jpeg", -file => $thumb, -gamma => $config{Gamma});
# if there is already an image ...
if ($picLB->itemCget($dpic, $picLB->{thumbcol}, -itemtype) eq "imagetext") {
# ... configure it
$picLB->itemConfigure($dpic, $picLB->{thumbcol}, -image => $thumbs{$thumb}, -itemtype => "imagetext");
}
else {
$picLB->itemCreate($dpic, $picLB->{thumbcol}, -style => $thumbS, -itemtype => 'imagetext', -image => $thumbs{$thumb}, -text => getThumbCaption($dpic));
}
}
}
##############################################################
# proccount - count the spawned processes
# returns the number of running processes if no
# parameter is given
##############################################################
sub proccount {
my $diff = shift; # optional parameter
return $proccount unless (defined $diff);
$proccount = 0 unless (defined $proccount); # todo why?
$proccount += $diff;
$proccount = 0 if ($proccount < 0); # should never happen!
$top->update;
print "proccount = $proccount\n" if $verbose;
}
##############################################################
# showPicViewList
##############################################################
sub showPicViewList {
my $fs = $top->FileSelect(-title => "read picture view list from file",
-directory => $actdir,
-width => 30, -height => 30);
my $file = $fs->Show;
return if ((!defined $file) or ($file eq "") or (!-f $file));
my @pics = readArrayFromFile($file);
# todo: handle absolute and relative paths in lists
# check pic list
my $error_text = '';
foreach (@pics) {
$error_text .= "$_\n" unless (-f $_);
}
if ($error_text ne '') {
$error_text = "These pictures of the list in $file are missing:\n".$error_text;
showText('Info about picture view list', $error_text, NO_WAIT);
}
$userinfo = "loading thumbnails ...";
$top->update;
checkCachedPics();
canvasHide();
# delete all photo objects (thumbnnails)
foreach (keys %thumbs) {
print "updateThumbs: deleting thumbnail object of $_\n" if $verbose;
$thumbs{$_}->delete if (defined $thumbs{$_}); # delete photo object
delete $thumbs{$_}; # delete hash entry
}
if ($verbose) {
my @check = $top->imageNames;
print " there are ".scalar @check." pics left\n";
}
# clean the thumbnail table
# with this step all references to the already deleted photo objects are cleared
# so the memory is now free again
$picLB->delete("all");
if (showThumbsInList($picLB, \@pics)) {
$userinfo = "loading thumbnails ... ready"; $userInfoL->update;
#generateThumbs(ASK, SHOW);
} else {
$userinfo = "user abord (not all pictures are loaded!)"; $userInfoL->update;
}
showNrOf();
}
##############################################################
# smart_update - reread actual directory, add new and remove
# deleted pics, without reloading the existing
# thumbnails; the goal is to have a faster
# update for large directories
##############################################################
sub smart_update {
# get the new list of pics in the actual folder
my @act_pics = getPics($actdir, WITH_PATH);
sortPics($config{SortBy}, $config{SortReverse}, \@act_pics);
# get the displayed pics from the listbox
my @disp_pics = $picLB->info('children');
my $removed_pics = 0;
my $new_pics = 0;
# remove deleted pictures first
foreach my $dpic (@disp_pics) {
if ((!isInList($dpic, \@act_pics)) and ($picLB->info('exists', $dpic))) {
print "deleting $dpic from picLB\n" if $verbose;
$removed_pics++;
$picLB->delete('entry', $dpic);
}
}
# get the displayed pics from the listbox again after the deletion
@disp_pics = $picLB->info('children');
# count new pictures first
foreach my $dpic (@act_pics) {
$new_pics++ if (!$picLB->info('exists', $dpic));
}
if ($new_pics > 0) {
# todo this init is not the perfect solution as a rename of the
# first pic will be shown as second pic
my $after = $disp_pics[0];
my $pw = progressWinInit($picLB, "Smart update");
my $n = 0;
# add the new pics to the listbox
foreach my $dpic (@act_pics) {
last if progressWinCheck($pw);
if (!$picLB->info('exists', $dpic)) {
$n++;
progressWinUpdate($pw, "adding new picture ($n/$new_pics) ...", $n, $new_pics);
print "adding $dpic to picLB\n" if $verbose;
addOneRow($picLB, $dpic, 1, $after);
}
$after = $dpic;
}
progressWinEnd($pw);
}
showNrOf();
$userinfo = "ready! removed $removed_pics and added $new_pics picture(s)"; $userInfoL->update;
generateThumbs(ASK, SHOW);
}
##############################################################
# showThumbs - display all thumbnail pictures of the actual
# directory in the listbox
##############################################################
sub showThumbs {
# clean the thumbnail table
# with this step all references to the already deleted photo objects are cleared
# so the memory is now free again
$picLB->delete('all');
if ($verbose) {
my @check = $top->imageNames;
print " there are ".scalar @check." pics left\n";
}
my @pics = getPics($actdir, WITH_PATH);
sortPics($config{SortBy}, $config{SortReverse}, \@pics);
cleanOneDir($actdir) if (@pics == 0); # remove .thumbs subdir etc.
my $rc = showThumbsInList($picLB, \@pics);
return $rc;
}
##############################################################
# showThumbsInList
##############################################################
sub showThumbsInList {
my $lb = shift; # the listbox widget
my $listR = shift; # the list of pics to show
# show some infos to the user while loading
my $n = 0; # actual number
my $nr = @$listR; # total number
if (@$listR > $config{ThumbMaxLimit}) {
$lb->messageBox(-icon => 'info', -message => "There are $nr pictures to show. The thumbnail limit is set to ".$config{ThumbMaxLimit}.". ".($nr - $config{ThumbMaxLimit})." pictures will be displayed with a default thumbnail.",
-title => "Info", -type => 'OK');
}
my $pw = progressWinInit($lb, "Load pictures");
foreach my $dpic (@$listR) {
last if progressWinCheck($pw);
$n++;
progressWinUpdate($pw, "loading picture ($n/$nr) ...", $n, $nr);
my $with_thumb = 0;
$with_thumb = 1 if ($n <= $config{ThumbMaxLimit});
addOneRow($lb, $dpic, $with_thumb);
}
progressWinEnd($pw);
if (($lb == $picLB) and ($n != $nr)) {
$userinfo = "user abord at $n of $nr"; $userInfoL->update;
$lb->after(1000); # just a litte delay to show the message above
return 0;
}
return 1;
}
##############################################################
# addOneRow - adds a new row, or updates an existing row
##############################################################
sub addOneRow {
my $lb = shift;
my $dpic = shift;
my $with_thumb = shift; # bool 1 = thumb, 0 = defaultthumb
my $after;
$after = shift; # optional
unless ($lb->info("exists", $dpic)) {
# create new row, we use the path and file name (=$dpic) as unique index for the hlist entry
if (($after) and ($lb->info("exists", $after))) {
$lb->add($dpic, -after => $after);
}
else {
$lb->add($dpic);
}
}
my $thumb = getThumbFileName($dpic);
my $thumbP = undef;
if ($config{ShowThumbs} and -f $thumb) {
$thumbP = $lb->Photo(-format => "jpeg", -file => $thumb, -gamma => $config{Gamma});
$thumbs{$dpic} = $thumbP; # save all thumb photo objects in global hash %thumbs to delete them when changing the dir
}
# test feature to improve speed: read meta info only if there is no info in the DB or the modification date has changed
# on windows this is 10 times faster to read in a folder with 200 pics (34 secs vs. 3 secs)
# todo there should be a possibility to force a reread, if somebody added metainfo without changing the modification date - however this is still possible using add to database
if ($searchDB{$dpic} and $searchDB{$dpic}{MOD}) {
if ($searchDB{$dpic}{MOD} != getFileDate($dpic, NO_FORMAT)) {
addToSearchDB($dpic); # save the infos into the search data base
}
}
else {
addToSearchDB($dpic); # save the infos into the search data base
}
my $iptc = ''; my $exif = ''; my $com = ''; my $size = '';
my $pic = basename($dpic);
my $dir = dirname($dpic);
$com = $searchDB{$dpic}{COM};
$exif = $searchDB{$dpic}{EXIF};
$iptc = displayIPTC($dpic);
$size = getAllFileInfo($dpic);
$com = formatString($com, $config{LineLength}); # format the comment for the list
$iptc = formatString($iptc, $config{LineLength}); # format the IPTC info for the list
my $image;
if ((defined $thumbP) and $with_thumb) {
$image = $thumbP;
} else {
if ($config{UseDefaultThumb} and $defaultthumbP) {
$image = $defaultthumbP;
}
else {
undef $image;
}
}
if (defined $image) {
$lb->itemCreate($dpic, $lb->{thumbcol}, -style => $thumbS, -itemtype => 'imagetext', -image => $image, -text => getThumbCaption($dpic));
}
# insert items in the table row
$lb->itemCreate($dpic, $lb->{filecol}, -text => $size, -style => $fileS);
$lb->itemCreate($dpic, $lb->{iptccol}, -text => $iptc, -style => $iptcS);
$lb->itemCreate($dpic, $lb->{comcol}, -text => $com, -style => $comS);
$lb->itemCreate($dpic, $lb->{exifcol}, -text => $exif, -style => $exifS);
$lb->itemCreate($dpic, $lb->{dircol}, -text => $dir, -style => $dirS);
}
##############################################################
# displayIPTC - convert the searchdb info into a formated string
##############################################################
sub displayIPTC {
my $dpic = shift;
my $iptc = "";
$iptc = displayUrgency($searchDB{$dpic}{URG});
$iptc .= "Keywords: ".$searchDB{$dpic}{KEYS}."\n" if (defined $searchDB{$dpic}{KEYS});
$iptc .= $searchDB{$dpic}{IPTC} if (defined $searchDB{$dpic}{IPTC});
return $iptc;
}
##############################################################
# displayUrgency - convert the integer value into a string with stars (*)
##############################################################
sub displayUrgency {
my $urg = shift;
return '' unless (defined $urg);
my $durg = '';
for (my $x = 8; $x >= $urg; $x -= 1) {
$durg .= '*';
}
return "Rating : $durg ($urg)\n";
}
##############################################################
# addToSearchDB - add a picture to the search data base
# this function can be called with one or four
# parameters
##############################################################
sub addToSearchDB {
my $dpic = shift;
# normalize the path
$dpic =~ s/\\/\//g; # replace Windows path delimiter with UNIX style \ -> /
$dpic =~ s/\/+/\//g; # replace multiple slashes with one // -> /
$dpic =~ s/\/\.\//\//g; # replace dot dir /./ -> /
if (!-f $dpic) {
warn "addToSearchDB: $dpic not found!";
return undef;
}
#print "addToSearchDB $dpic\n";
# do not save pics to the database which are located in .thumbs/ .xvpics/ .exif/
my $dir = dirname($dpic);
$dir =~ s!/$!!g; # remove trailing /
if ($dir =~ m/$thumbdirname|$exifdirname|$xvpicsdirname$/) {
print "addToSearchDB: ignoring $dpic\n" if $verbose;
return undef;
}
my ($com, $exif, $ctime, $mtime, $iptc, $urgency, $size, $x, $y, $keys, @keys, $pop);
# $meta is returned at the end of the sub,
# the SOF segment is needed for the latter call of getAllFileInfo
my $meta = getMetaData($dpic, "COM|APP1|APP13|SOF", 'FASTREADONLY');
$exif = getShortEXIF( $dpic, WRAP, $meta);
$com = getComment( $dpic, LONG, $meta);
$iptc = getIPTC( $dpic, SHORT, $meta);
$size = getFileSize( $dpic, NO_FORMAT);
($x,$y) = getSize( $dpic, $meta);
$mtime = getFileDate( $dpic, NO_FORMAT);
@keys = getIPTCkeywords($dpic, $meta);
$pop = 0;
$pop = $searchDB{$dpic}{POP} if (defined $searchDB{$dpic}{POP});
# build a string from the keyword list
foreach (@keys) { $keys .= "$_ "; }
# check if the pictures contain new keywords
if ($config{CheckNewKeywords}) {
foreach (@keys) {
# store all keywords in a hash and count them
if (defined $new_keywords{$_}) {
$new_keywords{$_}++;
}
else {
$new_keywords{$_} = 1;
}
}
}
# try to get the EXIF date from the short EXIF info format: "dd.mm.yyyy hh:mm:ss"
# there may be [t] or [s] before the date!
undef $ctime;
if (defined($exif) and ($exif =~ m/(\d\d)\.(\d\d)\.(\d\d\d\d)\s(\d\d):(\d\d):(\d\d)/)) {
my $mon = $2;
my $year = $3;
$mon--;
if ($year > $copyright_year) { # fix wrong dates
print "Mapivi warning: $dpic: EXIF year: $year is in the future, correcting to $copyright_year\n";
$year = $copyright_year;
}
$year -= 1900;
if ($mon >= 0 and $mon <= 11) {
# calculate the time as value in seconds since the Epoch (Midnight, January 1, 1970)
$ctime = timelocal($6,$5,$4,$1,$mon,$year);
#warn "using exifdate for $dpic: $ctime\n" if $verbose;
# optional checks
#my ($s,$m,$h,$d,$mo,$y) = localtime $ctime;
#$y += 1900; $mo++; # do some adjustments
# build up the date time string, sim#lar to the EXIF format
#my $date1 = sprintf "%04d:%02d:%02d %02d:%02d:%02d", $y, $mo, $d, $h, $m, $s;
#my $date2 = "$3:$2:$1 $4:$5:$6";
#print "$date2 $date $dpic\n" if ($date1 ne $date2);
}
#else { print "mon = $mon $3:$2:$1 $4:$5:$6\n";}
}
#else { print "no exif date: $exif" if $verbose; }
# if there is no exif time available use the file modification date
unless (defined $ctime) {
$ctime = (lstat $dpic)[9]; # 9 is the modification date time
#warn "using filedate for $dpic: $ctime\n" if $verbose;
}
# replace all newlines with space before adding to the database
#$com =~ s/\n/ /g if (defined $com);
#$exif =~ s/\n/ /g if (defined $exif);
#$iptc =~ s/\n/ /g if (defined $iptc);
# maybe there was something defined before, so we better overwrite it with ""
$com = "" unless (defined $com);
$exif = "" unless (defined $exif);
$iptc = "" unless (defined $iptc);
$iptc =~ s/urgency\s*:\s*\d*\s*//i; # remove urgency from the IPTC field
$iptc =~ s/keywords\s*:\s*.*\n//i; # remove keywords from the IPTC field
$urgency = getIPTCurgency($dpic, $meta);
$urgency = undef if ($urgency == 9);
delete $searchDB{$dpic}; # clear hash item first
#print "adding: IPTC: $iptc\n";
#print "adding: Keys: $keys\n";
#print "adding: URG : $urgency\n";
$searchDB{$dpic}{COM} = $com; # save (complete!) comment
$searchDB{$dpic}{EXIF} = $exif; # save short EXIF info
$searchDB{$dpic}{SIZE} = $size; # save file size in Bytes
$searchDB{$dpic}{PIXX} = $x; # save pixel size (x = width)
$searchDB{$dpic}{PIXY} = $y; # save pixel size (y = height)
$searchDB{$dpic}{TIME} = $ctime; # save EXIF/file creation time
$searchDB{$dpic}{MOD} = $mtime; # save file modification time
$searchDB{$dpic}{IPTC} = $iptc; # save complete IPTC info
$searchDB{$dpic}{URG} = $urgency; # save IPTC urgency
$searchDB{$dpic}{KEYS} = $keys; # save IPTC keywords
$searchDB{$dpic}{POP} = $pop if ($config{trackPopularity}); # save popularity (how often the pic was shown)
#print "---IPTC: $searchDB{$dpic}{IPTC}---\n";
return $meta;
}
##############################################################
# getMetaData - returns the Image::MetaData::JPEG
# object of $dpic
##############################################################
sub getMetaData {
my $dpic = shift;
my $what = shift; # regex to match the needed segments e.g. "COM" for comment,
# or "APP13|COM" for IPTC info and comment segments
my $option = shift; # optional option, if set to 'FASTREADONLY' will speed things up
return undef unless is_a_JPEG($dpic);
# mapivi just needs the comments (COM), EXIF (APP1), IPTC (APP13) and size (SOF) segments
my $meta = new Image::MetaData::JPEG($dpic, $what, $option);
print "getMetaData: Kind:$what pic:$dpic\n" if $verbose;
warn "Error: " . Image::MetaData::JPEG::Error() unless $meta;
return $meta;
}
##############################################################
# getAllFileInfo
##############################################################
sub getAllFileInfo {
my $dpic = shift;
my $bpic = buildBackupName($dpic);
my $size = '';
my $w = 0;
my $h = 0;
return '' if (!-f $dpic);
$size = basename($dpic)."\n\n";
$size .= int($searchDB{$dpic}{SIZE}/1024).'kB';
$size .= '[bak]' if (-f $bpic); # show that there is a backup file
my ($basename, $suffix) = getBasenameSuffix($dpic);
$size .= '[raw]' if (-f $basename.'.nef'); # show that there is a raw file
$size .= '[raw]' if (-f $basename.'.crw'); # show that there is a raw file
$size .= "\n".buildDateTime($searchDB{$dpic}{MOD}) if ($config{ShowFileDate});
$w = $searchDB{$dpic}{PIXX};
$h = $searchDB{$dpic}{PIXY};
my $p = sprintf "%.2f", ($w*$h/1000000); # MP = MegaPixel
$size .= "\n${w}x$h (${p}MP)";
if ($config{BitsPixel}) {
my $bitPix = getBitPix($dpic);
$bitPix = sprintf "%.2f", $bitPix;
$size .= "\n${bitPix}b/p";
}
$size .= "\n".getAspectRatio($w, $h) if ($config{AspectRatio} and ($w > 0) and ($h > 0));
if (-l $dpic) { $size .= "\n(Link)"; }
$size .= "\nViewed ".$searchDB{$dpic}{POP}.' times' if (($config{trackPopularity}) and (defined $searchDB{$dpic}{POP}));
return $size;
}
##############################################################
# getAspectRatio
##############################################################
sub getAspectRatio {
my $w = shift;
my $h = shift;
return "" if (($h == 0) or ($w == 0));
my $aspectdelta = 1 + ($config{AspectSloppyFactor} / 100); # delta factor for aspect ratio
my $r = $w/$h; # aspect ratio
my $ratio = "";
if (($r <= $aspectdelta*4/3) and ($r >= (4/3)/$aspectdelta)) {
$ratio = "[4:3]";
} elsif (($r <= $aspectdelta*3/4) and ($r >= (3/4)/$aspectdelta)) {
$ratio = "[3:4]";
} elsif (($r <= $aspectdelta*2/3) and ($r >= (2/3)/$aspectdelta)) {
$ratio = "[2:3]";
} elsif (($r <= $aspectdelta*3/2) and ($r >= (3/2)/$aspectdelta)) {
$ratio = "[3:2]";
} elsif (($r <= $aspectdelta*5/4) and ($r >= (5/4)/$aspectdelta)) {
$ratio = "[5:4]";
} elsif (($r <= $aspectdelta*4/5) and ($r >= (4/5)/$aspectdelta)) {
$ratio = "[4:5]";
} elsif (($r <= $aspectdelta*7/5) and ($r >= (7/5)/$aspectdelta)) {
$ratio = "[7:5]";
} elsif (($r <= $aspectdelta*5/7) and ($r >= (5/7)/$aspectdelta)) {
$ratio = "[5:7]";
} elsif (($r <= $aspectdelta*16/9) and ($r >= (16/9)/$aspectdelta)) {
$ratio = "[16:9]";
} elsif (($r <= $aspectdelta*9/16) and ($r >= (9/16)/$aspectdelta)) {
$ratio = "[9:16]";
} elsif ($w == $h) {
$ratio = "[1:1]";
} else {
if ($w > $h) { $ratio = sprintf "[%.2f:1]", ($w/$h); }
else { $ratio = sprintf "[1:%.2f]", ($h/$w); }
}
return $ratio;
}
##############################################################
# removeIPTC
##############################################################
sub removeIPTC {
my @sellist = $picLB->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
my $rc = $top->messageBox(-icon => 'question', -message => "Please press Ok to remove all IPTC info of the ".scalar @sellist." selected pictures.\nThere is no undo!",
-title => "Remove all IPTC info?", -type => 'OKCancel');
return if ($rc !~ m/Ok/i);
my ($dpic, $ii, $iptcread, $iptcL);
my $errors = "";
my $i = 0;
my $pw = progressWinInit($top, "Remove IPTC info");
foreach $dpic (@sellist){
last if progressWinCheck($pw);
$i++;
progressWinUpdate($pw, "Removing IPTC info ($i/".scalar @sellist.") ...", $i, scalar @sellist);
next unless (-f $dpic);
next if (!checkWriteable($dpic));
my $meta = getMetaData($dpic, "APP13");
$meta->remove_app13_info(-1, 'IPTC'); # remove all APP13 IPTC segments
unless ($meta->save()) {
$errors .= "removeIPTC: save $dpic failed!\n";
}
updateOneRow($dpic, $picLB);
}
progressWinEnd($pw);
$userinfo = "ready! (removed IPTC info of $i/".scalar @sellist.")"; $userInfoL->update;
showText("Errors while removing IPTC infos", $errors, NO_WAIT) if ($errors ne "");
return;
}
##############################################################
# cutString - cat a string to a given length, remove newline
# and carriage return and add e.g. dots if cut
# examples: cutString("elephant",20,"..") -> "elephant"
# cutString("elephant", 7,"..") -> "eleph.."
# cutString("elephant",-7,"..") -> "..phant"
##############################################################
sub cutString {
my $str = shift; # input string
my $len = shift; # the max length
my $dot = shift; # the dots (e.g. ".." or "...")
return unless (defined $str);
return if ($str eq "");
my $dotlen = length($dot);
my $out = $str;
if (length($dot) >= abs($len)) {
warn "cutString: lenght of dots is longer or equal than length";
return $out;
}
if ($len >= 0) {
$out = substr($out, 0, ($len-$dotlen)).$dot if (length($out) > $len);
}
else {
$out = $dot.substr($out, ($len+$dotlen), length($str)) if (length($out) > -$len);
}
$out =~ s/\n//g; # remove newlines
$out =~ s/\r//g; # remove \r (carriage return)
return $out;
}
##############################################################
# formatString - cuts and formats a string to
# a width of $linelenght chars and a length of
# $config{LineLimit} lines.
# this function wont work as expected with
# comments containing a lot of nearly empty lines
##############################################################
sub formatString {
my $string = shift;
my $linelenght = shift;
return "" if ((!defined $string) or ($string eq ""));
$Text::Wrap::columns = $linelenght+1;
# $string =~ s/^\s+//; # cut leading white
# $string =~ s/\s+$//; # cut trailing white
$string =~ s/\r//g; # cut \r (carriage return)
# cut long strings and add a ...
# $string = substr($string, 0, $chars)."..." if (($chars > 0) and (length($string) > ($chars + 3)));
# $string =~ s/$/ /; # add a trailing space
# $string =~ s/(.{0,$linelenght})\s+/$1\n/g; # insert a newline every $linelenght chars with withespace
$string =~ tr[\200-\377][\000-\177]; # remove the eight bit
$string = wrap("","",$string);
my @l = split /\n/, $string; # limit the lines
my $max = $config{LineLimit};
$max = @l if (@l < $config{LineLimit});
$string = "";
for ( 0 .. ($max - 1)) {
$string .= sprintf "%s\n", $l[$_];
}
$string =~ s/\n+$//; # cut off trailing newline(s)
return $string;
}
##############################################################
# getFileSize - get the size in kB of a file, even if it is a link
##############################################################
sub getFileSize {
my $dpic = shift;
my $format = shift; # NO_FORMAT = return size unformated in Bytes (integer) FORMAT = with "kB" added (string)
my $size = "";
return $quickSortHashSize{$dpic} if ($quickSortSwitch and defined $quickSortHashSize{$dpic});
if (!-f $dpic) {
warn "getFileSize: $dpic is no file!";
if ((defined $format) and ($format == NO_FORMAT)) {
return 0;
}
else {
return "";
}
}
if (-l $dpic) {
$size = (lstat (getLinkTarget($dpic)))[7];
}
else {
$size = (lstat $dpic)[7];
}
if ((defined $format) and ($format == FORMAT)) {
$size = int($size/1024)."kB" if $size;
}
$quickSortHashSize{$dpic} = $size if $quickSortSwitch;
return $size;
}
##############################################################
# makeDir - create the directory for storing the
# thumbnail pictures or EXIF infos
##############################################################
sub makeDir {
my $dir = shift;
my $ask = shift; # ASK = ask before creating a dir, NO_ASK
return 1 if (-d $dir);
if ( ($ask == ASK) and $config{AskMakeDir} ) {
my $rc = checkDialog("Create new directory?",
"MaPiVi would like to create this directory:\n$dir\nContinue?",
\$config{AskMakeDir},
"ask every time",
"",
'OK', 'Cancel');
return if ($rc ne 'OK');
}
# 0755 = rwxr.xr.x
eval { mkpath($dir, 0, 0755) }; # 0 = no output, 0755 = access rights
if ($@) {
$top->messageBox(-icon => 'warning', -message => "makeDir: can not create $dir: $@",
-title => 'Error', -type => 'OK');
return 0;
}
return 1;
}
##############################################################
# aNewerThanb - true if file a is newer than file b, or if
# file a exists and file b does not
##############################################################
sub aNewerThanb {
my $afile = shift;
my $bfile = shift;
if (-f $afile) {
if (-f $bfile) {
# compare modification times
return (lstat $afile)[9] > (lstat $bfile)[9];
}
return 1;
}
return 0;
}
##############################################################
# nextPic - get the index of the next picture in the directory
##############################################################
sub nextPic {
my $actpic = shift;
my @pics = $picLB->info('children');
# if there are no pics return an empty string
return "" if (@pics == 0);
# if there is no actpic we start with the first
return $pics[0] if ($actpic eq "");
# try to get the next pic
my $next = $picLB->info('next', $actpic);
# if there is no next pic
unless ($next) {
# we have reached the end and start again with the first picture
beep() if ($config{BeepWhenLooping});
$next = $pics[0];
}
return $next;
}
##############################################################
# nextSelectedPic - get the index of the next selected picture
# in the directory
##############################################################
sub nextSelectedPic {
my $actpic = shift;
my @pics = $picLB->info('children');
my @sel = $picLB->info('selection');
# if there are no pics return an empty string
return "" if (@pics == 0);
return "" if (@sel == 0);
my $start = 0;
my $next = "";
my $nextsel = "";
foreach my $dpic (@pics) {
# skip all pics until we reach the actual picture
$start = 1 if ($dpic eq $actpic);
next unless $start;
# get the next picture
$next = $picLB->info('next', $dpic);
# check if it is selected
if ($next and isInList($next, \@sel)) {
$nextsel = $next;
last;
}
}
# if there is no next pic
if ($nextsel eq "") {
# we have reached the end and start again with the first selected picture
#beep() if ($config{BeepWhenLooping});
$nextsel = $sel[0];
}
return $nextsel;
}
##############################################################
# prevPic - show the previous picture in the directory
##############################################################
sub prevPic {
my $actpic = shift;
my @pics = $picLB->info('children');
# if there are no pics return an empty string
return "" if (@pics == 0);
# if there is no actpic we start with the first
return $pics[-1] if ($actpic eq "");
# try to get the previous pic
my $prev = $picLB->info('prev', $actpic);
# if there is no prev pic
unless ($prev) {
# we have reached the start and jump to the last picture
beep() if ($config{BeepWhenLooping});
$prev = $pics[-1];
}
return $prev;
}
##############################################################
# gotoPic
##############################################################
sub gotoPic {
my $lb = shift;
return if (stillBusy()); # block, until last picture is loaded
if ($slideshow == 1) {
$slideshow = 0; slideshow();
} # switch slideshow off
my @childs = $lb->info('children');
return if (!@childs);
my $goto = "";
my $rc = myEntryDialog("Go to picture/select pictures", "Please enter a part of the name or the index number of the picture(s) to select/show.\nIndex number are entered like this: /number.\nUse /c to switch to case sensitive and /s if the filename starts with the search string.\n\nExamples:\nabc show and select all pictures containing abc (any case)\n/10 show picture number 10\n/sabc show and select all pictures starting with abc (any case)\n/cABC show and select all pictures containing an upper case ABC\n/s/cABC show and select all pictures starting with an upper case ABC", \$goto);
return if (($rc ne 'OK') or ($goto eq ""));
if ($goto =~ m/(\/)(\d+)/) { # $goto is a number
if (($2 > 0) and ($2 < @childs + 1)) {
# saved here for undo function
@savedselection2 = @savedselection;
@savedselection = $lb->info('selection');
$lb->selectionClear();
showPic($childs[$2-1]) if ($lb == $picLB);
}
else {
$userinfo = "number $2 is out of range!"; $userInfoL->update;
}
}
else { # $goto is a string
my @pics;
my $case = "i";
my $start = ".*";
if ($goto =~ m/.*\/c/) { $case = ""; $goto =~ s/\/c//; }
if ($goto =~ m/.*\/s/) { $start = "^"; $goto =~ s/\/s//; }
foreach (@childs) {
if (basename($_) =~ m/(?$case)$start$goto.*/) {
push @pics, $_;
}
}
if (@pics) {
# saved here for undo function
@savedselection2 = @savedselection;
@savedselection = $lb->info('selection');
$lb->selectionClear();
showPic($pics[0]) if ($lb == $picLB);
reselect($lb, @pics);
$userinfo = "selected ".scalar @pics." pictures matching \"$goto\""; $userInfoL->update;
}
else {
$userinfo = "string $goto was not found in the picture names"; $userInfoL->update;
}
}
}
##############################################################
# showImageInfo - display infos and comment of given image
# if availabel
##############################################################
sub showImageInfo {
my $dpic = shift;
if (!-f $dpic) {
$widthheight = "";
$size = "";
$exif = "";
$urgencyStr = "";
$urgencyScale = 0;
$commentText->delete( 0.1, 'end') if ($config{ShowCommentField});
}
else {
my $meta = getMetaData($dpic, "COM|APP13|APP1|SOF", 'FASTREADONLY');
($width, $height) = getSize($dpic, $meta);
$widthheight = $width.'x'.$height;
if ($config{ShowEXIFField}) {
$exif = getShortEXIF($dpic, NO_WRAP, $meta);
}
if ($config{ShowCommentField}) {
my $comment = getComment($dpic, LONG, $meta);
# does not work! mh 14.07.03
# # determine the height of the textbox by counting the number of lines
# my $height = ($comment =~ tr/\n//);
# $height++;
# $height = 10 if ($height > 10); # not to big, we have scrollbars
# print "h = $height\n";
# $commentText->configure(-height => $height);
$commentText->delete( 0.1, 'end'); # remove old comment
$commentText->insert('end', $comment); # insert new comment
}
if ($config{ShowUrgency}) {
$urgencyStr = getIPTCurgency($dpic, $meta);
$urgencyScale = 9 - $urgencyStr;
$urgencyScale = 0 if (($urgencyStr < 1) or ($urgencyStr > 8));
$urgencyStr = "" if ($urgencyStr > 8);
}
$size = getFileSize($dpic, FORMAT);
}
setTitle();
}
##############################################################
# showImageInfoCanvas - display infos on the canvas
##############################################################
sub showImageInfoCanvas {
my $dpic = shift;
$c->delete('withtag', 'TEXT');
return unless (defined $dpic);
return unless (-f $dpic);
return unless ($config{ShowInfoInCanvas});
my $info = "";
my $meta = getMetaData($dpic, "COM|APP13|APP1|SOF", 'FASTREADONLY');
my $exif = formatString(getShortEXIF($dpic, NO_WRAP, $meta), 80);
my $comm = formatString(getComment($dpic, LONG, $meta), 80);
my $iptc = formatString(getIPTC($dpic, SHORT, $meta), 80);
$info .= "EXIF:\n$exif\n" if ($exif ne "");
$info .= "--------------------\n" if (($exif ne "") and (($comm ne "") or ($iptc ne "")));
$info .= "Comment:\n$comm\n" if ($comm ne "");
$info .= "--------------------\n" if (($comm ne "") and ($iptc ne ""));
$info .= "IPTC:\n$iptc" if ($iptc ne "");
return if ($info eq '');
# show image info on canvas white font with black shadow
$c->createText( 5, 5, -font => $font, -text => $info, -anchor => 'nw', -fill => 'black', -tags => ['TEXT']);
$c->createText( 4, 4, -font => $font, -text => $info, -anchor => 'nw', -fill => 'white', -tags => ['TEXT']);
}
##############################################################
# showZoomInfo - calculate the zoom factor of the displayed
# pic by messuring the size of the file
# and the size on the canvas
##############################################################
sub showZoomInfo {
my $dpic = shift;
my $id = shift;
if (-f $dpic) {
my ($width, $height) = getSize($dpic);
my ($x1, $y1, $x2, $y2) = $c->bbox($id);
if (defined $x2 and defined $x1 and ($x2 - $x1 != 0)) {
my $z = $width/($x2 - $x1);
if ($z > 0) { # avoid divison by zero
$zoomFactorStr = int(1/$z * 100)."%";
return;
}
}
}
$zoomFactorStr = "?%";
}
##############################################################
# handleNonJPEG
##############################################################
sub handleNonJPEG {
my $dir = shift;
my @pics = @_;
my $changed = 0; # counter
return 0 if ((defined $nonJPEGdirNoAskAgain{"$dir"}) and ($nonJPEGdirNoAskAgain{"$dir"} == 1));
# open window
my $myDiag = $top->Toplevel();
$myDiag->title('Non-JPEG pictures');
$myDiag->Label(-text => "There are ".scalar @pics." non-JPEG pictures in directory ".basename($dir).".\nShould I convert these pictures to JPEG format?\n(After convertion these pictures will be visible in Mapivi.)",
-bg => $config{ColorBG}
)->pack(-fill => 'x', -padx => 3, -pady => 3);
my $qS = labeledScale($myDiag, 'top', 40, "Quality of JPEG picture when converting", \$config{PicQuality}, 10, 100, 1);
qualityBalloon($qS);
my $removeOrig = 0;
$myDiag->Checkbutton(-variable => \$removeOrig, -text => "Remove the original pictures after conversion")->pack(-anchor=>'w');
my $ButF =
$myDiag->Frame()->pack(-fill =>'x', -padx => 0, -pady => 0);
my $OKB =
$ButF->Button(-text => 'OK',
-command => sub {
$myDiag->withdraw();
$myDiag->destroy();
$changed = convertToJPEG($dir, $removeOrig, @pics);
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 2, -pady => 3);
$ButF->Button(-text => "Show picture list",
-command => sub {
my $info = "Non-JPEG pictures in $dir:\n\n";
foreach (sort @pics) {
my $size = getFileSize("$dir/$_", NO_FORMAT);
$info .= sprintf "%-45s %12s Bytes\n", $_, $size;
}
showText("Non-JPEG pictures", $info, WAIT);
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 2, -pady => 3);
$ButF->Button(-text => 'Cancel',
-command => sub {
# save dir in hash, so we don't bother the user again if he reopens the dir
$nonJPEGdirNoAskAgain{"$dir"} = 1;
$myDiag->withdraw();
$myDiag->destroy();
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 2, -pady => 3);
$myDiag->Popup(-popover => 'cursor');
repositionWindow($myDiag);
if ($EvilOS) { # sometimes to dialog disappears when clicked on, so we need a short grab
$myDiag->grab;
$myDiag->after(50, sub{$myDiag->grabRelease});
}
$myDiag->waitWindow;
my $reread = ($changed > 0) ? 1 : 0;
return $reread;
}
##############################################################
# convertToJPEG - convert the piclist to JPEG format
##############################################################
sub convertToJPEG {
my $dir = shift;
my $del = shift; # delete orig after conversion (bool)
my @pics = @_;
my $converted = 0;
foreach (@pics) {
my $dpic = "$dir/$_";
my $tpic = $dpic;
$tpic =~ s/($nonJPEGsuffixes)$/jpg/i;
print "convertToJPEG: $_ -> $tpic\n" if $verbose;
if (-f $tpic) {
$top->messageBox(-icon => 'warning', -message => "$tpic exists - skipping!",
-title => 'Warning', -type => 'OK');
next;
}
$userinfo = "converting $_ to JPEG $tpic ..."; $userInfoL->update;
my $command = "convert";
$command .= " -quality ".$config{PicQuality}." \"$dpic\" \"$tpic\"";
$top->Busy;
#(system "$command") == 0 or warn "$command failed: $!";
execute($command);
$top->Unbusy;
$converted++ if ((-f $tpic) and (!-z $tpic));
if (($del) and ((-f $tpic) and (!-z $tpic))) { removeFile($dpic); }
}
return $converted;
}
##############################################################
# showNonJPEGS - show all non JPEG files of the actual dir
##############################################################
sub showNonJPEGS {
my @files = getFiles($actdir);
# put just the files not matching jpg, jpeg, JPG or JPEG in the file list
my @nonjpeg = grep {!m/.*\.jp(g|eg)$/i} @files;
my $info = "There are ".scalar @nonjpeg." non-JPEGs in $actdir:\n\n";
foreach (sort @nonjpeg) {
my $size = getFileSize("$actdir/$_", NO_FORMAT);
$info .= sprintf "%-45s %12s Bytes\n", $_, $size;
}
showText("Non-JPEGs", $info, WAIT);
}
##############################################################
# convertNonJPEGS
##############################################################
sub convertNonJPEGS {
my @files = getFiles($actdir);
# put just the files not matching jpg, jpeg, JPG or JPEG in the file list
my @nonjpeg = grep {!m/.*\.jp(g|eg)$/i} @files;
handleNonJPEG($actdir, @nonjpeg);
updateThumbs();
}
##############################################################
# getPics - returns the piclist of the given dir
##############################################################
sub getPics {
my $dir = shift;
my $with_path = shift; # WITH_PATH or JUST_FILE
my @other;
my @files = getFiles($dir);
# are there non-JPEG pictures in this directory?
if ($config{CheckForNonJPEGs}) {# and !$dirHotlist{$dir}) {
@other = grep {m/.*\.($nonJPEGsuffixes)$/i} @files;
my @otherNoJPEG;
foreach (@other) {
$_ =~ m/(.*)\.($nonJPEGsuffixes)$/i; # separate the name from the suffix
my $jpeg = "$1.jpg"; # built the corresponding jpeg file name
if (!-f "$dir/$jpeg") { # if this doesn't exists
push @otherNoJPEG, $_ # we push it to this list
}
}
# are there some non-JPEGs without corresponding JPEGs?
if (@otherNoJPEG > 0) {
my $reread = handleNonJPEG($dir, @otherNoJPEG); # ask the user to convert them
@files = getFiles($dir) if $reread; # reread file list if necessary
}
}
# put just the files matching jpg, jpeg, JPG or JPEG in the file list
#my @jpegs = grep {m/.*\.(jp(g|eg))|(gif)|(xpm)|(ppm)|(xbm)|(ti(f|ff))|(svg)|(png)|(bmp)$/i} @files;
my @jpegs;
if ($config{supportOtherPictureFormats}) {
@jpegs = grep {m/.*\.(jp(g|eg))|(gif)|(xpm)|(ppm)|(xbm)|(ti(f|ff))|(svg)|(png)|(bmp)|(nef)|(raw)$/i} @files;
}
else {
@jpegs = grep {m/.*\.jp(g|eg)$/i} @files;
}
# if we are in the actual dir, display the number of non-JPEG files
if ($dir eq $actdir) {
$otherFiles = @files - @jpegs;
$otherFiles = "" if ($otherFiles == 0);
}
$dir =~ s|/*$||; # remove trailing slashes
if ($with_path == WITH_PATH) {
foreach (@jpegs) { $_ = "$dir/$_"; } # add the path to each file
}
return @jpegs;
}
##############################################################
# sortPics - sorts a list of pictures according to $sortby
##############################################################
sub sortPics {
my $sortby = shift;
my $sortreverse = shift;
my $pics = shift; # reference on array to sort
print "sortby = $sortby\n" if $verbose;
my $str = "sorting ".scalar @$pics." pictures by $sortby";
$str .= " (reverse)" if $sortreverse;
$userinfo = "$str ...";
$userInfoL->update;
clearQuickSortHashes(); # remove old values
$quickSortSwitch = 1; # activate quick sort/buffering
if ($sortby eq "name") { # sort alphabetical with no case
@$pics = sort { uc(basename($a)) cmp uc(basename($b)) } @$pics;
}
elsif ($sortby eq "date") { # sort by file date and name
#@$pics = sort { getFileDate($b, NO_FORMAT) <=> getFileDate($a, NO_FORMAT) ||
#uc($a) cmp uc($b) } @$pics;
@$pics = sort { $searchDB{$b}{MOD} <=> $searchDB{$a}{MOD} ||
uc($a) cmp uc($b) } @$pics;
}
elsif ($sortby eq "exifdate") {
#@$pics = sort { getEXIFDate($b) cmp getEXIFDate($a) ||
#uc($a) cmp uc($b) } @$pics;
@$pics = sort { $searchDB{$b}{TIME} <=> $searchDB{$a}{TIME} ||
uc($a) cmp uc($b) } @$pics;
}
elsif ($sortby eq "aperture") {
@$pics = sort { getEXIFAperture($a, NUMERIC) <=> getEXIFAperture($b, NUMERIC) ||
uc($a) cmp uc($b) } @$pics;
}
elsif ($sortby eq "exposuretime") {
@$pics = sort { getEXIFExposureTime($a, NUMERIC) <=> getEXIFExposureTime($b, NUMERIC) ||
uc($a) cmp uc($b) } @$pics;
}
elsif ($sortby eq "model") {
@$pics = sort { uc(getEXIFModel($a)) cmp uc(getEXIFModel($b)) ||
uc($a) cmp uc($b) } @$pics;
}
elsif ($sortby eq "artist") {
@$pics = sort { uc(getEXIFArtist($a)) cmp uc(getEXIFArtist($b)) ||
uc($a) cmp uc($b) } @$pics;
}
elsif ($sortby eq "size") {
#@$pics = sort { getFileSize($a, NO_FORMAT) <=> getFileSize($b, NO_FORMAT) ||
#uc($b) cmp uc($a) } @$pics;
@$pics = sort { $searchDB{$b}{SIZE} <=> $searchDB{$a}{SIZE} ||
uc($a) cmp uc($b) } @$pics;
}
elsif ($sortby eq "pixel") {
@$pics = sort { getPixels($a) <=> getPixels($b) ||
uc($b) cmp uc($a) } @$pics;
}
elsif ($sortby eq "bitpix") {
@$pics = sort { getBitPix($a) <=> getBitPix($b) ||
uc($b) cmp uc($a) } @$pics;
}
elsif ($sortby eq "urgency") {
@$pics = sort { getIPTCurgencyDB($a) <=> getIPTCurgencyDB($b) ||
uc($a) cmp uc($b) } @$pics;
}
elsif ($sortby eq "popularity") {
@$pics = sort { $searchDB{$b}{POP} <=> $searchDB{$a}{POP} ||
uc($a) cmp uc($b) } @$pics;
}
elsif ($sortby eq "byline") {
@$pics = sort { uc(getIPTCByLine($a)) cmp uc(getIPTCByLine($b)) ||
uc($a) cmp uc($b) } @$pics;
}
elsif ($sortby eq "random") {
fisher_yates_shuffle($pics);
#@$pics = @$pics;
}
else {
my $sort = "undefined!";
$sort = $sortby if (defined $sortby);
warn "sortPics: error: wrong sort: $sort - sorting by name";
@$pics = sort { uc($a) cmp uc($b); } @$pics;
}
clearQuickSortHashes(); # free mem
$quickSortSwitch = 0; # stop quick search
if ($sortreverse and ($sortby ne "random")) {
@$pics = reverse @$pics;
}
}
##############################################################
# clearQuickSortHashes - reset all sort hashes
##############################################################
sub clearQuickSortHashes {
undef %quickSortHash;
undef %quickSortHashSize;
undef %quickSortHashPixel;
undef %quickSortHashBitsPixel;
}
##############################################################
# getFileDate - parameter: file (with absolute path)
# format
##############################################################
sub getFileDate {
my $dpic = shift;
my $format = shift; # FORMAT = the date is returned in this date format (dd.mm.yyyy hh:mm:ss); NO_FORMAT
return $quickSortHash{$dpic} if ($quickSortSwitch and defined $quickSortHash{$dpic});
unless (-f $dpic) {
warn "$dpic is no file!" if $verbose;
return 0;
}
my $filedate = (lstat $dpic)[9]; # 9 is the modify time
$filedate = buildDateTime($filedate) if ((defined $format) and ($format == FORMAT));
$quickSortHash{$dpic} = $filedate if $quickSortSwitch;
return $filedate;
}
##############################################################
# getEXIFDate - parameter: file (with absolute path)
# image info (optional)
# returns yyyy:mm:dd hh:mm:ss
##############################################################
sub getEXIFDate {
my $dpic = shift;
my $er = shift; # optional, the EXIF hash ref if available
return "" unless (is_a_JPEG($dpic));
return $quickSortHash{$dpic} if ($quickSortSwitch and defined $quickSortHash{$dpic});
unless (defined($er)) {
my $meta = getMetaData($dpic, 'APP1$', 'FASTREADONLY') ;
$er = $meta->get_Exif_data('ALL', 'TEXTUAL');
warn "$dpic has no exif info" if ($verbose and (!defined($er)));
}
my $date = [];
my $datestr = "";
if (defined $er->{'SUBIFD_DATA'}->{DateTimeOriginal}) {
$datestr = ${$er->{'SUBIFD_DATA'}->{DateTimeOriginal}}[0];
} elsif (defined $er->{'SUBIFD_DATA'}->{DateTimeDigitized}) {
$datestr = ${$er->{'SUBIFD_DATA'}->{DateTimeDigitized}}[0];
} elsif (defined $er->{'IFD0_DATA'}->{DateTime}) {
$datestr = ${$er->{'IFD0_DATA'}->{DateTime}}[0];
} else {
}
$datestr =~ tr/\000/ /; # remove null termination (\000) chars
$datestr =~ s/( )*$//g; # remove trailing space
printf "getEXIFDate: -%s- (%s)\n", $datestr, basename($dpic) if $verbose;
$quickSortHash{$dpic} = $datestr if $quickSortSwitch;
return $datestr;
}
##############################################################
# getEXIFModel - parameter: file (with absolute path)
# image info (optional)
##############################################################
sub getEXIFModel {
my $dpic = shift;
my $er = shift; # optional, the EXIF hash ref if available
return $quickSortHash{$dpic} if ($quickSortSwitch and defined $quickSortHash{$dpic});
unless (defined($er)) {
my $meta = getMetaData($dpic, 'APP1$', 'FASTREADONLY') ;
$er = $meta->get_Exif_data('ALL', "TEXTUAL");
warn "$dpic has no exif info" unless (defined $er);
}
my $maker = "";
if (defined $er->{'IFD0_DATA'}->{'Make'}) {
$maker = ${$er->{'IFD0_DATA'}->{'Make'}}[0];
$maker =~ s/( co\.,ltd)//i; # some companies are a little to verbose here,
$maker =~ s/( co\., ltd\.)//i;
$maker =~ s/( optical)//i; # so we try to short some words
$maker =~ s/( electric)//i;
$maker =~ s/(\.)//i;
$maker =~ s/( corporation)//i;
$maker =~ s/(eastman kodak company)/KODAK/i;
$maker =~ s/(hewlett-packard company)/Hewlett-Packard/i;
$maker =~ s/(konica)/Konica/i;
$maker =~ s/(pentax)/Pentax/i;
$maker =~ s/(nikon)/Nikon/i;
}
my $model = "";
if (defined $er->{'IFD0_DATA'}->{'Model'}) {
$model = ${$er->{'IFD0_DATA'}->{'Model'}}[0];
$model =~ s/(digital camera )//i; # uh, really! :) - ok it could also be a scanner ...
$model =~ s/(digital camera)//i; # sometimes with trailing space, sometimes not ...
$model =~ s/(digital science )//i; # this is really to verbose ...
$model =~ s/(digital science)//i; # sometimes with trailing space, sometimes not ...
$model =~ s/( digital)//i; #
$model =~ s/(kodak )//i; # hello! we already had this in the Make field ...
$model =~ s/(canon )//i;
$model =~ s/(konica )//i;
$model =~ s/(pentax )//i;
$model =~ s/(nikon )//i;
$model =~ s/(sigma )//i;
$model =~ s/(HP )//;
}
$quickSortHash{$dpic} = "$maker $model" if $quickSortSwitch;
return "$maker $model";
}
##############################################################
# getEXIFArtist - parameter: file (with absolute path)
# image info (optional)
##############################################################
sub getEXIFArtist {
my $dpic = shift;
my $er = shift; # optional, the EXIF hash ref if available
return $quickSortHash{$dpic} if ($quickSortSwitch and defined $quickSortHash{$dpic});
unless (defined($er)) {
my $meta = getMetaData($dpic, 'APP1$', 'FASTREADONLY') ;
$er = $meta->get_Exif_data('ALL', "TEXTUAL");
warn "$dpic has no exif info" unless (defined $er);
}
my $artist = "";
if (defined $er->{'IFD0_DATA'}->{Artist}) {
$artist = ${$er->{'IFD0_DATA'}->{Artist}}[0];
}
$quickSortHash{$dpic} = $artist if $quickSortSwitch;
print "Artist: $artist pic:$dpic\n" if $verbose;
return $artist;
}
##############################################################
# getEXIFAperture - parameter: file (with absolute path)
# format (boolean)
# image info (optional)
##############################################################
sub getEXIFAperture {
my $dpic = shift;
my $format = shift; # NUMERIC or STRING
my $er = shift; # optional, the EXIF hash ref if available
return $quickSortHash{$dpic} if ($quickSortSwitch and defined $quickSortHash{$dpic});
unless (defined($er)) {
my $meta = getMetaData($dpic, 'APP1$', 'FASTREADONLY') ;
$er = $meta->get_Exif_data('ALL', "TEXTUAL");
warn "$dpic has no exif info" unless (defined $er);
}
# FNumber: The actual F-number (F-stop) of lens when the image was taken.
my $aperture = 0;
if (defined $er->{'SUBIFD_DATA'}->{FNumber}) {
$aperture = calc($er->{'SUBIFD_DATA'}->{FNumber});
}
elsif (defined $er->{'SUBIFD_DATA'}->{ApertureValue}) {
$aperture = calc($er->{'SUBIFD_DATA'}->{ApertureValue});
}
else { }
$aperture = sprintf("F%02.1f ", $aperture) if (($format == STRING) and ($aperture != 0));
$quickSortHash{$dpic} = $aperture if $quickSortSwitch;
return $aperture;
}
##############################################################
# getEXIFExposureTime - parameter: file (with absolute path)
# format (boolean)
# image info (optional)
##############################################################
sub getEXIFExposureTime {
my $dpic = shift;
my $format = shift; # STRING -> return a string ("1/20s "), NUMERIC -> return a value (0,05)
my $er = shift; # optional, EXIF hash ref
my $exti = ""; # exposure time as string
my $extiN = 0; # exposure time as number
return $quickSortHash{$dpic} if ($quickSortSwitch and defined $quickSortHash{$dpic});
unless (defined($er)) {
my $meta = getMetaData($dpic, 'APP1$', 'FASTREADONLY') ;
$er = $meta->get_Exif_data('ALL', "TEXTUAL");
if ($verbose) { warn "$dpic has no exif info" unless (defined $er); }
}
if (defined $er->{'SUBIFD_DATA'}->{'ExposureTime'}) {
my $time = $er->{'SUBIFD_DATA'}->{'ExposureTime'};
warn "getEXIFExposureTime: not enough numbers!" if (@{$time} < 2);
# this should not happen
if ($$time[1] == 0) {
warn "error ".basename($dpic)." wrong EXIF exposure time t0:$$time[0] t1:$$time[1]";
$format == STRING ? return "" : return 0;
}
if (($$time[0]/$$time[1]) >= 1) { # handle long time exposure (e.g. 800/100)
$exti = sprintf "%.2f",($$time[0]/$$time[1]);
$extiN = $exti;
}
else { # handle everything faster than one second
if ($$time[0] != 1) { # some cameras use the format 10/600
if ($$time[0] == 0) {
print "error ".basename($dpic)." div by zero exti:$exti t0: $$time[0] t1:$$time[1]\n" if $verbose;
$exti = "1/$$time[1]?";
$extiN = 0;
}
else {
$exti = "1/".int($$time[1]/$$time[0]); # instead of 1/60 so we have to normalize this
$extiN = 1/int($$time[1]/$$time[0]);
}
}
else {
$exti = "1/".$$time[1];
$extiN = 1/$$time[1];
}
}
}
elsif (defined $er->{'SUBIFD_DATA'}->{'ShutterSpeedValue'}) {
my $time = $er->{'SUBIFD_DATA'}->{'ShutterSpeedValue'};
$exti = ($$time[0]/$$time[1]);
$exti = int(2**$exti);
$extiN = 1/$exti;
$exti = "1/".$exti;
}
else {
$exti = "";
$extiN = 0;
}
my $rc = 0;
if ($format == STRING) {
if ($exti eq "") {
$rc = "";
} else {
$rc = $exti."s "; # add the time unit (s = second)
}
} else { #$format == NUMERIC
$rc = $extiN;
}
$quickSortHash{$dpic} = $rc if $quickSortSwitch;
return $rc;
}
##############################################################
# getFiles - returns the filelist of the given dir
##############################################################
sub getFiles {
my $dir = shift;
print " getFiles: in $dir\n" if $verbose;
my @fileDirList = readDir($dir);
my @fileList;
foreach (@fileDirList) {
# put only files which are not empty into the filelist
push @fileList, $_ if ((-f "$dir/$_") and (!-z "$dir/$_"));
}
return @fileList;
}
##############################################################
# getDirs - returns the dir list of the given dir
##############################################################
sub getDirs {
my $dir = shift;
my @fileDirList = readDir($dir);
my @dirList;
foreach (@fileDirList) {
next if (($_ eq ".") or ($_ eq ".."));
push @dirList, $_ if (-d "$dir/$_");
}
@dirList = sort { uc($a) cmp uc($b) } @dirList;
return @dirList;
}
##############################################################
# getDirsRecursive - returns all subdirs of the given dir
# $dir is also included in list
# mapivi and gimp subdirs are skipped
# dirs starting with "." are skipped
##############################################################
sub getDirsRecursive {
my $dir = shift;
my @dirs;
find(sub {
if (-d and ($_ !~ m|^\.|) and ($_ ne $thumbdirname) and ($_ ne $exifdirname)) {
push @dirs, $File::Find::name;
}
}, $dir);
return @dirs;
}
##############################################################
# readDir - reads the contents of the given directory
##############################################################
sub readDir {
my $dir = shift;
if (! -d $dir) {
warn "readDir: $dir is no dir!: $!" unless (($dir =~ m/.*$thumbdirname$/) or ($dir =~ m/.*$plugindir$/));
return 0;
}
my @fileDirList;
# open the directory
if (!opendir ACTDIR, "$dir") {
warn "Can't open directory $dir: $!";
return 0;
}
# show no files starting with a '.', but '..'
@fileDirList = grep /^(\.\.)|^[^\.]+.*$/, readdir ACTDIR;
closedir ACTDIR;
return @fileDirList;
}
##############################################################
# restart
##############################################################
sub restart {
saveAllConfig();
freeMem();
system "mapivi &";
exit;
}
##############################################################
# quitMain
##############################################################
sub quitMain {
saveAllConfig();
freeMem();
exit;
}
##############################################################
# freeMem
##############################################################
sub freeMem {
# clean up all photo objects
$userinfo = "free mem ..."; $userInfoL->update;
foreach ($top->imageNames) {
if (defined $_) {
print "cleaning up: $_\n" if $verbose;
$_->delete;
}
else {
warn "image $_ is not defined!";
}
}
$userinfo = "exit ..."; $userInfoL->update;
}
##############################################################
# saveAllConfig
##############################################################
sub saveAllConfig {
$userinfo = "saving configuration ..."; $userInfoL->update;
$config{Geometry} = $top->geometry;
$keyXBut->invoke if (Exists($keyw)); # this will trigger the saving of the treemode and win geometry
saveAdjusterPos();
$config{LastDir} = $actdir if (-d $actdir);
# we don't want to start in full screen mode
# so if we've been in fullscreen mode, we save the settings from before the fullscreen switch
if ($topFullScreen) {
print "saveAllConfig called in full screen mode\n" if $verbose;
$config{Geometry} = $topFullSceenConf{Geometry};
$config{ShowMenu} = $topFullSceenConf{ShowMenu};
$config{ShowInfoFrame} = $topFullSceenConf{ShowInfoFrame};
$config{ShowCommentField} = $topFullSceenConf{ShowCommentField};
$config{ShowEXIFField} = $topFullSceenConf{ShowEXIFField};
$config{Layout} = $topFullSceenConf{Layout};
}
else { print "saveAllConfig called in normal screen mode\n" if $verbose; }
$userinfo = "saving options ..."; $userInfoL->update;
saveConfig($configFile, \%config);
if ($config{SaveDatabase}) {
$userinfo = "saving search database ..."; $userInfoL->update;
store(\%searchDB, "$configdir/SearchDataBase") or warn "could not store searchDB in file $configdir/SearchDataBase: $!";
}
$userinfo = "saving dir hotlist ..."; $userInfoL->update;
store(\%dirHotlist, "$configdir/hotlist") or warn "could not store $configdir/hotlist: $!";
my $datetime = getDateTime();
# save a copy of the old hash in the trash # todo: remove very old backups
$userinfo = "saving dir check list ..."; $userInfoL->update;
mycopy("$configdir/dirProperties", "$trashdir/dirProperties-$datetime", OVERWRITE) if (-f "$configdir/dirProperties");
store(\%dirProperties, "$configdir/dirProperties") or warn "could not store $configdir/dirProperties: $!";
store(\%ignore_keywords, "$configdir/keywords_ignore") or warn "could not store $configdir/keywords_ignore: $!";
if (MatchEntryAvail) {
$userinfo = "saving entry values ..."; $userInfoL->update;
store(\%entryHistory, $file_Entry_values) or warn "could not store $file_Entry_values: $!";
}
$userinfo = "saving categories ..."; $userInfoL->update;
saveArrayToFile("$configdir/categories", \@precats);
$userinfo = "saving keywords ..."; $userInfoL->update;
saveArrayToFile("$configdir/keywords", \@prekeys);
$userinfo = "ready!"; $userInfoL->update;
}
##############################################################
# getComment - returns a string containing all Comments
# (if available) of the given pic (up to 64K per
# block, nr of blocks is not limited, so this can
# get pretty huge!)
##############################################################
sub getComment {
my $dpic = shift;
my $format = shift; # LONG or SHORT
my $meta = shift; # optional, the Image::MetaData::JPEG object of $dpic if available
return "" unless is_a_JPEG($dpic); # todo support GIF and PNG comments
my @comments = getComments($dpic, $meta);
return "" if (@comments <= 0);
my $comment = "";
# put the comments togehter, adding a newline after each comment
foreach (@comments) {
$comment .= "$_\n";
}
$comment =~ s/\r*//g; # remove \r (carriage return)
$comment =~ s/\n+$//; # cut off last newline(s)
$comment = formatString($comment, $config{LineLength}) if ($format == SHORT);
print "getComment: $comment $dpic\n" if $verbose;
return $comment;
}
##############################################################
# getComments - returns an array containing all Comments
# (if available) of the given pic (up to 64K per
# block, nr of blocks is not limited, so this can
# get pretty huge!)
##############################################################
sub getComments {
my $dpic = shift;
my $meta = shift; # optional, the Image::MetaData::JPEG object of $dpic if available
$meta = getMetaData($dpic, "COM", 'FASTREADONLY') unless (defined($meta));
my @coms = ();
if ($meta) {
@coms = $meta->get_comments();
#print "getComments: $dpic:\n"; foreach (@coms) { print " com: $_\n"; } print "\n";
#foreach (@coms) {
# if (Encode::is_utf8($_)) {
# $_ = decode("utf8", $_);
# #print "getComments: decoded UTF8: $_\n";
# }
#}
}
else {
warn "*** getComments: no meta for $dpic available!" if ($verbose);
}
#foreach (@coms) { print "getComments: $_\n"; }
return @coms;
}
##############################################################
# getShortEXIF - returns a string containing some of the
# EXIF-Data (if available) of the given pic
# if wrap is true the string is broken in
# several lines (for thumbnail view)
##############################################################
sub getShortEXIF {
my $dpic = shift;
my $wrap = shift; # WRAP or NO_WRAP
my $meta = shift; # optional
my $exif = "";
return $exif unless is_a_JPEG($dpic);
$meta = getMetaData($dpic, 'APP1$', 'FASTREADONLY') unless (defined($meta));
# add a symbol ([s]) to the exif column for each picture with saved EXIF data
if (-f dirname($dpic)."/$exifdirname/".basename($dpic)) {
$exif .= "[s] ";
}
return unless (defined($meta));
my $er = $meta->get_Exif_data('ALL', 'TEXTUAL'); # er = exif hash ref todo: use IMAGE_DATA instead of ALL?
unless (defined $er) {
return $exif;
}
# Some cameras store settings in Maker Notes, so it is important to know
# the make of the camera.
my $make = "";
if (defined $er->{'IFD0_DATA'}->{'Make'}) {
$make = ${$er->{'IFD0_DATA'}->{'Make'}}[0];
}
# check for thumbnail
if (defined $er->{ROOT_DATA}->{ThumbnailData}) {
$exif .= "[t] ";
}
my $datestr = "";
$datestr = getEXIFDate($dpic, $er);
if ($datestr ne "") {
if (my ($y, $M, $d, $h, $m, $s) = $datestr =~ m/(\d\d\d\d):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)/) {
$exif .= "$d.$M.$y $h:$m:$s ";
$exif .= "\n" if $wrap;
}
else {
warn "picture has an unusual EXIF date: \"$datestr\" ($dpic)\n" if $config{MetadataWarn};
}
}
if (defined $er->{'SUBIFD_DATA'}->{FocalLength}) {
my $flength = int(calc($er->{'SUBIFD_DATA'}->{FocalLength}));
$exif .= $flength."mm ";
}
if (defined $er->{'SUBIFD_DATA'}->{'FocalLengthIn35mmFilm'}) {
$exif .= "(".join('', @{$er->{'SUBIFD_DATA'}->{'FocalLengthIn35mmFilm'}})."mm) ";
}
my $aperture = getEXIFAperture($dpic, STRING, $er);
$exif .= $aperture if ($aperture ne "0");
my $exti = getEXIFExposureTime($dpic, STRING, $er);
$exif .= "$exti";
if (defined $er->{'SUBIFD_DATA'}->{'ExposureBiasValue'}) {
my $bias = calc($er->{'SUBIFD_DATA'}->{'ExposureBiasValue'});
if (($bias eq "-") and $config{MetadataWarn}) {
warn "unusal EXIF ExposureBiasValue (".$er->{'SUBIFD_DATA'}->{'ExposureBiasValue'}.") in picture $dpic\n";
}
$exif .= sprintf("+%1.1f ", $bias) if (($bias ne "-") and ($bias > 0));
$exif .= sprintf( "%1.1f ", $bias) if (($bias ne "-") and ($bias < 0));
}
if (defined $er->{'SUBIFD_DATA'}->{'ISOSpeedRatings'}) {
$exif .= "ISO".${$er->{'SUBIFD_DATA'}->{'ISOSpeedRatings'}}[0]." ";
}
else{ # Same as ISOSpeedRatings. Only Kodak's camera uses this tag instead of ISOSpeedRating
if (defined $er->{'SUBIFD_DATA'}->{'ExposureIndex'}) {
my $iso = calc($er->{'SUBIFD_DATA'}->{'ExposureIndex'});
$exif .= "ISO$iso ";
}
else { # Nikon and Canon hide the ISO settings in the Makernotes
my $seg = $meta->retrieve_app1_Exif_segment();
if ($seg) {
my $makernote = $seg->get_Exif_data('MAKERNOTE_DATA', 'TEXTUAL');
if ($make =~ m/Canon/) {
if (exists $makernote->{'CameraSettings'}) {
my $iso = $makernote->{'CameraSettings'}[16];
if ($iso == 15) {
$exif .= "ISO-Auto ";
} elsif (16 <= $iso && $iso <= 19) {
$exif .= "ISO".(50 * (1 << ($iso - 16)))." ";
}
}
} elsif (exists $makernote->{'ISOSetting'}) {
my $iso = $makernote->{'ISOSetting'};
$exif .= "ISO$$iso[1] ";
}
}
}
}
# this part will repair Nikon D70 files (ISO info is just available in the Makernotes)
# by setting the ISO value in the right EXIF tag (ISOSpeedRatings)
#if (($iso_value > 1) and ($iso_value < 30000)) {
#print "adding ISO value $iso_value to $dpic\n";
## the other $meta is read only
#my $meta2= new Image::MetaData::JPEG($dpic, 'APP1$');
#my $hash = $meta2->set_Exif_data({'ISOSpeedRatings' => $iso_value}, 'IMAGE_DATA', 'ADD');
#if (%$hash) {
# print "ISO record rejected\n";
#}
#else {
# unless ($meta2->save()) {
# print "Save ISO failed for $dpic\n";
# }
#}
$exif .= "\n" if $wrap;
my $exposureStr = "";
# Canon places specific exposure program in maker note.
if ($make =~ m/Canon/) {
my $seg = $meta->retrieve_app1_Exif_segment();
if ($seg) {
my $makernote = $seg->get_Exif_data('MAKERNOTE_DATA', 'TEXTUAL');
if (exists $makernote->{'CameraSettings'}) {
my %CanonExp = (
0 => "Easy shooting",
1 => "Program",
2 => "Shutter priority",
3 => "Aperture priority",
4 => "Manual",
5 => "Auto-DEP",
6 => "DEP"
);
my %CanonEasy = (
0 => "Auto",
1 => "Manual",
2 => "Landscape",
3 => "Fast shutter",
4 => "Slow shutter",
5 => "Night",
6 => "B/W",
7 => "Sepia",
8 => "Portrait",
9 => "Sports",
10 => "Macro/Close-Up",
11 => "Pan focus"
);
my $exp = $makernote->{'CameraSettings'}[20];
if (defined $exp) {
$exposureStr = $CanonExp{$exp} if (defined $CanonExp{$exp});
if ($exp == 0) { # Find more specific "Easy shooting" mode
$exp = $makernote->{'CameraSettings'}[11];
$exposureStr = "\$" . $exp;
$exposureStr = $CanonEasy{$exp} if (defined $CanonEasy{$exp});
}
}
}
}
}
if (($exposureStr eq "") && defined $er->{'SUBIFD_DATA'}->{'ExposureProgram'}) {
my @ExposureProgram = ("Not defined",
"Manual",
"Program",
"Aperture priority",
"Shutter priority",
"Creative program",
"Action program",
"Portrait mode",
"Landscape mode");
my $prog = ${$er->{'SUBIFD_DATA'}->{ExposureProgram}}[0];
#print "$dpic: ".$ExposureProgram[$prog]; foreach (@{$er->{'SUBIFD_DATA'}->{ExposureProgram}}) { print " +Expo : $_"; } print "\n";
$exposureStr = $ExposureProgram[$prog] if ($prog > 0);
}
if ($exposureStr eq "") {
# some camera uses this tag instead of ExposureProgram
if (defined $er->{'SUBIFD_DATA'}->{ExposureMode}) {
my @ExposureMode = ("Auto exposure",
"Manual exposure",
"Auto bracket");
my $mode = ${$er->{'SUBIFD_DATA'}->{ExposureMode}}[0];
$exposureStr = $ExposureMode[$mode] if ($mode >= 0);
}
}
$exif .= $exposureStr." " if ($exposureStr ne "");
if (defined $er->{'SUBIFD_DATA'}->{'Flash'}) {
if (${$er->{'SUBIFD_DATA'}->{'Flash'}}[0] & 1) {
$exif .= "flash ";
}
}
if ($config{ShowMoreEXIF}) { # show contrast sharpness saturation metering white balance
my @automanual = ("Auto",
"Manual");
my @saturation = ("Normal",
"Low",
"High");
my @contrast = ("Normal",
"Soft",
"Hard");
my @metering = ("unknown",
"Average",
"CenterWeightedAverage",
"Spot",
"MultiSpot",
"Pattern",
"Partial",
"Other");
my $exifplus = "";
if (defined $er->{'SUBIFD_DATA'}->{Contrast}) {
my $con = ${$er->{'SUBIFD_DATA'}->{Contrast}}[0];
$exifplus .= "Contrast: ".$contrast[$con]." " if ($con > 0);
}
if (defined $er->{'SUBIFD_DATA'}->{Sharpness}) {
my $sha = ${$er->{'SUBIFD_DATA'}->{Sharpness}}[0];
$exifplus .= "Sharpness: ".$contrast[$sha]." " if ($sha > 0);
}
if (defined $er->{'SUBIFD_DATA'}->{Saturation}) {
my $sat = ${$er->{'SUBIFD_DATA'}->{Saturation}}[0];
$exifplus .= "Saturation: ".$saturation[$sat]." " if ($sat > 0);
}
$exifplus = "\n$exifplus" if ($wrap and ($exifplus ne ""));
if (defined $er->{'SUBIFD_DATA'}->{MeteringMode}) {
my $met = ${$er->{'SUBIFD_DATA'}->{MeteringMode}}[0];
$exifplus .= "\n" if $wrap;
$met = 7 if ($met > 7);
$exifplus .= "Metering: ".$metering[$met]." " if ($met >= 0);
}
if ($verbose and (defined $er->{'SUBIFD_DATA'}->{'OwnerName'})) { print "*** Owner $dpic: ".join('', @{$er->{'SUBIFD_DATA'}->{'OwnerName'}})."\n"; }
if ($verbose and (defined $er->{'SUBIFD_DATA'}->{'UserComment'})) { print "*** EXIF comment $dpic: -".join('', @{$er->{'SUBIFD_DATA'}->{'UserComment'}})."-\n"; }
my $wbStr = ""; # white balance string
# Canon places specific white balance in maker note.
if ($make =~ m/Canon/) {
my $seg = $meta->retrieve_app1_Exif_segment();
if ($seg) {
my $makernote = $seg->get_Exif_data('MAKERNOTE_DATA', 'TEXTUAL');
if (exists $makernote->{'ShotInfo'}) {
my %CanonWB = (
0 => "Auto",
1 => "Daylight",
2 => "Cloudy",
3 => "Tungsten",
4 => "Fluorescent",
5 => "Flash",
6 => "Custom",
7 => "B/W",
8 => "Shade",
9 => "Manual Temperature",
14 => "FluorescentH"
);
my $wb = $makernote->{'ShotInfo'}[7];
$wbStr = $CanonWB{$wb} if exists $CanonWB{$wb};
}
}
}
if (($wbStr eq "") && defined $er->{'SUBIFD_DATA'}->{WhiteBalance}) {
my $wb = ${$er->{'SUBIFD_DATA'}->{WhiteBalance}}[0];
$wbStr = $automanual[$wb] if ($wb >= 0);
}
if ($wbStr ne "") {
$exifplus .= "\n" if $wrap;
$exifplus .= "WB: $wbStr ";
}
#if (defined $er->{'SUBIFD_DATA'}->{'Orientation'}) {
# $exifplus .= "Orientation: ".$er->{'SUBIFD_DATA'}->{'Orientation'}." ";
#}
my $artist = getEXIFArtist($dpic, $er);
$exifplus .= "\nArtist: $artist" if ($artist ne "");
if ($exifplus ne "") {
$exif .= "$exifplus" ;
}
}
my $exmod = getEXIFModel($dpic, $er);
$exif .= "\n$exmod" if ($exmod ne "");
$exif =~ tr/\000/ /; # remove null termination (\000) chars
$exif =~ s/( )+/ /g; # replace more than one space with one
my $tmp = $exif;
$tmp =~ s/\n//g; # remove newlines
$tmp =~ s/\s//g; # remove whitespaces
# if there are just newlines and spaces we return an empty string
$exif = "" if ($tmp eq "");
return $exif;
}
##############################################################
# getEXIFMeta
##############################################################
sub getEXIFMeta {
my $dpic = shift;
my $exif = "";
return $exif unless is_a_JPEG($dpic);
my $pic = basename($dpic);
my $meta = getMetaData($dpic, 'APP1$', 'FASTREADONLY');
my $hash_ref = $meta->get_Exif_data('ALL', "TEXTUAL");
#if (defined $hash_ref->{APP1}->{ThumbnailData}) {
#printf "[t] %s\n", basename($dpic);
#}
#return unless ($verbose);
my $num = $meta->retrieve_app1_Exif_segment(-1);
print "getEXIFMeta: $pic has $num EXIF APP1 segments\n" if $verbose;
my $ref = $meta->retrieve_app1_Exif_segment();
unless (defined $ref) {
print "getEXIFMeta: $pic has no EXIF APP1 segments\n" if $verbose;
return $exif;
}
while (my ($d, $h) = each %$hash_ref) {
while (my ($t, $a) = each %$h) {
my $a2 = "";
foreach (@$a) {
$a2 .= sprintf "%-5s", $_;
}
$a2 = cutString($a2, 30 , "..");
$exif .= sprintf "%-25s\t%-25s\t-> %-s\n", $d, $t, $a2;
}
}
return $exif;
}
##############################################################
# calc - make a number from an array ref containing two numbers
# input e.g. [28, 10] -> output: 2.8
##############################################################
sub calc {
my $value = shift;
if (@{$value} != 2) {
warn "calc: no separator -> no values! or division by zero\n" if $config{MetadataWarn};
return join("/", $value);
}
if ($$value[1] == 0) {
if ($$value[0] == 0) {
return 0;
}
else {
warn "calc: division by zero" if $config{MetadataWarn};
return 0;
}
}
return ($$value[0] / $$value[1]); #return the calculated number
}
##############################################################
# displayEXIFData - displays all EXIF-Data in a window
##############################################################
sub displayEXIFData($) {
my $lb = shift;
my @sellist = $lb->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
return unless askSelection(\@sellist, 10, "EXIF info");
my $selected = @sellist;
my ($pic, $dpic, $i, $thumb);
$userinfo = "displaying EXIF data of $selected pictures"; $userInfoL->update;
my $pw = progressWinInit($lb, "Display EXIF data");
$i = 0;
foreach $dpic (@sellist) {
last if progressWinCheck($pw);
$i++;
progressWinUpdate($pw, "Display EXIF data ($i/$selected) ...", $i, $selected);
$pic = basename($dpic);
$thumb = getThumbFileName($dpic);
# check if file is a link and get the real target
next if (!getRealFile(\$dpic));
my $ii = getImageInfo($dpic);
if ($ii eq "") {
$lb->messageBox(-icon => 'warning', -message => "There are no EXIF-Infos in $dpic!",
-title => "No EXIF infos", -type => 'OK');
next;
}
my $title = "EXIF info of $pic";
my $exifs = getShortEXIF($dpic, NO_WRAP);
my $exif = "compact EXIF info:\n$exifs\n\n" if ($exifs ne "");
$exif .= "detailed EXIF info (from Image::Info):\n";
foreach (sort { uc($a) cmp uc($b); } keys %{$ii}) {
next if (($_ eq "MakerNote") or ($_ eq "ColorComponentsDecoded") or ($_ =~ m/^App.*/));
if (ref($ii->{$_}) eq "ARRAY") { # handle array entries
$exif .= sprintf "%-25s ",$_;
foreach (@{$ii->{$_}}) {
if (ref($_) eq "ARRAY") { # handle array in array entries
foreach (@{$_}) {
$exif .= "$_, ";
}
} elsif (ref($_) eq "HASH") { # handle hash in array entries
my %hash = %{$_};
foreach (sort keys %hash) {
$exif .= "$_=".$hash{$_}.", ";
}
} else { # handle normal strings in array entries
$exif .= "$_, ";
}
}
$exif =~ s/, $//; # remove trailing comma and space
}
else { # handle normal string entries
$exif .= sprintf "%-25s %s",$_, $ii->{$_};
}
$exif .= "\n";
}
if ($config{EXIFshowApp}) {
foreach (sort { uc($a) cmp uc($b); } keys %{$ii}) {
next unless (($_ eq "MakerNote") or ($_ eq "ColorComponentsDecoded") or ($_ =~ m/^App.*/));
if (ref($ii->{$_}) eq "ARRAY") { # handle array entries
$exif .= sprintf "%-25s ",$_;
foreach (@{$ii->{$_}}) {
if (ref($_) eq "ARRAY") { # handle array in array entries
foreach (@{$_}) {
$exif .= "$_, ";
}
} elsif (ref($_) eq "HASH") { # handle hash in array entries
my %hash = %{$_};
foreach (sort keys %hash) {
$exif .= "$_=".$hash{$_}.", ";
}
} else { # handle normal strings in array entries
$exif .= "$_, ";
}
}
$exif =~ s/, $//; # remove trailing comma and space
} else { # handle normal string entries
my $part = sprintf "%-25s %s",$_, $ii->{$_};
$part =~ s/\n//g;
$exif .= $part;
}
$exif .= "\n";
}
}
$exif .= "\ndetailed EXIF info (from Image::MetaData::JPEG):\n";
$exif .= getEXIFMeta($dpic);
$exif =~ tr/\n -~//cd; # remove non-printable characters (but not \n)
showText($title, $exif, NO_WAIT, $thumb);
}
progressWinEnd($pw);
$userinfo = "ready! ($i of $selected displayed)"; $userInfoL->update;
}
##############################################################
# removeEXIFData - remove all EXIF data in all selected pictures
##############################################################
sub removeEXIFData {
my $mode = shift;
if (!defined $mode) {
warn "removeEXIFData: Missing a mode, should be thumb or all!";
return;
}
my @sellist = $picLB->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
my $selected = @sellist;
my ($pic, $dpic, $i, $dirthumb, $text);
if ($mode eq "all") {
$text = "Remove all EXIF infos (picture and camera data and embedded thumbnail picture) of $selected selected pictures.";
}
elsif ($mode eq "thumb") {
$text = "Remove the embedded EXIF thumbnails and other non-camera settings from the EXIF headers of $selected selected pictures.";
}
else {
warn "removeEXIFData: Wrong mode ($mode), should be thumb or all!";
return;
}
my $rc = $top->messageBox(-icon => 'question',
-message => "$text\nOk to continue?",
-title => "Question",
-type => 'OKCancel');
return if ($rc !~ m/Ok/i);
$userinfo = "removing EXIF data of $selected pictures"; $userInfoL->update;
$i = 0;
my $errors = "";
my $pw = progressWinInit($top, "Remove EXIF data");
foreach $dpic (@sellist) {
last if progressWinCheck($pw);
$i++;
progressWinUpdate($pw, "Remove EXIF data ($i/$selected) ...", $i, $selected);
$pic = basename($dpic);
$dirthumb = getThumbFileName($dpic);
# check if file is a link and get the real target
next if (!getRealFile(\$dpic));
next if (!checkWriteable($dpic));
next if (!removeEXIF($dpic, $mode, \$errors));
# touch the thumbnail pic (set actual time stamp), to suppress rebuilding the next time
touch($dirthumb);
updateOneRow($dpic, $picLB);
showImageInfo($dpic) if ($dpic eq $actpic);
}
progressWinEnd($pw);
$userinfo = "ready! ($i of $selected infos removed)"; $userInfoL->update;
showText("Errors while removing EXIF data", $errors, NO_WAIT) if ($errors ne "");
}
##############################################################
# removeEXIF
##############################################################
sub removeEXIF {
my $dpic = shift;
my $mode = shift;
my $errors = shift; # reference
my $meta = getMetaData($dpic, "APP1");
unless ($meta) {
$$errors .= "No EXIF data in $dpic\n";
return 0;
}
if ($mode eq "all") {
$meta->remove_app1_Exif_info(-1);
} elsif ($mode eq "thumb") {
my $nothumb = "";
my $hash = $meta->set_Exif_data(\$nothumb, 'THUMBNAIL', 'REPLACE');
$$errors .= "Thumbnail record rejected for $dpic\n" if (keys %$hash);
} else {
die;
}
unless ($meta->save()) {
$$errors .= "Save failed $dpic\n";
return 0;
}
return 1;
}
##############################################################
# getEXIFThumb - extract the embedded EXIF thumbnail
##############################################################
sub getEXIFThumb {
my @sellist = $picLB->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
my $selected = @sellist;
my $rc = $top->messageBox(-icon => 'question',
-message => "Extract embedded EXIF thumbnails of $selected selected pictures and write them to a (new created) subdirectory \"EXIFThumbs/\" in the current directory.\nShould I continue?",
-title => "Question",
-type => 'OKCancel');
return if ($rc !~ m/Ok/i);
$userinfo = "extracting embedded EXIF thumbnails of $selected pictures"; $userInfoL->update;
if (!-d "$actdir/EXIFThumbs") {
if ( !mkdir "$actdir/EXIFThumbs", 0755) {
warn "makedir: can not create $actdir/EXIFThumbs: $!";
return;
}
}
my $i = 0;
my $errors = "";
my $pw = progressWinInit($top, "Extracting EXIF thumbnails");
foreach my $dpic (@sellist) {
last if progressWinCheck($pw);
$i++;
progressWinUpdate($pw, "Extracting EXIF thumbnail ($i/$selected) ...", $i, $selected);
my $pic = basename($dpic);
my $dthumb = "$actdir/EXIFThumbs/$pic";
next if (!getRealFile(\$dpic));
extractThumb($dpic, $dthumb, \$errors);
}
progressWinEnd($pw);
$userinfo = "ready! ($i of $selected thumbs extracted)"; $userInfoL->update;
showText("Errors while saving EXIF thumbnail", $errors, NO_WAIT) if ($errors ne "");
}
##############################################################
# setEXIFDate - adjust the date and time field in the EXIF header
##############################################################
sub setEXIFDate {
my @sellist = $picLB->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
my $selected = @sellist;
my ($pic, $dpic, $i, $dirthumb, $rc, $command);
my $count = 0;
if (!$config{setEXIFDateAskAgain}) {
$rc = checkDialog("Change EXIF date/time?",
"Change the date and time info (EXIF: DateTimeOriginal) of $selected selected pictures. The previous information will be lost!\nShould I continue?",
\$config{setEXIFDateAskAgain},
"don't ask again",
"",
'OK', 'Cancel');
return if ($rc ne 'OK');
}
my $datetime = $config{EXIFDateAbs};
$rc = setEXIFDateDialog(\$datetime);
return if ($rc ne 'OK');
if (($config{EXIFAbsRel} eq "abs") and !($datetime =~ m/\d{4}:\d{2}:\d{2}-\d{2}:\d{2}:\d{2}/)) {
$top->messageBox(-icon => 'warning',
-message => "Sorry, but $datetime has a wrong format!\nShould be: yyyy:mm:dd-hh:mm:ss Aborting.",
-title => 'Error', -type => 'OK');
return;
}
$config{EXIFDateAbs} = $datetime if ($config{EXIFAbsRel} eq "abs");
$userinfo = "changing the date and time of $selected pictures"; $userInfoL->update;
$i = 0;
my $errors = "";
my $pw = progressWinInit($top, "Changing EXIF date and time");
foreach $dpic (@sellist) {
last if progressWinCheck($pw);
$i++;
progressWinUpdate($pw, "Changing EXIF date and time ($i/$selected) ...", $i, $selected);
$pic = basename($dpic);
$dirthumb = getThumbFileName($dpic);
# check if file is a link and get the real target
next if (!getRealFile(\$dpic));
next if (!checkWriteable($dpic));
if ($config{EXIFAbsRel} eq "abs") {
# nothing to do, we just use $datetime
$datetime =~ s/-/ /; # replace just the "-" with a space between date and time
} elsif ($config{EXIFAbsRel} eq "rel") {
my $exif = getEXIFDate($dpic);
if (defined($exif) and ($exif =~ m/(\d\d\d\d):(\d\d):(\d\d)\s(\d\d):(\d\d):(\d\d)/)) {
my $mon = $2;
my $year = $1;
$mon--;
$year -= 1900;
if ($mon >= 0 and $mon <= 11) {
# calculate the time as value in seconds since the Epoch (Midnight, January 1, 1970)
my $ctime = timelocal($6,$5,$4,$3,$mon,$year);
my $hours = $config{EXIFyears} * 365 * 24 + $config{EXIFdays} * 24 + $config{EXIFhours};
my $seconds = $hours * 60 * 60 + $config{EXIFmin} * 60 + $config{EXIFsec};
if ($config{EXIFPlusMin} eq "+") {
$ctime = $ctime + $seconds;
} else {
$ctime = $ctime - $seconds;
}
my ($s,$m,$h,$d,$mo,$y) = localtime $ctime;
$y += 1900; $mo++; # do some adjustments
# build up the date time string, similar to the EXIF format
$datetime = sprintf "%04d:%02d:%02d %02d:%02d:%02d", $y, $mo, $d, $h, $m, $s;
} else {
$errors .= "Wrong month in EXIF date in $dpic\n";
}
} else {
$errors .= "No EXIF date in $dpic\n";
}
} else {
warn "setEXIFDate: wrong value: ", $config{EXIFAbsRel};
return 0;
}
print "set EXIF datetime: $datetime to $dpic\n" if $verbose;
my $meta = getMetaData($dpic, 'APP1$');
unless (defined $meta) {
$errors .= "No meta available: $dpic\n";
next;
}
#date time format: 2006:04:04 11:12:13
my $hash = $meta->set_Exif_data({'DateTime' => $datetime,
'DateTimeOriginal' => $datetime,
'DateTimeDigitized' => $datetime}, 'IMAGE_DATA', 'ADD');
if (keys %$hash) {
$errors .= "DateTime record rejeced: $dpic\n";
next;
}
unless ($meta->save()) {
$errors .= "Save failed $dpic\n";
next;
}
$count++;
# touch the thumbnail pic (set actual time stamp), to suppress rebuilding the next time
touch($dirthumb);
updateOneRow($dpic, $picLB);
showImageInfo($dpic) if ($dpic eq $actpic);
}
progressWinEnd($pw);
$userinfo = "ready! ($i/$selected)"; $userInfoL->update;
showText("Errors while adjusting EXIF date", $errors, NO_WAIT) if ($errors ne "");
}
##############################################################
# setEXIFDateDialog - get the date/time info from the user
# returns 'OK' or 'Cancel'
##############################################################
sub setEXIFDateDialog {
my $datetime = shift; # var ref date time string (absolute)
my $rc = 'Cancel';
# open window
my $dtw = $top->Toplevel();
$dtw->title('Set EXIF date and time');
$dtw->iconimage($mapiviicon) if $mapiviicon;
$dtw->Label(-text => "You may set the date and time to an absolute or relative value",
-bg => $config{ColorBG},
)->pack(-anchor => 'w');
my $f = $dtw->Frame()->pack;
my $af = $f->Frame(-bd => 1, -relief => "raised")->pack(-fill => "y", -side => "left"); # absolut
my $rf = $f->Frame(-bd => 1, -relief => "raised")->pack(-fill => "y", -side => "left"); # relative
######### absolute
$af->Radiobutton(-text => "use absolute value", -variable => \$config{EXIFAbsRel}, -value => "abs")->pack(-anchor => 'w');
$af->Label(-text => "Please enter the new date and time to store\nin the selected pictures\n(please use the format: yyyy:mm:dd-hh:mm:ss\nexample: 2006:05:21-11:07:59)",
-bg => $config{ColorBG}, -justify => "left")->pack(-anchor => 'w');
my $entry = $af->Entry(-textvariable => \$$datetime,
-width => 40,
)->pack(-fill => 'x', -padx => 3, -pady => 3);
# todo that's not enough to switch when focusIn
#$entry->bind('<FocusIn>', sub { $config{EXIFAbsRel} = "abs"; $af->update(); } );
$entry->selectionRange(0,'end'); # select all
$entry->icursor('end');
$entry->xview('end');
######### relative
$rf->Radiobutton(-text => "use relative value", -variable => \$config{EXIFAbsRel}, -value => "rel")->pack(-anchor => 'w');
$rf->Radiobutton(-text => "+ (add time)", -variable => \$config{EXIFPlusMin}, -value => "+")->pack(-anchor => 'w');
$rf->Radiobutton(-text => "- (subtract time)", -variable => \$config{EXIFPlusMin}, -value => "-")->pack(-anchor => 'w');
labeledScale($rf, 'top', 8, "years", \$config{EXIFyears}, 0, 100, 1);
labeledScale($rf, 'top', 8, "days", \$config{EXIFdays}, 0, 365, 1);
labeledScale($rf, 'top', 8, "hours", \$config{EXIFhours}, 0, 24, 1);
labeledScale($rf, 'top', 8, "minutes", \$config{EXIFmin}, 0, 59, 1);
labeledScale($rf, 'top', 8, "seconds", \$config{EXIFsec}, 0, 59, 1);
my $OKB;
$entry->bind('<Return>', sub { $OKB->invoke; } );
$entry->focus;
my $ButF = $dtw->Frame()->pack(-fill =>'x', -padx => 3, -pady => 3);
$OKB = $ButF->Button(-text => 'OK',
-command => sub {
$rc = 'OK';
$dtw->destroy();
})->pack(-side => 'left', -expand => 1, -fill => 'x',
-padx => 3, -pady => 3);
my $XBut = $ButF->Button(-text => 'Cancel',
-command => sub {
$rc = 'Cancel';
$dtw->destroy();
}
)->pack(-side => 'left', -expand => 1, -fill => 'x',
-padx => 3, -pady => 3);
$dtw->bind('<Key-Escape>', sub { $XBut->invoke; });
$dtw->Popup;
$dtw->waitWindow();
return $rc;
}
##############################################################
# showEXIFThumb - displays the embedded EXIF thumbnail
##############################################################
sub showEXIFThumb {
my $noThumbIn = "";
my @sellist = $picLB->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
return unless askSelection(\@sellist, 10, "EXIF thumbnail");
if (!-d $trashdir) { # we need the trash dir for the temp files
$top->messageBox(-icon => 'warning', -message => "Trash directory $trashdir not found!\nPlease create this directory (shell: mkdir $trashdir) and retry.\n\nAborting.",
-title => "No trash directory", -type => 'OK');
return;
}
my $pw = progressWinInit($top, "Show EXIF thumbnail");
my $i = 0;
foreach my $dpic (@sellist) {
last if progressWinCheck($pw);
$i++;
progressWinUpdate($pw, "Show EXIF thumbnail ($i/".scalar @sellist.") ...", $i, scalar @sellist);
my $pic = basename($dpic);
my $exifthumb = "$trashdir/EXIFthumb-$pic";
if (-f $exifthumb) {
$top->messageBox(-icon => 'warning', -message => "There is something wrong, $exifthumb already exists.\nPlease delete it first.\nSkipping!",
-title => 'Warning', -type => 'OK');
next;
}
my $errors = "";
extractThumb($dpic, $exifthumb, \$errors);
if (!-f $exifthumb) {
$noThumbIn .= "$pic\n";
next;
}
showPicInOwnWin($exifthumb); # show the thumb
# remove the thumb
removeFile($exifthumb);
}
progressWinEnd($pw);
showText("No EXIF thumbnail",
"Sorry, there seems to be no embedded EXIF thumbnail in the following pictures:\n\n$noThumbIn"
,NO_WAIT) if ($noThumbIn ne "");
$userinfo = "ready! ($i of ".scalar @sellist." thumbs)"; $userInfoL->update;
}
##############################################################
# copyEXIFData - copy the EXIF infos from one picture to others
##############################################################
sub copyEXIFData {
my $direction = shift;
if (!defined $direction) {
warn "copyEXIFData: Missing a direction, should be from or to!";
return;
}
#return if (!checkExternProgs("copyEXIFData", "jhead"));
my @sellist = $picLB->info('selection');
my $selected = @sellist;
my ($pic, $dpic, $i, $dirthumb);
my $errors = "";
if ($direction eq "from") { # set the copy source
if (@sellist != 1) {
$top->messageBox(-icon => 'warning', -message => "Please select exactly one picture (the picture from which the EXIF info should be taken) for this function!",
-title => 'Error', -type => 'OK');
return;
}
$copyEXIFDataSource = $sellist[0]; # save source pic to global variable
$userinfo = "copy source set to ".basename($copyEXIFDataSource); $top->update;
return; # that's all for now ;-)
}
elsif ($direction eq "to") {
return unless checkSelection($top, 1, 0, \@sellist);
if ((!defined $copyEXIFDataSource) or (!-f $copyEXIFDataSource)) {
$top->messageBox(-icon => 'warning', -message => "Please select a source picture (the picture from which the EXIF info should be taken) first, and than choose EXIF info->copy from!",
-title => 'Error', -type => 'OK');
return;
}
my $exif = getShortEXIF($copyEXIFDataSource, WRAP);
my $EXIFthumb = ""; # temp file holding the embedded EXIF thumbnail
$EXIFthumb = "$configdir/".basename($copyEXIFDataSource);
extractThumb($copyEXIFDataSource, $EXIFthumb, \$errors);
my $message = "Copy the EXIF infos:\
-------------\
$exif\
-------------\
and the embedded thumbnail from\
\"".basename($copyEXIFDataSource)."\"\
to $selected selected pictures.\
The original EXIF infos and thumbnails of these pictures will be lost!\
Ok to continue?";
my $rc = myButtonDialog("Copy EXIF data", "$message", $EXIFthumb, 'OK', 'Cancel');
removeFile($EXIFthumb); # remove temp thumbnail file
return if ($rc ne 'OK');
$userinfo = "transfering EXIF infos to $selected pictures"; $userInfoL->update;
$i = 0;
my $pw = progressWinInit($picLB, "Copy EXIF data");
foreach $dpic (@sellist) {
last if progressWinCheck($pw);
$i++;
progressWinUpdate($pw, "transfering EXIF info ($i/$selected) ...", $i, $selected);
$pic = basename($dpic);
$dirthumb = getThumbFileName($dpic);
# check if file is a link and get the real target
next if (!getRealFile(\$dpic));
next if (!checkWriteable($dpic));
my $rc = copyEXIF( $copyEXIFDataSource, $dpic);
$errors .= "$rc\n" if ($rc ne "1");
updateOneRow($dpic, $picLB);
showImageInfo($dpic) if ($dpic eq $actpic);
# touch the thumbnail pic (set actual time stamp), to suppress rebuilding the next time
touch($dirthumb);
}
progressWinEnd($pw);
} else {
warn "copyEXIFData: Wrong direction ($direction), should be from or to!";
return;
}
$userinfo = "ready! ($i/$selected copied)"; $userInfoL->update;
showText("Errors while copying EXIF infos", $errors, NO_WAIT) if ($errors ne "");
}
##############################################################
# copyEXIF
##############################################################
sub copyEXIF {
my $from = shift;
my $to = shift;
if (!-f $from) {
warn "copyEXIF: file $from does not exists!\n";
return;
}
if (!-f $to) {
warn "copyEXIF: file $to does not exists!\n";
return;
}
# from file
my $meta = getMetaData($from, '^APP1$', 'FASTREADONLY');
return "Could not get EXIF info of source $from!" unless (defined $meta);
# to file
my $meta2 = getMetaData($to, '^APP1$');
return "Could not get EXIF info of target $to!" unless (defined $meta2);
# find the EXIF segment
my $seg = extract_app1_Exif_segment($meta);
return "Could not get EXIF segment of source $from!" unless (defined $seg);
# insert the segment and save the picture
insert_app1_Exif_segment($meta2, $seg);
my $result = $meta2->save();
return "save failed for $to" unless ($result);
return 1;
}
##############################################################
# extract_app1_Exif_segment - sub supplied from Stefano Bettelli
##############################################################
sub extract_app1_Exif_segment {
my ($this) = @_;
my $segment = $this->retrieve_app1_Exif_segment();
return undef unless $segment;
# this removes the segment from the picture (in memory)
# you could skip this if the picture is no more used
@{$this->{segments}} = grep { $_ != $segment } @{$this->{segments}};
# this unlinks the picture from the segment, orphaning it
$segment->{parent} = undef;
return $segment;
}
##############################################################
# insert_app1_Exif_segment - sub supplied from Stefano Bettelli
##############################################################
sub insert_app1_Exif_segment {
my ($this, $segment) = @_;
# this locates or produces an Exif segment
my $old = $this->provide_app1_Exif_segment();
for (@{$this->{segments}}) {
# looking for the segment to replace ...
next unless $_ == $old;
# tell the segment it now belongs to the picture
$segment->{parent} = $this;
# tell the picture it now owns the segment
$_ = $segment;
last;
}
}
##############################################################
# restoreComments - remove existing comments and store the
# given list of comments
##############################################################
sub restoreComments {
my $dpic = shift;
my @comments = @_;
my $meta = getMetaData($dpic, "COM");
if ($meta) {
# remove all existing comments, we want to restore exactly
$meta->remove_all_comments();
# write the old comments back
if (@comments) {
foreach (@comments) {
$meta->add_comment($_);
}
}
unless ($meta->save()) {
warn "restoreComments: save $dpic failed!";
}
}
}
##############################################################
# EXIFsave - make a new subdir .exif, copy the thumbnail of
# the selected pics to this dir, copy the EXIF
# info from the original pics to the thumbs
##############################################################
sub EXIFsave {
my @sellist = $picLB->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
# make EXIF subdir
return if (!makeDir("$actdir/$exifdirname", ASK));
my ($pic, $dpic, $i, $exiffile);
my $errors = "";
$i = 0;
my $pw = progressWinInit($top, "Save EXIF infos");
foreach $dpic (@sellist) {
last if progressWinCheck($pw);
$i++;
progressWinUpdate($pw, "Saving EXIF info ($i/".scalar @sellist.") ...", $i, scalar @sellist);
$pic = basename($dpic);
$exiffile = "$actdir/$exifdirname/$pic";
# check if file is a link and get the real target
next if (!getRealFile(\$dpic));
my $meta = getMetaData($dpic, '^APP1$', 'FASTREADONLY');
unless (defined $meta) {
$errors .= "Could not get EXIF info of $pic!\n";
next;
}
my $seg = extract_app1_Exif_segment($meta);
unless (defined $seg) {
$errors .= "Could not get EXIF segment of $pic!\n";
next;
}
unless (store($seg, $exiffile)) {
$errors .= "could not store EXIF segment in file $exiffile: $!\n";
next;
}
updateOneRow($dpic, $picLB); # display the new exif info (flag [s] is now set)
showImageInfo($dpic) if ($dpic eq $actpic);
}
progressWinEnd($pw);
$userinfo = "ready! ($i/".scalar @sellist." saved)"; $userInfoL->update;
showText("Errors while saving EXIF infos", $errors, NO_WAIT) if ($errors ne "");
}
##############################################################
# EXIFrestore - copy the saved EXIF info back to the selected
# pics
##############################################################
sub EXIFrestore {
my @sellist = $picLB->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
if (!-d "$actdir/$exifdirname") {
$top->messageBox(-icon => 'warning', -message => "Found no saved EXIF infos in this directory!",
-title => "No EXIF infos", -type => 'OK');
return;
}
# message for one picture
my $message = "Restore saved EXIF infos to ".basename($sellist[0]).".\nThe actual EXIF infos of this picture will be lost!\nOk to continue?";
# message for more than one picture
if (@sellist > 1) {
$message = "Restore saved EXIF infos\nto the ".scalar @sellist." pictures.\nThe actual EXIF infos of this picture will be lost!\nOk to continue?"
}
return if (myButtonDialog("Restore EXIF data", "$message", undef, 'OK', 'Cancel') ne 'OK');
my $errors = "";
my $i = 0;
my $pw = progressWinInit($top, "Restore EXIF info");
foreach my $dpic (@sellist) {
last if progressWinCheck($pw);
$i++;
progressWinUpdate($pw, "Restore EXIF info ($i/".scalar @sellist.") ...", $i, scalar @sellist);
my $pic = basename($dpic);
my $dirthumb = getThumbFileName($dpic);
my $exiffile = "$actdir/$exifdirname/$pic";
unless (-f $exiffile) {
$errors .= "Found no saved EXIF infos for $dpic!\n";
next;
}
# check if file is a link and get the real target
next if (!getRealFile(\$dpic));
next if (!checkWriteable($dpic));
my $meta = getMetaData($dpic, '^APP1$');
unless (defined $meta) {
$errors .= "Could not get EXIF info of $dpic!\n";
next;
}
# load stored EXIF segment from the file
my $exif = retrieve($exiffile);
unless (defined $exif) {
$errors .= "could not retrieve saved EXIF info\n";
next;
}
insert_app1_Exif_segment($meta, $exif);
unless ($meta->save()) {
$errors .= "save failed for $dpic\n";
next;
}
updateOneRow($dpic, $picLB);
showImageInfo($dpic) if ($dpic eq $actpic);
# touch the thumbnail pic (set actual time stamp), to suppress rebuilding the next time
touch($dirthumb);
}
progressWinEnd($pw);
$userinfo = "ready! ($i/".scalar @sellist."restored)"; $userInfoL->update;
showText("Errors while restoring EXIF data", $errors, NO_WAIT) if ($errors ne "");
}
##############################################################
# EXIFremoveSaved - remove the saved exif info file
##############################################################
sub EXIFremoveSaved {
my @sellist = $picLB->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
if (!-d "$actdir/$exifdirname") {
$top->messageBox(-icon => 'warning', -message => "Sorry, but there are no saved EXIF infos in this directory!",
-title => "no EXIF infos", -type => 'OK');
return;
}
my $rc = $top->messageBox(-icon => 'warning', -message => "Remove the saved EXIF infos and the embedded thumbnails of ".scalar @sellist." pictures.\nOk to continue?",
-title => "Warning", -type => 'OKCancel');
return if ($rc !~ m/Ok/i);
my ($pic, $dpic, $i, $exifthumb);
$i = 0;
my $pw = progressWinInit($top, "Remove saved EXIF infos");
foreach $dpic (@sellist) {
last if progressWinCheck($pw);
$i++;
progressWinUpdate($pw, "Removing saved EXIF info ($i/".scalar @sellist.") ...", $i, scalar @sellist);
$pic = basename($dpic);
$exifthumb = "$actdir/$exifdirname/$pic";
if ((!-f $exifthumb) and (@sellist == 1)) { # show this info only when removing from one file
$top->messageBox(-icon => 'warning', -message => "Sorry, but there are no saved EXIF infos for $pic!",
-title => "no EXIF infos", -type => 'OK');
next;
}
# check if file is a link and get the real target
next if (!getRealFile(\$dpic));
# remove the saved EXIF info file
removeFile($exifthumb );
updateOneRow($dpic, $picLB);
showImageInfo($dpic) if ($dpic eq $actpic);
}
progressWinEnd($pw);
$userinfo = "ready! ($i/".scalar @sellist." exif removed)"; $userInfoL->update;
}
##############################################################
# copyComment - copy the comment from one picture to others
##############################################################
sub copyComment {
my $direction = shift;
if (!defined $direction) {
warn "copyComment: Missing a direction, should be from or to!";
return;
}
my @sellist = $picLB->info('selection');
my $selected = @sellist;
my ($pic, $dpic, $i, $dirthumb);
if ($direction eq "from") { # set the copy source
if (@sellist != 1) {
$top->messageBox(-icon => 'warning', -message => "Please select exactly one picture (the picture from which comments should be taken) for this function!",
-title => 'Error', -type => 'OK');
return;
}
$copyCommentSource = $sellist[0]; # save source pic to global variable
$userinfo = "copy source set to ".basename($copyCommentSource); $top->update;
return; # that's all for now ;-)
}
elsif ($direction eq "to") {
return unless checkSelection($top, 1, 0, \@sellist);
if ((!defined $copyCommentSource) or (!-f $copyCommentSource)) {
$top->messageBox(-icon => 'warning', -message => "Please select a source picture (the picture from which the EXIF info should be taken) first, and than choose EXIF info->copy from!",
-title => 'Error', -type => 'OK');
return;
}
my $com = getComment($copyCommentSource, SHORT);
my $thumb = getThumbFileName($copyCommentSource);
my $message = "Copy the comments:\
-------------\
$com\
-------------\
from\
\"".basename($copyCommentSource)."\"\
to $selected selected pictures.\
The original comments won't be lost!\
Ok to continue?";
my $rc = myButtonDialog("Copy comments", "$message", $thumb, 'OK', 'Cancel');
return if ($rc ne 'OK');
$userinfo = "transfering comments to $selected pictures"; $userInfoL->update;
my $pw = progressWinInit($top, "Transfer comments");
$i = 0;
foreach $dpic (@sellist) {
last if progressWinCheck($pw);
$i++;
progressWinUpdate($pw, "transfering comments ($i/$selected) ...", $i, $selected);
$dirthumb = getThumbFileName($dpic);
next if (!checkWriteable($dpic));
# check if file is a link and get the real target
next if (!getRealFile(\$dpic));
my @comments = getComments($copyCommentSource);
my $meta = getMetaData($dpic, "COM");
next unless ($meta);
# add the comments
foreach (@comments) {
$meta->add_comment($_);
}
unless ($meta->save()) { warn "copyComment: save $dpic failed!"; }
updateOneRow($dpic, $picLB);
# touch the thumbnail pic (set actual time stamp), to suppress rebuilding the next time
touch($dirthumb);
} # foreach end
progressWinEnd($pw);
} else {
warn "copyComment: Wrong direction ($direction), should be from or to!";
return;
}
$userinfo = "ready! ($i of $selected copied)"; $userInfoL->update;
}
##############################################################
# displayIPTCData - displays all IPTC-Data in a window
##############################################################
sub displayIPTCData {
my $lb = shift;
my @sellist = $lb->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
return unless askSelection(\@sellist, 10, "IPTC info");
my ($pic, $dpic, $iptc, $title, $thumb);
my $i = 0;
my $pw = progressWinInit($lb, "Display IPTC data");
foreach $dpic (@sellist) {
last if progressWinCheck($pw);
$i++;
$iptc = "";
progressWinUpdate($pw, "displaying IPTC data ($i/".scalar @sellist.") ...", $i, scalar @sellist);
$pic = basename($dpic);
$thumb = getThumbFileName($dpic);
# check if file is a link and get the real target
next if (!getRealFile(\$dpic));
$title = "IPTC/IIM info of $pic";
$iptc = getIPTC($dpic, LONG);
if ($iptc eq '') {
$iptc = "Found no IPTC/IIM info in \"$pic\"\n";
}
showText($title, $iptc, NO_WAIT, $thumb);
}
progressWinEnd($pw);
if ($lb == $picLB) {
$userinfo = "ready! ($i/".scalar @sellist." IPTC displayed)";
$userInfoL->update;
}
}
##############################################################
# saveIPTC - save IPTC info hash as template to a file
##############################################################
sub saveIPTC {
my @sellist = $picLB->info('selection');
if (@sellist != 1) {
$top->messageBox(-icon => 'warning', -message => "Please select exactly one picture.",
-title => "Save IPTC info", -type => 'OK');
return;
}
my $dpic = $sellist[0];
my $meta = getMetaData($dpic, 'APP13');
my $iptc = $meta->get_app13_data('TEXTUAL', 'IPTC');
unless (defined $iptc) {
$top->messageBox(-icon => 'warning', -message => "There is no IPTC info in $dpic!",
-title => "Save IPTC info", -type => 'OK');
return;
}
if (!-d $iptcdir) {
if ( !mkdir $iptcdir, 0755 ) {
$top->messageBox(-icon => 'warning', -message => "Error making IPTC template directory $iptcdir: $!",
-title => "Save IPTC template", -type => 'OK');
return;
}
}
my $fileSelect = $top->FileSelect(-title => "Set file name (please use the .iptc2 suffix)",
-initialfile => "template.iptc2",
-create => 1,
-directory => $iptcdir,
-width => 30, -height => 30);
my $file = $fileSelect->Show;
return unless (defined $file);
return if ($file eq '');
if (-f $file) {
my $rc = $top->messageBox(-icon => 'warning',
-message => "file $file exist. Ok to overwrite?",
-title => "Save IPTC info", -type => 'OKCancel');
return if ($rc !~ m/Ok/i);
}
my $rc = store($iptc, $file) or warn "could not store IPTC in file $file: $!";
$userinfo = "IPTC template saved ($rc)"; $userInfoL->update;
}
##############################################################
# copyFromIPTC -
##############################################################
sub copyIPTC {
my @sellist = $picLB->info('selection');
if (@sellist != 1) {
$top->messageBox(-icon => 'warning', -message => "Please select exactly one picture.",
-title => "Copy IPTC info", -type => 'OK');
return;
}
my $dpic = $sellist[0];
my $meta = getMetaData($dpic, 'APP13');
$iptcCopy = $meta->get_app13_data('TEXTUAL', 'IPTC');
unless (defined $iptcCopy) {
$top->messageBox(-icon => 'warning', -message => "There is no IPTC info in $dpic!",
-title => "Copy IPTC info", -type => 'OK');
return;
}
$userinfo = "IPTC copy ready"; $userInfoL->update;
}
##############################################################
# pasteIPTC -
##############################################################
sub pasteIPTC {
my @sellist = $picLB->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
applyIPTC($picLB, $iptcCopy, \@sellist);
}
##############################################################
# mergeIPTC - merge a IPTC info hash template to a file
##############################################################
sub mergeIPTC {
my @sellist = $picLB->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
my $file = $top->FileSelect(-title => "Open IPTC template",
-directory => $iptcdir,
-width => 30, -height => 30)->Show;
return unless (defined $file);
return if ($file eq "");
return unless (-f $file);
my $iptc = retrieve($file);
unless (defined $iptc) {
warn "could not retrieve $file";
return;
}
applyIPTC($picLB, $iptc, \@sellist);
}
##############################################################
# applyIPTC - apply a IPTC info hash to a list of pics
##############################################################
sub applyIPTC {
my $lb = shift; # reference to listbox widget
my $iptc = shift; # reference to a IPTC hash as provided by Image::MetaData::JPEG
my $piclist = shift; # picture list reference
my $errors = "";
my $pw = 0;
$pw = progressWinInit($lb, "Apply IPTC template ") if (@$piclist > 1);
my $i = 0;
foreach my $dpic (@$piclist) {
last if ($pw and progressWinCheck($pw));
$i++;
progressWinUpdate($pw, "applying IPTC template ($i/".scalar @$piclist.") ...", $i, scalar @$piclist) if $pw;
next if (!checkWriteable($dpic));
my $meta = getMetaData($dpic, 'APP13');
unless (defined $meta) {
$errors .= "could not create IPTC info for $dpic!";
next;
}
# todo, we could also use UPDATE or REPLACE here
$meta->set_app13_data($iptc, 'ADD', 'IPTC');
# make the SupplementalCategories and Keywords unique and sorted
uniqueIPTC($meta);
if ($meta->save()) {
my $dirthumb = getThumbFileName($dpic);
# touch the thumbnail pic (set actual time stamp), to suppress rebuilding the next time
touch($dirthumb);
updateOneRow($dpic, $lb);
showImageInfoCanvas($dpic) if ($dpic eq $actpic);
}
else {
$errors .= "save failed for $dpic\n";
}
}
progressWinEnd($pw) if $pw;
$userinfo = "ready! ($i of ".scalar @$piclist." processed)"; $userInfoL->update;
showText("Errors while applying IPTC infos", $errors, NO_WAIT) if ($errors ne "");
}
##############################################################
# uniqueArray
##############################################################
sub uniqueArray {
my $listR = shift;
my %d; # build a hash
foreach (@{$listR}) { $d{$_} = 1; }
@{$listR} = (sort { uc($a) cmp uc($b); } keys %d);
}
##############################################################
# uniqueIPTC - remove double entries from SupplementalCategories
# and Keywords and sort them
# !Function will not save IPTC!
##############################################################
sub uniqueIPTC {
my $meta = shift;
my $iptc = $meta->get_app13_data('TEXTUAL', 'IPTC');
my %d; # build a hash
foreach (@{$iptc->{SupplementalCategory}}) { $d{$_} = 1; }
@{$iptc->{SupplementalCategory}} = (sort { uc($a) cmp uc($b); } keys %d);
%d = (); # completely empty %d
foreach (@{$iptc->{Keywords}}) { $d{$_} = 1; }
@{$iptc->{Keywords}} = (sort { uc($a) cmp uc($b); } keys %d);
$meta->set_app13_data($iptc, 'REPLACE', 'IPTC');
}
##############################################################
# editIPTCCategories
##############################################################
sub editIPTCCategories {
my $lb = shift;
if (Exists($catw)) {
$catw->deiconify;
$catw->raise;
$catw->focus;
return;
}
# open window
$catw = $lb->Toplevel();
$catw->withdraw;
$catw->title('Categories');
$catw->iconimage($mapiviicon) if $mapiviicon;
my $cattree;
my $XBut = $catw->Button(-text => "Close",
-command => sub {
saveTreeMode($cattree);
store($cattree->{m_mode}, "$configdir/categoryMode") or warn "could not store $configdir/categoryMode: $!";
$catw->destroy;
})->pack(-expand => 0,-fill => 'x',-padx => 1,-pady => 1);
my $af = $catw->Frame()->pack(-fill =>'x', -padx => 3, -pady => 3);
$af->Radiobutton(-text => "all", -variable => \$config{CategoriesAll}, -value => 1)->pack(-side => 'left');
$af->Radiobutton(-text => "join", -variable => \$config{CategoriesAll}, -value => 2)->pack(-side => 'left');
$af->Radiobutton(-text => "last", -variable => \$config{CategoriesAll}, -value => 0)->pack(-side => 'left');
my $addB =
$af->Button(-text => "add",
-command => sub {
my @cats = $cattree->info('selection');
return unless checkSelection($catw, 1, 0, \@cats);
my @sellist = $lb->info('selection');
return unless checkSelection($catw, 1, 0, \@sellist);
my $warning = '';
my @catlist;
foreach my $cat (@cats) {
my @items;
if ($config{CategoriesAll} == 1) { # all, separated
@items = getAllItems($cat);
}
elsif ($config{CategoriesAll} == 2) { # all, joined
@items = getAllItems($cat);
my $joined = join('.', @items);
if (length($joined) > 32) {
$warning .= "Category $joined has ".length($joined)." characters";
next;
}
undef @items;
push @items, $joined;
}
elsif ($config{CategoriesAll} == 0) { # last
@items = getLastItem($cat);
}
else {
warn "editIPTCCategories: should never be reached ($config{CategoriesAll})!";
}
push @catlist, @items;
}
if (@catlist) {
my $iptc = { SupplementalCategory => \@catlist };
applyIPTC($lb, $iptc, \@sellist);
}
if ($warning ne '') {
$warning = "IPTC supp. categories are limited to 32 characters. Please shorten category.\n$warning";
showText("Warnings while adding keywords", $warning, NO_WAIT);
}
} )->pack(-side => 'left', -expand => 0, -fill => 'x', -padx => 1, -pady => 1);
$balloon->attach($addB, -msg => "Add the selected categories to the selected pictures");
my $rmB =
$af->Button(-text => "remove",
-command => sub {
my @cats = $cattree->info('selection');
return unless checkSelection($catw, 1, 0, \@cats);
my @sellist = $lb->info('selection');
return unless checkSelection($catw, 1, 0, \@sellist);
my $pw = progressWinInit($catw, "Remove category");
my $i = 0;
my $sum = @sellist;
foreach my $dpic (@sellist) {
last if progressWinCheck($pw);
$i++;
progressWinUpdate($pw, "removing category ($i/$sum) ...", $i, $sum);
foreach my $cat (@cats) {
last if progressWinCheck($pw);
progressWinUpdate($pw, "removing category $cat ($i/$sum) ...", $i, $sum);
my $item;
if ($config{CategoriesAll} == 2) { # all, joined
my @items = getAllItems($cat);
$item = join('.', @items);
}
else { # last
$item = getLastItem($cat);
}
print "remove category $item ($cat) from $dpic\n" if $verbose;
removeIPTCItem($dpic, 'SupplementalCategory', $item);
updateOneRow($dpic, $lb);
}
}
progressWinEnd($pw);
})->pack(-side => 'left', -expand => 0, -fill => 'x', -padx => 1, -pady => 1);
$balloon->attach($rmB, -msg => "Remove the selected categories from the selected pictures");
$cattree = $catw->Scrolled('Tree',
-separator => '/',
-scrollbars => 'osoe',
-selectmode => 'extended',
-exportselection => 0,
-width => 25,
-height => 25,
)->pack(-expand => 1, -fill =>'both', -padx => 4, -pady => 2);
bindMouseWheel($cattree->Subwidget("scrolled"));
$balloon->attach($cattree, -msg => "Double click on a category to insert it.\nIt's possible to edit the categories, use the\nright mouse button to open the edit menu.");
# try to get the saved mode
if (-f "$configdir/categoryMode") {
my $hashRef = retrieve("$configdir/categoryMode");
warn "could not retrieve mode" unless defined $hashRef;
$cattree->{m_mode} = $hashRef;
}
$cattree->bind('<Double-Button-1>', sub { $addB->invoke; });
addTreeMenu($cattree, \@precats);
insertTreeList($cattree, @precats);
$catw->bind('<Key-q>', sub { $XBut->invoke; });
$catw->bind('<Key-Escape>', sub { $XBut->invoke; });
$catw->Popup;
$catw->waitWindow;
}
##############################################################
# editIPTCKeywords
##############################################################
sub editIPTCKeywords {
my $lb = shift;
if (Exists($keyw)) {
my $x = $keyw->parent; print "parent widget = $x lb = $lb keyw = $keyw\n";
# todo this doesn't work
# but there should be a difference because when the win is already open from the main win and is called from the search win, the keywords of the wrong window are being modified!
if ($lb eq $keyw->parent) {
print "editIPTCKeywords called from same widget\n";
}
else {
print "editIPTCKeywords called from other widget\n";
}
$keyw->deiconify;
$keyw->raise;
$keyw->focus;
return;
}
# open window
$keyw = $lb->Toplevel();
$keyw->withdraw;
$keyw->title('Keywords');
$keyw->iconimage($mapiviicon) if $mapiviicon;
my $keytree;
my $af = $keyw->Frame()->pack(-fill =>'x', -padx => 2, -pady => 2);
# global button, as it has to be called from saveAllConfig (todo: find better solution for this)
$keyXBut = $af->Button(-text => "Close",
-command => sub {
saveTreeMode($keytree);
store($keytree->{m_mode}, "$configdir/keywordMode") or warn "could not store $configdir/keywordMode: $!";
$config{KeyGeometry} = $keyw->geometry;
$keyw->destroy;
})->pack(-side => 'left', -expand => 1,-fill => 'x');
my $addB =
$af->Button(-text => "add",
-command => sub {
my @keys = $keytree->info('selection');
return unless checkSelection($keyw, 1, 0, \@keys);
my @sellist = $lb->info('selection');
return unless checkSelection($keyw, 1, 0, \@sellist);
my @keylist;
my $warning = '';
foreach my $key (@keys) {
my @items;
if ($config{KeywordsAll} == 1) { # all, separated
@items = getAllItems($key);
}
elsif ($config{KeywordsAll} == 2) { # all, joined
@items = getAllItems($key);
my $joined = join('.', @items);
if (length($joined) > 64) {
$warning .= "Keyword $joined has ".length($joined)." characters";
next;
}
undef @items;
push @items, $joined;
}
elsif ($config{KeywordsAll} == 0) { # last
@items = getLastItem($key);
}
else {
warn "editIPTCKeywords: should never be reached!";
}
push @keylist, @items;
}
if (@keylist) {
my $iptc = { Keywords => \@keylist };
applyIPTC($lb, $iptc, \@sellist);
}
if ($warning ne '') {
$warning = "IPTC keywords are limited to 64 characters. Please shorten keyword.\n$warning";
showText("Warnings while adding keywords", $warning, NO_WAIT);
}
} )->pack(-side => 'left', -expand => 0, -fill => 'x');
$balloon->attach($addB, -msg => "Add the selected keywords to the selected pictures");
my $rmB =
$af->Button(-text => "remove",
-command => sub {
my @keys = $keytree->info('selection');
return unless checkSelection($keyw, 1, 0, \@keys);
my @sellist = $lb->info('selection');
return unless checkSelection($keyw, 1, 0, \@sellist);
my $pw = progressWinInit($keyw, "Remove keyword");
my $i = 0;
my $sum = @sellist;
foreach my $dpic (@sellist) {
last if progressWinCheck($pw);
$i++;
progressWinUpdate($pw, "removing keyword ($i/$sum) ...", $i, $sum);
foreach my $key (@keys) {
last if progressWinCheck($pw);
progressWinUpdate($pw, "removing keyword $key ($i/$sum) ...", $i, $sum);
my $item;
if ($config{KeywordsAll} == 2) { # all, joined
my @items = getAllItems($key);
$item = join('.', @items);
}
else { # last
$item = getLastItem($key);
}
print "remove key $item ($key) from $dpic\n" if $verbose;
removeIPTCItem($dpic, 'Keywords', $item);
updateOneRow($dpic, $lb);
}
}
progressWinEnd($pw);
})->pack(-side => 'left', -expand => 0, -fill => 'x');
$balloon->attach($rmB, -msg => "Remove the selected keywords from the selected pictures");
my $bf = $keyw->Frame()->pack(-fill =>'x', -padx => 2, -pady => 2);
$bf->Radiobutton(-text => "all", -variable => \$config{KeywordsAll}, -value => 1)->pack(-side => 'left');
$bf->Radiobutton(-text => "join", -variable => \$config{KeywordsAll}, -value => 2)->pack(-side => 'left');
$bf->Radiobutton(-text => "last", -variable => \$config{KeywordsAll}, -value => 0)->pack(-side => 'left');
$balloon->attach($bf, -msg => "Keyword add mode\nExample keyword: Friend/Bundy/Kelly\nmode all: three keywords: Friend, Bundy and Kelly\nmode join: one keyword: Friend.Bundy.Kelly\nmode last: one keyword: Kelly");
$keytree = $keyw->Scrolled('Tree',
-separator => '/',
-scrollbars => 'osoe',
-selectmode => 'extended',
-exportselection => 0,
-width => 25,
-height => 25,
)->pack(-expand => 1, -fill =>'both', -padx => 4, -pady => 2);
$keyw->{tree} = $keytree;
bindMouseWheel($keytree->Subwidget("scrolled"));
$balloon->attach($keytree, -msg => "Double click on a keyword to insert it.\nIt's possible to edit the keywords, use the\nright mouse button to open the edit menu.");
# try to get the saved mode
if (-f "$configdir/keywordMode") {
my $hashRef = retrieve("$configdir/keywordMode");
warn "could not retrieve mode" unless defined $hashRef;
$keytree->{m_mode} = $hashRef;
}
$keytree->bind('<Double-Button-1>', sub { $addB->invoke; });
addTreeMenu($keytree, \@prekeys);
insertTreeList($keytree, @prekeys);
$keyw->bind('<Key-q>', sub { $keyXBut->invoke; });
$keyw->bind('<Key-Escape>', sub { $keyXBut->invoke; });
# invoke $but when the window is closed by the window manager (x-button)
$keyw->protocol("WM_DELETE_WINDOW" => sub { $keyXBut->invoke; });
$keyw->Popup;
checkGeometry(\$config{KeyGeometry});
$keyw->geometry($config{KeyGeometry});
$keyw->waitWindow;
}
##############################################################
# editCommentKeywords
##############################################################
sub editCommentKeywords {
my $lb = shift;
if (Exists($keycw)) {
$keycw->deiconify;
$keycw->raise;
$keycw->focus;
return;
}
# open window
$keycw = $top->Toplevel();
$keycw->withdraw;
$keycw->title('Keywords for comments');
$keycw->iconimage($mapiviicon) if $mapiviicon;
my $keytree;
my $XBut = $keycw->Button(-text => "Close",
-command => sub {
saveTreeMode($keytree);
store($keytree->{m_mode}, "$configdir/keywordMode") or warn "could not store $configdir/keywordMode: $!";
$keycw->destroy;
})->pack(-expand => 0,-fill => 'x',-padx => 1,-pady => 1);
my $af = $keycw->Frame()->pack(-fill =>'x', -padx => 3, -pady => 3);
$af->Radiobutton(-text => "all", -variable => \$config{KeywordsAll}, -value => 1)->pack(-side => 'left');
$af->Radiobutton(-text => "last", -variable => \$config{KeywordsAll}, -value => 0)->pack(-side => 'left');
my $addB =
$af->Button(-text => "add",
-command => sub {
my @keys = $keytree->info('selection');
return unless checkSelection($keycw, 1, 0, \@keys);
my @sellist = $lb->info('selection');
return unless checkSelection($keycw, 1, 0, \@sellist);
my $comment;
foreach my $key (@keys) {
my @items;
if ($config{KeywordsAll}) {
@items = getAllItems($key);
}
else {
@items = getLastItem($key);
}
$comment .= "$_ " foreach (@items);
}
# todo add to end of existing comment or as new comment
foreach my $dpic (@sellist) {
# todo progressbar
addCommentToPic($comment, $dpic, TOUCH);
updateOneRow($dpic, $lb);
showImageInfo($dpic) if ($dpic eq $actpic);
}
} )->pack(-side => 'left', -expand => 0, -fill => 'x', -padx => 1, -pady => 1);
$balloon->attach($addB, -msg => "Add the selected keywords to the selected pictures");
=pod
my $rmB =
$af->Button(-text => "remove",
-command => sub {
my @keys = $keytree->info('selection');
return unless checkSelection($keycw, 1, 0, \@keys);
my @sellist = $lb->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
my $pw = progressWinInit($keycw, "Remove keyword");
my $i = 0;
my $sum = @sellist;
foreach my $dpic (@sellist) {
last if progressWinCheck($pw);
$i++;
progressWinUpdate($pw, "removing keyword ($i/$sum) ...", $i, $sum);
foreach my $key (@keys) {
last if progressWinCheck($pw);
progressWinUpdate($pw, "removing keyword $key ($i/$sum) ...", $i, $sum);
my $name = getLastItem($key);
print "remove key $name ($key) from $dpic\n" if $verbose;
removeIPTCItem($dpic, 'Keywords', $name);
updateOneRow($dpic, $lb);
}
}
progressWinEnd($pw);
})->pack(-side => 'left', -expand => 0, -fill => 'x', -padx => 1, -pady => 1);
$balloon->attach($rmB, -msg => "Remove the selected keywords from the selected pictures");
=cut
$keytree = $keycw->Scrolled('Tree',
-separator => '/',
-scrollbars => 'osoe',
-selectmode => 'extended',
-exportselection => 0,
-width => 25,
-height => 25,
)->pack(-expand => 1, -fill =>'both', -padx => 4, -pady => 2);
bindMouseWheel($keytree->Subwidget("scrolled"));
$balloon->attach($keytree, -msg => "Double click on a keyword to insert it.\nIt's possible to edit the keywords, use the\nright mouse button to open the edit menu.");
# try to get the saved mode
if (-f "$configdir/keywordMode") {
my $hashRef = retrieve("$configdir/keywordMode");
warn "could not retrieve mode" unless defined $hashRef;
$keytree->{m_mode} = $hashRef;
}
$keytree->bind('<Double-Button-1>', sub { $addB->invoke; });
addTreeMenu($keytree, \@prekeys);
insertTreeList($keytree, @prekeys);
$keycw->bind('<Key-q>', sub { $XBut->invoke; });
$keycw->bind('<Key-Escape>', sub { $XBut->invoke; });
$keycw->Popup;
$keycw->waitWindow;
}
##############################################################
# addTreeMenu - add a menu to a tree widget to edit a tree
##############################################################
sub addTreeMenu {
my $tree = shift; # tree widget
my $listRef = shift; # the list displayed in the tree
my $menu = $tree->Menu(-title => "Tree edit menu");
$menu->command(-label => "add new item", -command => sub {
my @keys = $tree->info('selection');
return unless checkSelection($tree, 1, 1, \@keys);
my $item = "";
my $parent = $keys[0];
if ($parent !~ m/.*\/.*/) {
$parent = '';
}
else {
# cut of last element
$parent = $1 if ($parent =~ m/(.*\/).*/);
$parent .= '/' if (($parent ne '') and ($parent !~ m/.*\/$/));
}
my $rc = myEntryDialog('New item',
"Please enter the new item (below $parent)",
\$item);
return if ($rc ne 'OK');
return if ($item eq '');
push @{$listRef}, $parent.$item;
insertTreeList($tree, @{$listRef});
});
$menu->command(-label => "add new item below selected item", -command => sub {
my @keys = $tree->info('selection');
return unless checkSelection($tree, 1, 1, \@keys);
my $item = "";
my $parent = $keys[0];
my $rc = myEntryDialog('New sub item',
"Please enter the new sub item (below $parent)",
\$item);
return if ($rc ne 'OK');
return if ($item eq '');
$parent .= '/' if (($parent ne '') and ($parent !~ m/.*\/$/));
push @{$listRef}, $parent.$item;
insertTreeList($tree, @{$listRef});
});
$menu->separator;
$menu->command(-label => "rename (move) selected item", -command => sub {
my @keys = $tree->info('selection');
return unless checkSelection($tree, 1, 1, \@keys);
my $parent = $keys[0];
my $rc = myEntryDialog('Rename item',
"Please enter the new name for item $parent",
\$parent);
return if ($rc ne 'OK');
return if ($parent eq '');
$parent =~ s|^/||; # cut leading slash
for my $t (0 .. $#{@{$listRef}} ) {
if ($$listRef[$t] =~ m/^$keys[0](.*)/) {
print "rename: $$listRef[$t] ($t) to $parent$1\n" if $verbose;
$$listRef[$t] = $parent.$1;
}
}
insertTreeList($tree, @{$listRef});
});
$menu->separator;
$menu->command(-label => "delete selected item", -command => sub {
my @keys = $tree->info('selection');
return unless checkSelection($tree, 1, 1, \@keys);
for my $t (reverse 0 .. $#{@{$listRef}} ) {
if ($$listRef[$t] =~ m/^$keys[0].*/) {
print "trow out: $$listRef[$t] ($t)\n" if $verbose;
splice @{$listRef}, $t, 1; # remove it from list
}
}
insertTreeList($tree, @{$listRef});
});
$menu->separator;
$menu->command(-label => "search selected items", -command => sub {
my @keys = $tree->info('selection');
return unless checkSelection($tree, 1, 0, \@keys);
my $pat = '';
foreach (@keys) {
my @parts = split /\//, $_; # todo add join and all mode
$pat .= $parts[-1].' ';
}
$pat =~ s/\s+$//; # cut trailing whitespace
$pat =~ s/^\s+//; # cut leading whitespace
my $pat_orig = $pat;
if (@keys > 1) {
$pat = "(?=.*".$pat; # and-function with look-ahead
$pat =~ s/\s+/)(?=.*/g; # replace one or more whitespaces with )(?=.*
$pat .= ")"; # "Tom Tim" is now: "(?=.*Tom)(?=.*Tim)"
}
my $start_time = Tk::timeofday();
my $case = 'i';
my $count = 0;
my @dpics;
# loop through all database entries
foreach my $dpic (sort keys %searchDB) {
my $keys = $searchDB{$dpic}{KEYS};
if ((defined $keys) and ($keys =~ m/(?$case).*$pat.*/)) {
$count ++;
push @dpics, $dpic;
}
}
my $time_elapsed = sprintf "%.2f", (Tk::timeofday() - $start_time);
my $rc = myButtonDialog('Search finished',
"Found $count pictures in ${time_elapsed}sec matching \"$pat_orig\"",
undef,
'Show found pictures', 'Cancel',);
# todo showing the pics in the light table is not always the best idea! -> showThumbListInNewWin
light_table_add(\@dpics) if ((@dpics > 0) and ($rc eq 'Show found pictures'));
});
$tree->bind('<ButtonPress-3>', sub {
$menu->Popup(-popover => "cursor", -popanchor => "nw");
} );
}
##############################################################
# showThumbListInNewWin
##############################################################
sub showThumbListInNewWin {
}
##############################################################
# getLastItem - returns the last item of a scalar separated with
# a slash: family/Miller/Robert -> Robert
##############################################################
sub getLastItem($) {
my $item = shift;
my @names = split /\//, $item;
my $name = $names[-1];
$name = $item if ((!defined $name) or ($name eq ""));
return $name;
}
##############################################################
# getAllItems - returns a list of all items of a scalar
# separated with a slash:
# family/Miller/Robert -> family, Miller, Robert
##############################################################
sub getAllItems($) {
my $item = shift;
return split /\//, $item;
}
##############################################################
# insertTreeList
##############################################################
sub insertTreeList {
my $tree = shift;
my %mode;
saveTreeMode($tree);
%mode = %{$tree->{m_mode}} if (defined $tree->{m_mode});
$tree->delete("all");
# insert the list (@_)
foreach (sort { uc($a) cmp uc($b); } @_ ) {
my @names = split /\//, $_;
my $name = $names[-1];
$name = $_ if ((!defined $name) or ($name eq ""));
$tree->add($_, -text=>$name);
}
$tree->autosetmode;
# reset mode to the the old setting for the first 3 levels
foreach ($tree->info('children')) {
$tree->close($_) if ((defined $mode{$_}) and ($mode{$_} eq 'open'));
$tree->open($_) if ((defined $mode{$_}) and ($mode{$_} eq 'close'));
foreach ($tree->info('children', $_)) {
$tree->close($_) if ((defined $mode{$_}) and ($mode{$_} eq 'open'));
$tree->open($_) if ((defined $mode{$_}) and ($mode{$_} eq 'close'));
foreach ($tree->info('children', $_)) {
$tree->close($_) if ((defined $mode{$_}) and ($mode{$_} eq 'open'));
$tree->open($_) if ((defined $mode{$_}) and ($mode{$_} eq 'close'));
}
}
}
}
##############################################################
# saveTreeMode - save the mode (open, close) of the first 3
# levels of a tree in $widget->{m_mode}
# {m_mode} is mapivi private data stored in the
# widget hash
##############################################################
sub saveTreeMode {
my $tree = shift;
my %mode;
%mode = %{$tree->{m_mode}} if (defined $tree->{m_mode});
# save mode (open, close) of existing items for the first 3 levels
foreach ($tree->info('children')) {
$mode{$_} = $tree->getmode($_);
foreach ($tree->info('children', $_)) {
$mode{$_} = $tree->getmode($_);
foreach ($tree->info('children', $_)) {
$mode{$_} = $tree->getmode($_);
}
}
}
$tree->{m_mode} = \%mode;
}
##############################################################
# removeIPTCItem
##############################################################
sub removeIPTCItem {
my $dpic = shift;
my $kind = shift;
my $item = shift;
if (($kind ne 'Keywords') and ($kind ne 'SupplementalCategory')) {
warn "removeIPTCItem: $kind is wrong kind";
return;
}
print "removeIPTCItem: kind:$kind item:$item pic:$dpic\n" if $verbose;
my $meta = getMetaData($dpic, 'APP13');
unless (defined $meta) {
print "removeIPTCItem: Could not create IPTC info for $dpic!\n";
return;
}
my $iptc = $meta->get_app13_data('TEXTUAL', 'IPTC');
my %d; # build a hash
foreach (@{$iptc->{$kind}}) { $d{$_} = 1; }
return unless (defined $d{$item});
delete $d{$item}; # remove item from list
@{$iptc->{$kind}} = (sort { uc($a) cmp uc($b); } keys %d);
$meta->set_app13_data($iptc, 'REPLACE', 'IPTC');
if ($meta->save()) {
my $dirthumb = getThumbFileName($dpic);
# touch the thumbnail pic (set actual time stamp), to suppress rebuilding the next time
touch($dirthumb);
}
else {
print "removeIPTCItem: save failed for $dpic\n";
}
}
##############################################################
# getIPTC - returns all IPTC-Data of the given picture
##############################################################
sub getIPTC {
# the pic with complete path
my $dpic = shift;
# bool, if = LONG a better complete readable output,
# if = SHORT a compact but complete IPTC info for e.g. the search database
my $format = shift;
my $meta = shift; # optional, the Image::MetaData::JPEG object of $pic if available
my $iptc = "";
return $iptc unless is_a_JPEG($dpic);
my $shortkey;
# todo: is , 'FASTREADONLY' here possible?
$meta = getMetaData($dpic, 'APP13') unless (defined($meta));
if ($meta) {
my $seg = $meta->retrieve_app13_segment(undef, 'IPTC');
if ($seg) {
my $hashref = $seg->get_app13_data("TEXTUAL", 'IPTC');
foreach my $key (@IPTCAttributes) {
# this causes trouble (cuts off the rest) because it's binary
next if ($key eq "RecordVersion");
if (defined($hashref->{$key})) {
if (($format == LONG)) {
$iptc .= sprintf "%-31s: ", $key;
} else {
my $shortkey = $key;
$shortkey =~ s/SupplementalCategory/SuppCategories/;
$shortkey = substr($shortkey, 0, 7)."." if (length($shortkey) > 8);
$iptc .= sprintf "%-8s: ", $shortkey;
}
$iptc .= "$_ " for @{$hashref->{$key}};
$iptc =~ s/\s+$//; # cut trailing whitespace
$iptc .= "\n";
}
}
}
}
return $iptc;
}
##############################################################
# getShortIPTC - get just one attribute of the IPTC comment
# I decided to use the caption/abstract, but
# I am not sure if this is the best attribute
# here?
# if there is no file or no IPTC info in the file
# an empty string is returned
##############################################################
sub getShortIPTC {
my $dpic = shift;
# optional, if set to LONG the complete contents of the @iptcs attributes
# (see below) will be returned
# else (SHORT) it will be cut to fit in the hlist
my $format = shift; # LONG or SHORT
return "" unless (-f $dpic);
my $info = getIPTC($dpic, SHORT);
$info = formatString($info, $config{LineLength}) if ((defined $format) and ($format == SHORT));
return $info;
}
##############################################################
# getImageInfo - returns a hash containing the image info
##############################################################
sub getImageInfo {
my $pic = shift;
if (!-f $pic) {
return "";
}
my $ii = image_info($pic);
if (!$ii) {
return "";
}
if ($ii->{Errno} and $ii->{Errno} ne "0") {
return "";
}
return $ii;
}
##############################################################
# getNearestItem - finds the nearest item to the mouse pointer
# in a listbox
##############################################################
sub getNearestItem {
my($LB) = @_;
my ($X,$Y) = $LB->pointerxy();
my $y = $LB->rooty();
my $yy = $Y - $y;
return ($LB->nearest($yy));
}
##############################################################
# processARGV - handels the command line arguments (if any)
##############################################################
sub processARGV {
my $nr = @ARGV;
if ($nr < 1) { # open the last dir
$actdir = $config{LastDir};
dirSave($actdir);
return;
}
if ($nr > 1) {
print "\nmapivi error: to many command line options\n";
printUsage();
exit;
}
my $item = abs_path($ARGV[0]);
if (-f $item) {
$actpic = basename($item);
$actdir = dirname($item);
}
elsif (-d $item) {
$actdir = $item;
}
else {
printUsage();
exit;
}
dirSave($actdir);
}
##############################################################
# getDirAndOpen - let the user select a new dir and open it
# with a simple text entry
##############################################################
sub getDirAndOpen {
my $dir = $actdir;
my $rc = myEntryDialog("open dir","Please enter directory:",\$dir);
return if ($rc ne 'OK');
print " --$dir--\n" if $verbose;
$dir = glob("$dir");
print "g--$dir--\n" if $verbose;
while (!-d $dir) {
$top->messageBox(-icon => 'warning', -message => "Sorry, but I can't find the directory \"$dir\"",
-title => "No valid directory", -type => 'OK');
$rc = myEntryDialog("open dir","Please enter directory:",\$dir);
return if ($rc ne 'OK');
$dir = glob("$dir");
}
openDirPost($dir);
}
##############################################################
# openDir - let the user select a new dir and open it
# with a real dir dialog
##############################################################
sub openDir {
my $dir = dirDialog($actdir);
openDirPost($dir);
}
##############################################################
# openDirPost - things to do when opening a new dir
##############################################################
sub openDirPost {
my $dir = shift;
$dir =~ s/\/\//\//g; # replace all // with /
return unless (defined $dir);
return unless (-d $dir);
$actdir = $dir;
my $path = cutString($dir, -22, "..");
$userinfo = "opening $path ..."; $userInfoL->update;
$actpic = ""; # reset var $actpic - needed to get a correct window title
setDirProperties();
dirSave($dir);
clearLabels();
showImageInfoCanvas();
setTitle();
$exif = "" if ($config{ShowEXIFField});
$commentText->delete( 0.1, 'end') if ($config{ShowCommentField} and defined $commentText);
$dirtree->configure(-directory => $actdir);
# Set the directory
exists &Tk::DirTree::chdir ? $dirtree->chdir($actdir) : $dirtree->set_dir($actdir);
selectDirInTree($actdir);
updateThumbs();
}
##############################################################
# setDirProperties
##############################################################
sub setDirProperties {
$dirPropSORT = 0;
$dirPropMETA = 0;
$dirPropPRIO = 0;
$dirPropSORT = $dirProperties{$actdir}{SORT} if (defined $dirProperties{$actdir}{SORT});
$dirPropMETA = $dirProperties{$actdir}{META} if (defined $dirProperties{$actdir}{META});
$dirPropPRIO = $dirProperties{$actdir}{PRIO} if (defined $dirProperties{$actdir}{PRIO});
#foreach my $prop (@dirPropList) {
# $dirProp{$prop} = 0;
# $dirProp{$prop} = $dirProperties{$actdir}{SORT}
}
##############################################################
# showDirProperties
##############################################################
sub showDirProperties {
if (Exists($dpw)) {
$dpw->deiconify;
$dpw->raise;
$dpw->focus;
return;
}
# open window
$dpw = $top->Toplevel();
$dpw->withdraw;
$dpw->title('Directory Checklist');
$dpw->iconimage($mapiviicon) if $mapiviicon;
my $topf = $dpw->Frame()->pack();
my $dplb = $dpw->Scrolled("HList",
-header => 1,
-separator => ';', # todo here we hope that ; will never be in a directory or file name
-pady => 1,
-columns => 5,
-scrollbars => 'osoe',
#-selectmode => "dragdrop", todo
-selectmode => "extended",
-background => $config{ColorBG}, #8fa8bf
-width => 40,
-height => 60,
)->pack(-expand => 1, -fill => "both");
bindMouseWheel($dplb);
my $count = 0;
$dplb->{dircol} = $count;
$dplb->header('create', $count++, -text => 'Folder', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
$dplb->{sortcol} = $count;
$dplb->header('create', $count++, -text => 'Sort', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
$dplb->{metacol} = $count;
$dplb->header('create', $count++, -text => 'Meta', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
$dplb->{priocol} = $count;
$dplb->header('create', $count++, -text => 'Prio', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
$dplb->{commcol} = $count;
$dplb->header('create', $count++, -text => 'Comment', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
my $Xbut = $topf->Button(-text => "Close",
-command => sub { $dpw->withdraw; $dpw->destroy; }
)->pack(-side => 'left', -expand => 0,-fill => 'x',-padx => 1,-pady => 1);
my $upd_but = $topf->Button(-text => "Update",
-command => sub {
my @dirs = $dplb->info('selection');
my $last = $dirs[-1];
$dplb->delete("all");
insertDirProperties($dplb);
reselect($dplb, @dirs);
$dplb->see($last) if ($dplb->info("exists", $last));;
})->pack(-side => 'left', -expand => 0,-padx => 1,-pady => 1);
$topf->Checkbutton(-text => "Show unfinished directories",
-variable => \$config{ShowUnfinishedDirs}
)->pack(-side => 'left', -expand => 0,-fill => 'x',-padx => 1,-pady => 1);
$topf->Checkbutton(-text => "Show finished directories",
-variable => \$config{ShowFinishedDirs}
)->pack(-side => 'left', -expand => 0,-fill => 'x',-padx => 1,-pady => 1);
my $dpmenu = $dpw->Menu(-title => "Directory Checklist Menu");
$dpmenu->command(-label => "open directory",
-command => sub {
my @dirs = $dplb->info('selection');
return unless checkSelection($dpw, 1, 1, \@dirs);
if (-d $dirs[0]) {
openDirPost($dirs[0]);
# show main window
$top->deiconify;
$top->raise;
} else {
$dplb->messageBox(-icon => 'info', -message => "Sorry, but this folder is currently not available!", -title => "Directory not available", -type => 'OK');
}
} );
$dpmenu->command(-label => "add all sub folders to this list",
-command => sub {
my @dirs = $dplb->info('selection');
return unless checkSelection($dpw, 1, 1, \@dirs);
@dirs = getDirsRecursive($dirs[0]);
my $nr = 0;
foreach (@dirs) {
# todo skip empty dirs
if (!defined $dirProperties{$_}) {
print "adding $_\n" if $verbose;
$dirProperties{$_}{SORT} = 0 ;
$dirProperties{$_}{META} = 0 ;
$dirProperties{$_}{PRIO} = 0 ;
$nr++;
}
}
$upd_but->invoke;
$dplb->messageBox(-icon => 'info', -message => "Added $nr folders.",
-title => "Added sub folders", -type => 'OK');
} );
$dpmenu->command(-label => "remove selected from list",
-command => sub {
my @dirs = $dplb->info('selection');
return unless checkSelection($dpw, 1, 0, \@dirs);
foreach my $dir (@dirs) {
delete $dirProperties{$dir};
$dplb->delete("entry", $dir) if ($dplb->info('exists', $dir));
}
} );
$dpmenu->command(-label => "edit comment",
-command => sub {
my @dirs = $dplb->info('selection');
return unless checkSelection($dpw, 1, 1, \@dirs);
my $text = "";
$text = $dirProperties{$dirs[0]}{COMM} if (defined $dirProperties{$dirs[0]}{COMM});
my $rc = myTextDialog("Edit comment", "Please edit comment of $dirs[0]", \$text);
return if ($rc ne 'OK');
# replace (german) umlaute by corresponding letters
$text =~ s/([$umlaute])/$umlaute{$1}/g if ($config{ConvertUmlaut});
$dirProperties{$dirs[0]}{COMM} = $text;
$dplb->itemConfigure($dirs[0], $dplb->{commcol}, -text => $dirProperties{$dirs[0]}{COMM}, -style => $fileS);
} );
my $sort_menu = $dpmenu->cascade(-label => "Sort");
my $meta_menu = $dpmenu->cascade(-label => "Meta");
my $prio_menu = $dpmenu->cascade(-label => "Prio");
my $all_menu = $dpmenu->cascade(-label => "All");
$sort_menu->command(-label => "set", -command => sub { setProperty($dplb, 'SORT', 1); } );
$sort_menu->command(-label => "reset", -command => sub { setProperty($dplb, 'SORT', 0); } );
$meta_menu->command(-label => "set", -command => sub { setProperty($dplb, 'META', 1); } );
$meta_menu->command(-label => "reset", -command => sub { setProperty($dplb, 'META', 0); } );
$prio_menu->command(-label => "set", -command => sub { setProperty($dplb, 'PRIO', 1); } );
$prio_menu->command(-label => "reset", -command => sub { setProperty($dplb, 'PRIO', 0); } );
$all_menu->command( -label => "set", -command => sub { setProperty($dplb, 'ALL', 1); } );
$all_menu->command( -label => "reset", -command => sub { setProperty($dplb, 'ALL', 0); } );
$dplb->bind('<ButtonPress-3>', sub {
$dpmenu->Popup(-popover => "cursor", -popanchor => "nw");
} );
$dplb->bind('<Double-Button-1>', sub {
my @dirs = $dplb->info('selection');
return unless checkSelection($dpw, 1, 1, \@dirs);
if (-d $dirs[0]) {
openDirPost($dirs[0]);
# show main window
$top->deiconify;
$top->raise;
} else {
$dplb->messageBox(-icon => 'info', -message => "Sorry, but this folder is currently not available!", -title => "Directory not available", -type => 'OK');
}
} );
$dpw->bind('<Control-q>', sub { $Xbut->invoke; });
$dpw->bind('<Key-Escape>', sub { $Xbut->invoke; });
$dpw->Popup;
my $ws = 0.7; # window size is 70% of screen
my $w = int($ws * $dpw->screenwidth);
my $h = int($ws * $dpw->screenheight);
my $x = int(($dpw->screenwidth - $w)/3);
my $y = int(($dpw->screenheight - $h)/3);
$dpw->geometry("${w}x${h}+${x}+${y}");
insertDirProperties($dplb);
$dpw->waitWindow;
}
##############################################################
# insertDirProperties
##############################################################
sub insertDirProperties {
my $lb = shift;
my $normal_S = $lb->ItemStyle('text', -anchor=>'nw', -foreground=>'#009', -background=>$config{ColorBG});
my $finished_S = $lb->ItemStyle('text', -anchor=>'nw', -foreground=>'#090', -background=>$config{ColorBG});
my $not_avail_S = $lb->ItemStyle('text', -anchor=>'nw', -foreground=>'#900', -background=>$config{ColorBG});
my $last_time;
foreach my $dir (sort { uc($a) cmp uc($b); } keys %dirProperties) {
my $style = $normal_S;
$style = $finished_S if (defined $dirProperties{$dir}{SORT} and
defined $dirProperties{$dir}{META} and
defined $dirProperties{$dir}{PRIO} and
$dirProperties{$dir}{SORT} == 1 and
$dirProperties{$dir}{META} == 1 and
$dirProperties{$dir}{PRIO} == 1);
next if (!$config{ShowFinishedDirs} and $style == $finished_S);
next if (!$config{ShowUnfinishedDirs} and $style != $finished_S);
$style = $not_avail_S unless (-d $dir);
# create new row
$lb->add($dir);
$lb->itemCreate($dir, $lb->{dircol}, -text => $dir, -style => $style);
$lb->itemCreate($dir, $lb->{sortcol}, -text => $dirProperties{$dir}{SORT}, -style => $comS);
$lb->itemCreate($dir, $lb->{metacol}, -text => $dirProperties{$dir}{META}, -style => $iptcS);
$lb->itemCreate($dir, $lb->{priocol}, -text => $dirProperties{$dir}{PRIO}, -style => $comS);
$lb->itemCreate($dir, $lb->{commcol}, -text => $dirProperties{$dir}{COMM}, -style => $iptcS);
# show progress every 0.5 seconds - idea from Slaven
if (!defined $last_time || Tk::timeofday()-$last_time > 0.5) {
$lb->update;
$last_time = Tk::timeofday();
}
}
}
##############################################################
# showDirSizes
##############################################################
sub showDirSizes {
if (Exists($dsw)) {
$dsw->deiconify;
$dsw->raise;
$dsw->focus;
return;
}
my @dirs = @_; # just one dir at the moment, because the dir tree is configured to single selection
# will contain all dirs
my @alldirs;
my $break = 0;
my $i = 0;
my $pw = progressWinInit($top, "Collect sub directories");
foreach my $dir (@dirs) {
if (progressWinCheck($pw)) {
$break = 1;
last;
}
find(sub {
# process just dirs, but not .thumbs/ .xvpics/ etc.
if (progressWinCheck($pw)) { $break = 1; $File::Find::prune = 1; }
if (-d and ($_ ne $thumbdirname) and ($_ ne ".xvpics") and ($_ ne $exifdirname)) {
$i++; $i = 0 if ($i > 10);
progressWinUpdate($pw, "collecting directories, found ".scalar @alldirs." ...", $i, 10);
push @alldirs, $File::Find::name;
# add dir if it contains at least one picture
#if (getPics($File::Find::name, JUST_FILE) > 0) {
#}
}
}, $dir);
}
progressWinEnd($pw);
return if ($break);
shift @alldirs if (@alldirs > 1); # remove the parent (starting) dir if there are subdirs
#$label = "Found ".scalar @alldirs." directories, getting size ...";
# hash key: directory value: size of dir in Bytes (including all subdirs)
my %dirsize;
my $max = 0;
#my $allsize = 0;
my $dirCount = 0;
my $fileCount = 0;
$i = 0;
$pw = progressWinInit($top, "Calculate directory sizes");
foreach my $dir (@alldirs) {
if (progressWinCheck($pw)) {
$break = 1;
last;
}
$i++;
progressWinUpdate($pw, "in directory $dir ($i/".scalar @alldirs.") ...", $i, scalar @alldirs);
my $size = 0;
$dirCount++;
find(sub {
$fileCount++;
$size += -s if (defined -s);
}, $dir);
$dirsize{$dir} = $size;
$max = $size if ($size > $max);
#$allsize += $size; # this will count deeper structures several times
}
progressWinEnd($pw);
return if ($break);
# open window
$dsw = $top->Toplevel();
#$dsw->withdraw;
$dsw->title('Directory Sizes');
$dsw->iconimage($mapiviicon) if $mapiviicon;
#$dsw->{label} = "Starting soon";
my $label = "Starting soon";
my $Xbut = $dsw->Button(-text => "Close",
-command => sub { $dsw->withdraw; $dsw->destroy; }
)->pack(-expand => 0,-fill => 'x',-padx => 1,-pady => 1);
$dsw->Label(-textvariable => \$label,
)->pack(-expand => 0,-fill => 'x',-padx => 1,-pady => 1);
my $dc_width = 700;
my $dc = $dsw->Scrolled('Canvas',
-scrollbars => 'osoe',
-width => $dc_width,
-height => 400,
-relief => 'sunken',
-bd => $config{Borderwidth})->pack(-expand => 1,-fill => 'both',-padx => 1, -pady => 1);
my $height = 16;
$dc->configure(-scrollregion => [0, 0, $dc_width, ($#alldirs * $height)]);
$max = 1 if ($max <= 0); # avoid divison by zero
my $scale = ($dc_width - 2)/$max;
my $y = 2;
my $x = 2;
foreach my $dir (sort keys %dirsize) {
$dc->createRectangle( $x, $y, $x + ($dirsize{$dir} * $scale), $y+$height,
-tags => ['RECT'],
#-outline => undef,
-outline => 'black',
-fill => 'goldenrod3',
);
my $text = sprintf "%6s", computeUnit($dirsize{$dir});
$dc->createText( $x+1, $y+1, -text => $text, -anchor => 'nw');
$dc->createText( $x+50, $y+1, -text => $dir, -anchor => 'nw');
$y += $height;
}
$max = computeUnit($max);
#$allsize = computeUnit($allsize);
$label = "Ready! $dirCount folders, $fileCount files, (max folder size: $max)";
$dsw->waitWindow;
}
##############################################################
# setProperty
##############################################################
sub setProperty($$$) {
my $lb = shift;
my $prop = shift;
my $value = shift;
my @dirs = $lb->info('selection');
return unless checkSelection($dpw, 1, 0, \@dirs);
if ((!defined $value) or ($value < 0) or ($value > 1)) {
warn "wrong value $value";
return;
}
if ((!defined $prop) or (($prop ne 'SORT') and ($prop ne 'META') and ($prop ne 'PRIO') and ($prop ne 'ALL'))) {
warn "wrong property $prop";
return;
}
foreach my $dir (@dirs) {
# set property to given value
unless ($prop eq 'ALL') {
$dirProperties{$dir}{$prop} = $value;
}
else {
$dirProperties{$dir}{SORT} = $value;
$dirProperties{$dir}{META} = $value;
$dirProperties{$dir}{PRIO} = $value;
}
# show changed property
my $style = $iptcS;
$style = $exifS if (defined $dirProperties{$dir}{SORT} and
defined $dirProperties{$dir}{META} and
defined $dirProperties{$dir}{PRIO} and
$dirProperties{$dir}{SORT} == 1 and
$dirProperties{$dir}{META} == 1 and
$dirProperties{$dir}{PRIO} == 1);
$lb->itemConfigure($dir, $lb->{dircol}, -text => $dir, -style => $style);
$lb->itemConfigure($dir, $lb->{sortcol}, -text => $dirProperties{$dir}{SORT}, -style => $comS);
$lb->itemConfigure($dir, $lb->{metacol}, -text => $dirProperties{$dir}{META}, -style => $iptcS);
$lb->itemConfigure($dir, $lb->{priocol}, -text => $dirProperties{$dir}{PRIO}, -style => $comS);
$lb->itemConfigure($dir, $lb->{commcol}, -text => $dirProperties{$dir}{COMM}, -style => $iptcS);
}
}
##############################################################
# selectDirInTree
##############################################################
sub selectDirInTree {
my $dir = shift;
$dirtree->selectionClear();
if ($dirtree->info('exists', "/$dir")) {
$dirtree->selectionSet("/$dir");
$dirtree->show('entry', "/$dir");
}
elsif ($dirtree->info('exists', $dir)) {
$dirtree->selectionSet($dir);
$dirtree->show('entry', $dir);
}
}
##############################################################
# dirSave - save the last used dirs, build a hotlist of
# often used dirs and update the dir menu
##############################################################
sub dirSave {
my $dir = shift;
return if ($dir eq $trashdir);
# check if dir is already in history list
my $i = 0;
foreach (@dirHist) {
if ($_ eq $dir) {
splice @dirHist, $i, 1; # throw old entry away
last;
}
$i++;
}
# add dir to history list
push @dirHist, $dir;
# no more than 10 entries in history list
if (@dirHist > 10) {
shift @dirHist;
}
# count the number of accesses to each dir
if (defined $dirHotlist{$dir}) {
$dirHotlist{$dir}++;
}
else {
$dirHotlist{$dir} = 1;
}
updateDirMenu();
}
##############################################################
# clearLabels - clear the labels containing infos about the
# actual picture
##############################################################
sub clearLabels {
# show index number in window
$nrof = "0/0 (0)";
$widthheight = "";
$size = "";
$zoomFactorStr = "";
$urgencyStr = "";
$urgencyScale = 0;
}
##############################################################
# dirDialog - open a window and a dir tree
##############################################################
sub dirDialog {
my $dir = shift;
if ($EvilOS) {
if ($win32FOAvail) {
print "FileOp is available!\n" if $verbose;
# this is untested!!! todo
$dir = BrowseForFolder("Choose Directory", "CSIDL_DESKTOP");
$dir =~ s|\\|/|g; # perl likes the slashes like this
return $dir;
}
else { # windows, but no win32 FileOp available
print "FileOp is not available!\n" if $verbose;
# checkDialog('Select file instead of directory',
# 'There is no directory selector available, so please select a file instead of the directory.
#You may use any file, Mapivi will use the directory of that file.
#If the directory is empty, you may create a new file and select this.
#Sorry for that inconvenience!
#Example:
#To use the directory C:\pictures\2006\ select e.g. C:\pictures\2006\pic1.jpg',
# \$config{winDirRequesterAskAgain},
# "remind everytime",
# "",
# 'OK') if ($config{winDirRequesterAskAgain});
# my $file = $top->getOpenFile(); # little tricky here
# if ((defined $file) and (-f $file)) { # until there is no win directory dialog
# $dir = dirname($file); # we take a file and jump to the dir of that file
# } # but empty dirs are a problem!!!
# else {
# $dir = "";
# }
$dir = $top->chooseDirectory(-title => "Select directory", -initialdir => $dir);
$dir = "" unless (-d $dir);
return $dir;
}
} else { # non windows system
# code based on Tk::chooseDirectory
my $t = $top->Toplevel;
$t->withdraw;
$t->title('Open directory ...');
$t->iconimage($mapiviicon) if $mapiviicon;
my $ok = 0; # flag: "1" means OK, "0" means cancelled
# Create Frame widget before the DirTree widget, so it's always visible
# if the window gets resized.
my $f = $t->Frame->pack(-fill => 'x', -side => "bottom");
my $d;
my $mkdB = $t->Button(-text => 'Make new directory',
-command => sub { makeNewDir($dir, $d); })->pack(-fill => 'x');
$balloon->attach($mkdB, -msg => "The new directory will be created underneath the selected directory.\nSo, please select a directory in the tree first");
$d = $t->Scrolled('DirTree',
-scrollbars => 'osoe',
-showhidden => $config{ShowHiddenDirs},
-selectmode => 'browse',
-exportselection => 1,
-browsecmd => sub {
# this function will show all subdirs when pressing on the + sign
$dir = shift;
return if (@_ >= 1);
if (!-d $dir) { print "$dir does not exists!\n"; return; }
$t->Busy;
my @dirs = getDirs($dir);
$t->Unbusy;
return if (@dirs < 1);
$t->Busy;
my $lastdir = $dir."/".$dirs[-1];
if ($d->info("exists", "$lastdir")) {
$d->see($lastdir) if (-d $lastdir);
}
$t->Unbusy;
},
# With this version of -command a double-click will
# select the directory
-command => sub { $ok = 1; $t->destroy; },
# With this version of -command a double-click will
# open a directory. Selection is only possible with
# the Ok button.
#-command => sub { $d->opencmd($_[0]) },
)->pack(-fill => "both", -expand => 1);
# Set the initial directory
exists &Tk::DirTree::chdir ? $d->chdir($dir) : $d->set_dir($dir);
$f->Button(-text => 'Ok',
-command => sub { $ok = 1; $t->destroy; })->pack(-side => 'left',-fill => 'x', -expand => 1);
$f->Button(-text => 'Cancel',
-command => sub { $ok = 0; $t->destroy; })->pack(-side => 'left',-fill => 'x', -expand => 1);
# file and dir requester should always be big! (50% of screenwidth and 90% of screenheight)
my $w = int(0.5 * $t->screenwidth);
my $h = int(0.9 * $t->screenheight);
$t->geometry("${w}x${h}+0+0");
$t->deiconify;
$t->raise;
$f->waitWindow();
$t->destroy() if (Exists($t));
$dir = "" if ($ok != 1);
return $dir;
}
}
##############################################################
# printUsage - show the user how to use mapivi
##############################################################
sub printUsage {
print "\nUsage: mapivi [file|directory]\n\n";
}
##############################################################
# touch - set the modification date of the given file to the
# actual date and time
##############################################################
sub touch {
my $file = shift;
my $now = time;
utime($now, $now, $file);
}
##############################################################
# addComment - add a comment to all selected pics in the given
# listbox
##############################################################
sub addComment($) {
my $lb = shift; # the reference to the active listbox widget
my @sellist = $lb->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
my ($dpic, $i);
$userinfo = "adding comments to ".scalar @sellist." pictures"; $userInfoL->update;
# check if some files are links
return if (!checkLinks($lb, @sellist));
my $info = "Please enter comment to add to the ".scalar @sellist." selected pictures";
my $text = "";
my $thumb = "";
# if just one pic should be commented we show the thumbnail and the real name
if (@sellist == 1) {
$thumb = getThumbFileName($sellist[0]);
$info = "Please enter comment to add to ".basename($sellist[0]);
}
my $rc = myTextDialog("Add comment", $info, \$text, $thumb);
return if ($rc ne 'OK' or $text eq "");
# replace (german) umlaute by corresponding letters
# (a lot of programs seem to have problems with Umlauten in comments)
$text =~ s/([$umlaute])/$umlaute{$1}/g if ($config{ConvertUmlaut});
$config{Comment} = $text; # save changed comment to global config hash
my $pw = progressWinInit($lb, "Add comment");
$i = 0;
foreach $dpic (@sellist) {
last if progressWinCheck($pw);
$i++;
progressWinUpdate($pw, "adding comment ($i/".scalar @sellist.") ...", $i, scalar @sellist);
next if (!checkWriteable($dpic));
addCommentToPic($text, $dpic, TOUCH); # touch thumbnail
updateOneRow($dpic, $lb);
showImageInfo($dpic) if ($dpic eq $actpic);
}
progressWinEnd($pw);
$userinfo = "ready! ($i of ".scalar @sellist." commented)"; $userInfoL->update;
}
##############################################################
# grayscalePic
##############################################################
sub grayscalePic {
my $lb = shift; # the reference to the active listbox widget
# check if ImageMagick convert version is at least or bigger than 6
if ((`convert 2>&1` =~ m/.*ImageMagick (\d+)\.(\d+)\.(\d+).*/) and ($1 < 6)) {
$top->messageBox(-icon => 'warning', -message => "Sorry, but for these function you need at least ImageMagick (convert) in version 6.x.x. You have $1.$2.$3.\nPlease download at http://www.imagemagick.org.", -title => "Wrong ImageMagick version ($1.$2.$3)", -type => 'OK');
return;
}
#return if (!checkExternProgs("grayscalePic", "jpegtran"));
my @sellist = $lb->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
# check if some files are links
return if (!checkLinks($lb, @sellist));
my $rc = 0;
# open window
my $win = $top->Toplevel();
$win->title('Convert to B/W');
$win->iconimage($mapiviicon) if $mapiviicon;
my $topF = $win->Frame()->pack(-expand => 1, -fill =>'both', -padx => 5);
my $picF = $topF->Frame(-height => $config{FilterPrevSize}, -width => $config{FilterPrevSize})->pack(-side => 'left', -expand => 1, -fill =>'both');
my $presetF = $topF->Frame()->pack(-side => 'left', -expand => 1, -fill =>'both');
$win->{status} = $picF->Label(-textvariable => \$win->{label})->pack();
my $w = 18;
labeledScale($win, 'top', $w, "Red channel (%)", \$config{ChannelRed}, -100, 200, 1);
labeledScale($win, 'top', $w, "Green channel (%)", \$config{ChannelGreen}, -100, 200, 1);
labeledScale($win, 'top', $w, "Blue channel (%)", \$config{ChannelBlue}, -100, 200, 1);
my $original_pic = $sellist[0];
my $preview_start_pic = $trashdir.'/'.basename($original_pic).'-start';
my $preview_pic = $trashdir.'/'.basename($original_pic);
my $preview_photo;
$win->Button(-text => "update",
-command => sub {
$win->Busy;
$win->{label} = "preparing preview ...";
return if (!mycopy ($preview_start_pic, $preview_pic, OVERWRITE));
grayscalePicInt($preview_pic, PREVIEW);
$preview_photo = $win->Photo(-file => $preview_pic, -gamma => $config{Gamma});
$win->{photo}->configure(-image => $preview_photo);
$win->{label} = "preview finished";
$win->Unbusy;
})->pack();
$presetF->Label(-text => 'Presets')->pack();
my $preset =
$presetF->Scrolled('Listbox',
-scrollbars => 'osoe',
-selectmode => 'single',
-exportselection => 0,
-width => 20,
-height => 10,
)->pack(-expand => 1, -fill =>'both', -padx => 2, -pady => 2);
bindMouseWheel($preset->Subwidget("scrolled"));
# preset for channel mixer (hash of lists HoL; list is red, green , blue = RGB)
my %channel_mixer = (
'Filter Yellow' => [30, 70, 20],
'Filter Orange' => [78, 22, 0],
'Filter Red' => [75, 0, 25],
'Filter Red II' => [150,-25,-25],
'Filter Red 25a' => [200, 0,-100],
'Filter Green' => [20, 60, 40],
'Normal 1' => [30, 59, 11],
'Normal 2' => [80, 15, 5],
'Normal 3' => [70, 20, 10],
'Normal 4' => [80, 20,-20],
'Normal 5' => [65, 25, 10],
'Contrast High' => [40, 34, 60],
'Contrast Normal' => [43, 33, 30],
);
$preset->insert('end', (sort keys %channel_mixer));
$preset->bind('<Button-1>', sub {
my @sel = $preset->curselection();
my $key = $preset->get($sel[0]);
$config{ChannelRed} = @{$channel_mixer{$key}}[0];
$config{ChannelGreen} = @{$channel_mixer{$key}}[1];
$config{ChannelBlue} = @{$channel_mixer{$key}}[2];
$win->update();
$win->Busy;
$win->{label} = "preparing preview ...";
return if (!mycopy ($preview_start_pic, $preview_pic, OVERWRITE));
grayscalePicInt($preview_pic, PREVIEW);
$preview_photo = $win->Photo(-file => $preview_pic, -gamma => $config{Gamma});
$win->{photo}->configure(-image => $preview_photo);
$win->{label} = "preview finished";
$win->Unbusy;
} );
$win->Checkbutton(-variable => \$config{ChannelBright}, -text => "Keep brightness")->pack(-anchor=>'w', -padx => 5, -pady => 3);
my $decoF = $win->Frame()->pack(-fill =>'x', -padx => 5);
$decoF->Checkbutton(-variable => \$config{ChannelDeco},
-anchor => 'w',
-text => "Add border or text (not visible in preview)")->pack(-side => "left", -anchor => 'w', -fill => 'x', -expand => 1);
$decoF->Button(-text => "Options",
-anchor => 'w',
-command => sub {decorationDialog(scalar @sellist,0);})->pack(-side => "left", -anchor => 'w', -padx => 3);
buttonBackup($win, 'top');
my $qs = labeledScale($win, 'top', 18, "Quality (%)", \$config{PicQuality}, 10, 100, 1);
qualityBalloon($qs);
my $plural = 's'; $plural = '' if (@sellist == 1);
$win->Label(-text => "Convert ".scalar @sellist." selected picture$plural to grayscale (B/W) picture$plural.\nPress OK to continue.")->pack();
my $but_frame =
$win->Frame()->pack(-fill =>'x');
my $ok_but =
$but_frame->Button(-text => 'OK',
-command => sub {
$rc = 1;
$win->withdraw();
$win->destroy();
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 2, -pady => 3);
my $x_but =
$but_frame->Button(-text => 'Cancel',
-command => sub {
$win->withdraw();
$win->destroy();
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 2, -pady => 3);
$win->{label} = "preparing preview ...";
$win->Popup(-popover => 'cursor');
repositionWindow($win);
$win->Busy;
$win->update;
return if (!mycopy ($original_pic, $preview_start_pic, OVERWRITE));
return if (!resizePic($preview_start_pic, $config{FilterPrevSize}, $config{FilterPrevSize}, 80));
return if (!mycopy ($preview_start_pic, $preview_pic, OVERWRITE));
grayscalePicInt($preview_pic, PREVIEW);
$preview_photo = $win->Photo(-file => $preview_pic, -gamma => $config{Gamma});
$win->{photo} = $picF->Label(-image => $preview_photo, -relief => "sunken",
)->pack(-padx => 3, -pady => 3);
$win->{label} = "preview finished";
$win->Unbusy;
$win->waitWindow;
return unless ($rc);
$userinfo = "converting ".scalar @sellist." pictures to grayscale"; $userInfoL->update;
my $pw = progressWinInit($lb, "Convert to grayscale");
my $i = 0;
foreach my $dpic (@sellist) {
last if progressWinCheck($pw);
progressWinUpdate($pw, "converting ($i/".scalar @sellist.") this may take a while ...", $i, scalar @sellist);
next if (!checkWriteable($dpic));
next if (!makeBackup($dpic));
grayscalePicInt($dpic, NO_PREVIEW);
$i++;
progressWinUpdate($pw, "converting ($i/".scalar @sellist.") ...", $i, scalar @sellist);
updateOneRow($dpic, $lb);
showImageInfo($dpic) if ($dpic eq $actpic);
showPic($dpic) if ($dpic eq $actpic); # redisplay the picture if it is the actual one
}
progressWinEnd($pw);
reselect($lb, @sellist);
$userinfo = "ready! ($i of ".scalar @sellist." converted)"; $userInfoL->update;
generateThumbs(ASK, SHOW);
$preview_photo->delete if $preview_photo;
}
##############################################################
# grayscalePicInt
##############################################################
sub grayscalePicInt {
my $dpic = shift;
my $preview = shift;
my $sum = 100;
if ($config{ChannelBright}) {
$sum = $config{ChannelRed}+$config{ChannelGreen}+$config{ChannelBlue};
}
$sum = 1 if ($sum == 0); # avoid division by zero
my $command = "convert ";
$command .= " \"$dpic\" -fx \"(r*$config{ChannelRed}+g*$config{ChannelGreen}+b*$config{ChannelBlue})/$sum\" ";
# windows needs the " instead of '
#\'(r*$config{ChannelRed}+g*$config{ChannelGreen}+b*$config{ChannelBlue})/$sum\' ";
$command .= makeDrawOptions($dpic) if ($config{ChannelDeco} and !$preview);
$command .= " \"$dpic\" ";
print "grayscalePicInt: command: $command\n" if $verbose;
execute($command);
}
##############################################################
# updateOneRow - update the (changed) metainfo of one picture
# in the given listbox and store them in the
# search database
##############################################################
sub updateOneRow($$) {
my $dpic = shift; # pic with path
my $lb = shift; # the listbox reference
return unless (-f $dpic);
# check if listbox entry exists
unless ($lb->info('exists', $dpic)) {
warn "entry $dpic not found in listbox!";
return;
}
my $iptc = ''; my $exif = ''; my $com = ''; my $size = '';
my $meta = addToSearchDB($dpic); # save meta data of picture into the search data base
$com = $searchDB{$dpic}{COM};
$exif = $searchDB{$dpic}{EXIF};
$iptc = displayIPTC($dpic);
$size = getAllFileInfo($dpic);
$com = formatString($com, $config{LineLength}); # format the comment for the list
$iptc = formatString($iptc, $config{LineLength}); # format the IPTC info for the list
# update the metainfo in the listbox
$lb->itemConfigure($dpic, $lb->{thumbcol}, -text => getThumbCaption($dpic));
$lb->itemConfigure($dpic, $lb->{comcol}, -text => $com);
$lb->itemConfigure($dpic, $lb->{exifcol}, -text => $exif);
$lb->itemConfigure($dpic, $lb->{iptccol}, -text => $iptc);
$lb->itemConfigure($dpic, $lb->{filecol}, -text => $size) if (defined $lb->{filecol});
}
##############################################################
# addCommentToPic - add a comment to a single picture
##############################################################
sub addCommentToPic($$$) {
my $com = shift;
my $dpic = shift;
my $touch = shift; # TOUCH = touch thumbnail, NO_TOUCH
return if (!-f $dpic);
# check if file is a link and get the real target
return if (!getRealFile(\$dpic));
my $meta = getMetaData($dpic, "COM");
return unless ($meta);
printf "addCommentToPic: %-30s %s\n", cutString($com,30,".."), $dpic if $verbose;
#$com = encode("utf8", $com);
$meta->add_comment($com);
unless ($meta->save()) { warn "addCommentToPic: save $dpic failed!"; }
# touch the thumbnail pic (set actual time stamp), to suppress rebuilding the next time
touch(getThumbFileName($dpic)) if ($touch == TOUCH);
addToSearchDB($dpic);
}
##############################################################
# replaceComment - search/replace a string in a comment to all
# selected pics in the given listbox
##############################################################
sub replaceComment {
my $lb = shift; # the reference to the active listbox widget
my @sellist = $lb->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
my ($dpic, $dthumb, $i, $j, $pic, $meta, @com, $replace, $spat, $stextd, $rtextd);
$userinfo = "replacing comments in ".scalar @sellist." pictures"; $userInfoL->update;
# check if some files are links
return if (!checkLinks($lb, @sellist));
my $info = "Please enter the string to replace in the ".scalar @sellist." selected pictures";
my $stext = $config{SearchPattern}; # search string
my $rtext = ''; # replace string
# if just one pic should be commented we show the real name
if (@sellist == 1) {
$info = "Please enter the string to replace in ".basename($sellist[0]);
}
my $test = 1;
while ($test) {
# todo: one search/replace dialog with upper/lower case support
my $rc = myReplaceDialog("Replace comment", $info, \$stext, \$rtext);
return if (($rc eq 'Cancel') or ($stext eq ''));
$test = 0 if ($rc eq 'OK');
$config{SearchPattern} = $stext;
# replace (german) umlaute by corresponding letters
# (a lot of programs seem to have problems with Umlauten in comments)
$stext =~ s/([$umlaute])/$umlaute{$1}/g if ($config{ConvertUmlaut});
$rtext =~ s/([$umlaute])/$umlaute{$1}/g if ($config{ConvertUmlaut});
$spat = makePattern($stext);
$config{Comment} = $rtext; # save changed comment to global config hash
my $nocom = "";
my $nostr = "";
my $countComments = 0;
my $countFiles = 0;
my $pw = progressWinInit($lb, "Replace comments");
$i = 0;
foreach $dpic (@sellist) {
last if progressWinCheck($pw);
$i++;
progressWinUpdate($pw, "replacing comments ($i/".scalar @sellist.") ...", $i, scalar @sellist);
$pic = basename($dpic);
print "replaceComment: pic:$pic\n" if $verbose;
$dthumb = getThumbFileName($dpic);
next if (!checkWriteable($dpic));
$meta = getMetaData($dpic, "COM");
unless ($meta) {
$nocom .= "$dpic\n";
next;
}
@com = getComments($dpic, $meta); # get all comments from the file
unless (@com) {
$nocom .= "$dpic\n";
next;
}
$replace = 0;
for $j (0 .. $#com) {
if ($com[$j] =~ m/$spat/) { # todo handle lower/uppercase
unless ($test) {
print "replacing $stext with $rtext in $pic: -$com[$j]- " if $verbose;
$com[$j] =~ s/$spat/$rtext/g;
print "to -$com[$j]-\n" if $verbose;
$meta->set_comment($j, $com[$j]);
}
$replace++;
$countComments++;
}
}
if ($replace > 0) {
unless ($test) {
unless ($meta->save()) {
warn "replaceComment: save $pic failed!";
}
# touch the thumbnail pic (set actual time stamp), to suppress rebuilding the next time
touch($dthumb);
updateOneRow($dpic, $lb);
}
$countFiles++;
} else {
$nostr .= "$dpic\n";
}
}
progressWinEnd($pw);
# short the strings for better output
$stextd = cutString($stext, 20, "..");
$rtextd = cutString($rtext, 20, "..");
my $text = "Replaced ";
$text = "Test mode:\nMapivi would replace " if $test;
$text .= "the string \"$stextd\" with \"$rtextd\"\nin $countComments comments of $countFiles pictures\n\n";
if (($nocom ne "") or ($nostr ne "")) {
$text .= "Found no comments in these pictures:\n$nocom\n" if ($nocom ne "");
$text .= "Found no string matching \"$stextd\" in these pictures:\n$nostr\n" if ($nostr ne "");
}
showText("Replace comment log", $text, WAIT);
}
$userinfo = "ready! ($i of ".scalar @sellist." pictures processed)"; $userInfoL->update;
}
##############################################################
# nameToComment - add the filename as comment to all selected
# pictures
##############################################################
sub nameToComment {
my @sellist = $picLB->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
my $selected = @sellist;
my ($pic, $dpic, $dirthumb, $i, $com);
my $dia = $top->DialogBox(-title => "Add filename to comment",
-buttons => ['OK', 'Cancel']);
$dia->add("Label", -text => "This function will add a comment containing\nthe individual filename of $selected pictures!", -bg => $config{ColorBG}, -justify => "left")->pack;
$dia->add("Checkbutton", -text => "Remove suffix (.jpg)", -variable => \$config{NameComRmSuffix})->pack;
my $rc = $dia->Show();
$top->focusForce;
return if ($rc ne 'OK');
$userinfo = "adding filename as comment of $selected pictures"; $userInfoL->update;
# check if some files are links
return if (!checkLinks($picLB, @sellist));
my $pw = progressWinInit($top, "Adding file name as comment");
$i = 0;
foreach $dpic (@sellist) {
last if progressWinCheck($pw);
$i++;
progressWinUpdate($pw, "Adding file name ($i/$selected) ...", $i, $selected);
$pic = basename($dpic);
$dirthumb = getThumbFileName($dpic);
$com = $pic;
next if (!checkWriteable($dpic));
if (($config{NameComRmSuffix}) and ($pic =~ /(.*)(\.jp(g|eg))/i)) {
$com = $1; # remove .jp(e)g suffix
}
# check if file is a link and get the real target
next if (!getRealFile(\$dpic));
my $meta = getMetaData($dpic, "COM");
next unless ($meta);
$meta->add_comment($com);
unless ($meta->save()) { warn "nameToComment: save $pic failed!"; }
# touch the thumbnail pic (set actual time stamp), to suppress rebuilding the next time
touch($dirthumb);
updateOneRow($dpic, $picLB);
showImageInfo($dpic) if ($dpic eq $actpic);
}
progressWinEnd($pw);
$userinfo = "ready! ($i of $selected processed)"; $userInfoL->update;
}
##############################################################
# showComment - show the comment of all selected pictures
##############################################################
sub showComment {
my @sellist = $picLB->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
return unless askSelection(\@sellist, 10, "comment");
my $selected = @sellist;
my $nocomment = "";
my ($pic, $dpic, $i, $plural, $thumb);
$userinfo = "displaying JPEG comments of $selected pictures"; $userInfoL->update;
my $pw = progressWinInit($top, "Display comments");
$i = 0;
foreach $dpic (@sellist) {
last if progressWinCheck($pw);
$i++;
progressWinUpdate($pw, "displaying comment ($i/$selected) ...", $i, $selected);
$pic = basename($dpic);
$thumb = getThumbFileName($dpic);
# check if file is a link and get the real target
next if (!getRealFile(\$dpic));
my @comments = getComments($dpic);
my $comment = "";
foreach (@comments) {
$comment .= "$_\n";
}
(@comments > 1) ? ($plural = "s") : ($plural = "");
if ($comment ne "") {
showText("$pic contains ".scalar @comments." comment$plural", $comment, NO_WAIT, $thumb);
}
else {
$nocomment .= "$pic\n";
}
}
progressWinEnd($pw);
if ($nocomment ne "") {
showText("no comments", "no comments in:\n$nocomment", NO_WAIT);
}
$userinfo = "ready! ($i of $selected displayed)"; $userInfoL->update;
}
##############################################################
# addDecoration
##############################################################
sub addDecoration {
return if (!checkExternProgs("addDecoration", "mogrify"));
my $index = shift;
my @sellist;
if ((defined $index) and ($index >= 0) and ($index < $picLB->info('children'))) {
push @sellist, $index;
}
else {
@sellist = $picLB->info('selection');
}
my $selected = @sellist;
my ($dpic, $i, $command);
return unless checkSelection($top, 1, 0, \@sellist);
$userinfo = "adding decorations to $selected pictures"; $userInfoL->update;
# check if some files are links
return if (!checkLinks($picLB, @sellist));
return if (!decorationDialog($selected,1));
my $pw = progressWinInit($top, "Adding decoration");
$i = 0;
foreach $dpic (@sellist) {
last if progressWinCheck($pw);
$i++;
progressWinUpdate($pw, "adding decorations ($i/$selected) ...", $i, $selected);
# check if file is a link and get the real target
next if (!getRealFile(\$dpic));
next if (!checkWriteable($dpic));
next if (!makeBackup($dpic));
$command = "mogrify ".makeDrawOptions($dpic)."-quality ".$config{PicQuality}." \"$dpic\"";
execute($command);
addDropShadow($dpic);
deleteCachedPics($dpic);
showPic($dpic) if ($dpic eq $actpic); # redisplay the picture if it is the actual one
updateOneRow($dpic, $picLB);
}
progressWinEnd($pw);
reselect($picLB, @sellist);
$userinfo = "ready! ($i of $selected)"; $userInfoL->update;
generateThumbs(ASK, SHOW);
}
##############################################################
# addDropShadow - to be called after makeDrawOptions and
# mogrify
# operates on the pic directly
# a backup has to be made before
##############################################################
sub addDropShadow {
my $dpic = shift;
return unless (-f $dpic);
return unless ($config{DropShadow});
my $b4 = $config{DropShadowWidth} * 4;
my $b3 = $config{DropShadowWidth} * 3;
my $command = "convert -depth 8 -colors 1 -gamma 0 \"$dpic\" -bordercolor \"".$config{DropShadowBGColor}."\" -border ${b4}x${b4} -gaussian 0x".$config{DropShadowBlur}." -shave ${b3}x${b3} - | composite -quality ".$config{PicQuality}." -gravity northwest \"$dpic\" - \"$dpic\"";
#(system "$command") == 0 or warn "$command failed: $!";
print "addDropShadow: $command\n" if $verbose;
execute($command);
}
##############################################################
# makeDrawOptions
##############################################################
sub makeDrawOptions {
my $dpic = shift;
my $command = "";
my $x = $config{CopyX};
my $y = $config{CopyY};
if ($config{BorderAdd}) {
$command .= '-bordercolor "'.$config{BorderColor1}.'" -border '.$config{BorderWidth1x}.'x'.$config{BorderWidth1y}.' ';
$command .= '-bordercolor "'.$config{BorderColor2}.'" -border '.$config{BorderWidth2x}.'x'.$config{BorderWidth2y}.' ' if (($config{BorderWidth2x} > 0) or ($config{BorderWidth2y} > 0));
$command .= '-bordercolor "'.$config{BorderColor3}.'" -border '.$config{BorderWidth3x}.'x'.$config{BorderWidth3y}.' ' if (($config{BorderWidth3x} > 0) or ($config{BorderWidth3y} > 0));
$command .= '-bordercolor "'.$config{BorderColor4}.'" -border '.$config{BorderWidth4x}.'x'.$config{BorderWidth4y}.' ' if (($config{BorderWidth4x} > 0) or ($config{BorderWidth4y} > 0));
}
if ($config{CopyAdd}) {
if ($config{CopyTextOrLogo} eq "text") { # text
$command .= "-gravity $config{CopyPosition} ";
my $geo1 = ($x+1).",".($y+1);
my $geo2 = "$x,$y";
print "drawoptions: x = $x y = $y geo1 = $geo1 geo2 = $geo2\n" if $verbose;
$command .= "-font '-*-".$config{CopyFontFamily}."-medium-r-*-*-".$config{CopyFontSize}."-*-*-*-*-*-iso8859-*' ";
$command .= "-fill \"".$config{CopyFontColBG}."\" -draw 'text $geo1 \"".$config{Copyright}."\"' " if $config{CopyFontShadow};
$command .= "-fill \"".$config{CopyFontColFG}."\" -draw 'text $geo2 \"".$config{Copyright}."\"' ";
}
else { # logo image
my ($lw, $lh) = getSize($config{CopyrightLogo});
my ($pw, $ph) = getSize($dpic);
if ($config{BorderAdd}) { # calc new size of pic (including borders)
$pw += 2 * $config{BorderWidth1x};
$pw += 2 * $config{BorderWidth2x};
$pw += 2 * $config{BorderWidth3x};
$ph += 2 * $config{BorderWidth1y};
$ph += 2 * $config{BorderWidth2y};
$ph += 2 * $config{BorderWidth3y};
}
if ($config{CopyPosition} eq 'NorthEast') {
$x = $pw - $lw - $x;
} elsif ($config{CopyPosition} eq 'North') {
$x = $pw/2 - $lw/2 - $x;
} elsif ($config{CopyPosition} eq 'SouthWest') {
$y = $ph - $lh - $y;
} elsif ($config{CopyPosition} eq 'South') {
$y = $ph - $lh - $y;
$x = $pw/2 - $lw/2 - $x;
} elsif ($config{CopyPosition} eq 'SouthEast') {
$y = $ph - $lh - $y;
$x = $pw - $lw - $x;
}
$x = int($x); $y = int($y);
my $geo = "$x,$y";
$command .= "-draw \"image Over $geo $lw,$lh '".$config{CopyrightLogo}."'\" ";
}
}
print "command == $command\n" if $verbose;
return $command;
}
##############################################################
# buildBackupName
##############################################################
sub buildBackupName($) {
my $bpic = shift;
$bpic =~ s/(.*)\.(.*)/$1-bak.$2/i;
return $bpic;
}
##############################################################
# getBasenameSuffix
##############################################################
sub getBasenameSuffix {
my $suffix;
my $base;
my $file = shift;
my @parts = split /\./, $file;
if (@parts > 1) {
$suffix = $parts[-1];
$base = substr($file, 0, length($file)-length($suffix)-1);
}
else {
$suffix = '';
$base = $file;
}
return ($base, $suffix);
}
##############################################################
# makeBackup
##############################################################
sub makeBackup($) {
my $dpic = shift;
return 0 if (!-f $dpic);
return 1 if (!$config{MakeBackup});
my $dir = dirname($dpic);
my $dthumb = getThumbFileName($dpic);
my $bpic = buildBackupName($dpic);
# make a backup file
if (!mycopy("$dpic", "$bpic", ASK_OVERWRITE)) {
my $rc =
$top->messageBox(-icon => 'question', -message => "Proceed anyway?",
-title => "Proceed?", -type => 'OKCancel');
if ($rc =~ m/Ok/i) {
return 1;
}
else {
return 0;
}
}
# copy the thumbnail too
mycopy($dthumb, getThumbFileName($bpic), OVERWRITE);
if (!-f $bpic) {
warn "backup failed, there is no $bpic, giving up ...";
return 0;
}
else {
# copy meta info in search database (needed e.g. for nr. of views)
$searchDB{$bpic} = $searchDB{$dpic};
# insert backup in listbox
addOneRow($picLB, $bpic, 1, $dpic);
}
return 1;
}
my $decoW;
##############################################################
# decorationDialog
##############################################################
sub decorationDialog {
if (Exists($decoW)) {
$decoW->deiconify;
$decoW->raise;
return;
}
my $pics = shift;
my $QandB = shift; # bool - show Quality-Scale and Backup-Checkbutton
my $rc = 0;
my $max = 1000;
my @fontFamilies = sort $top->fontFamilies;
# open window
$decoW = $top->Toplevel();
$decoW->title('Add border/copyright/shadow');
$decoW->iconimage($mapiviicon) if $mapiviicon;
my $addF = $decoW->Frame(-bd => $config{Borderwidth}, -relief => 'groove')->pack(-anchor => 'w', -fill => 'x', -padx => 5, -pady => 3);
$addF->Label(-text => "Process $pics pictures", -bg => $config{ColorBG})->pack(-side => 'left', -anchor => 'w', -fill => 'x', -padx => 5, -pady => 3);
$addF->Label(-text => "Add ", -bg => $config{ColorBG})->pack(-side => 'left', -anchor => 'w');
$addF->Checkbutton(-text => "border ", -variable => \$config{BorderAdd})->pack(-side => 'left', -anchor => 'w');
$addF->Checkbutton(-text => "copyright info ", -variable => \$config{CopyAdd})->pack(-side => 'left', -anchor => 'w');
$addF->Checkbutton(-text => "drop shadow", -variable => \$config{DropShadow})->pack(-side => 'left', -anchor => 'w');
my $notebook =
$decoW->NoteBook(#-width => 500,
-background => $config{ColorBG}, # background of active page (including its tab)
-inactivebackground => $config{ColorEntry}, # tabs of inactive pages
-backpagecolor => $config{ColorBG}, # background behind notebook
)->pack(-expand => "yes",
-fill => "both",
-padx => 5, -pady => 5);
my $cF = $notebook->add("border", -label => "Border");
my $bF = $notebook->add("copy", -label => "Copyright");
my $dF = $notebook->add("shadow", -label => "Drop shadow");
if ($QandB) {
my $qS = labeledScale($decoW, 'top', 19, "Quality (%)", \$config{PicQuality}, 10, 100, 1);
qualityBalloon($qS);
buttonBackup($decoW, 'top');
buttonComment($decoW, 'top');
}
# ### copyright ###
my $pfa = $bF->Frame()->pack(-anchor => 'w');
$pfa->Label(-text => "Position in picture", -bg => $config{ColorBG})->pack(-side => "left", -anchor => 'w', -padx => 3);
my $pf = $pfa->Frame(-bd => $config{Borderwidth}, -relief => 'groove')->pack(-side => "left");
my $pfn = $pf->Frame()->pack();
my $pfs = $pf->Frame()->pack();
foreach my $gravity qw(NorthWest North NorthEast) {
my $but = $pfn->Radiobutton(-text => "", -variable => \$config{CopyPosition}, -value => $gravity)->pack(-side => 'left');
$balloon->attach($but, -msg => "Align the copyright text or logo in $gravity position");
}
foreach my $gravity qw(SouthWest South SouthEast) {
my $but = $pfs->Radiobutton(-text => "", -variable => \$config{CopyPosition}, -value => $gravity)->pack(-side => 'left');
$balloon->attach($but, -msg => "Align the copyright text or logo in $gravity position");
}
labeledScale($bF, 'top', 17, "x offset", \$config{CopyX}, 0, $max, 1);
labeledScale($bF, 'top', 17, "y offset", \$config{CopyY}, 0, $max, 1);
my $ctF = $bF->Frame(-bd => $config{Borderwidth}, -relief => 'groove')->pack(-anchor => 'w', -fill => 'x',-padx => 5, -pady => 5);
my $clF = $bF->Frame(-bd => $config{Borderwidth}, -relief => 'groove')->pack(-anchor => 'w', -fill => 'x', -padx => 5, -pady => 5);
$ctF->Radiobutton(-text => "add copyright text", -variable => \$config{CopyTextOrLogo}, -value => "text")->pack(-anchor => 'w');
labeledEntry($ctF, 'top', 17, "Copyright text", \$config{Copyright});
my $fontF = $ctF->Frame(-bd => 0)->pack(-anchor => 'w', -padx => 5, -pady => 3);
my $fontF2 = $ctF->Scrolled('Pane', -bd => $config{Borderwidth}, -relief => 'groove', -scrollbars => 'osoe', -height => 80, -width => 480)->pack(-anchor => 'w', -padx => 5, -pady => 3);
$fontF->Label(-text => "Font family", -bg => $config{ColorBG})->pack(-side => "left");
my $fontL = $fontF2->Label(-textvariable => \$config{Copyright}, -bg => $config{ColorBG})->pack(-side => "left");
$fontF->Optionmenu(-textvariable => \$config{CopyFontFamily},
-options => \@fontFamilies,
-command => sub {
$decoW->Busy;
my $font = $top->Font(-family => $config{CopyFontFamily},
-size => $config{CopyFontSize});
$fontL->configure(-font => $font) if (ref($font) eq 'HASH');
$fontL->update();
$decoW->Unbusy;
})->pack(-side => "left", -anchor => 'w');
$fontF->Label(-text => "Font size", -bg => $config{ColorBG})->pack(-side => "left");
$fontF->Scale(
-variable => \$config{CopyFontSize},
-from => 5,
-to => 200,
-resolution => 1,
-sliderlength => 30,
-orient => 'horizontal',
-showvalue => 0,
-width => 15,
-bd => $config{Borderwidth},
-command => sub {
$decoW->Busy;
my $font = $top->Font(-family => $config{CopyFontFamily},
-size => $config{CopyFontSize});
$fontL->configure(-font => $font);
$fontL->update();
$decoW->Unbusy;
})->pack(-side => "left", -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$fontF->Label(-textvariable => \$config{CopyFontSize})->pack(-side => "left");
labeledEntryColor($ctF, 'top', 17, "Foreground color", 'Set', \$config{CopyFontColFG});
$ctF->Checkbutton(-variable => \$config{CopyFontShadow},
-anchor => 'w',
-text => "Add a shadow to the copyright text"
)->pack(-anchor => 'w', -padx => 5, -pady => 3);
labeledEntryColor($ctF, 'top', 17, "Shadow color", 'Set', \$config{CopyFontColBG});
$clF->Radiobutton(-text => "add copyright logo (image)", -variable => \$config{CopyTextOrLogo}, -value => "logo")->pack(-anchor => 'w');
labeledEntryButton($clF,'top',17,"path/name of logo",'Set',\$config{CopyrightLogo});
# ### border ###
$cF->Label(-text => "Add one or several borders around pictures", -bg => $config{ColorBG})->pack(-anchor => 'w', -padx => 3);
my $wi = 25;
my $bF1 = $cF->Frame(-bd => $config{Borderwidth}, -relief => 'groove')->pack(-fill => 'x', -padx => 3, -pady => 3);
$bF1->Label(-text => "Border 1 - innermost border", -bg => $config{ColorBG})->pack(-anchor => 'w', -padx => 3);
labeledScale($bF1, 'top', $wi, "Border width x-direction", \$config{BorderWidth1x}, 0, $max, 1);
labeledScale($bF1, 'top', $wi, "Border width y-direction", \$config{BorderWidth1y}, 0, $max, 1);
labeledEntryColor($bF1, 'top', $wi, "Color", 'Set', \$config{BorderColor1});
my $bF2 = $cF->Frame(-bd => $config{Borderwidth}, -relief => 'groove')->pack(-fill => 'x', -padx => 3, -pady => 3);
$bF2->Label(-text => "Border 2 - border around border 1 (use width 0 to disable)", -bg => $config{ColorBG})->pack(-anchor => 'w', -padx => 3);
labeledScale($bF2, 'top', $wi, "Border width x-direction", \$config{BorderWidth2x}, 0, $max, 1);
labeledScale($bF2, 'top', $wi, "Border width y-direction", \$config{BorderWidth2y}, 0, $max, 1);
labeledEntryColor($bF2, 'top', $wi, "Color", 'Set', \$config{BorderColor2});
my $bF3 = $cF->Frame(-bd => $config{Borderwidth}, -relief => 'groove')->pack(-fill => 'x', -padx => 3, -pady => 3);
$bF3->Label(-text => "Border 3 - border around border 2 (use width 0 to disable)", -bg => $config{ColorBG})->pack(-anchor => 'w', -padx => 3);
labeledScale($bF3, 'top', $wi, "Border width x-direction", \$config{BorderWidth3x}, 0, $max, 1);
labeledScale($bF3, 'top', $wi, "Border width y-direction", \$config{BorderWidth3y}, 0, $max, 1);
labeledEntryColor($bF3, 'top', $wi, "Color", 'Set', \$config{BorderColor3});
my $bF4 = $cF->Frame(-bd => $config{Borderwidth}, -relief => 'groove')->pack(-fill => 'x', -padx => 3, -pady => 3);
$bF4->Label(-text => "Border 4 - border around border 3 (use width 0 to disable)", -bg => $config{ColorBG})->pack(-anchor => 'w', -padx => 3);
labeledScale($bF4, 'top', $wi, "Border width x-direction", \$config{BorderWidth4x}, 0, $max, 1);
labeledScale($bF4, 'top', $wi, "Border width y-direction", \$config{BorderWidth4y}, 0, $max, 1);
labeledEntryColor($bF4, 'top', $wi, "Color", 'Set', \$config{BorderColor4});
# ### drop shadow ###
$dF->Label(-text => "Add a drop shadow to the pictures", -bg => $config{ColorBG})->pack(-anchor => 'w', -padx => 3);
$dF->Label(-text => "(conversion may take some time)", -bg => $config{ColorBG})->pack(-anchor => 'w', -padx => 3);
labeledScale($dF, 'top', 17, "Border width", \$config{DropShadowWidth}, 1, $max, 1);
labeledScale($dF, 'top', 17, "Shadow blur", \$config{DropShadowBlur}, 1, 9, 1);
labeledEntryColor($dF, 'top', 17, "Background color", 'Set', \$config{DropShadowBGColor});
my $ButF =
$decoW->Frame()->pack(-fill =>'x', -padx => 3, -pady => 3);
my $OKB =
$ButF->Button(-text => 'OK',
-command => sub {
$decoW->withdraw();
$decoW->destroy();
$rc = 1;
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
my $Xbut = $ButF->Button(-text => 'Cancel',
-command => sub { $rc = 0;
$decoW->withdraw();
$decoW->destroy();
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$decoW->bind('<Key-q>', sub { $Xbut->invoke; });
$decoW->bind('<Key-Escape>', sub { $Xbut->invoke; });
$decoW->Popup;
$decoW->waitWindow;
return $rc;
}
my $colw;
##############################################################
# colorDialog
##############################################################
sub colorDialog {
if (Exists($colw)) {
$colw->deiconify;
$colw->raise;
return;
}
my $rc = 0;
# open window
$colw = $top->Toplevel();
$colw->title('Color options');
$colw->iconimage($mapiviicon) if $mapiviicon;
foreach (qw(Brightness Saturation Hue)) {
labeledScale($colw, 'top', 16, "$_ (%)", \$config{"Pic$_"}, 0, 200, 1);
}
labeledScale($colw, 'top', 16, "Gamma", \$config{PicGamma}, 0.1, 10.0, 0.01);
$colw->Button(-text => "Reset",
-command => sub {
foreach (qw(Brightness Saturation Hue)) {
$config{"Pic$_"} = 100;
}
$config{PicGamma} = 1.00;
})->pack(-anchor => 'w', -padx => 3, -pady => 3);
my $OKB =
$colw->Button(-text => "Close",
-command => sub { $rc = 1; $colw->destroy; })->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$colw->bind('<Key-q>', sub { $OKB->invoke; });
$colw->bind('<Key-Escape>', sub { $OKB->invoke; });
$colw->Popup;
$colw->waitWindow;
}
my $uw;
##############################################################
# unsharpDialog
##############################################################
sub unsharpDialog {
if (Exists($uw)) {
$uw->deiconify;
$uw->raise;
return;
}
my $rc = 0;
# open window
$uw = $top->Toplevel();
$uw->title('Unsharp mask options');
$uw->iconimage($mapiviicon) if $mapiviicon;
my $usr =labeledScale($uw, 'top', 16, "Radius (pixel)", \$config{UnsharpRadius}, 0, 10, 1);
$balloon->attach($usr, -msg => "The radius of the Gaussian, in pixels,
not counting the center pixel.
Use a radius of 0 and the function selects a suitable radius
for you (default 0)");
my $uss = labeledScale($uw, 'top', 16, "Sigma (pixel)", \$config{UnsharpSigma}, 0.1, 10, 0.1);
$balloon->attach($uss, -msg => "The standard deviation of the Gaussian,\nin pixels (default 1.0)");
my $usa = labeledScale($uw, 'top', 16, "amount (%)", \$config{UnsharpAmount}, 0, 100, 0.1);
$balloon->attach($usa, -msg => "The percentage of the difference between the original\nand the blur image that is added back into the original\n(default 1.0)");
my $ust = labeledScale($uw, 'top', 16, "Threshold (frac)", \$config{UnsharpThreshold}, 0, 10, 0.01);
$balloon->attach($ust, -msg => "The threshold, as a fraction of MaxRGB,\nneeded to apply the difference amount\n(default 0.05)");
$uw->Button(-text => "Default",
-command => sub {
$config{UnsharpRadius} = 0;
$config{UnsharpSigma} = 1.0;
$config{UnsharpAmount} = 1.0;
$config{UnsharpThreshold} = 0.05;
})->pack(-anchor => 'w', -padx => 3, -pady => 3);
my $OKB =
$uw->Button(-text => "Close",
-command => sub { $rc = 1; $uw->destroy; })->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$uw->bind('<Key-q>', sub { $OKB->invoke; });
$uw->bind('<Key-Escape>', sub { $OKB->invoke; });
$uw->Popup;
$uw->waitWindow;
}
my $lw;
##############################################################
# levelDialog
##############################################################
sub levelDialog {
if (Exists($lw)) {
$lw->deiconify;
$lw->raise;
return;
}
my $rc = 0;
# open window
$lw = $top->Toplevel();
$lw->title('Levels');
$lw->iconimage($mapiviicon) if $mapiviicon;
my $lws = labeledScale($lw, 'top', 18, "White point (%)", \$config{LevelWhite}, 0, 100, 1);
$balloon->attach($lws, -msg => "White point specifies the lightest color in the image.
Colors brighter than the white point are set to the maximum quantum value.");
my $lms = labeledScale($lw, 'top', 18, "Mid point (gamma)", \$config{LevelGamma}, 0.1, 10.0, 0.1);
$balloon->attach($lms, -msg => "Mid point specifies a gamma correction to apply to the image.");
my $lbs = labeledScale($lw, 'top', 18, "Black point (%)", \$config{LevelBlack}, 0, 100, 1);
$balloon->attach($lbs, -msg => "The black point specifies the darkest color in the image.
Colors darker than the black point are set to zero.");
$lw->Button(-text => "Reset",
-command => sub {
$config{LevelWhite} = 100;
$config{LevelGamma} = 1.0;
$config{LevelBlack} = 0;
})->pack(-anchor => 'w', -padx => 3, -pady => 3);
my $OKB =
$lw->Button(-text => "Close",
-command => sub { $rc = 1; $lw->destroy; })->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$lw->bind('<Key-q>', sub { $OKB->invoke; });
$lw->bind('<Key-Escape>', sub { $OKB->invoke; });
$lw->Popup;
$lw->waitWindow();
}
##############################################################
# editIPTC - edit IPTC info of one or multiple pictures
##############################################################
sub editIPTC($) {
my $lb = shift;
my @sellist = $lb->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
my ($pic, $dpic, $dirthumb, @in, @out, %saw);
# check if some files are links
return if (!checkLinks($lb, @sellist));
$dpic = $sellist[0];
$pic = basename($dpic);
my %iptcmh;
my $iptcm = \%iptcmh; # $iptcm = IPTC master, must be a hash reference
if (@sellist == 1) {
# if we edit just one file, we use the IPTC info as master (no matter if it's empty)
my $meta = getMetaData($dpic, 'APP13');
unless ($meta) {
warn "no APP13 in $dpic";
return;
}
if (defined $meta->get_app13_data('TEXTUAL', 'IPTC')) {
$iptcm = $meta->get_app13_data('TEXTUAL', 'IPTC');
}
}
my $rc = iptcDialog($iptcm, $pic, scalar @sellist);
return if ($rc ne 'OK');
my $IPTC_action = $config{IPTC_action};
$IPTC_action = 'REPLACE' if (@sellist == 1);
my $errors = "";
my $i = 0;
my $pw = progressWinInit($lb, "Writing IPTC info");
foreach $dpic (@sellist) {
last if progressWinCheck($pw);
$i++;
progressWinUpdate($pw, "Writing IPTC info ($i/".scalar @sellist.") ...", $i, scalar @sellist);
$pic = basename($dpic);
$dirthumb = getThumbFileName($dpic);
# check if file is a link and get the real target
next if (!getRealFile(\$dpic));
next if (!checkWriteable($dpic));
my $meta = getMetaData($dpic, 'APP1'); # APP1 includes EXIF and IPTC (APP13)
my $er = $meta->get_Exif_data('ALL', 'TEXTUAL');
my $iptc = $iptcm;
if (($config{IPTCdateEXIF}) or ($config{IPTCtimeEXIF})) {
my $date = getEXIFDate($dpic, $er); # date format YYYY:MM:DD HH:mm:SS
if (my ($y, $M, $d, $h, $m, $s) = $date =~ m/(\d\d\d\d):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)/) {
my $time = timelocal($s,$m,$h,$d,($M-1),($y-1900));
my $diff = ((localtime($time))[2] - (gmtime($time))[2]);
my $GMToffset = sprintf("%+03d00", $diff);
my $IPTCdate = $y.$M.$d;
my $IPTCtime = $h.$m.$s.$GMToffset;
# according to IPTC - NAA INFORMATION INTERCHANGE MODEL, Version No. 4, 1999, http://www.iptc.org/IIM/
${$iptc->{DateCreated}}[0] = $IPTCdate if ($config{IPTCdateEXIF}); # format CCYYMMDD
${$iptc->{TimeCreated}}[0] = $IPTCtime if ($config{IPTCtimeEXIF}); # format HHMMSS+HHMM
}
else {
warn "picture has an unusual EXIF date: \"$date\" ($dpic)\n" if $config{MetadataWarn};
}
}
if ($config{IPTCbylineEXIF}) {
if (defined $er) {
my $owner = '';
if (defined $er->{SUBIFD_DATA}->{OwnerName}) {
$owner = join('', @{$er->{SUBIFD_DATA}->{OwnerName}});
}
elsif (defined $er->{IFD0_DATA}->{Artist}) {
$owner = join('', @{$er->{IFD0_DATA}->{Artist}});
}
elsif (defined $er->{SUBIFD_DATA}->{UserComment}) {
$owner = join('', @{$er->{SUBIFD_DATA}->{UserComment}});
}
else { }
if ($owner ne '') {
$owner =~ tr/\n -~//cd; # remove non-printable characters (but not \n)
$owner =~ s/\r//g; # cut \r (carriage return)
$owner =~ s/\n//g; # cut \n (newline)
$owner =~ s/ASCII//g; # cut 'ASCII'
$owner =~ s/^\s+//; # cut leading white
$owner =~ s/\s+$//; # cut trailing white
print "*** Writing \"$owner\" to $dpic\n" if $verbose;
${$iptc->{ByLine}}[0] = $owner;
}
}
}
if ($config{IPTCaddMapivi}) {
${$iptc->{OriginatingProgram}}[0] = 'Mapivi';
${$iptc->{ProgramVersion}}[0] = $version;
}
$meta->set_app13_data($iptc, $IPTC_action, 'IPTC');
uniqueIPTC($meta);
unless ($meta->save()) { $errors .= "save failed for $dpic\n"; }
# touch the thumbnail pic (set actual time stamp), to suppress rebuilding
touch($dirthumb);
updateOneRow($dpic, $lb);
showImageInfoCanvas($dpic) if ($dpic eq $actpic);
}
progressWinEnd($pw);
$userinfo = "ready! ($i/".scalar @sellist." written)"; $userInfoL->update;
showText("Errors while editing IPTC info", $errors, NO_WAIT) if ($errors ne "");
}
##############################################################
# setIPTCurgency - set the urgency flag to a given value (0 .. 8)
##############################################################
sub setIPTCurgency {
my $lb = shift; # the reference to the active listbox widget
my $urgency = shift;
return unless (defined($urgency));
return if (($urgency < 0) or ($urgency > 9)); # 9 is used to clear the urgency flag
my @sellist = getSelection($lb);
return unless checkSelection($lb, 1, 0, \@sellist);
my ($pic, $dpic, $dirthumb, $msg);
# check if some files are links
return if (!checkLinks($lb, @sellist));
$urgency = "" if ($urgency == 9); # 9 is used to clear the urgency flag
$msg = "Writing IPTC urgence $urgency";
$msg = "Deleting IPTC urgence flag" if ($urgency eq "");
my $errors = "";
my $i = 0;
my $pw = progressWinInit($lb, $msg);
foreach $dpic (@sellist) {
last if progressWinCheck($pw);
$i++;
progressWinUpdate($pw, "$msg ($i/".scalar @sellist.") ...", $i, scalar @sellist);
$pic = basename($dpic);
$dirthumb = getThumbFileName($dpic);
# check if file is a link and get the real target
next if (!getRealFile(\$dpic));
next if (!checkWriteable($dpic));
my $meta = getMetaData($dpic, 'APP13');
my $iptc = $meta->get_app13_data('TEXTUAL', 'IPTC');
warn "IPTC segment of $dpic has errors!" if ($iptc->{error});
if ($config{UrgencyChangeWarning} and (defined $iptc->{"Urgency"}) and (${$iptc->{"Urgency"}}[0] != $urgency)) {
$errors .= "Info: Urgency changed from ".${$iptc->{"Urgency"}}[0]." to $urgency $dpic\n";
}
$iptc->{"Urgency"} = $urgency;
$meta->set_app13_data($iptc, 'REPLACE', 'IPTC');
if (!$meta->save()) {
$errors .= "save failed for $dpic\n";
}
else { # urgency changed successfully!
print "saved IPTC urgency $urgency to $pic\n" if $verbose;
if ($dpic eq $actpic) {
$urgencyStr = $urgency; # display new urgency in the status bar
unless ($urgency eq "") {
$urgencyScale = 9 - $urgencyStr;
$urgencyScale = 0 if (($urgencyStr < 1) or ($urgencyStr > 8));
}
}
}
# touch the thumbnail pic (set actual time stamp), to suppress rebuilding
touch($dirthumb);
updateOneRow($dpic, $lb);
}
progressWinEnd($pw);
$msg = "urgency $urgency written to";
$msg = "removed urgency flag in" if ($urgency eq "");
$userinfo = "ready! ($msg $i/".scalar @sellist.") pictures"; $userInfoL->update;
showText("Errors and infos while saving IPTC urgency", $errors, NO_WAIT) if ($errors ne "");
}
##############################################################
# getIPTCurgencyDB - get the urgency flag of a given file from
# the search database
# returns 9 if there is no file or no urgency
##############################################################
sub getIPTCurgencyDB {
my $dpic = shift;
my $urgency = 9;
$urgency = $searchDB{$dpic}{URG} if (defined $searchDB{$dpic}{URG});
return $urgency;
}
##############################################################
# getIPTCurgency - get the urgency flag of a given file
# returns 9 if there is no file or no urgency
##############################################################
sub getIPTCurgency {
my $dpic = shift;
my $meta = shift; # optional, the Image::MetaData::JPEG object of $dpic if available
my $urgency = 9;
return $quickSortHash{$dpic} if ($quickSortSwitch and defined $quickSortHash{$dpic});
return 9 unless (-f $dpic);
$meta = getMetaData($dpic, "APP13", 'FASTREADONLY') unless (defined($meta));
return 9 unless ($meta);
my $seg = $meta->retrieve_app13_segment(undef, 'IPTC'); # todo should be possible without segement
return 9 unless ($seg);
my $hashref = $seg->get_app13_data("TEXTUAL", 'IPTC');
if (defined($hashref->{Urgency})) {
$urgency = ${$hashref->{Urgency}}[0];
$urgency = 8 if ($urgency =~ /l/i);
$urgency = 1 if ($urgency =~ /h/i);
$urgency = 9 if ($urgency !~ /\d/);
$urgency = 9 if ( ($urgency > 9) or ($urgency < 0) );
}
$quickSortHash{$dpic} = $urgency if $quickSortSwitch;
print "getIPTCurgency: -$urgency- $dpic\n" if $verbose;
return $urgency;
}
##############################################################
# getIPTCkeywords - get the keywords of a given file
# returns empty list if there is no file or
# no keyword
##############################################################
sub getIPTCkeywords {
my $dpic = shift;
my $meta = shift; # optional, the Image::MetaData::JPEG object of $dpic if available
my @keywords = ();
return @keywords unless (-f $dpic);
$meta = getMetaData($dpic, 'APP13', 'FASTREADONLY') unless (defined($meta));
return @keywords unless ($meta);
my $seg = $meta->retrieve_app13_segment(undef, 'IPTC'); # todo should be possible without segement
return @keywords unless ($seg);
my $hashref = $seg->get_app13_data('TEXTUAL', 'IPTC');
if (defined($hashref->{Keywords})) {
@keywords = @{$hashref->{Keywords}};
}
return @keywords;
}
##############################################################
# getIPTCByLine - get the by-line info of a given file
##############################################################
sub getIPTCByLine($) {
my $dpic = shift;
my $byline = "";
return $quickSortHash{$dpic} if ($quickSortSwitch and defined $quickSortHash{$dpic});
return $byline unless (-f $dpic);
my $meta = getMetaData($dpic, "APP13", 'FASTREADONLY');
return $byline unless ($meta);
my $seg = $meta->retrieve_app13_segment(undef, 'IPTC'); # todo should be possible without segement
return $byline unless ($seg);
my $hashref = $seg->get_app13_data("TEXTUAL", 'IPTC');
$byline = ${$hashref->{ByLine}}[0] if (defined($hashref->{ByLine}));
$quickSortHash{$dpic} = $byline if $quickSortSwitch;
print "getIPTCByLine: $byline ($dpic)\n" if $verbose;
return $byline;
}
##############################################################
# getIPTCAttr - get an IPTC attribute of a given file
##############################################################
sub getIPTCAttr {
my $dpic = shift;
my $name = shift;
my $val = "";
if (-f $dpic) {
my $meta = getMetaData($dpic, "APP13", 'FASTREADONLY');
if ($meta) {
my $seg = $meta->retrieve_app13_segment(undef, 'IPTC'); # todo should be possible without segement
if ($seg) {
my $hashref = $seg->get_app13_data("TEXTUAL", 'IPTC');
if (defined($hashref->{$name})) {
$val = ${$hashref->{$name}}[0];
print "getIPTCAttr: $name=$val ($dpic)\n" if $verbose;
}
}
}
}
return $val;
}
##############################################################
# getIPTCObjectName - get the object name of a given file
##############################################################
sub getIPTCObjectName {
my $dpic = shift;
return getIPTCAttr($dpic, "ObjectName");
}
##############################################################
# getIPTCHeadline - get the headline of a given file
##############################################################
sub getIPTCHeadline {
my $dpic = shift;
return getIPTCAttr($dpic, "Headline");
}
##############################################################
# getIPTCCaption - get the caption of a given file
##############################################################
sub getIPTCCaption {
my $dpic = shift;
return getIPTCAttr($dpic, "Caption/Abstract");
}
##############################################################
# getIPTCByLineTitle - get the by-line title of a given file
##############################################################
sub getIPTCByLineTitle {
my $dpic = shift;
return getIPTCAttr($dpic, "ByLineTitle");
}
##############################################################
# getIPTCSublocation - get the sublocation of a given file
##############################################################
sub getIPTCSublocation {
my $dpic = shift;
return getIPTCAttr($dpic, "SubLocation");
}
##############################################################
# getIPTCCity - get the city of a given file
##############################################################
sub getIPTCCity {
my $dpic = shift;
return getIPTCAttr($dpic, "City");
}
##############################################################
# getIPTCProvince - get the province/state of a given file
##############################################################
sub getIPTCProvince {
my $dpic = shift;
return getIPTCAttr($dpic, "Province/State");
}
##############################################################
# getIPTCCountryCode - get the country code of a given file
##############################################################
sub getIPTCCountryCode {
my $dpic = shift;
return getIPTCAttr($dpic, "Country/PrimaryLocationCode");
}
##############################################################
# iptcDialog
##############################################################
sub iptcDialog {
my $iptc = shift;
my $picname = shift;
my $nr = shift; # number of pics
my $rc = 'Cancel';
my @tag_list; # used to store all IPTC tags which are already displayed, all others will go to the misc tab
# open window
my $t = $top->Toplevel();
$t->title("Edit IPTC/IIM information of $nr pictures ($picname)");
$t->iconimage($mapiviicon) if $mapiviicon;
my $notebook =
$t->NoteBook(-width => 750,
-background => $config{ColorBG}, # background of active page (including its tab)
-inactivebackground => $config{ColorEntry}, # tabs of inactive pages
-backpagecolor => $config{ColorBG}, # background behind notebook
)->pack(-expand => 1,
-fill => 'both',
-padx => 5, -pady => 5);
my $aN = $notebook->add('stan', -label => 'Standard');
my $bN = $notebook->add('misc', -label => 'Misc');
my $cN = $notebook->add('opt', -label => 'Options');
$notebook->raise($config{IPTCLastPad});
my $w = 11;
my $ent;
####### Standart IPTC tags #############
# left and right frame on standard tab
my $aF = $aN->Frame(-bd => 0)->pack(-side => 'left', -expand => 1, -fill => 'both', -padx => 3, -pady => 0);
my $bF = $aN->Frame(-bd => 0)->pack(-side => 'left', -expand => 1, -fill => 'both', -padx => 3, -pady => 0);
my @alist = ('Headline', 'ObjectName');
foreach (@alist) {
$ent = labeledEntry($aF,'top',$w,$_,\${$iptc->{$_}}[0], 5);
if (defined $iptcHelp{$_}) {
# todo this cuts very long desc because of config{LineLimit}
$balloon->attach($ent, -msg => formatString($_.":\n".$iptcHelp{$_}, 80)) if (Exists $ent);
}
}
push @tag_list, @alist; # add already displayed elements to the list
####### Caption #############
my $capF = $aF->Frame(-bd => 0)->pack(-anchor=>'w', -expand => 1, -fill => 'both', -padx => 3, -pady => 3);
$capF->Label(-text => 'Caption/Abstract', -bg => $config{ColorBG})->pack(-anchor => 'w', -padx => 2, -pady => 2);
my $caption = $capF->Scrolled("Text",
-scrollbars => 'osoe',
-wrap => 'word',
-width => 60,
-height => 6,
)->pack(-expand => 1, -fill => 'both', -padx => 2, -pady => 2);
$caption->insert('end', ${$iptc->{'Caption/Abstract'}}[0]);
$caption->see(0.1);
push @tag_list, 'Caption/Abstract'; # add already displayed elements to the list
####### Urgency #############
my $oF = $aF->Frame(-bd => 0)->pack(-anchor=>'w', -padx => 3, -pady => 6);
$balloon->attach($oF, -msg => "Rating/Urgency\n0 = no\n1 = High ********\n2 = *******\n3 = ******\n4 = *****\n5 = Normal ****\n6 = ***\n7 = **\n8 = Low *");
$oF->Label(-text => "Rating/Urgency", -bg => $config{ColorBG}, -width => 15, -anchor => 'w')->pack(-side => "left", -anchor => 'w', -padx => 2, -pady => 2);
$oF->Optionmenu(-variable => \${$iptc->{Urgency}}[0], -textvariable => \${$iptc->{Urgency}}[0], -options => [0,1,2,3,4,5,6,7,8])->pack(-side => "left", -anchor => 'w', -padx => 0);
push @tag_list, 'Urgency'; # add already displayed elements to the list
if ($config{IPTCProfessional}) {
####### Writer/Editor and Credit #############
labeledDoubleEntry($aF, 'top', $w, 'Writer/Editor', 'Credit',
\${$iptc->{'Writer/Editor'}}[0],
formatString("Writer/Editor:\n".$iptcHelp{'Writer/Editor'}, 80),
\${$iptc->{'Credit'}}[0],
formatString("Credit:\n".$iptcHelp{'Credit'}, 80));
push @tag_list, ('Writer/Editor', 'Credit'); # add already displayed elements to the list
}
####### BylineTitle and Byline #############
# !!! todo byline and bylinetitle are repeatable use e.g. .= "$_, " for @{$iptc->{$_}};
labeledDoubleEntry($aF, 'top', $w, 'ByLineTitle', 'Name',
\${$iptc->{ByLineTitle}}[0],
formatString("ByLineTitle:\n".$iptcHelp{'ByLineTitle'}, 80),
\${$iptc->{ByLine}}[0],
formatString("ByLine:\n".$iptcHelp{'ByLine'}, 80));
push @tag_list, ('ByLineTitle', 'ByLine'); # add already displayed elements to the list
####### EditStatus etc. ##############
if ($config{IPTCProfessional}) {
@alist = ('EditStatus', 'SpecialInstructions', 'Contact', 'Source', 'CopyrightNotice');
foreach (@alist) {
$ent = labeledEntry($aF,'top',$w,$_,\${$iptc->{$_}}[0]);
if (defined $iptcHelp{$_}) {
# todo this cuts very long desc because of config{LineLimit}
$balloon->attach($ent, -msg => formatString($_.":\n".$iptcHelp{$_}, 80)) if (Exists $ent);
}
}
push @tag_list, @alist; # add already displayed elements to the list
}
####### Location ##############
my $locF = $aF->Frame(-relief => 'raised')->pack(-anchor=>'w', -padx => 3, -pady => 3, -fill => 'x');
$locF->Label(-text => 'Location')->pack(-anchor => 'w', -padx => 2, -pady => 2);
$ent = labeledEntry($locF,'top',$w,'SubLocation',\${$iptc->{'SubLocation'}}[0]);
if (defined $iptcHelp{'SubLocation'}) {
# todo this cuts very long desc because of config{LineLimit}
$balloon->attach($ent, -msg => formatString("SubLocation:\n".$iptcHelp{'SubLocation'}, 80)) if (Exists $ent);
}
labeledDoubleEntry($locF, 'top', $w, 'City', 'Province/State',
\${$iptc->{'City'}}[0],
formatString("City:\n".$iptcHelp{'City'}, 80),
\${$iptc->{'Province/State'}}[0],
formatString("Province/State:\n".$iptcHelp{'Province/State'}, 80));
labeledDoubleEntry($locF, 'top', $w, 'Country', 'Code',
\${$iptc->{'Country/PrimaryLocationName'}}[0],
formatString("Country/PrimaryLocationName:\n".$iptcHelp{'Country/PrimaryLocationName'}, 80),
\${$iptc->{'Country/PrimaryLocationCode'}}[0],
formatString("Country/PrimaryLocationCode:\n".$iptcHelp{'Country/PrimaryLocationCode'}, 80));
push @tag_list, ('SubLocation', 'City', 'Province/State', 'Country/PrimaryLocationName', 'Country/PrimaryLocationCode');
####### Date and Time ############
if ($config{IPTCProfessional}) {
@alist = ('ReleaseDate', 'ReleaseTime', 'DateCreated', 'TimeCreated');
my $dateF = $aF->Frame(-bd => $config{Borderwidth}, -relief => 'raised')->pack(-anchor=>'w', -padx => 3, -pady => 3, -fill => 'x');
$dateF->Label(-text => 'Date and time')->pack(-anchor => 'w', -padx => 2, -pady => 2);
labeledDoubleEntry($dateF, 'top', $w, 'Date created', 'Time',
\${$iptc->{DateCreated}}[0],
formatString("DateCreated:\n".$iptcHelp{'DateCreated'}, 80),
\${$iptc->{TimeCreated}}[0],
formatString("TimeCreated:\n".$iptcHelp{'TimeCreated'}, 80));
labeledDoubleEntry($dateF, 'top', $w, 'Date released', 'Time',
\${$iptc->{ReleaseDate}}[0],
formatString("ReleaseDate:\n".$iptcHelp{'ReleaseDate'}, 80),
\${$iptc->{ReleaseTime}}[0],
formatString("ReleaseTime:\n".$iptcHelp{'ReleaseTime'}, 80));
push @tag_list, @alist; # add already displayed elements to the list
}
####### Keywords ############
my $keyword_frame = $bF->Frame(-bd => 0)->pack(-expand => 1, -fill => 'both', -padx => 0, -pady => 0);
# get the keywords (list ref)
doubleList($keyword_frame, \@prekeys, \@{$iptc->{Keywords}}, 'keywords');
push @tag_list, 'Keywords';
####### Categories ##########
my $category_frame;
if ($config{IPTCProfessional}) {
$category_frame = $bF->Frame(-bd => 0)->pack(-expand => 1, -fill => 'both', -padx => 0, -pady => 0);
$ent = labeledEntry($category_frame,'top',$w,'Category',\${$iptc->{Category}}[0]);
if (defined $iptcHelp{Category}) {
$balloon->attach($ent, -msg => formatString("Category:\n".$iptcHelp{Category}, 80)); # todo
}
# supp categories ###
doubleList($category_frame, \@precats, \@{$iptc->{SupplementalCategory}}, 'supplemental categories');
push @tag_list, ('Category', 'SupplementalCategory');
}
####### Misc #################
my $p = $bN->Scrolled("Pane", -scrollbars => "oe", -height => 300)->pack(-fill => "both", -expand => "1");
# build a frame, a label and an entry for every tag which is not yet displayed
foreach (@IPTCAttributes) {
next if (isInList($_, \@tag_list));
$ent = labeledEntry($p,'top',40,$_,\${$iptc->{$_}}[0]);
if (defined $iptcHelp{$_}) {
$balloon->attach($ent, -msg => formatString($_.":\n".$iptcHelp{$_}, 80)); # todo
}
}
###### bottom frame
my $exf = $t->Frame()->pack(-anchor=>'w');
#my $exf2 = $t->Frame()->pack(-anchor=>'w');
my $edb =
$exf->Checkbutton(-variable => \$config{IPTCdateEXIF},
-text => "EXIF date -> creation date ")->pack(-anchor => 'w', -side => 'left');
$balloon->attach($edb, -msg => 'This option will copy EXIF date,
to the IPTC date created tag.');
my $etb =
$exf->Checkbutton(-variable => \$config{IPTCtimeEXIF},
-text => "EXIF time -> creation time ")->pack(-anchor => 'w', -side => 'left');
$balloon->attach($etb, -msg => 'This option will copy EXIF time,
to the IPTC time created tag.');
my $IbEo =
$exf->Checkbutton(-variable => \$config{IPTCbylineEXIF},
-text => "EXIF owner -> ByLine ")->pack(-anchor => 'w', -side => 'left');
$balloon->attach($IbEo, -msg => 'This option will copy the content of EXIF Owner,
or if not available the content of EXIF Artist,
or if not available the content of EXIF UserComment
to the IPTC ByLine tag.');
my $IMap =
$exf->Checkbutton(-variable => \$config{IPTCaddMapivi},
-text => "Add Mapivi infos")->pack(-anchor => 'w', -side => 'left');
$balloon->attach($IMap, -msg => 'This option will insert Mapivi
in the IPTC OriginatingProgram tag
and the actual Mapivi version
into the ProgramVersion tag.');
my $optF = $cN->Frame()->pack();
$optF->Label(-text => 'IPTC dialog layout')->pack(-side => 'left', -anchor => 'w');
$optF->Radiobutton(-text => 'Simple', -variable => \$config{IPTCProfessional}, -value => 0)->pack(-side => 'left', -anchor => 'w');
$optF->Radiobutton(-text => 'Professional', -variable => \$config{IPTCProfessional}, -value => 1)->pack(-side => 'left', -anchor => 'w');
$cN->Label(-text => 'Please choose IPTC dialog layout, close dialog and open it again to see changes.')->pack();
my $f = $t->Frame()->pack(-anchor=>'w',-fill => 'x', -expand => 0);
# edit mode buttons only for more than one pictures
if ($nr > 1) {
my $rf = $f->Frame()->pack(-side => 'left', -anchor=>'w', -fill => 'x', -expand => 0);
my $radioB =
$rf->Label(-text => 'Edit mode')->pack(-side => 'left', -anchor => 'w');
$rf->Radiobutton(-text => 'Add', -variable => \$config{IPTC_action}, -value => 'ADD')->pack(-side => 'left', -anchor => 'w');
$rf->Radiobutton(-text => 'Update', -variable => \$config{IPTC_action}, -value => 'UPDATE')->pack(-side => 'left', -anchor => 'w');
$rf->Radiobutton(-text => 'Replace', -variable => \$config{IPTC_action}, -value => 'REPLACE')->pack(-side => 'left', -anchor => 'w');
$balloon->attach($rf, -msg =>
'Add: new records are added and nothing is deleted; however, if you
try to add a non-repeatable record which is already present,
the newly supplied value ejects (replaces) the pre-existing value.
Update: new records replace those characterised by the same tags,
but the others are preserved. This makes it possible to modify
some repeatable IPTC records without deleting the other tags.
Replace: all records present in the IPTC subdirectory are deleted
before inserting the new ones.');
}
my $okb =
$f->Button(-text => 'OK', -command =>
sub {
# get the caption
${$iptc->{'Caption/Abstract'}}[0] = $caption->get(0.1, 'end');
${$iptc->{'Caption/Abstract'}}[0] =~ s/\s+$//; # remove trailing whitespace
$config{IPTCLastPad} = $notebook->raised();
if (Exists $keyword_frame) {
saveTreeMode($keyword_frame->{m_tree}); # todo
store($keyword_frame->{m_tree}->{m_mode}, "$configdir/keywordMode") or warn "could not store $configdir/keywordMode: $!";
}
if (Exists $category_frame) {
saveTreeMode($category_frame->{m_tree}); # todo
store($category_frame->{m_tree}->{m_mode}, "$configdir/categoryMode") or warn "could not store $configdir/categoryMode: $!";
}
$t->destroy; # close window
$rc = 'OK';
}
)->pack(-side => "left", -fill => 'x', -expand => 1, -padx => 3, -pady => 3);
$balloon->attach($okb, -msg => "You can press Control-x to close the dialog (like OK button)");
$t->bind('<Control-x>', sub { $okb->invoke; });
my $Xbut = $f->Button(-text => 'Cancel', -command =>
sub {
$config{IPTCLastPad} = $notebook->raised();
$t->destroy; # close window
$rc = 'Cancel';
}
)->pack(-side => "left", -fill => 'x', -expand => 1, -padx => 3, -pady => 3);
$balloon->attach($Xbut, -msg => "You can press ESC to close the dialog (like Cancel button)");
$t->bind('<Key-Escape>', sub { $Xbut->invoke; });
$t->waitWindow;
return $rc;
}
##############################################################
# cleanList - remove empty elements from a list reference
##############################################################
sub cleanList {
my $listRef = shift;
if (ref($listRef) ne 'ARRAY') {
warn "cleanList: $listRef is no an array ref!";
return;
}
my @list;
foreach (@$listRef) {
push @list, $_ if ($_ ne "");
}
$listRef = \@list;
}
##############################################################
# doubleList - mega widget containing two listboxes, a entry
# and some buttons
##############################################################
sub doubleList($$$$) {
my $widget = shift; # mother widget
my $l1 = shift; # predefined list ref
my $l2 = shift; # real list ref
my $name = shift;
# build a frame for the supplemental categories
my $f = $widget->Frame(-bd => $config{Borderwidth}, -relief => 'raised')->pack(-expand => 1, -fill => 'both', -anchor=>'w', -padx => 3, -pady => 3);
$f->Label(-text => $name, -bg => $config{ColorBG})->pack(-anchor=>'w', -padx => 2, -pady => 2);
my $fc1 = $f->Frame()->pack(-expand => 1, -fill => "both", -side => "left", -anchor=>"n");
my $fc2 = $f->Frame()->pack(-expand => 0, -fill => 'x', -side => "left", -anchor=>"n");
my $fc3 = $f->Frame()->pack(-expand => 1, -fill => "both", -side => "left", -anchor=>"n");
$fc1->Label(-text => "common tags", -bg => $config{ColorBG})->pack(-anchor=>'w', -padx => 2, -pady => 2);
my $catLB2;
my $category = "";
my $fcent = $fc1->Entry(-textvariable => \$category,
-width => 20)->pack(-fill => 'x', -padx => 2, -pady => 2);
$fcent->bind('<Return>',
sub {
return if ($category eq "");
# check if category is allready in list
return if isInList($category, $l2);
push @$l2, $category;
$category = "";
@$l2 = sort { uc($a) cmp uc($b) } @$l2;
$catLB2->delete(0, 'end');
$catLB2->insert('end', @$l2);
});
my $tree = $fc1->Scrolled('Tree',
-separator => '/',
-scrollbars => 'osoe',
-selectmode => 'extended',
-exportselection => 0,
-width => 16,
-height => 14,
)->pack(-expand => 1, -fill => 'both', -padx => 2, -pady => 2);
$widget->{m_tree} = $tree;
bindMouseWheel($tree->Subwidget("scrolled"));
$balloon->attach($tree, -msg => "Double click on a item to insert it.\nIt's possible to edit the items, use the\nright mouse button to open the edit menu.");
# try to get the saved mode
my $modeRef;
if ($name eq 'keywords' and -f "$configdir/keywordMode") {
$modeRef = retrieve("$configdir/keywordMode");
}
if ($name eq 'supplemental categories' and -f "$configdir/categoryMode") {
$modeRef = retrieve("$configdir/categoryMode");
}
$tree->{m_mode} = $modeRef if (defined $modeRef);
addTreeMenu($tree, $l1);
insertTreeList($tree, @$l1);
# $tree->bind("<Double-Button-1>", sub {
# my @keys = $keytree->info('selection');
# return unless checkSelection($myDiag, 1, 0, \@keys);
# $entry->insert("insert", getLastItem($keys[0])." ");
# });
$fc2->Label(-text => "command", -bg => $config{ColorBG})->pack(-expand => 0, -anchor=>'w', -padx => 2, -pady => 2);
my $all = 0;
my $all_ref = \$all;
$all_ref = \$config{CategoriesAll} if ($name eq 'supplemental categories');
$all_ref = \$config{KeywordsAll} if ($name eq 'keywords');
my $addB =
$fc2->Button(-text => "add",
-command => sub {
my @keys = $tree->info('selection');
return unless checkSelection($widget, 1, 0, \@keys);
my @keylist;
my $warning = '';
my @items;
foreach my $key (@keys) {
if ($$all_ref == 1) { # all, separated
push @items, getAllItems($key);
}
elsif ($$all_ref == 2) { # all, joined
my $joined = join('.', getAllItems($key));
if (length($joined) > 64) {
$warning .= "Keyword $joined has ".length($joined)." characters";
next;
}
push @items, $joined;
}
elsif ($$all_ref == 0) { # last
push @items, getLastItem($key);
}else {
warn "doubleList: should never be reached!";
}
}
foreach my $item (@items) {
next if isInList($item, $l2); # make @$l2 unique
push @$l2, $item; # by adding just new items
@$l2 = sort { uc($a) cmp uc($b) } @$l2; # sort alphabetical
$catLB2->delete(0, 'end');
$catLB2->insert('end', @$l2);
}
} )->pack(-expand => 0, -fill => 'x', -padx => 1, -pady => 1);
$balloon->attach($addB, -msg => "Add the selected items to the picture");
my $fc2a = $fc2->Frame()->pack();
$fc2a->Radiobutton(-text => "all", -variable => $all_ref, -value => 1)->pack(-anchor => 'w');
$fc2a->Radiobutton(-text => "join", -variable => $all_ref, -value => 2)->pack(-anchor => 'w');
$fc2a->Radiobutton(-text => "last", -variable => $all_ref, -value => 0)->pack(-anchor => 'w');
$balloon->attach($fc2a, -msg => "$name add mode\nExample $name: Friend/Bundy/Kelly\nmode all: three $name: Friend, Bundy and Kelly\nmode join: one $name: Friend.Bundy.Kelly\nmode last: one $name: Kelly");
my $rmB =
$fc2->Button(-text => "remove",
-command => sub {
my @sellist = $catLB2->curselection();
if (@sellist < 1) {
print "nothing selected\n" if $verbose;
return;
}
# delete the selected elements in reverse order
foreach (reverse @sellist) {
splice @$l2, $_, 1;
}
$catLB2->delete(0, 'end');
$catLB2->insert('end', @$l2);
})->pack(-expand => 0, -fill => 'x', -padx => 1, -pady => 1);
$balloon->attach($rmB, -msg => "Remove the selected items from the picture");
$tree->bind('<Double-Button-1>', sub { $addB->invoke(); } );
$fc3->Label(-text => "tags of picture", -bg => $config{ColorBG})->pack(-anchor=>'w');
$catLB2 =
$fc3->Scrolled('Listbox',
-scrollbars => 'osoe',
-selectmode => 'extended',
-exportselection => 0,
-width => 25,
-height => 14,
)->pack(-expand => 1, -fill =>'both', -padx => 2, -pady => 2);
bindMouseWheel($catLB2->Subwidget("scrolled"));
$catLB2->insert('end', @$l2);
$catLB2->bind('<Double-Button-1>', sub { $rmB->invoke(); } );
}
##############################################################
# removeAllComments
##############################################################
sub removeAllComments {
my $ask = shift;
unless ($ask == ASK or $ask == NO_ASK) { warn "removeAllComments called with wrong argument: $ask"; return; }
my @sellist = $picLB->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
my $selected = @sellist;
my ($pic, $dpic, $dirthumb, $dirtpic, $i, $com);
if ($ask == ASK) {
my $rc = $top->messageBox(-icon => 'question', -message => "Ok to remove all comments of $selected selected pictures?\nThere is no undo!",
-title => "Remove all comments?", -type => 'OKCancel');
return if ($rc !~ m/Ok/i);
}
$userinfo = "removing comments ..."; $userInfoL->update;
# check if some files are links
return if (!checkLinks($picLB, @sellist));
my $pw = progressWinInit($top, "Remove all comments");
$i = 0;
foreach $dpic (@sellist) {
last if progressWinCheck($pw);
$i++;
progressWinUpdate($pw, "removing all comments ($i/$selected) ...", $i, $selected);
$pic = basename($dpic);
$dirthumb = getThumbFileName($dpic);
next if (!checkWriteable($dpic));
# check if file is a link and get the real target
next if (!getRealFile(\$dpic));
my $meta = getMetaData($dpic, "COM");
next unless ($meta);
$meta->remove_all_comments();
unless ($meta->save()) { warn "removeAllComments: save $pic failed!"; }
# touch the thumbnail pic (set actual time stamp), to suppress rebuilding the next time
touch($dirthumb);
updateOneRow($dpic, $picLB);
showImageInfo($dpic) if ($dpic eq $actpic);
}
progressWinEnd($pw);
$userinfo = "ready! (removed comments in $i of $selected pictures)"; $userInfoL->update;
}
##############################################################
# editComment
##############################################################
sub editComment {
my $lb = shift; # the reference to the listbox widget to update
my @sellist = $lb->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
my $selected = @sellist;
my ($pic, $dpic, $dirthumb, $dirtpic, $com);
$userinfo = "editing comments from $selected pictures"; $userInfoL->update;
# check if some files are links
return if (!checkLinks($lb, @sellist));
my $pw = progressWinInit($lb, "Edit comments");
my $i = 0;
foreach $dpic (@sellist) {
last if progressWinCheck($pw);
$i++;
progressWinUpdate($pw, "editing comment ($i/$selected) ...", $i, $selected);
$pic = basename($dpic);
$dirthumb = getThumbFileName($dpic);
next if (!checkWriteable($dpic));
# check if file is a link and get the real target
next if (!getRealFile(\$dpic));
my @comsellist = ();
my $text = "";
my @comments = getComments($dpic);
if (@comments <= 0) {
next; # no comment -> no edit
} elsif (@comments == 1) {
$text = $comments[0]; # one comment -> select the first
$comsellist[0] = 0;
} else {
# more than one comment, let the user select one comment to edit
my $nr = @comments;
my @shortComments;
foreach (@comments) { push @shortComments, cutString($_, 80, "..."); }
next if (!mySelListBoxDialog("Edit comment of $pic",
"Please select one of the $nr comments to edit",
"Edit", \@comsellist, @shortComments));
if (@comsellist != 1) {
$top->messageBox(-icon => 'warning', -message => "Please select just one comment.", -title => "Wrong selection", -type => 'OK');
next;
}
$text = $comments[$comsellist[0]];
}
my $rc = myTextDialog("Edit comment", "Please edit comment of $pic", \$text, $dirthumb);
next if ($rc ne 'OK');
# replace (german) umlaute by corresponding letters
$text =~ s/([$umlaute])/$umlaute{$1}/g if ($config{ConvertUmlaut});
$config{Comment} = $text; # save changed comment to global config hash
my $meta = getMetaData($dpic, "COM");
next unless ($meta);
$meta->set_comment($comsellist[0], $text);
unless ($meta->save()) { warn "editComment: save $pic failed!"; }
# touch the thumbnail pic (set actual time stamp), to suppress rebuilding the next time
touch($dirthumb);
updateOneRow($dpic, $lb);
showImageInfo($dpic) if ($dpic eq $actpic);
}
progressWinEnd($pw);
$userinfo = "ready! ($i of $selected edited)"; $userInfoL->update;
}
##############################################################
# joinComments
##############################################################
sub joinComments {
my $ask = shift;
unless ($ask == ASK or $ask == NO_ASK) { warn "joinComments called with wrong argument: $ask"; return; }
my @sellist = $picLB->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
my ($pic, $dpic, $dirthumb, $meta, $com, $nr);
my $separator = "\n";
if ($ask == ASK) {
my $rc = myButtonDialog('Join comments?', "Ok to join all comments to one comment in each of the ".scalar @sellist." selected pictures?\n\n(Some programms are only able to display the fist comment of a JPEG picture.\nPictures with no or just one comment will be skipped.)\nPlease choose the desired separator when joining the comments.", undef, 'Space', 'Newline', 'Nothing', 'Cancel');
return if ($rc =~ m/Cancel/i);
$separator = ' ' if ($rc =~ m/Space/i);
$separator = '' if ($rc =~ m/Nothing/i);
}
$userinfo = "joining comments from ".scalar @sellist." pictures"; $userInfoL->update;
# check if some files are links
return if (!checkLinks($picLB, @sellist));
my $pw = progressWinInit($top, "Join comments");
my $i = 0;
foreach $dpic (@sellist) {
last if progressWinCheck($pw);
$i++;
progressWinUpdate($pw, "joining comments ($i/".scalar @sellist.") ...", $i, scalar @sellist);
$pic = basename($dpic);
$dirthumb = getThumbFileName($dpic);
next if (!checkWriteable($dpic));
# check if file is a link and get the real target
next if (!getRealFile(\$dpic));
$meta = getMetaData($dpic, "COM");
next unless ($meta);
$nr = $meta->get_number_of_comments();
next if ($nr <= 1); # no or just one comment -> no join
$com = getComments($dpic, 0);
if ((defined $com) and (length $com > $maxCommentLength)) { # a JPEG comment may have max 64kB
my $rc = $top->messageBox(-icon => 'warning', -message => "The joined comments of $dpic are too long (".length $com." characters).\nJPEG-Comments may only be up to 64K.\nOK will skip this picture, Cancel will abort the operation.",
-title => "Comment to big", -type => 'OKCancel');
return if ($rc !~ m/Ok/i);
next;
}
# join comments with configurable separator string
$meta->join_comments($separator);
unless ($meta->save()) { warn "editComment: save $pic failed!"; }
# touch the thumbnail pic (set actual time stamp), to suppress rebuilding the next time
touch($dirthumb);
updateOneRow($dpic, $picLB);
}
progressWinEnd($pw);
$userinfo = "ready! ($i of ".scalar @sellist." joined)"; $userInfoL->update;
}
##############################################################
# checkTempFile - check if temp file exists
# returns 0 if it exists
# return s1 if not
##############################################################
sub checkTempFile($) {
my $tmpfile = shift;
if (-f $tmpfile) {
$top->messageBox(-icon => 'warning', -message => "Temporary file $tmpfile already exists. Skipping!",
-title => 'Error', -type => 'OK');
return 0;
}
return 1;
}
##############################################################
# removeComment - remove a JPEG comment from a picture
# if there is more than one comment in the
# picture the user can
# choose which to delete
# if the same comment is selected in two pics
# we ask, if we should delete this one in all
##############################################################
sub removeComment {
my @sellist = $picLB->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
my $selected = @sellist;
my $doForAll = 0;
my ($pic, $dpic, $dirthumb, $meta, $com, @removedComments);
$userinfo = "removing comments from $selected pictures"; $userInfoL->update;
# check if some files are links
return if (!checkLinks($picLB, @sellist));
my $pw = progressWinInit($top, "Remove comments");
my $i = 0;
my $j = 0; # the real number of changed pictures
foreach $dpic (@sellist) {
last if progressWinCheck($pw);
$i++;
progressWinUpdate($pw, "removing comment ($i/$selected) ...", $i, $selected);
$pic = basename($dpic);
$dirthumb = getThumbFileName($dpic);
next if (!checkWriteable($dpic));
# check if file is a link and get the real target
next if (!getRealFile(\$dpic));
my @comments = getComments($dpic);
next if (@comments <= 0);
# let the user select the comments to delete
my @comsellist = ();
# normal modus - let the user select what to remove
if (!$doForAll) {
my @shortComments;
foreach (@comments) { push @shortComments, cutString($_, 80, "..."); }
next if (!mySelListBoxDialog("Remove comments",
"Please select comment(s) to remove from $pic",
"Remove", \@comsellist, @shortComments));
}
# comment remove wizard mode :) - we choose the right comment to delete
else {
for (0 .. $#comments) { # search in all comments
if ($comments[$_] eq $removedComments[-1]) { # for the magic comment
$comsellist[0] = $_; # remember the index
last;
}
}
}
if ( (@comsellist == 1) and ($doForAll == 0) ) { # if just one comment is removed
push @removedComments, $comments[$comsellist[0]]; # remember the removed comments
if (@removedComments >= 2) { # when we collected at least two ...
if ($removedComments[-1] eq $removedComments[-2]) { # and they are the same ...
if ($i < @sellist) { # and there is still some work to be done ...
my $com = $removedComments[-1];
$com = substr($com, 0, 100)."..." if (length($com) > 103);
my $rc = $top->messageBox(-icon => 'question', -message => "You've selected the same comment two times. Should I remove this comment:\n-------------\n$com\n-------------\nfrom the rest (".(@sellist - $i).") of the selected pictures?",
-title => "Comment remove wizard", -type => 'OKCancel');
$doForAll = 1 if ($rc =~ m/Ok/i);
}
}
}
}
# this can only happen in wizard mode (for pictures not containing the comment to remove)
next if (@comsellist == 0);
$meta = getMetaData($dpic, "COM");
next unless ($meta);
# delete the selected elements in reverse order, the unselected stay in the @comments
foreach (reverse @comsellist) {
$meta->remove_comment($_);
}
unless ($meta->save()) { warn "editComment: save $pic failed!"; }
$j++; # count the modified pics
# touch the thumbnail pic (set actual time stamp), to suppress rebuilding the next time
touch ($dirthumb);
updateOneRow($dpic, $picLB);
showImageInfo($dpic) if ($dpic eq $actpic);
}
progressWinEnd($pw);
$userinfo = "ready! (removed comments in $j of $selected pictures)"; $userInfoL->update;
}
##############################################################
# rotate - rotate all selected pictures by 90, 180 or 270
# degrees or do a flip transformation
##############################################################
sub rotate {
my @sellist = $picLB->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
my $selected = @sellist;
my ($pic, $dpic, $dirtpic, $i);
return if (!checkExternProgs("rotate", "jpegtran"));
my $deg = shift; # 90, 180, 270, auto, clear, norot, horizontal or vertical
my $mode = 0;
if ($deg eq "auto") {
$mode = 1;
return if (!checkExternProgs("auto rotate", "jhead"));
my $usage = `jhead -h 2>&1`;
if ($usage !~ m/.*-autorot.*/) {
$top->messageBox(-icon => 'warning', -message => "Sorry, but your version of jhead does not support automatic rotation!\nTry to get a newer version at: ".$exprogsres{jhead},
-title => "Wrong jhead version", -type => 'OK');
return;
}
}
elsif ($deg eq "clear") {
$mode = 2;
return if (!checkExternProgs("auto rotate", "jhead"));
my $usage = `jhead -h 2>&1`;
if ($usage !~ m/.*-norot.*/) {
$top->messageBox(-icon => 'warning', -message => "Sorry, but your version of jhead does not support the clearing of the rotation tag!\nTry to get a newer version at: ".$exprogsres{jhead},
-title => "Wrong jhead version", -type => 'OK');
return;
}
}
else { $mode = 0; }
my $transform = "-rotate $deg";
if (($deg eq "horizontal") or ($deg eq "vertical")) {
$transform = "-flip $deg";
}
my $errors = "";
my $trim = "";
$trim = "-trim " if $config{jpegtranTrim};
$userinfo = "rotating $selected pictures"; $userInfoL->update;
# check if some files are links
return if (!checkLinks($picLB, @sellist));
my $pw = progressWinInit($top, "rotate pictures");
$i = 0;
foreach $dpic (@sellist) {
last if progressWinCheck($pw);
$i++;
$pic = basename($dpic);
$dirtpic = dirname($dpic)."/$pic"."-cjpg"; # temporary file
next if (!checkWriteable($dpic));
# check if temp file exists
next if (!checkTempFile($dirtpic));
my $command = "";
if ($mode == 1) { # auto
if (is_a_JPEG($dpic)) {
# call external command jhead and auto rotate the file directly
$command = "jhead -autorot \"$dpic\" ";
}
else {
$errors .= "auto rotation is only supported for JPEGs ($dpic)\n";
}
}
elsif ($mode == 2) { # clear
if (is_a_JPEG($dpic)) {
# call external command jhead and clear the rotation flag of the file directly
$command = "jhead -norot \"$dpic\" ";
}
else {
$errors .= "clear rotation is only supported for JPEGs ($dpic)\n";
}
}
else {
if (is_a_JPEG($dpic)) {
# call external command jpegtran and rotate to the temp file
$command = "jpegtran -copy all $transform $trim -outfile \"$dirtpic\" \"$dpic\" ";
}
else {
$transform = "-rotate $deg";
if ($deg eq "horizontal") {
$transform = "-flip";
}
if ($deg eq "vertical") {
$transform = "-flop";
}
$command = "mogrify $transform \"$dpic\" ";
}
}
next if ($command eq "");
execute($command);
progressWinUpdate($pw, "rotating ($i/$selected) ...", $i, $selected);
# now overwrite the original pic with the temp file and delete the temp file
# (not needed for jhead and mogrify)
# todo rotate also thumbs of autorotated pics (but how?)
if (($mode == 0) and (is_a_JPEG($dpic))) {
rotateThumb("$dirtpic", $transform) if ($config{RotateThumb});
next if (!overwrite("$dpic", "$dirtpic"));
}
updateOneRow($dpic, $picLB);
deleteCachedPics($dpic);
showPic($dpic) if ($dpic eq $actpic); # redisplay the picture if it is the actual one
}
progressWinEnd($pw);
reselect($picLB, @sellist);
$userinfo = "ready! ($i of $selected rotated)"; $userInfoL->update;
showText("Errors while rotating pictures", $errors, NO_WAIT) if ($errors ne "");
generateThumbs(ASK, SHOW);
}
##############################################################
# rotateThumb
##############################################################
sub rotateThumb {
my $dpic = shift;
my $pic = basename($dpic);
my $tmppic = "$trashdir/$pic";
my $tmppic2 = "$trashdir/$pic.tcjpeg";
my $transform = shift;
print "rotateThumb: $pic $transform\n" if $verbose;
my $errors = "";
extractThumb($dpic, $tmppic, \$errors);
return unless (-f $tmppic); # there is no EXIF thumbnail
my $trim = "";
$trim = "-trim " if $config{jpegtranTrim};
my $command = "jpegtran -copy all $transform $trim -outfile \"$tmppic2\" \"$tmppic\" ";
execute($command);
removeFile($tmppic);
writeThumb($dpic, $tmppic2);
removeFile($tmppic2);
}
##############################################################
# extractThumb
##############################################################
sub extractThumb {
my $dpic = shift; # picture file with path
my $dthumb = shift; # thumbnail file with path (will be overwritten!)
my $errors = shift; # reference to error text scalar
my $meta = getMetaData($dpic, 'APP1');
if ($meta) {
my $thumbData = $meta->get_Exif_data('THUMBNAIL');
if ($thumbData and ($$thumbData ne "")) {
my $thumb = new Image::MetaData::JPEG($thumbData);
if ($thumb) {
unless ($thumb->save($dthumb)) {
$errors .= "Couldn't save $dthumb";
}
} else {
$errors .= "Couldn't create thumb $dpic\n";
}
} else {
$$errors .= "No EXIF thumbnail in $dpic\n";
}
} else {
$$errors .= "No EXIF data in $dpic\n";
}
}
##############################################################
# writeThumb - returns 1 if OK, else an error string
##############################################################
sub writeThumb {
my $dpic = shift; # the picture file with path to which the thumb will be written
my $dthumb = shift; # the thumbnail file name with path
my $error = 1;
my $image = new Image::MetaData::JPEG($dpic, 'APP1');
return "Could not read meta data of $dpic" unless ($image);
my $thimage = new Image::MetaData::JPEG($dthumb);
return "Could not read meta data of $dthumb" unless ($thimage);
my $data = "dummy";
unless ($thimage->save(\$data)) {
return "Could not build thumbnail for $dthumb";
}
my $hash = $image->set_Exif_data(\$data, 'THUMBNAIL');
return "JPEG thumbnail rejected for $dpic" if (keys %$hash);
my $result = $image->save();
return "save failed for $dpic" unless ($result);
return 1;
}
##############################################################
# copyThumbnail
##############################################################
sub copyThumbnail {
my @sellist = $picLB->info('selection');
my $selected = @sellist;
my ($pic, $dpic, $i, $dirthumb);
return unless checkSelection($top, 1, 0, \@sellist);
if ((!defined $copyEXIFDataSource) or (!-f $copyEXIFDataSource)) {
$top->messageBox(-icon => 'warning', -message => 'Please select a source picture first. This picture will be used as thumbnail, you may use "Save thumbnail ..." first. Than choose EXIF info->copy from!',
-title => 'No source picture', -type => 'OK');
return;
}
my $size = getFileSize($copyEXIFDataSource, NO_FORMAT); # file size in bytes
if ($size > 65535) {
$top->messageBox(-icon => 'warning', -message => "Sorry, the thumbnail picture is too big ($size bytes). The thumbnail picture must have less than 65535 bytes.",
-title => "Thumbnail too big", -type => 'OK');
return;
}
my $message = "Copy this thumbnail from\
\"".basename($copyEXIFDataSource)."\"\
to $selected selected pictures.\
The original thumbnails of these pictures will be lost!\
Ok to continue?";
my $rc = myButtonDialog("Copy EXIF data", "$message", $copyEXIFDataSource, 'OK', 'Cancel');
return if ($rc ne 'OK');
$userinfo = "transfering thumbnail to $selected pictures"; $userInfoL->update;
my $errors = "";
$i = 0;
my $pw = progressWinInit($top, "Copy thumbnail");
foreach $dpic (@sellist) {
last if progressWinCheck($pw);
$i++;
progressWinUpdate($pw, "transfering thumbnail ($i/$selected) ...", $i, $selected);
$pic = basename($dpic);
$dirthumb = getThumbFileName($dpic);
# check if file is a link and get the real target
next if (!getRealFile(\$dpic));
next if (!checkWriteable($dpic));
my $rc = writeThumb($dpic, $copyEXIFDataSource);
$errors .= "$rc\n" if ($rc ne '1');
updateOneRow($dpic, $picLB);
# touch the thumbnail pic (set actual time stamp), to suppress rebuilding the next time
touch($dirthumb);
}
progressWinEnd($pw);
$userinfo = "ready! ($i/$selected thumbnails transfered)"; $userInfoL->update;
showText("Errors while transfering thumbnails", $errors, NO_WAIT) if ($errors ne "");
}
##############################################################
# buildEXIFThumb
##############################################################
sub buildEXIFThumb {
my $rc = $top->messageBox(-icon => "question",
-message => "This function will (re)build the embedded EXIF thumbnail of the selected pictures.\nThe original EXIF thumnail (if existent) will be overwritten!\nOk to continue?",
-title => "(Re)Build EXIF thumbnail", -type => 'OKCancel');
return if ($rc !~ m/Ok/i);
my @sellist = $picLB->info('selection');
my $selected = @sellist;
my ($pic, $dpic, $i, $dirthumb, $thumb);
return unless checkSelection($top, 1, 0, \@sellist);
$userinfo = "(re)building EXIF thumbnail in $selected pictures"; $userInfoL->update;
$i = 0;
my $pw = progressWinInit($top, "(Re)build EXIF thumbnail");
foreach $dpic (@sellist) {
last if progressWinCheck($pw);
progressWinUpdate($pw, "(Re)building EXIF thumbnail ($i/$selected) ...", $i, $selected);
$i++;
$pic = basename($dpic);
$dirthumb = getThumbFileName($dpic);
$thumb = "$trashdir/$pic-exifthumb";
if (-f $thumb) {
warn "the temp file $thumb exists - skipping!";
next;
}
# check if file is a link and get the real target
next if (!getRealFile(\$dpic));
next if (!checkWriteable($dpic));
my $command = "convert -size 160x160 -geometry 160x160 -quality 75 -sharpen 0.4 -filter Lanczos \"$dpic\" \"$thumb\"";
$top->Busy;
execute($command);
$top->Unbusy;
if (!-f $thumb) {
warn "file $thumb not generated - skipping!";
next;
}
my $errors;
removeEXIF($thumb, 'all', \$errors);
my $size = getFileSize($thumb, NO_FORMAT); # file size in bytes
if ($size > 65535) {
$top->messageBox(-icon => 'warning', -message => "Sorry, builded EXIF thumbnail picture is too big ($size bytes). The thumbnail picture must have less than 65535 bytes.\nSkipping picture ...",
-title => "Thumbnail too big", -type => 'OK');
next;
}
writeThumb($dpic, $thumb);
removeFile($thumb);
# touch the thumbnail pic (set actual time stamp), to suppress rebuilding the next time
touch($dirthumb);
updateOneRow($dpic, $picLB);
showImageInfo($dpic) if ($dpic eq $actpic);
}
progressWinEnd($pw);
$userinfo = "ready! ($i/$selected EXIF thumbnails (re)builded)"; $userInfoL->update;
}
##############################################################
# reselect - selects the index in the given list, if they exist
# and shows the selection information in the status
# bar
##############################################################
sub reselect {
my $lb = shift;
foreach (@_) { $lb->selectionSet($_) if ($lb->info("exists", $_)); }
showNrOf() if ($lb == $picLB);
}
##############################################################
# rotateAny - rotate all selected pictures in any angle
##############################################################
sub rotateAny {
return if (!checkExternProgs("rotateAny", "mogrify"));
my @sellist = $picLB->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
my $selected = @sellist;
my ($dpic, $i, $command);
$userinfo = "rotating $selected pictures"; $userInfoL->update;
# check if some files are links
return if (!checkLinks($picLB, @sellist));
my $doforall = 0;
my $degree = 0;
my $color = "gray30";
my $pw = progressWinInit($top, "Rotate pictures");
$i = 0;
foreach $dpic (@sellist) {
last if progressWinCheck($pw);
$i++;
if (!$doforall) {
last if (!rotateDialog(\$degree, \$color, \$doforall, $dpic, $selected));
}
progressWinUpdate($pw, "rotating ($i/$selected) ...", $i, $selected);
# check if file is a link and get the real target
next if (!getRealFile(\$dpic));
next if (!checkWriteable($dpic));
next if (!makeBackup($dpic));
$command = "mogrify -rotate $degree -bordercolor \"$color\" -background \"$color\" -quality $config{PicQuality} ";
$command .= "-unsharp ".$config{UnsharpRadius}.'x'.$config{UnsharpSigma}."+".$config{UnsharpAmount}."+".$config{UnsharpThreshold}." " if $config{Unsharp};
$command .= "\"$dpic\" ";
print "$command\n" if $verbose;
execute($command);
if ($config{AddMapiviComment}) {
$command =~ s/\"//g;
$command = "Picture processed by Mapivi ($mapiviURL):\n".$command;
addCommentToPic($command, $dpic, NO_TOUCH);
}
updateOneRow($dpic, $picLB);
deleteCachedPics($dpic);
showPic($dpic) if ($dpic eq $actpic); # redisplay the picture if it is the actual one
}
progressWinEnd($pw);
reselect($picLB, @sellist);
$userinfo = "ready! ($i of $selected rotated)"; $userInfoL->update;
generateThumbs(ASK, SHOW);
}
my $rotw;
##############################################################
# rotateDialog
##############################################################
sub rotateDialog {
my $deg = shift; # reference
my $col = shift; # reference
my $doforall = shift; # reference
my $pic = shift; # the preview pic
my $nr = shift; # the number of pics
if (Exists($rotw)) {
$rotw->deiconify;
$rotw->raise;
return;
}
my $orig = "$trashdir/".basename($pic);
my $new = "$trashdir/x-".basename($orig);
unless (mycopy($pic, $orig, OVERWRITE)) {
warn "rotateDialog: copy error $pic -> $orig ($new)\ncopy";
return 0;
}
my ($w, $h) = getSize($orig);
if ($w > $cropPreviewSize or $h > $cropPreviewSize) {
$userinfo = "rotate: resizing preview picture ..."; $userInfoL->update;
my $command = "mogrify -geometry ${cropPreviewSize}x${cropPreviewSize} -quality 70 \"$orig\"";
$top->Busy;
execute($command);
$top->Unbusy;
$userinfo = "ready!"; $userInfoL->update;
}
return 0 unless (-f $orig);
# open window
$rotw = $top->Toplevel();
$rotw->title("Rotate picture");
$rotw->iconimage($mapiviicon) if $mapiviicon;
my $rc = 0;
my $preview = $rotw->Photo(-file => "$orig", -gamma => $config{Gamma}) if (-f $orig);
my $fc = $rotw->Frame()->pack();
my $prevC = $fc->Scrolled("Canvas",
-scrollbars => 'osoe',
-width => $cropPreviewSize,
-height => $cropPreviewSize,
-relief => 'sunken',
-bd => $config{Borderwidth})->pack(-side => "left", -padx => 3, -pady => 3,-anchor => 'w') if $preview;
my $horizont = 0;
my $vertical = 0;
$fc->Scale(-variable => \$horizont,
-length => $cropPreviewSize,
-from => 0,
-to => $cropPreviewSize,
-resolution => 1,
-sliderlength => 10,
-orient => 'vertical',
-width => 10,
-bd => 1,
-showvalue => 0,
-relief => 'groove',
-command => sub {
drawHorizont($prevC, $horizont, $vertical);
} )->pack(-side => "left", -padx => 3,-pady => 3);
$rotw->Scale(-variable => \$vertical,
-length => $cropPreviewSize,
-from => 0,
-to => $cropPreviewSize,
-resolution => 1,
-sliderlength => 10,
-orient => 'horizontal',
-width => 10,
-bd => 1,
-showvalue => 0,
-relief => 'groove',
-command => sub {
drawHorizont($prevC, $horizont, $vertical);
} )->pack(-anchor => 'w', -padx => 3,-pady => 3);
$prevC->createImage(0, 0, -image => $preview, -tag => "image", -anchor => "nw");
my $f1 = $rotw->Frame()->pack(-anchor => 'w');
my $auto = 0;
$f1->Checkbutton(-text => "auto update", -variable => \$auto)->pack(-side => "left", -expand => 1, -fill => 'x');
$f1->Button(-text => "--", -command => sub {
$$deg--;
rotUpdate($prevC, $preview, $orig, $new, $deg, $col) if $auto;
})->pack(-side => "left", -expand => 1, -fill => 'x');
$f1->Button(-text => "-", -command => sub {
$$deg -= 0.1;
rotUpdate($prevC, $preview, $orig, $new, $deg, $col) if $auto;
})->pack(-side => "left", -expand => 1, -fill => 'x');
$f1->Label(-textvariable => $deg, -relief => "sunken", -width => 5)->pack(-side => "left", );
$f1->Button(-text => "+", -command => sub {
$$deg += 0.1;
rotUpdate($prevC, $preview, $orig, $new, $deg, $col) if $auto;
})->pack(-side => "left", -expand => 1, -fill => 'x');
$f1->Button(-text => "++", -command => sub {
$$deg++;
rotUpdate($prevC, $preview, $orig, $new, $deg, $col) if $auto;
})->pack(-side => "left", -expand => 1, -fill => 'x');
labeledScale($rotw, 'top', 26, "Angle (degrees, clockwise)", $deg, 0, 359.9, 0.1);
my $qS = labeledScale($rotw, 'top', 26, "Quality (%)", \$config{PicQuality}, 10, 100, 1);
qualityBalloon($qS);
labeledEntryColor($rotw,'top',26,"Background color",'Set',$col);
# check, if a new version of ImageMagick's mogrify with the unsharp option is available
my $unsharp = 0;
$unsharp = 1 if (`mogrify` =~ m/.*-unsharp.*/);
# sharpen the image with an unsharp mask operator
if ($unsharp) {
my $umF = $rotw->Frame()->pack(-fill =>'x');
my $umcB = $umF->Checkbutton(-variable => \$config{Unsharp},
-anchor => 'w',
-text => "Unsharp mask")->pack(-side => "left", -anchor => 'w', -fill => 'x', -expand => 1);
$balloon->attach($umcB, -msg => "The -unsharp option sharpens an image.
We convolve the image with a Gaussian operator of the given radius
and standard deviation (sigma).
For reasonable results, radius should be larger than sigma.
Use a radius of 0 to have the method select a suitable radius.");
$umF->Button(-text => "Options",
-anchor => 'w',
-command => sub { unsharpDialog(); })->pack(-side => "left", -anchor => 'w', -padx => 3);
}
buttonBackup($rotw, 'top');
buttonComment($rotw, 'top');
if ($nr > 1) {
$rotw->Checkbutton(-variable => \$$doforall,
-anchor => 'w',
-text => "use this setting for all pics"
)->pack(-anchor => 'w');
}
my $ButF = $rotw->Frame()->pack(-fill =>'x', -padx => 3, -pady => 3);
my $OKB = $ButF->Button(-text => 'OK',
-command => sub {
$rc = 1;
$rotw->withdraw();
$rotw->destroy();
}
)->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$ButF->Button(-text => "Preview",
-command => sub {
rotUpdate($prevC, $preview, $orig, $new, $deg, $col);
}
)->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3) if $preview;
my $XBut = $ButF->Button(-text => 'Cancel',
-command => sub {
$rc = 0;
$rotw->withdraw();
$rotw->destroy();
}
)->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$rotw->bind('<Key-q>', sub { $XBut->invoke; });
$rotw->bind('<Key-Escape>', sub { $XBut->invoke; });
$rotw->Popup;
$rotw->waitWindow;
$preview->delete;
removeFile($orig);
removeFile($new);
return $rc;
}
##############################################################
# drawHorizont
##############################################################
sub drawHorizont {
my $canvas = shift;
my $y = shift; # in percent of the canvas height
my $x = shift; # in percent of the canvas width
$canvas->delete('withtag', 'line');
$canvas->createLine( 0, $y, $canvas->width, $y,
-tags => "line",
-fill => "black",
-dash => [6,4,2,4],
);
$canvas->createLine( 0, $y, $canvas->width, $y,
-tags => "line",
-fill => "white",
-dash => [2,6,2,4],
);
$canvas->createLine( $x, 0, $x, $canvas->height,
-tags => "line",
-fill => "black",
-dash => [6,4,2,4],
);
$canvas->createLine( $x, 0, $x, $canvas->height,
-tags => "line",
-fill => "white",
-dash => [2,6,2,4],
);
}
##############################################################
# rotUpdate - update the picture in the rotateDialog with the
# new degree setting
##############################################################
sub rotUpdate {
my ($prevC, $preview, $orig, $new, $deg, $col) = @_;
return if !mycopy("$orig", "$new", OVERWRITE);
$rotw->Busy;
# some versions of mogrify need bordercolor, some background so we supply both
my $command = "mogrify -rotate $$deg -bordercolor \"$$col\" -background \"$$col\" \"$new\" ";
execute($command);
$preview->configure(-file => "$new", -gamma => $config{Gamma});
my @ids = $prevC->find('withtag', 'image');
my ($x1, $y1, $x2, $y2) = $prevC->bbox($ids[0]);
$prevC->configure(-scrollregion => [0, 0, $x2-$x1, $y2-$y1]);
$rotw->Unbusy;
}
##############################################################
# getRealFile - alters the path and file name to the real file
# if it's a link, else do nothing
# returns 1 if everything worked, else 0
##############################################################
sub getRealFile($) {
my $dirfileR = shift; # reference to a file, which may be a link
if (!-f $$dirfileR) {
warn "getRealFile: $$dirfileR is no file!";
return 0;
}
if (-l $$dirfileR) {
my $linktargetfile = getLinkTarget($$dirfileR);
if ($linktargetfile eq "") {
warn "error in getLinkTarget! ($$dirfileR)";
return 0;
}
else {
$$dirfileR = $linktargetfile;
return 1;
}
}
else { # no link, change nothing, return true
return 1;
}
}
##############################################################
# getLinkTarget - returns the file a link is pointing to
# input (directory, link) or (dirlink) where
# dirlink consists of directory and link
# works with relative and absolute links
##############################################################
sub getLinkTarget {
my ($dir, $link);
if (@_ == 2) {
$dir = shift;
$link = shift;
}
elsif (@_ == 1) {
$dir = dirname($_[0]);
$link = basename($_[0]);
}
else {
warn "getLinkTarget: wrong # of parameters!";
return "";
}
# change first to the start dir (to handle relative links)
return "" if !changeDir($dir);
my $linktargetfile = readlink $link;
my $linktargetdir = dirname $linktargetfile;
# change to link target, this should now work for relative and absolute links
return "" if !changeDir($linktargetdir);
# get the current dir
my $cwd = cwd();
$linktargetfile = $cwd."/".basename($linktargetfile);
return $linktargetfile;
}
##############################################################
# overwrite - takes two files a and b, deletes a and moves b
# to a
# the filenames must include the absolute path
##############################################################
sub overwrite($$) {
my $dpic = shift;
my $dirtpic = shift;
if (!-f $dirtpic) {
warn "overwrite: $dirtpic not created. Giving up!";
return 0;
}
if (-l $dpic) {
my $linktargetfile = getLinkTarget($dpic);
$dpic = $linktargetfile;
}
return 0 if (! removeFile($dpic) );
if (!move ("$dirtpic", "$dpic")) {
$top->Dialog(-title => "Move $dirtpic",
-text => "Couldn't move $dirtpic to $dpic: $!",
-buttons => ["Ok"])->Show();
return 0;
}
return 1;
}
##############################################################
# myEntryDialog - get a string from the user
# returns 'OK' or 'Cancel'
##############################################################
sub myEntryDialog {
my $title = shift;
my $text = shift;
my $varRef = shift; # if $$varRef contains "no-entry" no entry is displayed
my $thumbnail = shift; # optional
my $icon;
my $rc = 'Cancel';
# open window
my $myDiag = $top->Toplevel();
$myDiag->title($title);
$myDiag->iconimage($mapiviicon) if $mapiviicon;
my $f = $myDiag->Frame()->pack;
if ((defined $thumbnail) and (-f $thumbnail)) {
$icon = $top->Photo(-file => "$thumbnail", -gamma => $config{Gamma});
if ($icon) {
$f->Label(-image => $icon, -bg => $config{ColorBG}, -relief => "sunken",
)->pack(-side => "left", -fill => 'x', -padx => 3, -pady => 3);
}
}
# determine the heigt of the textbox by counting the number of lines
my $height = ($text =~ tr/\n//);
$height += 2;
$height = 50 if ($height > 50); # not to big, we have scrollbars
my $rotext = $f->Scrolled("ROText",
-scrollbars => 'osoe',
-wrap => 'word',
-tabs => '4',
-width => 70,
-height => $height,
-relief => "flat",
-bg => $config{ColorBG},
-bd => 0
)->pack(-side => "right", -fill => 'both', -expand => "1", -padx => 3, -pady => 3);
$rotext->insert('end', $text);
my $OKB;
# if $$varRef contains no-entry we create a entry dialog without a entry :)
if ($$varRef ne "no-entry") {
my $entry =
$myDiag->Entry(-textvariable => \$$varRef,
-width => 40,
)->pack(-fill => 'x', -padx => 3, -pady => 3);
if ($$varRef =~ /(.*)(\.jp(g|eg))/i) { # if it is a jpeg image name
$entry->selectionRange(0,length($1)); # select only the part before the suffix
$entry->icursor(length($1));
}
else {
$entry->selectionRange(0,'end'); # else select all
$entry->icursor('end');
}
$entry->xview('end');
$entry->bind('<Return>', sub { $OKB->invoke; } );
$entry->focus;
}
else {
$myDiag->bind('<Return>', sub { $OKB->invoke; } );
}
my $ButF = $myDiag->Frame()->pack(-fill =>'x', -padx => 3, -pady => 3);
$OKB = $ButF->Button(-text => 'OK',
-command => sub {
$rc = 'OK';
$myDiag->destroy;
})->pack(-side => 'left', -expand => 1, -fill => 'x',
-padx => 3, -pady => 3);
$OKB->focus if ($$varRef eq "no-entry");
my $XBut = $ButF->Button(-text => 'Cancel',
-command => sub {
$rc = 'Cancel';
$myDiag->destroy;
}
)->pack(-side => 'left', -expand => 1, -fill => 'x',
-padx => 3, -pady => 3);
$myDiag->bind('<Key-Escape>', sub { $XBut->invoke; });
$myDiag->Popup;
repositionWindow($myDiag);
$myDiag->waitWindow();
$icon->delete if $icon;
return $rc;
}
##############################################################
# myFontDialog - dialog to select a font family
##############################################################
sub myFontDialog {
my $widget = shift;
my $title = shift;
#my $text = shift;
my $varRef = shift; # if $$varRef contains "no-entry" no entry is displayed
my $size = shift;
my $rc = 0;
# open window
my $myDiag = $widget->Toplevel();
$myDiag->title($title);
$myDiag->iconimage($mapiviicon) if $mapiviicon;
my $listBox = $myDiag->Scrolled('Listbox',
-scrollbars => 'osoe',
-selectmode => 'single',
-exportselection => 0,
-width => 30,
#-height => 40,
)->pack(-side => 'left', -anchor => 'w', -expand => 1, -fill =>'y', -padx => 3, -pady => 3);
my $f = $myDiag->Frame()->pack(-side => 'left', -expand => 1, -anchor => 'w', -fill =>'both');
my @fontFamilies = sort $top->fontFamilies;
shift @fontFamilies unless ($fontFamilies[0]);
bindMouseWheel($listBox);
$listBox->insert('end', @fontFamilies);
foreach my $i (0 .. $#fontFamilies) {
if ($fontFamilies[$i] eq $$varRef) {
$listBox->selectionSet($i);
$listBox->see($i);
last;
}
}
my $normalText = "This is a preview Text, here you can see how the selected font will look like.\n\nThe brown fox jumps over the brigde.\n\n1 :\n12 :\n123 :\n1234 :\n12345 :\nWWWWWWW:\niiiiiii:\n\040\041\042\043\044\045\046\047\050\051\052\053\054\055\056\057\040\041\042\043\044\045\046\047\050\051\052\053\054\055\056\057\060\061\062\063\064\065\066\067\070\071\072\073\074\075\076\077\100\n\101\102\103\104\105\106\107\110\111\112\113\114\115\116\117\120\121\122\123\124\125\126\127\130\131\132\133\134\135\136\137\140\141\142\143\144\145\146\147\150\151\152\153\154\155\156\157\160\161\162\163\164\165\166\167\170\171\172\173\174\175\176\n\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\n\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\n\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377";
my $ButF = $f->Frame()->pack(-fill =>'x', -padx => 3, -pady => 3);
my $pane = $f->Scrolled('Pane', -bd => $config{Borderwidth}, -relief => 'groove', -scrollbars => 'osoe', -width => 1000)->pack(-expand => 1, -anchor => 'w', -fill => 'both', -padx => 3, -pady => 3);
my $example = $pane->Label(-text => $normalText, -bg => $config{ColorBG}, -justify => 'left')->pack(-fill => 'both', -expand => 1, -anchor => 'w');
$listBox->bind('<ButtonRelease-1>', sub {
my @sell = $listBox->curselection();
return unless @sell;
my $actfont = $fontFamilies[$sell[0]];
return unless $actfont;
$myDiag->Busy;
my $font = $top->Font(-family => $actfont,
-size => $size);
$example->configure(-font => $font);
$example->update();
$myDiag->Unbusy;
} );
$ButF->Button(-text => 'next',
-command => sub {
my @sell = $listBox->curselection();
return unless @sell;
my $index = $sell[0];
$listBox->selectionClear(0, 'end');
$index++;
$index = 0 if ($index >= @fontFamilies);
$listBox->selectionSet($index);
$listBox->see($index);
my $actfont = $fontFamilies[$index];
return unless $actfont;
$myDiag->Busy;
my $font = $top->Font(-family => $actfont,
-size => $size);
$example->configure(-font => $font);
$example->update();
$myDiag->Unbusy;
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$ButF->Button(-text => 'previous',
-command => sub {
my @sell = $listBox->curselection();
return unless @sell;
my $index = $sell[0];
$listBox->selectionClear(0, 'end');
$index--;
$index = $#fontFamilies if ($index < 0);
$listBox->selectionSet($index);
$listBox->see($index);
my $actfont = $fontFamilies[$index];
return unless $actfont;
$myDiag->Busy;
my $font = $top->Font(-family => $actfont,
-size => $size);
$example->configure(-font => $font);
$example->update();
$myDiag->Unbusy;
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
my $OKB = $ButF->Button(-text => 'OK',
-command => sub {
my @sell = $listBox->curselection();
$$varRef = $fontFamilies[$sell[0]] if @sell;
$rc = 1;
$myDiag->destroy;
})->pack(-side => 'left', -expand => 1, -fill => 'x',
-padx => 3, -pady => 3);
$myDiag->bind ('<Return>', sub { $OKB->invoke; } );
$listBox->bind('<Double-Button-1>', sub { $OKB->invoke; } );
$OKB->focus;
my $XBut = $ButF->Button(-text => 'Cancel',
-command => sub {
$rc = 0;
$myDiag->destroy;
}
)->pack(-side => 'left', -expand => 1, -fill => 'x',
-padx => 3, -pady => 3);
$myDiag->bind('<Key-Escape>', sub { $XBut->invoke; });
my $ws = 0.5;
my $w = int($ws * $myDiag->screenwidth);
my $h = int($ws * $myDiag->screenheight);
my $x = int(((1 - $ws) * $myDiag->screenwidth)/3);
my $y = int(((1 - $ws) * $myDiag->screenheight)/3);
#print "geo==${w}x${h}+${x}+${y}\n";
$myDiag->geometry("${w}x${h}+${x}+${y}");
$myDiag->Popup;
repositionWindow($myDiag);
$myDiag->waitWindow();
return $rc;
}
##############################################################
# myPicDialog - show some thumbnails and a text to the user
# returns 'OK' or content of $button
##############################################################
sub myPicDialog {
my $title = shift;
my $text = shift;
my $button = shift; # optional button, if not needed set to ""
my @thumbnails = @_;
my @icons;
my $rc = $button;
# open window
my $myDiag = $top->Toplevel();
$myDiag->title($title);
$myDiag->iconimage($mapiviicon) if $mapiviicon;
# determine the heigt of the textbox by counting the number of lines
my $height = ($text =~ tr/\n//);
$height += 2;
$height = 50 if ($height > 50); # not to big, we have scrollbars
my $rotext = $myDiag->Scrolled("ROText",
-scrollbars => 'osoe',
-wrap => 'word',
-tabs => '4',
-width => 40,
-height => $height,
-relief => "flat",
-bg => $config{ColorBG},
-bd => "0"
)->pack(-fill => 'both', -expand => "1", -padx => 3, -pady => 3);
$rotext->insert('end', $text);
my $f = $myDiag->Frame()->pack;
my $i = 0;
# insert the thumbnails
foreach (@thumbnails) {
if ((defined $_) and (-f $_)) {
$icons[$i] = $top->Photo(-file => "$_", -gamma => $config{Gamma});
if ($icons[$i]) {
$f->Label(-image => $icons[$i], -bg => $config{ColorBG}, -relief => "sunken",
)->pack(-side => "left", -anchor => "n", -fill => 'x', -padx => 3, -pady => 3);
$i++;
}
}
}
my $bf = $myDiag->Frame()->pack(-expand => 1, -fill => 'x');
my $OKB = $bf->Button(-text => 'OK', -command => sub { $rc = 'OK'; $myDiag->destroy; }
)->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$OKB->focus;
if ($button ne "") {
$bf->Button(-text => $button, -command => sub { $rc = $button; $myDiag->destroy; }
)->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
}
$myDiag->bind('<Key-Escape>', sub { $OKB->invoke; });
$myDiag->Popup;
repositionWindow($myDiag);
$myDiag->waitWindow();
foreach (@icons) { $_->delete if $_; } # free memory
return $rc;
}
##############################################################
# myButtonDialog - get a feedback from the user
# you may specify as many buttons as you like
# the return value will be the text of the button pressed
# The first one is the default button
# the last one is invoked when pressing Escape
##############################################################
sub myButtonDialog {
my $title = shift;
my $text = shift;
my $thumbnail = shift;
my @buttons = @_;
my $icon;
my $rc = "";
# open window
my $myDiag = $top->Toplevel();
$myDiag->title($title);
$myDiag->iconimage($mapiviicon) if $mapiviicon;
my $f = $myDiag->Frame()->pack(-fill => 'both', -expand => "1");
if ((defined $thumbnail) and (-f $thumbnail)) {
$icon = $top->Photo(-file => "$thumbnail", -gamma => $config{Gamma});
if ($icon) {
$f->Label(-image => $icon, -bg => $config{ColorBG}, -relief => "sunken",
)->pack(-side => "left", -fill => 'x', -padx => 3, -pady => 3);
}
}
# determine the heigt of the textbox by counting the number of lines
my $height = ($text =~ tr/\n//);
$height += 2;
$height = 50 if ($height > 50); # not to big, we have scrollbars
my $rotext = $f->Scrolled("ROText",
-scrollbars => 'osoe',
-wrap => 'word',
-tabs => '4',
-width => 80,
-height => $height,
-relief => "flat",
-bg => $config{ColorBG},
-bd => "0"
)->pack(-side => 'right', -fill => 'both', -expand => "1", -padx => 3, -pady => 3);
$rotext->insert('end', $text);
my %buts;
my $ButF = $myDiag->Frame()->pack(-fill =>'x', -padx => 3, -pady => 3);
# add the buttons
foreach (@buttons) {
my $name = $_;
$buts{$name} = $ButF->Button(-text => "$name",
-command => sub {
$rc = "$name";
})->pack(-side => 'left', -expand => 1, -fill => 'x',
-padx => 3, -pady => 3);
}
# the first button gets the focus and is invoked with return
$myDiag->bind('<Return>', sub { $buts{$buttons[0]}->invoke; } );
$buts{$buttons[0]}->focus;
# the last button is invoked with the Escape key
$myDiag->bind('<Key-Escape>', sub { $buts{$buttons[-1]}->invoke; });
$myDiag->Popup;
repositionWindow($myDiag);
$myDiag->waitVariable(\$rc);
$icon->delete if $icon;
$myDiag->destroy();
$top->focus;
return $rc;
}
##############################################################
# checkDialog - a dialog with a Checkbutton (e.g. do not show
# this again ...)
##############################################################
sub checkDialog {
my $title = shift;
my $text = shift;
my $check = shift; # var ref
my $checkT = shift; # the text for the checkbutton
my $thumbnail = shift; # !!! not optional, supply "" if there is no thumbnail to show
my @buts = @_; # the button text, this text will be returned
my $icon;
my $rc;
# open window
my $myDiag = $top->Toplevel();
$myDiag->title($title);
$myDiag->iconimage($mapiviicon) if $mapiviicon;
my $f = $myDiag->Frame()->pack;
if ((defined $thumbnail) and (-f $thumbnail)) {
$icon = $top->Photo(-file => "$thumbnail", -gamma => $config{Gamma});
if ($icon) {
$f->Label(-image => $icon, -bg => $config{ColorBG},
)->pack(-side => "left", -fill => 'x', -padx => 3, -pady => 3);
}
}
# determine the heigt of the textbox by counting the number of lines
my $height = ($text =~ tr/\n//);
$height += 2;
$height = 50 if ($height > 50); # not to big, we have scrollbars
my $rotext = $f->Scrolled("ROText",
-scrollbars => 'osoe',
-wrap => 'word',
-tabs => '4',
-width => 55,
-height => $height,
-relief => "flat",
-bg => $config{ColorBG},
-bd => "0"
)->pack(-side => "right", -fill => 'both', -expand => "1", -padx => 3, -pady => 3);
$rotext->insert('end', $text);
my $OKB;
$myDiag->Checkbutton(-variable => \$$check,
-text => $checkT,
)->pack(-fill => 'x',
-padx => 3,
-pady => 3);
my $ButF =
$myDiag->Frame()->pack(-fill =>'x',
-padx => 3,
-pady => 3);
foreach my $text (@buts) {
$ButF->Button(-text => "$text",
-command => sub {
$rc = "$text";
})->pack(-side => 'left',
-expand => 1,
-fill => 'x',
-padx => 3,
-pady => 3);
}
$myDiag->Popup;
repositionWindow($myDiag);
$myDiag->waitVariable(\$rc);
$icon->delete if $icon;
$myDiag->withdraw();
$myDiag->destroy();
return $rc;
}
##############################################################
# myTextDialog - get a text from the user
##############################################################
sub myTextDialog {
my $title = shift;
my $text = shift;
my $varRef = shift;
my $thumb = shift; # optional file name of thumbnail
my ($rc, $icon);
# open window
my $myDiag = $top->Toplevel();
#$myDiag->grab();
$myDiag->title($title);
$myDiag->iconimage($mapiviicon) if $mapiviicon;
$myDiag->Label(-text => $text, -bg => $config{ColorBG}
)->pack(-fill => 'x', -padx => 3, -pady => 3);
my $fl = $myDiag->Frame()->pack(-anchor => "n", -side => "left");
my $fm = $myDiag->Frame()->pack(-expand => 1, -fill => "both", -anchor => "n", -side => "left");
my $fr = $myDiag->Frame()->pack(-expand => 1, -fill => "both", -anchor => "n", -side => "left");
if ((defined $thumb) and (-f $thumb)) {
$icon = $myDiag->Photo(-file => "$thumb", -gamma => $config{Gamma});
if ($icon) {
$fl->Label(-image => $icon, -bg => $config{ColorBG}, -relief => "sunken",
)->pack(-padx => 1, -pady => 2);
}
}
my $topButF = $fm->Frame(-bd => $config{Borderwidth}, -relief => 'groove')->pack(-fill =>'x', -padx => 3, -pady => 3);
my $midF = $fm->Frame()->pack(-expand => 1, -fill => "both", -padx => 0, -pady => 3);
my $entry = $midF->Scrolled("Text",
-scrollbars => 'osoe',
-wrap => 'none',
-width => 65,
-height => 20,
)->pack(-side => "left", -expand => 1, -fill => "both", -padx => 3, -pady => 3);
$entry->insert('end', $$varRef);
#$entry->selectionRange(0,'end');
$entry->see('end');
$entry->markSet("insert",'end');
my $keytree = $fr->Scrolled('Tree',
-separator => '/',
-scrollbars => 'osoe',
-selectmode => 'single',
-exportselection => 0,
-width => 20,
)->pack(-expand => 1, -fill => 'both', -padx => 2, -pady => 2);
bindMouseWheel($keytree->Subwidget("scrolled"));
$balloon->attach($keytree, -msg => "Double click on a keyword to insert it.\nIt's possible to edit the keywords, use the\nright mouse button to open the edit menu.");
# try to get the saved mode
if (-f "$configdir/keywordMode") {
my $hashRef = retrieve("$configdir/keywordMode");
warn "could not retrieve mode" unless defined $hashRef;
$keytree->{m_mode} = $hashRef;
}
addTreeMenu($keytree, \@prekeys);
insertTreeList($keytree, @prekeys);
$keytree->bind("<Double-Button-1>", sub {
my @keys = $keytree->info('selection');
return unless checkSelection($myDiag, 1, 0, \@keys);
$entry->insert("insert", getLastItem($keys[0])." ");
$entry->focus;
});
my $ButF = $fm->Frame()->pack(-fill =>'x', -padx => 3, -pady => 3);
my $umlautB = $ButF->Checkbutton(-variable => \$config{ConvertUmlaut}, -text => "convert german umlaute")->pack(-side => 'left', -anchor => 'w', -padx => 3, -pady => 1);
$balloon->attach($umlautB, -msg => "Convert german umlaute (e.g. -> ae)\nUmlaute often cause problems in other tools,\nso it's saver to convert them to plain ASCII.");
my $OKB =
$ButF->Button(-text => 'OK',
-command => sub {
$$varRef = $entry->get(0.1, 'end');
trimComment($varRef);
my $len = length($$varRef);
if ($len >= $maxCommentLength) {
$top->messageBox(-icon => 'warning', -message => "Sorry your comment is too long ($len characters).\nJPEG-Comments may only be up to 64K.\nPlease shorten your comment.",
-title => "Comment to long", -type => 'OK');
return;
}
$rc = 'OK';
saveTreeMode($keytree);
store($keytree->{m_mode}, "$configdir/keywordMode") or warn "could not store $configdir/keywordMode: $!";
$myDiag->destroy();
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$balloon->attach($OKB, -msg => "You can press Control-x to close the dialog (OK button)");
# key-desc,Ctrl-x,accept text and close (in text dialog)
$myDiag->bind('<Control-x>', sub { $OKB->invoke; });
$topButF->Label(-text => "Insert ...", -bg => $config{ColorBG},
)->pack(-side => 'left', -expand => 0, -fill => 'x', -padx => 3, -pady => 3);
my $crb =
$topButF->Button(-text => "copyright",
-command => sub {
$entry->insert("insert", $config{Copyright});
})->pack(-side => 'left', -expand => 0, -fill => 'x', -padx => 3, -pady => 3);
$myDiag->bind('<Control-c>', sub { $crb->invoke; });
$topButF->Button(-text => "file name",
-command => sub {
$entry->insert("insert", basename($actpic));
})->pack(-side => 'left', -expand => 0, -fill => 'x', -padx => 3, -pady => 3);
$topButF->Button(-text => "last comment",
-command => sub {
$entry->insert("insert", $config{Comment});
})->pack(-side => 'left', -expand => 0, -fill => 'x', -padx => 3, -pady => 1);
$topButF->Button(-text => "file ...",
-command => sub {
my $fs = $myDiag->FileSelect(-title => "read comment from file",
-directory => $actdir,
-width => 30, -height => 30);
my $file = $fs->Show;
if (!defined $file) { warn "not defined"; return;}
if ($file eq "") { warn "empty"; return;};
if (!-f $file) { warn "$file is no file"; return;};
my $fileH;
if (!open($fileH, "<$file")) {
warn "Sorry, I couldn't open the file $file: $!";
return;
}
my $buffer;
read $fileH, $buffer, 32768;
close($fileH);
$entry->insert("insert", $buffer);
})->pack(-side => 'left', -expand => 0, -fill => 'x', -padx => 3, -pady => 3);
$ButF->Button(-text => 'Cancel',
-command => sub {
$rc = 'Cancel';
saveTreeMode($keytree);
store($keytree->{m_mode}, "$configdir/keywordMode") or warn "could not store $configdir/keywordMode: $!";
$myDiag->destroy();
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$entry->focus;
$myDiag->Popup(-popover => 'cursor');
repositionWindow($myDiag);
$myDiag->waitWindow;
$icon->delete if $icon;
return $rc;
}
##############################################################
# myReplaceDialog - get two strings from the user
##############################################################
sub myReplaceDialog {
my $title = shift;
my $text = shift;
my $varARef = shift;
my $varBRef = shift;
my $rc = 'Cancel';
# open window
my $win = $top->Toplevel();
#$win->grab();
$win->title($title);
$win->iconimage($mapiviicon) if $mapiviicon;
$win->Label(-text => $text, -bg => $config{ColorBG}
)->pack(-anchor=>'w', -padx => 3, -pady => 3);
my $midF = $win->Frame()->pack(-expand => 1, -fill => "both", -padx => 0, -pady => 0);
$midF->Label(-text => "Replace this:", -bg => $config{ColorBG}
)->pack(-anchor=>'w', -padx => 3, -pady => 3);
my $entryA = $midF->Scrolled("Text",
-scrollbars => 'osoe',
-wrap => 'none',
-height => 4,
-width => 80,
)->pack(-side => 'top', -expand => 1, -fill => "both", -padx => 3, -pady => 3);
$midF->Label(-text => "with that:", -bg => $config{ColorBG}
)->pack(-anchor=>'w', -padx => 3, -pady => 3);
my $entryB = $midF->Scrolled("Text",
-scrollbars => 'osoe',
-wrap => 'none',
-height => 4,
-width => 80,
)->pack(-side => 'top', -expand => 1, -fill => "both", -padx => 3, -pady => 3);
$entryA->insert('end', $$varARef);
$entryA->see('end');
$entryA->markSet("insert",'end');
$entryB->insert('end', $$varBRef);
$entryB->see('end');
$entryB->markSet("insert",'end');
my $umlautB = $win->Checkbutton(-variable => \$config{ConvertUmlaut}, -text => "convert german umlaute")->pack(-anchor => 'w', -padx => 3, -pady => 3);
$balloon->attach($umlautB, -msg => "Convert german umlaute (e.g. -> ae)\nUmlaute often cause problems in other tools,\nso it's saver to convert them to plain ASCII.");
my $ButF = $win->Frame()->pack(-fill =>'x', -padx => 0, -pady => 0);
my $OKB =
$ButF->Button(-text => 'OK',
-command => sub {
$$varARef = $entryA->get(0.1, 'end');
trimComment($varARef);
my $len = length($$varARef);
if ($len >= $maxCommentLength) {
$top->messageBox(-icon => 'warning', -message => "Sorry your comment is too long ($len characters).\nJPEG-Comments may only be up to 64K.\nPlease shorten your comment.",
-title => "Comment to long", -type => 'OK');
return;
}
$$varBRef = $entryB->get(0.1, 'end');
trimComment($varBRef);
$len = length($$varBRef);
if ($len >= $maxCommentLength) {
$top->messageBox(-icon => 'warning', -message => "Sorry your comment is too long ($len characters).\nJPEG-Comments may only be up to 64K.\nPlease shorten your comment.",
-title => "Comment to long", -type => 'OK');
return;
}
$rc = 'OK';
$win->withdraw();
$win->destroy();
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$balloon->attach($OKB, -msg => "You can press Control-x to close the dialog (OK button)");
$ButF->Button(-text => "Test",
-command => sub {
$$varARef = $entryA->get(0.1, 'end');
trimComment($varARef);
my $len = length($$varARef);
if ($len >= $maxCommentLength) {
$top->messageBox(-icon => 'warning', -message => "Sorry your comment is too long ($len characters).\nJPEG-Comments may only be up to 64K.\nPlease shorten your comment.",
-title => "Comment to long", -type => 'OK');
return;
}
$$varBRef = $entryB->get(0.1, 'end');
trimComment($varBRef);
$len = length($$varBRef);
if ($len >= $maxCommentLength) {
$top->messageBox(-icon => 'warning', -message => "Sorry your comment is too long ($len characters).\nJPEG-Comments may only be up to 64K.\nPlease shorten your comment.",
-title => "Comment to long", -type => 'OK');
return;
}
$rc = "Test";
$win->withdraw();
$win->destroy();
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$win->bind('<Control-x>', sub { $OKB->invoke; });
$ButF->Button(-text => 'Cancel',
-command => sub {
$rc = 'Cancel';
$win->withdraw();
$win->destroy();
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$entryA->focus;
$win->Popup(-popover => 'cursor');
repositionWindow($win);
$win->waitWindow;
return $rc;
}
##############################################################
# trimComment
##############################################################
sub trimComment {
my $comRef = shift;
$$comRef =~ s/\n*$//; # remove trailing newlines
$$comRef =~ s/\r*//g; # remove \r (carriage return)
#$$comRef =~ s/"/\\"/g; # replace " with \"
$$comRef =~ s/\"/\'/g; # replace " with '
}
##############################################################
# mySelListBoxDialog - let the user select some items of the
# given list
##############################################################
sub mySelListBoxDialog {
my $title = shift;
my $text = shift;
my $OKBut = shift;
my $sellist = shift; # output list (list reference) - the list with the selected items
my @list = @_; # input list - the list to choose from
my $rc = 0;
# open window
my $myDiag = $top->Toplevel();
$myDiag->title($title);
$myDiag->iconimage($mapiviicon) if $mapiviicon;
$myDiag->Label(-anchor => 'w', -justify => "left", -text => $text, -bg => $config{ColorBG})->pack(-fill => 'x', -padx => 3, -pady => 3);
my $listBoxY = @list;
$listBoxY = 30 if ($listBoxY > 30); # not higher than 30 entries
my $listBox =
$myDiag->Scrolled('Listbox',
-scrollbars => 'osoe',
-selectmode => 'extended',
-exportselection => 0,
-width => 80,
-height => $listBoxY,
)->pack(-expand => 1, -fill =>'both', -padx => 3, -pady => 3);
bindMouseWheel($listBox);
$listBox->insert('end', @list);
$listBox->bind('<Double-Button-1>', sub {
@$sellist = $listBox->curselection();
$rc = 1;
} );
my $ubutF = $myDiag->Frame()->pack(-fill =>'x', -padx => 3, -pady => 3);
$ubutF->Button(-text => 'Select all',
-command => sub {
$listBox->selectionSet(0, 'end');
})->pack(-side => 'left', -padx => 3, -pady => 3);
$ubutF->Button(-text => 'Select none',
-command => sub {
$listBox->selectionClear(0, 'end');
})->pack(-side => 'left', -padx => 3, -pady => 3);
my $ButF = $myDiag->Frame()->pack(-fill =>'x', -padx => 3, -pady => 3);
my $OKB =
$ButF->Button(-text => $OKBut,
-command => sub {
@$sellist = $listBox->curselection();
$rc = 1;
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$OKB->bind('<Return>', sub { $OKB->invoke; } );
$ButF->Button(-text => 'Cancel',
-command => sub { $rc = 0; }
)->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$myDiag->Popup;
if ($EvilOS) { # sometimes to dialog disappears when clicked on, so we need a short grab
$myDiag->grab;
$myDiag->after(50, sub{$myDiag->grabRelease});
}
$OKB->focus;
$myDiag->waitVariable(\$rc);
$myDiag->destroy() if Tk::Exists($myDiag);
return $rc;
}
##############################################################
# createDirMenu
##############################################################
sub createDirMenu {
$dirMenu =
$top->Menu(-title => "Directory Menu");
}
##############################################################
# createDirMenu
##############################################################
sub updateDirMenu {
return if (!defined($dirMenu));
# clear dir menu
$dirMenu->delete(0, 'end');
$dirMenu->command(-label => "open directory ...", -command => sub {
my $dir = getRightDir();
openDirPost($dir);}, -accelerator => "double click");
$dirMenu->command(-label => "preview directory ...", -command => sub {
my $dir = getRightDir();
my @list = getPics($dir, WITH_PATH);
sortPics($config{SortBy}, $config{SortReverse}, \@list);
showThumbList(\@list, $dir); }, -accelerator => "middle click");
$dirMenu->command(-label => "search in directory ...", -command => sub {
my $tmp = $config{SearchOnlyInDir}; # save search mode
$config{SearchOnlyInDir} = 1; # set to local search
searchMetaInfo();
$config{SearchOnlyInDir} = $tmp; # restore search mode
});
my $dir_size = $dirMenu->cascade(-label => 'directory size');
$dir_size->command(-label => "calculate directory size ...", -command => sub { calcDirSize(); } );
$dir_size->command(-label => "display directory sizes (graphic) ...", -command => sub { showDirSizes(getRightDir()); } );
$dirMenu->separator;
$dirMenu->command(-label => "rename directory ...", -command => sub { renameDir(); });
$dirMenu->command(-label => "new directory ...", -command => sub {
my $dir = getRightDir();
if (!-d $dir) { warn "dir $dir is no dir"; return; }
makeNewDir($dir, $dirtree); });
$dirMenu->command(-label => "delete directory ...", -command => sub { deleteDir(); });
$dirMenu->separator;
my $dir_hot = $dirMenu->cascade(-label => 'directory hotlist');
$dir_hot->command(-label => "add to hotlist", -command => sub {
my $dir = getRightDir();
my $max = 0;
foreach (sort {$dirHotlist{$b} <=> $dirHotlist{$a}} keys %dirHotlist) {
$max = $dirHotlist{$_};
last;
}
$dirHotlist{$dir} = $max;
$userinfo = "added $dir to hotlist!"; $userInfoL->update;
updateDirMenu();
});
$dir_hot->command(-label => "remove from hotlist", -command => sub {
my $dir = getRightDir();
delete $dirHotlist{$dir} if (defined($dirHotlist{$dir}));
$userinfo = "removed $dir from hotlist!"; $userInfoL->update;
updateDirMenu();
});
my $i = 0;
# add the 12 most wanted hotlist directories :)
my @dirlist;
foreach (sort {$dirHotlist{$b} <=> $dirHotlist{$a}} keys %dirHotlist) {
# remove deleted dirs
if (!-d $_) {
delete $dirHotlist{$_};
next; # skip
}
next if ($_ eq $trashdir);
$i++;
push @dirlist, $_;
last if ($i > 11);
}
foreach (sort @dirlist) {
my $dir = $_; # we need a local copy
# this will add the number of accesses of the directory
#$dirMenu->command(-label => "$_", -command => sub { openDirPost($dir); }, -accelerator => "($dirHotlist{$_})");
$dirMenu->command(-label => "$_", -command => sub { openDirPost($dir); });
}
$dirMenu->separator;
# add the last used directories
foreach (reverse @dirHist) {
next if (!-d $_);
my $dir = $_; # we need a local copy
$dirMenu->command(-label => "$dir", -command => sub { openDirPost($dir); });
}
}
##############################################################
# createThumbMenu
##############################################################
sub createThumbMenu {
$thumbMenu =
$top->Menu(-title => "Thumbnail Menu");
addSelectMenu($thumbMenu);
$thumbMenu->separator;
addFileActionsMenu($thumbMenu, $picLB);
$thumbMenu->separator;
addPicProcessing($thumbMenu);
$thumbMenu->separator;
addMetaInfoMenu($thumbMenu);
$thumbMenu->separator;
$thumbMenu->command(-label => "rescan directory", -command => \&updateThumbsPlus, -accelerator => "<u>");
$thumbMenu->command(-label => "rebuild thumbs ...", -command => \&rebuildThumbs, -accelerator => "<Ctrl-r>");
$thumbMenu->command(-label => "add to light table", -command => sub {light_table_add_from_lb($picLB);}, -accelerator => "<Ctrl-l>");
}
##############################################################
# createPicMenu
##############################################################
sub createPicMenu {
$picMenu = $top->Menu(-title => "Picture Menu");
$picMenu->command(-label => "reload picture", -command => \&reloadPic );
$picMenu->command(-label => "show picture in new window", -command => \&showPicInOwnWin, -accelerator => "<d>" );
$picMenu->separator;
addPicProcessing($picMenu);
$picMenu->separator;
addZoomMenu($picMenu);
$picMenu->separator;
$picMenu->command(-label => "options ...", -command => \&options, -accelerator => "<Ctrl-o>");
$picMenu->command(-label => "switch layout", -command => sub { $config{Layout}++; layout(1); } );
$picMenu->command(-label => "toggle fullscreen mode", -command => sub { topFullScreen(); } );
}
##############################################################
# createMenubar
##############################################################
sub createMenubar {
$menubar = $top->Menu;
my $file_menu = $menubar->cascade(-label => "File"); # use "~File" for key shortcut
$file_menu->cget(-menu)->configure(-title => "File menu");
my $edit_menu = $menubar->cascade(-label => "Edit");
$edit_menu->cget(-menu)->configure(-title => "Edit menu");
my $view_menu = $menubar->cascade(-label => "View");
$view_menu->cget(-menu)->configure(-title => "View menu");
my $sort_menu = $menubar->cascade(-label => "Sort");
$sort_menu->cget(-menu)->configure(-title => "Sort menu");
my $find_menu = $menubar->cascade(-label => "Search");
$find_menu->cget(-menu)->configure(-title => "Search menu");
my $opti_menu = $menubar->cascade(-label => "Options");
$opti_menu->cget(-menu)->configure(-title => "Options menu");
my $extr_menu = $menubar->cascade(-label => "Extra");
$extr_menu->cget(-menu)->configure(-title => "Extra menu");
my $plug_menu = $menubar->cascade(-label => "PlugIns");
$plug_menu->cget(-menu)->configure(-title => "PlugIn menu");
my $help_menu = $menubar->cascade(-label => "Help");
$help_menu->cget(-menu)->configure(-title => "Help menu");
$file_menu->command(-label => "open directory ...", -command => \&openDir, -accelerator => "<o>");
$file_menu->command(-label => "preview directory ...", -command => sub {
my $dir = getRightDir();
my @list = getPics($dir, WITH_PATH);
sortPics($config{SortBy}, $config{SortReverse}, \@list);
showThumbList(\@list, $dir); }, -accelerator => "middle click");
$file_menu->command(-label => "search in directory ...", -command => sub {
my $tmp = $config{SearchOnlyInDir}; # save search mode
$config{SearchOnlyInDir} = 1; # set to local search
searchMetaInfo();
$config{SearchOnlyInDir} = $tmp; # restore search mode
});
my $dir_size = $file_menu->cascade(-label => 'directory size ...');
$dir_size->command(-label => "calculate directory size ...", -command => sub { calcDirSize(); } );
$dir_size->command(-label => "display directory sizes (graphic) ...", -command => sub { showDirSizes(getRightDir()); } );
$file_menu->separator;
$file_menu->command(-label => "rename directory ...", -command => \&renameDir);
$file_menu->command(-label => "new directory ...", -command => sub {
my $dir = getRightDir();
if (!-d $dir) { warn "dir $dir is no dir"; return; }
makeNewDir($dir, $dirtree); } );
$file_menu->command(-label => "delete directory ...", -command => \&deleteDir);
$file_menu->command(-label => "hot directories ...", -command => sub {
$dirMenu->Popup(-popover => "cursor", -popanchor => "nw");
}, , -accelerator => "<h>");
$file_menu->separator;
addFileActionsMenu($file_menu, $picLB);
$file_menu->separator;
my $trash_menu = $file_menu->cascade(-label => "trash");
$trash_menu->command(-label => "empty trash ...", -command => \&emptyTrash);
$trash_menu->command(-label => "open trash in main window", -command => [\&openDirPost, $trashdir]);
$file_menu->command(-label => "directory checklist ...", -command => sub { showDirProperties(); } );
$file_menu->command(-label => "import wizard ...", -command => \&importWizard);
$file_menu->separator;
$file_menu->command(-label => "light table (slideshow) ...", -command => \&light_table_open_window);
$file_menu->command(-label => "convert non-JPEG pictures ...", -command => \&convertNonJPEGS);
$file_menu->command(-label => "rescan directory", -accelerator => "<u>",
-command => \&updateThumbsPlus);
$file_menu->command(-label => "rebuild thumbs ...", -command => \&rebuildThumbs, -accelerator => "<Ctrl-r>");
$file_menu->command(-label => "build thumbs ...", -command => \&buildThumbsRecursive);
$file_menu->separator;
$file_menu->command(-label => "iconify", -accelerator => "<ESC>", -command => sub { $top->iconify; });
$file_menu->command(-label => "restart", -command => \&restart) unless ($EvilOS);
$file_menu->command(-label => "quit", -accelerator => "<q>", -command => \&quitMain);
addSelectMenu($edit_menu);
$edit_menu->separator;
addPicProcessing($edit_menu);
$edit_menu->separator;
$edit_menu->command(-label => "search ...", -command => \&searchMetaInfo, -accelerator => "<Ctrl-s>");
$edit_menu->separator;
# add the comments, EXIF and IPTC menu
addMetaInfoMenu($edit_menu);
$view_menu->command(-label => "next", -command => sub {
return if (stillBusy()); # block, until last picture is loaded
if ($slideshow == 1) {
$slideshow = 0; slideshow();
} # switch slideshow off
showPic(nextPic($actpic));
}, -accelerator => "<Space>");
$view_menu->command(-label => "previous", -command => sub {
return if (stillBusy()); # block, until last picture is loaded
if ($slideshow == 1) {
$slideshow = 0; slideshow();
} # switch slideshow off
showPic(prevPic($actpic));},
-accelerator => "<BackSpace>");
$view_menu->separator;
$view_menu->command(-label => "first", -command => sub {
return if (stillBusy()); # block, until last picture is loaded
if ($slideshow == 1) { $slideshow = 0; slideshow(); } # switch slideshow off
my @childs = $picLB->info('children');
return unless (@childs);
showPic($childs[0]); },
-accelerator => "<Home>");
$view_menu->command(-label => "last", -command => sub {
return if (stillBusy()); # block, until last picture is loaded
if ($slideshow == 1) {
$slideshow = 0; slideshow();
} # switch slideshow off
my @childs = $picLB->info('children');
return unless (@childs);
showPic($childs[-1]);
},
-accelerator => "<End>");
$view_menu->separator;
$view_menu->command(-label => "go to/select ...", -command => sub { gotoPic($picLB); },
-accelerator => "<Ctrl-g>");
$view_menu->separator;
addZoomMenu($view_menu);
$view_menu->separator;
$view_menu->checkbutton(-variable => \$config{ShowCoordinates}, -label => "display mouse coordinates");
$view_menu->separator;
$view_menu->command(-label => "open picture in new window", -command => \&showPicInOwnWin, -accelerator => "<d>");
$view_menu->command(-label => "open picture in external viewer", -command => sub{openPicInViewer($picLB);}, -accelerator => "<v>");
$view_menu->command(-label => "show infos about picture", -command => \&identifyPic);
$view_menu->command(-label => "show histogram (ImageMagick)", -command => sub { showHistogram($picLB); } );
$view_menu->command(-label => "show histogram (builtin)", -command => sub { showHistogram2($picLB); } );
$view_menu->command(-label => "show JPEG segments", -command => \&showSegments);
$view_menu->command(-label => "start/stop slideshow", -command => sub {
if ($slideshow == 0) {
$slideshow = 1;
} else {
$slideshow = 0;
}
slideshow();
}, -accelerator => "<s>");
$view_menu->command(-label => "use actual picture as desktop background",
-command => \&setBackground);
$view_menu->command(-label => "smart update",
-command => sub { smart_update(); });
$sort_menu->radiobutton(-label => "file name", -variable => \$config{SortBy}, -value => "name", -command => sub { updateThumbsPlus(); });
$sort_menu->radiobutton(-label => "file date", -variable => \$config{SortBy}, -value => "date", -command => \&updateThumbsPlus);
$sort_menu->radiobutton(-label => "file size", -variable => \$config{SortBy}, -value => "size", -command => \&updateThumbsPlus);
$sort_menu->separator;
$sort_menu->radiobutton(-label => "IPTC urgency/rating", -variable => \$config{SortBy}, -value => "urgency", -command => \&updateThumbsPlus);
$sort_menu->radiobutton(-label => "IPTC by-line", -variable => \$config{SortBy}, -value => "byline", -command => \&updateThumbsPlus);
$sort_menu->separator;
$sort_menu->radiobutton(-label => "number of views", -variable => \$config{SortBy}, -value => "popularity", -command => \&updateThumbsPlus);
$sort_menu->radiobutton(-label => "number of pixels", -variable => \$config{SortBy}, -value => "pixel", -command => \&updateThumbsPlus);
$sort_menu->radiobutton(-label => "number of bits per pixels (b/p)", -variable => \$config{SortBy}, -value => "bitpix", -command => \&updateThumbsPlus) if ($config{BitsPixel});
$sort_menu->separator;
$sort_menu->radiobutton(-label => "EXIF date", -variable => \$config{SortBy}, -value => "exifdate", -command => \&updateThumbsPlus);
$sort_menu->radiobutton(-label => "EXIF aperture", -variable => \$config{SortBy}, -value => "aperture", -command => \&updateThumbsPlus);
$sort_menu->radiobutton(-label => "EXIF exposure time", -variable => \$config{SortBy}, -value => "exposuretime", -command => \&updateThumbsPlus);
$sort_menu->radiobutton(-label => "EXIF camera maker/model", -variable => \$config{SortBy}, -value => "model", -command => \&updateThumbsPlus);
$sort_menu->radiobutton(-label => "EXIF artist", -variable => \$config{SortBy}, -value => "artist", -command => \&updateThumbsPlus);
$sort_menu->separator;
$sort_menu->radiobutton(-label => "sort randomly", -variable => \$config{SortBy}, -value => "random", -command => \&updateThumbsPlus);
$sort_menu->separator;
$sort_menu->checkbutton(-label => "sort reverse", -variable => \$config{SortReverse}, -command => \&updateThumbsPlus);
#my $data_menu = $extr_menu->cascade(-label => "Search database");
#$data_menu->cget(-menu)->configure(-title => "Search database");
$find_menu->command(-label => "search ...", -command => \&searchMetaInfo, -accelerator => "<Ctrl-s>");
$find_menu->command(-label => "search for file name ...", -command => sub { searchFileName($picLB);});
$find_menu->command(-label => "search duplicates ...", -command => \&findDups);
$find_menu->separator;
$find_menu->command(-label => "add to database ...", -command => \&buildDatabase);
$find_menu->command(-label => "clean database ...", -command => \&cleanDatabase);
$find_menu->command(-label => "check database ...", -command => \&checkDatabase);
$find_menu->command(-label => "edit database ...", -command => \&editDatabase);
$find_menu->separator;
$find_menu->command(-label => "browse database by timeline ...", -command => \&database_info);
$find_menu->command(-label => "browse database by keywords ...", -command => \&keyword_browse);
#$find_menu->command(-label => "check for new keywords ...", -command => \&check_new_keywords);
$opti_menu->command(-label => "options ...", -command => \&options, -accelerator => "<Ctrl-o>");
$opti_menu->command(-label => "save options", -command => \&saveAllConfig);
$opti_menu->separator;
$opti_menu->checkbutton(-label => "show picture", -variable => \$config{ShowPic},
-command => sub { showPic($actpic); });
$opti_menu->checkbutton(-label => "show menu bar", -variable => \$config{ShowMenu},
-command => \&showHideFrames);
$opti_menu->separator;
$opti_menu->radiobutton(-label => "thumbnail caption: none", -variable => \$config{ThumbCapt}, -value => "none", -command => sub { updateThumbsPlus(); });
$opti_menu->radiobutton(-label => "thumbnail caption: file name without suffix", -variable => \$config{ThumbCapt}, -value => "filename", -command => sub { updateThumbsPlus(); });
$opti_menu->radiobutton(-label => "thumbnail caption: file name with suffix", -variable => \$config{ThumbCapt}, -value => "filenameSuffix", -command => sub { updateThumbsPlus(); });
$opti_menu->radiobutton(-label => "thumbnail caption: IPTC object name", -variable => \$config{ThumbCapt}, -value => "objectname", -command => sub { updateThumbsPlus(); });
$opti_menu->separator;
$opti_menu->checkbutton(-label => "show file info", -variable => \$config{ShowFile}, -command => \&toggleHeaders);
$opti_menu->checkbutton(-label => "show IPTC/IIM", -variable => \$config{ShowIPTC}, -command => \&toggleHeaders);
$opti_menu->checkbutton(-label => "show comments", -variable => \$config{ShowComment}, -command => \&toggleHeaders);
$opti_menu->checkbutton(-label => "show EXIF", -variable => \$config{ShowEXIF}, -command => \&toggleHeaders);
$opti_menu->checkbutton(-label => "show folder", -variable => \$config{ShowDirectory}, -command => \&toggleHeaders);
$opti_menu->separator;
$opti_menu->command(-label => "switch layout", -command => sub { $config{Layout}++; layout(1); }, -accelerator => "<l>");
$extr_menu->command(-label => "export filelist ...", -command => \&exportFilelist);
$extr_menu->command(-label => "diff directories ...", -command => sub { dirDiffWindow(); } );
$extr_menu->command(-label => "show window list ...", -command => \&showWindowList, -accelerator => "<w>");
$extr_menu->separator;
$extr_menu->command(-label => "montage/index print ...", -command => sub { my @pics = getSelection($picLB); indexPrint(\@pics); });
$extr_menu->command(-label => "interpolate dead pixels ...", -command => \&interpolatePics);
$extr_menu->command(-label => "add fuzzy border ...", -command => \&fuzzyBorder);
$extr_menu->command(-label => "add lossless border ...", -command => \&losslessBorder);
$extr_menu->command(-label => "build difference picture", -command => \&diffPics);
$extr_menu->command(-label => "make screenshot ...", -command => \&screenshot);
$extr_menu->separator;
$extr_menu->command(-label => "build thumbnails database ...", -command => \&buildThumbsRecursive);
$extr_menu->command(-label => "clean thumbnail database ...", -command => sub { cleanThumbDB(); } );
$extr_menu->command(-label => "clean directory ...", -command => sub { cleanDir($actdir); } );
$extr_menu->command(-label => "edit entry history ...", -command => sub { editEntryHistory(); } );
# just an experiment:
#$extr_menu->separator;
#$extr_menu->command(-label => "show picture view list", -command => sub { showPicViewList(); });
$extr_menu->separator;
$extr_menu->command(-label => "mapivi test suite", -command => \&testSuite);
$extr_menu->separator;
$extr_menu->command(-label => "show TOP50 of most popular pictures", -command => \&showMostPopularPics);
makePlugInsMenu($plug_menu);
$help_menu->command(-label => "About", -command => \&about);
$help_menu->command(-label => "Keys", -command => \&showkeys);
$help_menu->command(-label => "Tips", -command => sub { showFile("$configdir/Tips.txt") }) if (-f "$configdir/Tips.txt");
$help_menu->command(-label => "System infos", -command => \&systemInfo);
$help_menu->command(-label => "License", -command => [\&showFile, "$configdir/License.txt"]) if (-f "$configdir/License.txt");
$help_menu->command(-label => "History", -command => [\&showFile, "$configdir/Changes.txt"]) if (-f "$configdir/Changes.txt");
$help_menu->command(-label => "FAQ", -command => [\&showFile, "$configdir/FAQ"]) if (-f "$configdir/FAQ");
$top->configure(-menu => $menubar) if $config{ShowMenu};
}
##############################################################
# addPicProcessing
##############################################################
sub addPicProcessing {
my $menu = shift;
my $rot_menu = $menu->cascade(-label => "rotate (clockwise) ...");
$rot_menu->cget(-menu)->configure(-title => "rotation menu");
$rot_menu->command(-label => "rotate 90 - right (lossless)", -command => [\&rotate, 90], -accelerator => "<9>");
$rot_menu->command(-label => "rotate 180 (lossless)", -command => [\&rotate, 180], -accelerator => "<8>");
$rot_menu->command(-label => "rotate 270 - left (lossless)", -command => [\&rotate, 270], -accelerator => "<7>");
$rot_menu->command(-label => "flip horizontal (lossless)", -command => [\&rotate, "horizontal"]);
$rot_menu->command(-label => "flip vertical (lossless)", -command => [\&rotate, "vertical"]);
$rot_menu->command(-label => "auto rotate (lossless)", -command => [\&rotate, "auto"], -accelerator => "<0>");
$rot_menu->command(-label => "clear rotate flag (lossless)", -command => [\&rotate, "clear"]);
$rot_menu->command(-label => "rotate ...", -command => [\&rotateAny]);
$menu->command(-label => "change size/quality ...", -command => \&changeSizeQuality, -accelerator => "<Ctrl-q>" );
$menu->command(-label => "crop (lossless) ...", -command => sub { crop($picLB); }, -accelerator => "<Ctrl-c>");
$menu->command(-label => "image processing ...", -command => \&filterPic, -accelerator => "<Ctrl-f>");
$menu->command(-label => "make grayscale ...", -command => sub { grayscalePic($picLB); } );
$menu->command(-label => "add border or copyright ...", -command => \&addDecoration, -accelerator => "<Ctrl-b>");
$menu->command(-label => "edit in GIMP", -command => \&GIMPedit, -accelerator => "<Ctrl-e>") unless ($exprogs{"gimp-remote"} or $exprogs{"gimp-win-remote"});
}
##############################################################
# addFileActionsMenu
##############################################################
sub addFileActionsMenu {
my $menu = shift;
my $lb = shift;
my $fop_menu = $menu->cascade(-label => "file operations ...");
$fop_menu->command(-label => "copy to ...", -command => sub { copyPicsDialog(COPY, $lb); } );
$fop_menu->command(-label => "link to ...", -command => \&linkPicsDialog) if (!$EvilOS);
$fop_menu->command(-label => "move to ...", -command => sub { movePicsDialog($lb); } );
$fop_menu->command(-label => "send to ...", -command => sub { sendTo($lb); } );
$fop_menu->command(-label => "convert ...", -command => sub { convertPics($lb); } );
$fop_menu->command(-label => "copy to print ...", -command => sub { copyToPrint($lb); }, -accelerator => "<Ctrl-p>");
$fop_menu->command(-label => "rename ...", -command => sub { renamePic($lb); }, -accelerator => "<r>");
$fop_menu->command(-label => "smart rename ...", -command => sub { renameSmart($lb); }, -accelerator => "<R>");
$fop_menu->command(-label => "make backup", -command => sub { copyPicsDialog(BACKUP, $lb); } );
$fop_menu->command(-label => "make HTML ...", -command => sub { makeHTML($lb); });
$fop_menu->separator;
$fop_menu->command(-label => "delete to trash", -accelerator => "<Delete>",
-command => sub { deletePics($lb, TRASH); } );
$fop_menu->command(-label => "delete ...", -accelerator => "<Shift-Delete>",
-command => sub { deletePics($lb, REMOVE); } );
}
##############################################################
# addSelectMenu
##############################################################
sub addSelectMenu {
my $menu = shift;
my $sel_menu = $menu->cascade(-label => "select ...");
$sel_menu->command(-label => "select all", -accelerator => "<Ctrl-a>", -command => sub {selectAll($picLB);} );
$sel_menu->command(-label => "select all backups", -command => \&selectBak );
$sel_menu->command(-label => "invert selection", -command => \&selectInv );
$sel_menu->command(-label => "redo selection", -command => sub { $picLB->selectionClear(); reselect($picLB, @savedselection2); } );
}
##############################################################
# addZoomMenu
##############################################################
sub addZoomMenu {
my $menu = shift;
$menu->checkbutton(-label => "Auto zoom", -variable => \$config{AutoZoom});
my $zoom_menu = $menu->cascade(-label => "Zoom level ...");
$zoom_menu->cget(-menu)->configure(-title => "Zoom menu");
$zoom_menu->command(-label => "fit",
-command => sub { fitPicture(); },
-accelerator => "<f>");
my $i;
for ($i = 0; $i < (@frac); $i += 2) {
my $z = $frac[$i];
my $s = $frac[$i+1];
my $l = sprintf "%4d%%",($z/$s*100);
unless ($l =~ m/\w*100%/) {
$zoom_menu->command(-label => $l,
-command => sub { zoom($z, $s); } );
}
else {
$zoom_menu->command(-label => $l,
-command => sub { zoom($z, $s); },
-accelerator => "<z>");
}
}
}
##############################################################
# addMetaInfoMenu
##############################################################
sub addMetaInfoMenu {
my $menu = shift;
my $iptc_menu = $menu->cascade(-label => "IPTC/IIM info");
$iptc_menu->cget(-menu)->configure(-title => "IPTC/IIM menu");
$iptc_menu->command(-label => "show", -command => sub { displayIPTCData($picLB); }, -accelerator => "<i>");
$iptc_menu->command(-label => "edit ...", -command => sub { editIPTC($picLB); }, -accelerator => "<Ctrl-i>");
$iptc_menu->command(-label => "remove ...", -command => \&removeIPTC);
$iptc_menu->separator;
$iptc_menu->command(-label => "copy from ...", -command => \©IPTC);
$iptc_menu->command(-label => "copy to ...", -command => \&pasteIPTC);
$iptc_menu->separator;
$iptc_menu->command(-label => "add/remove keywords ...", -command => sub { editIPTCKeywords($picLB); }, -accelerator => '<Ctrl-k>');
$iptc_menu->command(-label => "add/remove categories ...", -command => sub { editIPTCCategories($picLB); } , -accelerator => '<Ctrl-t>');
$iptc_menu->separator;
$iptc_menu->command(-label => "save template ...", -command => \&saveIPTC);
$iptc_menu->command(-label => "merge template ...", -command => \&mergeIPTC);
$iptc_menu->separator;
addRatingMenu($iptc_menu, $picLB);
addRatingMenu($menu, $picLB);
my $exif_menu = $menu->cascade(-label => "EXIF info");
$exif_menu->cget(-menu)->configure(-title => "EXIF menu");
$exif_menu->command(-label => "show info", -command => sub { displayEXIFData($picLB); }, -accelerator => "<x>");
$exif_menu->command(-label => "show thumbnail", -command => \&showEXIFThumb, -accelerator => "<t>");
$exif_menu->command(-label => "save thumbnail ...", -command => \&getEXIFThumb);
$exif_menu->command(-label => "(re)build thumbnail ...", -command => \&buildEXIFThumb);
$exif_menu->separator;
$exif_menu->command(-label => "copy from", -command => [\©EXIFData, "from"]);
$exif_menu->command(-label => "copy to ...", -command => [\©EXIFData, "to"]);
$exif_menu->command(-label => "copy thumbnail to ...", -command => \©Thumbnail);
$exif_menu->separator;
$exif_menu->command(-label => "save", -command => \&EXIFsave);
$exif_menu->command(-label => "restore ...", -command => \&EXIFrestore);
$exif_menu->command(-label => "remove saved info ...", -command => \&EXIFremoveSaved);
$exif_menu->separator;
$exif_menu->command(-label => "set date/time ...", -command => \&setEXIFDate);
$exif_menu->separator;
$exif_menu->command(-label => "remove thumbnail ...", -command => [\&removeEXIFData, "thumb"]);
$exif_menu->command(-label => "remove all ...", -command => [\&removeEXIFData, "all"]);
my $comm_menu = $menu->cascade(-label => "Comments");
$comm_menu->cget(-menu)->configure(-title => "Comment menu");
$comm_menu->command(-label => "show ...", -command => \&showComment, -accelerator => "<c>");
$comm_menu->separator;
$comm_menu->command(-label => "add ...", -command => sub{ addComment($picLB); }, -accelerator => "<a>");
$comm_menu->command(-label => "edit ...", -command => sub{ editComment($picLB); }, -accelerator => "<e>");
$comm_menu->command(-label => "join ...", -command => sub { joinComments(ASK); } );
$comm_menu->command(-label => "search/replace ...", -command => sub{ replaceComment($picLB); } );
$comm_menu->command(-label => 'add/remove keywords ...', -command => sub { editCommentKeywords($picLB); } );
$comm_menu->separator;
$comm_menu->command(-label => "remove ...", -command => \&removeComment);
$comm_menu->command(-label => "remove all ...", -command => sub { removeAllComments(ASK); } );
$comm_menu->separator;
$comm_menu->command(-label => "copy from", -command => [\©Comment, "from"]);
$comm_menu->command(-label => "copy to ...", -command => [\©Comment, "to"]);
$comm_menu->separator;
$comm_menu->command(-label => "add filename as comment ...", -command => [\&nameToComment, "to"]);
}
##############################################################
# addRatingMenu
##############################################################
sub addRatingMenu {
my $menu = shift;
my $widget = shift; # e.g. $picLB
my $iptc_urge = $menu->cascade(-label => "rating (IPTC urgency)");
$iptc_urge->cget(-menu)->configure(-title => "rating (IPTC urgency)");
$iptc_urge->command(-label => "******** (1 high)", -command => sub { setIPTCurgency($widget, 1); }, -accelerator => "<Ctrl-F1>");
$iptc_urge->command(-label => "******* (2)", -command => sub { setIPTCurgency($widget, 2); }, -accelerator => "<Ctrl-F2>");
$iptc_urge->command(-label => "****** (3)", -command => sub { setIPTCurgency($widget, 3); }, -accelerator => "<Ctrl-F3>");
$iptc_urge->command(-label => "***** (4)", -command => sub { setIPTCurgency($widget, 4); }, -accelerator => "<Ctrl-F4>");
$iptc_urge->command(-label => "**** (5 normal)", -command => sub { setIPTCurgency($widget, 5); }, -accelerator => "<Ctrl-F5>");
$iptc_urge->command(-label => "*** (6)", -command => sub { setIPTCurgency($widget, 6); }, -accelerator => "<Ctrl-F6>");
$iptc_urge->command(-label => "** (7)", -command => sub { setIPTCurgency($widget, 7); }, -accelerator => "<Ctrl-F7>");
$iptc_urge->command(-label => "* (8 low)", -command => sub { setIPTCurgency($widget, 8); }, -accelerator => "<Ctrl-F8>");
$iptc_urge->command(-label => "- (0 none)", -command => sub { setIPTCurgency($widget, 0); }, -accelerator => "<Ctrl-F9>");
$iptc_urge->command(-label => "remove rating", -command => sub { setIPTCurgency($widget, 9); }, -accelerator => "<Ctrl-F10>");
}
##############################################################
# makePlugInsMenu
##############################################################
sub makePlugInsMenu {
my $menu = shift;
my @plugins = getFiles($plugindir);
my $file;
foreach my $plugin (@plugins) {
if ($plugin =~ m/.*\.txt$/) { # process just the describtions
if (!open($file, "<$plugindir/$plugin")) {
warn "read plugin desc: Couldn't open $plugin: $!";
next;
}
while (<$file>) {
chomp; # no newline
s/^#.*//; # no comments (lines starting with #)
s/^\s+//; # no leading white
s/\s+$//; # no trailing white
next unless length; # anything left?
my ($prog, $menuitem, $update, $desc) = split(/\s\+\s/, $_, 4);
print "plugin: -$prog-$menuitem-$update-$desc-\n" if $verbose;
if (!-f "$plugindir/$prog") { # look for the corresponding plugin
warn "warning: plugin for description $plugin not fount in $plugindir\n";
next;
}
my $item = $menu->command(-label => "$menuitem", -command => sub {
print "$prog $menuitem $desc\n" if $verbose;
my @sellist = $picLB->info('selection');
#return unless checkSelection($top, 1, 0, \@sellist);
my $command = "\"$plugindir/$prog\" ";
foreach (@sellist) {
$command .= "\"$_\" ";
}
print "com = $command\n" if $verbose;
my $buffer = `$command`;
showText("Output of PlugIn $menuitem", $buffer, NO_WAIT) if ($buffer ne '');
updateThumbsPlus() if $update;
});
#$balloon->attach($item, -msg => "$desc"); # does not work :(
}
close $file;
}
}
}
##############################################################
# toggleHeaders - adjusts the width of the columns to zero
# or the width needed ("")
##############################################################
sub toggleHeaders {
my @col = ($config{ColorBG}, $config{ColorBG2});
my $c = 1;
if ($config{ShowFile}) { $picLB->columnWidth($picLB->{filecol},""); $fileS->configure(-background=>$col[$c%2]); $c++; }
else { $picLB->columnWidth($picLB->{filecol},0); }
if ($config{ShowIPTC}) { $picLB->columnWidth($picLB->{iptccol},""); $iptcS->configure(-background=>$col[$c%2]); $c++; }
else { $picLB->columnWidth($picLB->{iptccol},0); }
if ($config{ShowComment}) { $picLB->columnWidth($picLB->{comcol},""); $comS->configure(-background=>$col[$c%2]); $c++; }
else { $picLB->columnWidth($picLB->{comcol},0); }
if ($config{ShowEXIF}) { $picLB->columnWidth($picLB->{exifcol},""); $exifS->configure(-background=>$col[$c%2]); $c++; }
else { $picLB->columnWidth($picLB->{exifcol},0); }
if ($config{ShowDirectory}) { $picLB->columnWidth($picLB->{dircol},""); $dirS->configure(-background=>$col[$c%2]); $c++; }
else { $picLB->columnWidth($picLB->{dircol},0); }
}
##############################################################
# calcDirSize
##############################################################
sub calcDirSize {
my $dir = getRightDir();
my $size = 0;
my $break = 0;
my $pw = progressWinInit($top, "Calculate directory size");
find(sub {
if (progressWinCheck($pw)) { $break = 1; $File::Find::prune = 1; }
# we don't know how long it will take, so we leave the progressbar at 50%
progressWinUpdate($pw, "size $size Bytes", 5, 10);
$size += -s;
},$dir);
progressWinEnd($pw);
my $msg = "Calculation finished.";
if ($break) { $msg = "Warning: The calculation wasn't finished!\nReal size may be bigger than displayed."; }
my $unitSize = computeUnit($size);
$top->messageBox(-icon => 'question', -message => "$msg\nThe directory size of $dir is $unitSize ($size Bytes)",
-title => "Directory size", -type => 'OK');
}
##############################################################
# buildThumbsRecursive - scans through all subdirectories of
# the actual dir an collects JPEG files
# let the user select in which dirs
# mapivi should build/refresh thumbnails
##############################################################
sub buildThumbsRecursive {
my $basedir = getRightDir();
my $rc = $top->messageBox(-icon => 'question', -message => "MaPiVi will first scan through all sub directories of $basedir and collect all directories containing JPEG files.\nThen you are able to select in which directories mapivi should build/refresh thumbnails.",
-title => "Build thumbnails in all sub directories", -type => 'OKCancel');
return if ($rc !~ m/Ok/i);
$userinfo = "searching sub directories ..."; $userInfoL->update;
my @dirlist;
my @pictestlist;
# no questions about NON-JPEGS while searching please!
my $tmp = $config{CheckForNonJPEGs};
$config{CheckForNonJPEGs} = 0;
my $pic_count = 0;
my $break = 0;
my $i = 0;
my $pw = progressWinInit($top, "Collect sub directories");
find(sub {
if (progressWinCheck($pw)) { $break = 1; $File::Find::prune = 1; }
# process just dirs containing pictures, but not .thumbs/ .xvpics/ etc. dirs
if (-d and ($_ ne $thumbdirname) and ($_ ne ".xvpics") and ($_ ne $exifdirname)) {
$i++; $i = 0 if ($i > 10); # restart progressbar every 10 steps; todo
progressWinUpdate($pw, "collecting directories, found ".scalar @dirlist." ...", $i, 10);
@pictestlist = getPics($File::Find::name, JUST_FILE); # no sort needed
if (@pictestlist > 0) {
$pic_count += scalar @pictestlist;
push @dirlist, $File::Find::name;
$userinfo = "found ".@dirlist." subdirs ..."; $userInfoL->update;
}
}
}, $basedir);
progressWinEnd($pw);
if ($break) {
$userinfo = "user break while counting sub directories";
return;
}
$config{CheckForNonJPEGs} = $tmp;
$userinfo = "found ".@dirlist." sub directories"; $userInfoL->update;
my @sellist;
return if (!mySelListBoxDialog("Select directories",
"Found ".scalar @dirlist." directories with $pic_count JPEG pictures.\nThumbnails will be created/updated in the selected directories.",
"build thumbnails", \@sellist, @dirlist));
# copy the selected elements into the @sel_dirs list
my @sel_dirs;
foreach (@sellist) {
push @sel_dirs, $dirlist[$_];
}
my $rebuild = 0;
$rc = myButtonDialog('Update or rebuild thumbnails?', "Please select if you want to update or rebuild the thumbnails.\nUpdate will just create thumbnails for modified and new pictures, rebuild will rebuild all thumbnails.", undef, 'Update', 'Rebuild', 'Cancel');
if ($rc eq 'Cancel') { return; }
elsif ($rc eq 'Update') { $rebuild = 0; }
elsif ($rc eq 'Rebuild') { $rebuild = 1; }
else { warn "buildThumbsRecursive: Error wrong rc: $rc"; return; }
my $actdirold = $actdir;
my ($dir, $dirshort, @pics);
$tmp = $config{CheckForNonJPEGs};
$config{CheckForNonJPEGs} = 0;
$i = 0;
$pw = progressWinInit($top, "build/refresh thumbnails");
foreach $dir (@sel_dirs) {
last if progressWinCheck($pw);
$i++;
$dirshort = cutString($dir, -40, "...");
progressWinUpdate($pw, "processing ($i/".scalar @sel_dirs.") $dirshort", $i, scalar @sel_dirs);
$userinfo = "updating thumbnails in $dirshort ..."; $userInfoL->update;
$actdir = $dir;
if ($rebuild) {
my $thumbdir = dirname(getThumbFileName("$dir/dummy.jpg"));
my @thumbs = getPics($thumbdir, WITH_PATH);
foreach (@thumbs) {
#print "buildThumbsRecursive: remove $_\n";
if ( unlink($_) != 1) { # unlink returns the number of successfull removed files
warn "buildThumbsRecursive: could not remove $_";
}
}
}
generateThumbs(NO_ASK, NO_SHOW, 1);
# do not ask the user when making a thumbnail dir
# do not show (and sort!) the generated thumbs
# 1 = read the pics from $actdir, not from the listbox
}
progressWinEnd($pw);
$config{CheckForNonJPEGs} = $tmp;
$userinfo = "thumbnails are now up to date!"; $userInfoL->update;
$actdir = $actdirold;
}
##############################################################
# rebuildThumbs
##############################################################
sub rebuildThumbs {
my @sellist = $picLB->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
if ($config{AskDeleteThumb}) {
my $rc = checkDialog("Delete thumbnails?",
"Please press Ok to delete ".scalar @sellist." thumbnails.",
\$config{AskDeleteThumb},
"ask every time", "", 'OK', 'Cancel');
return if ($rc ne 'OK');
}
my $thumb;
my $i = 0;
my $pw = progressWinInit($top, "Delete thumbnails");
foreach my $dpic (@sellist) {
last if progressWinCheck($pw);
# when the element is not available we jump out completly
last if (!$picLB->info("exists", $dpic));
$i++;
progressWinUpdate($pw, "delete thumbnail ($i/".scalar @sellist.") ...", $i, scalar @sellist);
$thumb = getThumbFileName($dpic);
if (-f $thumb) {
if (!removeFile( $thumb)) {
next;
}
else {
# delete was successfull, so we insert the defaultthumb
$picLB->itemConfigure($dpic, $picLB->{thumbcol}, -image => $defaultthumbP, -itemtype => "imagetext") if $defaultthumbP;
}
}
}
progressWinEnd($pw);
generateThumbs(ASK, SHOW);
}
##############################################################
# copyPicsDialog - copy the selected pictures to a choosen dir
##############################################################
sub copyPicsDialog($$) {
my $mode = shift; # constant COPY or BACKUP
my $lb = shift; # the reference to the active listbox widget
my @sellist = $lb->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
my $targetdir;
if ($mode == BACKUP) {
$targetdir = $actdir;
} elsif ($mode == COPY) {
$targetdir = getDirDialog("Copy pictures to");
} else {
warn "copyPicsDialog: error wrong mode: $mode";
return;
}
return if ($targetdir eq "");
copyPics($targetdir, $mode, $lb, @sellist);
}
##############################################################
# copyPics - copy the selected pictures to a choosen dir
##############################################################
sub copyPics {
my $targetdir = shift;
my $mode = shift; # constant COPY or BACKUP
my $lb = shift; # the reference to the active listbox widget
my @sellist = @_;
return unless (-d $targetdir);
return if (@sellist < 1);
makeDir(dirname(getThumbFileName("$targetdir/dummy.jpg")), ASK);
my ($pic, $dpic, $tpic, $thumbpic, $thumbtpic, $njpic);
my $process = "copy";
my $i = 0;
my $rc = 1;
my $n = 0; # count successfull copied pictures
my $pw = progressWinInit($lb, "Copy pictures");
foreach $dpic (@sellist) {
last if progressWinCheck($pw);
$pic = basename($dpic);
$i++;
$tpic = "$targetdir/$pic";
$thumbpic = getThumbFileName($dpic);
$thumbtpic = getThumbFileName($tpic);
if ($mode == BACKUP) {
$process = "backup";
$tpic = buildBackupName($dpic);
$thumbtpic = buildBackupName(getThumbFileName($dpic));
print "copyPics: duplicate mode $tpic\n" if $verbose;
}
progressWinUpdate($pw, "$process picture ($i/".scalar @sellist.") ...", $i, scalar @sellist);
$rc = overwritePic($tpic, $dpic, (scalar(@sellist) - $i + 1)) if ($rc != 2);
next if ($rc == 0);
last if ($rc == -1);
if (mycopy ($dpic, $tpic, OVERWRITE)) {
$n++;
if ((-d dirname($thumbtpic)) and (-f $thumbpic)) {
mycopy ("$thumbpic","$thumbtpic", OVERWRITE)
}
$searchDB{$tpic} = $searchDB{$dpic}; # copy meta info in search database
if ($mode == BACKUP) {
hlistCopy($lb, $dpic, $tpic); # insert and show the backup in the listbox
$lb->itemConfigure($tpic, $lb->{thumbcol}, -text => getThumbCaption($tpic));
$lb->itemConfigure($tpic, $lb->{filecol}, -text => getAllFileInfo($tpic));
}
}
} # foreach - end
progressWinEnd($pw);
$userinfo = "ready! ($n/".scalar @sellist." copied)"; $userInfoL->update;
reselect($lb, @sellist);
}
##############################################################
# linkPicsDialog - link the selected pictures to a choosen dir
##############################################################
sub linkPicsDialog {
if ($EvilOS) {
$top->messageBox(-icon => 'warning', -message => "Sorry, but this OS does not support symbolic links.",
-title => 'Error', -type => 'OK');
return;
}
my @sellist = $picLB->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
my $targetdir = getDirDialog("Link pictures to");
return if ($targetdir eq "");
linkPics($targetdir, @sellist);
}
##############################################################
# linkPics - link the selected pictures to a choosen dir
##############################################################
sub linkPics {
my $targetdir = shift;
my @sellist = @_;
if ($EvilOS) {
$top->messageBox(-icon => 'warning', -message => "Sorry, but this OS does not support symbolic links.",
-title => 'Error', -type => 'OK');
return;
}
return unless (-d $targetdir);
return if (@sellist < 1);
makeDir(dirname(getThumbFileName("$targetdir/dummy.jpg")), ASK);
my ($pic, $dpic, $tpic, $thumbpic, $thumbtpic, $njpic);
my $i = 0;
my $rc = 1;
my $n = 0; # count successfull copied pictures
my $pw = progressWinInit($top, "Link pictures");
foreach $dpic (@sellist) {
last if progressWinCheck($pw);
$pic = basename($dpic);
$i++;
progressWinUpdate($pw, "linking ($i/".scalar @sellist.") ...", $i, scalar @sellist);
$tpic = "$targetdir/$pic";
# Do not link to a link. Always link to the original image.
next if (!getRealFile(\$dpic));
$thumbpic = getThumbFileName($dpic);
$thumbtpic = getThumbFileName($tpic);
$rc = overwritePic($tpic, $dpic, (scalar(@sellist) - $i + 1)) if ($rc != 2);
next if ($rc == 0);
last if ($rc == -1);
if (mylink ("$dpic", "$tpic", 1)) {
$n++;
# if the link is created successfully, we COPY the thumbnail
# should the thumb also be a link???
if ((-d dirname($thumbtpic)) and (-f $thumbpic)) {
mycopy ("$thumbpic","$thumbtpic", OVERWRITE)
}
# unless ((defined $mode) and ($mode eq "backup")) {
# # ask to link non-JPEG file, if any
# foreach my $suf (split /\|/, $nonJPEGsuffixes) {
# $njpic = $dpic;
# $njpic =~ s/(.*)\.jp(g|eg)$/$1.$suf/i;
# if (-f $njpic) {
# my $rc = $top->messageBox(-icon => 'question', -message => "There is a non-JPEG file\n\"".basename($njpic)."\"\nOk to link it too?",
# -title => "Link non-JPEG?", -type => 'OKCancel');
# next if ($rc !~ m/Ok/i);
# mylink("$njpic", "$targetdir");
# }
# }
# }
}
} # foreach - end
progressWinEnd($pw);
$userinfo = "ready! ($n/".scalar @sellist." linked)"; $userInfoL->update;
reselect($picLB, @sellist);
}
##############################################################
# getDirDialog - let the user select a dir
##############################################################
sub getDirDialog($) {
my $title = shift;
my $text = "Please choose a target directory from the list below or open the directory browser\nby double clicking the first item or by just pressing OK.\n\nDirectories from the hotlist and recently visited direcories:";
my $another = "Open directory browser";
my @list;
my @sellist;
# sort dirs hash by numerical value reverse (number of accesses)
# %dirHotlist contains directories used as target in open dir, copy, link, move, ... operations
foreach (sort { $dirHotlist{$b} <=> $dirHotlist{$a} } keys %dirHotlist) {
next if (!-d $_); # skip non existing dirs
next if ($_ eq $trashdir);
push @list, $_;
last if (@list > 15); # 15 entries should be enough
}
# add the last used directories
foreach (reverse @dirHist) {
next if (!-d $_);
push @list, $_;
}
# remove duplicates and sort directory list alphabetical
my %saw;
@saw{@list} = ();
@list = ();
@list = sort keys %saw;
# put the "Open directory browser" item at the first position
unshift @list, $another;
return '' unless (mySelListBoxDialog($title, $text, 'OK', \@sellist, @list));
my $dir = '';
$dir = $list[$sellist[0]] if $sellist[0];
if (($dir eq '') or ($dir eq $another)) {
my $dsdir = dirDialog($actdir);
if ( defined $dsdir ) {
$dir = $dsdir;
}
}
$dir =~ s/\/\//\//g; # replace all // with /
if (-d $dir) { dirSave($dir); }
else { $dir = ''; }
return $dir;
}
##############################################################
# movePicsDialog - move the selected pictures to a choosen dir
##############################################################
sub movePicsDialog($) {
my $lb = shift; # the reference to the active listbox widget
my @sellist = $lb->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
my $targetdir = getDirDialog("Move pictures to");
return if ($targetdir eq "");
movePics($targetdir, $lb, @sellist)
}
##############################################################
# movePics - move the selected pictures to a choosen dir
##############################################################
sub movePics {
my $targetdir = shift;
my $lb = shift; # the reference to the active listbox widget
my @sellist = @_;
return unless (-d $targetdir);
return if (@sellist < 1);
makeDir(dirname(getThumbFileName("$targetdir/dummy.jpg")), ASK);
my ($pic, $dpic, $dir, $tpic, $thumbpic, $thumbtpic, $njpic);
my $i = 0;
my $rc = 1;
my $changed = 0;
my $pw = progressWinInit($lb, "Move pictures");
foreach $dpic (@sellist) {
last if progressWinCheck($pw);
$pic = basename($dpic);
$dir = dirname($dpic);
next if ($targetdir eq $dir);
$i++;
progressWinUpdate($pw, "moving ($i/".scalar @sellist.") ...", $i, scalar @sellist);
$tpic = "$targetdir/$pic";
$thumbpic = getThumbFileName($dpic);
$thumbtpic = getThumbFileName($tpic);
$rc = overwritePic($tpic, $dpic, (scalar(@sellist) - $i + 1)) if ($rc != 2);
next if ($rc == 0);
last if ($rc == -1);
# move picture
if (!move ("$dpic","$tpic")) {
$lb->messageBox(-icon => 'warning', -message => "Could not move $dpic to $tpic: $!",
-title => 'Error', -type => 'OK');
} else {
$changed++; # count nr of successfull moves
# only if move was successfull, we also move the thumbnail
if ((-d dirname($thumbtpic)) and (-f $thumbpic)) {
if (!move ("$thumbpic","$thumbtpic")) {
$lb->messageBox(-icon => 'warning', -message => "Could not move $thumbpic to $thumbtpic: $!",
-title => 'Error', -type => 'OK');
}
}
# ask to move non-JPEG file, if any
# foreach my $suf (split /\|/, $nonJPEGsuffixes) {
# $njpic = $dpic;
# $njpic =~ s/(.*)\.jp(g|eg)$/$1.$suf/i;
# if (-f $njpic) {
# my $rc = $lb->messageBox(-icon => 'question', -message => "There is a non-JPEG file\n\"".basename($njpic)."\"\nOk to move it too?",
# -title => "Move non-JPEG?", -type => 'OKCancel');
# next if ($rc !~ m/Ok/i);
# if (!move ("$njpic","$targetdir")) {
# $lb->messageBox(-icon => 'warning', -message => "Could not move $njpic to $targetdir: $!",
# -title => 'Error', -type => 'OK');
# }
# }
# }
$searchDB{$tpic} = $searchDB{$dpic}; # copy meta info in search database
delete $searchDB{$dpic}; # delete meta info of moved pic in search database
}
}
progressWinEnd($pw);
if ($changed == 0) { # nothing happend, no update needed
$userinfo = "ready! (nothing moved)"; $userInfoL->update;
return;
}
my @pics = $lb->info('children');
if ($#pics > $#sellist) { # if not all pictures were selected
#stopButStart();
foreach $dpic (@sellist) {
#last if stopButCheck();
$lb->delete("entry", $dpic) if ($lb->info('exists', $dpic));
reloadPic() if (($lb == $picLB) and ($dpic eq $actpic));
}
#stopButEnd();
}
else { # all pictures were moved
updateThumbsPlus() if ($lb == $picLB);
}
showNrOf() if ($lb == $picLB);
$userinfo = "ready! ($changed/".scalar @sellist." moved)"; $userInfoL->update;
}
##############################################################
# overwritePic
##############################################################
sub overwritePic {
my $old = shift; # this will be overwritten ny $new
my $new = shift; # this will overwrite $old
my $nr = shift; # the number of all (left) files to check, if this nr is > 1 there will be two "for all" buttons
return 1 if (!-f $old); # if $old does not exists, we don't need to ask ...
my $rc = 3; # dummy value
my $olddir = dirname($old);
my $oldpic = basename($old);
my $oldthumb = getThumbFileName($old);
my $olddate = getFileDate($old, FORMAT);
my $oldsize = getFileSize($old, FORMAT);
my $newdir = dirname($new);
my $newpic = basename($new);
my $newthumb = getThumbFileName($new);
my $newdate = getFileDate($new, FORMAT);
my $newsize = getFileSize($new, FORMAT);
# open window
my $oww = $top->Toplevel();
$oww->title("Overwrite?");
$oww->iconimage($mapiviicon) if $mapiviicon;
$oww->Label(-anchor => 'w', -text => "\"$oldpic\" exists. Do you want to overwrite it?",
-bg => $config{ColorBG})->pack;
my $nF = $oww->Frame()->pack(-anchor => 'w', -padx => 3, -pady => 3);
my $ca = $oww->Canvas(-width => 100, -height => 50)->pack(-padx => 3, -pady => 3);
my $oF = $oww->Frame()->pack(-anchor => 'w', -padx => 3, -pady => 3);
# draw a red arrow
$ca->createLine(50, 0,50,50, -width => 6, -fill => "red");
$ca->createLine(50,50,70,20, -width => 6, -fill => "red");
$ca->createLine(50,50,30,20, -width => 6, -fill => "red");
my $newP = $oww->Photo(-file => "$newthumb", -gamma => $config{Gamma}) if (-f $newthumb);
my $oldP = $oww->Photo(-file => "$oldthumb", -gamma => $config{Gamma}) if (-f $oldthumb);
$nF->Label(-image => $newP)->pack(-side => "left") if $newP;
$oF->Label(-image => $oldP)->pack(-side => "left") if $oldP;
$nF->Label(-justify => "left", -text => "this file\n$newsize\n$newdate\n$newdir",
-bg => $config{ColorBG})->pack(-padx => 3, -side => "left");
$oF->Label(-justify => "left", -text => "will overwrite this file\n$oldsize\n$olddate\n$olddir",
-bg => $config{ColorBG})->pack(-padx => 3, -side => "left");
$oww->Label(-anchor => 'w', -text => "$nr files to go ...",
-bg => $config{ColorBG})->pack if ($nr > 1);
my $bF = $oww->Frame()->pack(-padx => 3, -pady => 3, -fill => 'x', -expand => 1);
$bF->Button(-text => "Overwrite", -command => sub { $rc = 1; })->pack(-side => "left",
-fill => 'x', -expand => 1);
$bF->Button(-text => "Overwrite All",
-command => sub { $rc = 2; })->pack(-side => "left", -fill => 'x', -expand => 1) if ($nr > 1);
$bF->Button(-text => 'Cancel', -command => sub { $rc = 0; })->pack(-side => "left",
-fill => 'x', -expand => 1);
$bF->Button(-text => "Cancel All",
-command => sub { $rc = -1; })->pack(-side => "left", -fill => 'x', -expand => 1)if ($nr > 1);
$oww->Popup;
$oww->waitVariable(\$rc);
$oww->withdraw();
$oww->destroy();
die "wrong rc value: $rc" if (($rc < -1) or ($rc > 2));
return $rc;
}
##############################################################
# sendTo - send all selected pics via email
##############################################################
sub sendTo {
my $lb = shift; # the reference to the active listbox widget
my @sellist = $lb->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
return if (!checkExternProgs("sendTo", "thunderbird"));
# check if some files are links
return if (!checkLinks($lb, @sellist));
# open dialog window
my $myDiag = $top->Toplevel();
$myDiag->title("Change size/quality before sending");
$myDiag->iconimage($mapiviicon) if $mapiviicon;
$myDiag->Label(-text =>"Change the size and/or quality of the ".scalar @sellist." selected pictures before sending via email.",
-bg => $config{ColorBG}
)->pack(-anchor => 'w',-padx => 3,-pady => 3);
$myDiag->Checkbutton(-variable => \$config{MailPicNoChange},
-text => "leave pictures untouched",
-command => sub {
my $state = "disabled";
$state = 'normal' unless ($config{MailPicNoChange});
setChildState($myDiag->{sq}, $state);
setChildState($myDiag->{sl}, $state);
})->pack(-anchor => 'w');
$myDiag->{sq} = labeledScale($myDiag, 'top', 24, "Quality (%)", \$config{MailPicQuality}, 10, 100, 1);
qualityBalloon($myDiag->{sq});
$myDiag->{sl} = labeledScale($myDiag, 'top', 24, "Maximum length (pixels)", \$config{MailPicMaxLength}, 10, 2000, 1);
my $ButF =
$myDiag->Frame()->pack(-fill =>'x', -padx => 3, -pady => 3);
my $OKB =
$ButF->Button(-text => 'OK',
-command => sub {
$myDiag->destroy();
$userinfo = "sending ".scalar @sellist." pictures via email"; $userInfoL->update;
my $pics = "";
my $dpic;
unless ($config{MailPicNoChange}) {
# copy to trash
$userinfo = "send to: copy pictures to temp directory"; $userInfoL->update;
foreach $dpic (@sellist) {
mycopy($dpic, $trashdir, OVERWRITE);
}
# exchange the directory from original to trash
foreach (@sellist) {
$_ = "$trashdir/".basename($_);
}
# resize
foreach $dpic (@sellist) {
$userinfo = "send to: resizing pictures ".basename($dpic); $userInfoL->update;
my $command = "mogrify";
$command .= " -geometry \"".$config{MailPicMaxLength}.'x'.$config{MailPicMaxLength}.">\"";
$command .= " -quality ".$config{MailPicQuality}." \"$dpic\"";
print "changeSizeQuality: com = $command\n" if $verbose;
execute($command);
}
}
foreach $dpic (@sellist) {
if ($pics eq "") {
$pics = "file://$dpic"; # the first one
} else {
$pics .= ",file://$dpic"; # additional pics
}
}
$userinfo = "send to: starting email client ..."; $userInfoL->update;
my $command = "thunderbird -compose \"subject=Fotos,attachment=\'$pics\'\"";
$command .= " &" unless ($EvilOS);
print "command = $command\n" if $verbose;
(system "$command") == 0 or warn "$command failed: $!";
# todo: this does not work, the pic still has to be there, when the user presses the send button
# extra dir which will be deleted at the next startup or simply leave it in the trash?
# $top->after(5000); # wait 5 secs for mail client to pic up the pictures (ToDo)
# $userinfo = "send to: removing temp pictures ..."; $userInfoL->update;
# $top->after(1000);
# unless ($config{MailPicNoChange}) {
# # remove pics in trash
# foreach (@sellist) {
# removeFile($_);
# }
# }
$userinfo = "ready!"; $userInfoL->update;
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$ButF->Button(-text => "Default",
-command => sub {
$config{MailPicNoChange} = 0;
$config{MailPicQuality} = 75;
$config{MailPicMaxLength} = 800;
my $state = "disabled";
$state = 'normal' unless ($config{MailPicNoChange});
setChildState($myDiag->{sq}, $state);
setChildState($myDiag->{sl}, $state);
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$OKB->bind('<Return>', sub { $OKB->invoke; } );
$ButF->Button(-text => 'Cancel',
-command => sub { $myDiag->destroy(); }
)->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$myDiag->Popup;
if ($EvilOS) { # sometimes to dialog disappears when clicked on, so we need a short grab
$myDiag->grab;
$myDiag->after(50, sub{$myDiag->grabRelease});
}
$OKB->focus;
$myDiag->waitWindow();
$myDiag->destroy() if Tk::Exists($myDiag);
}
##############################################################
# convertPics - convert selected pics to another format
##############################################################
sub convertPics {
my $lb = shift; # the reference to the active listbox widget
my @sellist = $lb->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
return if (!checkExternProgs("sendTo", "convert"));
# check if some files are links
return if (!checkLinks($lb, @sellist));
# open dialog window
my $win = $top->Toplevel();
$win->title("Convert to other picture formats");
$win->iconimage($mapiviicon) if $mapiviicon;
$win->Label(-text =>"Convert the ".scalar @sellist." selected pictures to another picture format.\nThe orininal files will be left untouched.\nThe converted pictures are stored in the actual diretory.",
-bg => $config{ColorBG}
)->pack(-anchor => 'w',-padx => 3,-pady => 3);
my $notebook =
$win->NoteBook(-width => 500,
-background => $config{ColorBG}, # background of active page (including its tab)
-inactivebackground => $config{ColorEntry}, # tabs of inactive pages
-backpagecolor => $config{ColorBG}, # background behind notebook
)->pack(-expand => "yes",
-fill => "both",
-padx => 5, -pady => 5);
my $format = "gif";
my $gifF = $notebook->add("gif", -label => "GIF", -raisecmd => sub { $format = "gif"; });
my $pngF = $notebook->add("png", -label => "PNG", -raisecmd => sub { $format = "png"; });
my $tifF = $notebook->add("tiff", -label => "TIFF", -raisecmd => sub { $format = "tiff"; });
$win->{PicQuality} = 95;
$pngF->{sq} = labeledScale($pngF, 'top', 24, "Quality (%)", \$win->{PicQuality}, 0, 100, 1);
$balloon->attach($pngF->{sq}, -msg => 'Quality range from 0% (fastest compression) to 100% (best but slowest).
For 0%, the Huffman-only strategy is used, which is fastest but not necessarily the worst compression.
The default is 75%, which means nearly the best compression with adaptive filtering.
If the image is a natural image (a photo), then use "adaptive" filtering with quality 95%.
The quality setting has no effect on the appearance of PNG images, since the compression is always lossless.
For PNG images, quality is regarded as two decimal figures.
The first (tens) is the zlib compression level, 1-9.
The second (ones digit) is the PNG filtering type:
0 is none,
1 is "sub",
2 is "up",
3 is "average",
4 is "Paeth", and
5 is "adaptive".');
my $ButF =
$win->Frame()->pack(-fill =>'x', -padx => 3, -pady => 3);
my $OKB =
$ButF->Button(-text => 'OK',
-command => sub {
$win->destroy();
#my $format = $notebook->raised();
print "format = $format\n";
$userinfo = "converting ".scalar @sellist." $format pictures"; $userInfoL->update;
print $userinfo."\n";
my ($dpic, $ndpic);
my $i = 0;
my $pw = progressWinInit($top, "Convert pictures");
foreach $dpic (@sellist) {
last if progressWinCheck($pw);
progressWinUpdate($pw, "convert picture ($i/".scalar @sellist.") ...", $i, scalar @sellist);
$i++;
$ndpic = $dpic;
$ndpic =~ s/(.*)\.jp(g|eg)$/$1.$format/i;
if (-f $ndpic) {
my $rc = $top->messageBox(-icon => 'question', -message => "$ndpic exists already.\nShould I really overwrite it?",
-title => "Overwrite?", -type => 'OKCancel');
next if ($rc !~ m/Ok/i);
}
$userinfo = "convert picture ".basename($dpic); $userInfoL->update;
my $command = "convert";
$command .= " -quality ".$win->{PicQuality} if ($format eq "png");
$command .= " \"$dpic\" \"$ndpic\"";
print "convertPics:: com = $command\n"; # if $verbose;
execute($command);
progressWinUpdate($pw, "convert picture ($i/".scalar @sellist.") ...", $i, scalar @sellist);
}
progressWinEnd($pw);
$userinfo = "ready!"; $userInfoL->update;
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$OKB->bind('<Return>', sub { $OKB->invoke; } );
$ButF->Button(-text => 'Cancel',
-command => sub { $win->destroy(); }
)->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$win->Popup;
if ($EvilOS) { # sometimes to dialog disappears when clicked on, so we need a short grab
$win->grab;
$win->after(50, sub{$win->grabRelease});
}
$OKB->focus;
$win->waitWindow();
$win->destroy() if Tk::Exists($win);
}
##############################################################
# renamePic - let the user rename the seleced pictures
##############################################################
sub renamePic {
my $lb = shift;
my @sellist = $lb->info('selection');
my @resellist = @sellist;
return unless checkSelection($lb, 1, 0, \@sellist);
my ($pic, $dir, $dpic, $newname, $rc, $thumb);
my $i = 0;
my $pw = progressWinInit($lb, "Rename pictures");
foreach $dpic (@sellist){
last if progressWinCheck($pw);
$i++;
progressWinUpdate($pw, "renaming picture ($i/".scalar @sellist.") ...", $i, scalar @sellist);
$pic = basename($dpic);
$dir = dirname($dpic);
$thumb = getThumbFileName($dpic);
$newname = $pic;
next if (!checkWriteable($dpic));
$rc = myEntryDialog("Rename picture", "Please enter a new name for file\n$pic\n(in $dir)", \$newname, getThumbFileName($dpic));
next if (($rc ne 'OK') or ($newname eq "") or ($newname eq $pic));
# check for correct JPEG suffix
if (is_a_JPEG($dpic) and ($newname !~ /(.*)(\.jp(g|eg))/i)) {
$newname =~ /(.*)\.(.*)/;
my $correct = "$1.jpg";
my $rc = $lb->messageBox(-icon => 'question', -message => "$newname has not a correct JPEG suffix.\nShould I change it to $correct?",
-title => "Change suffix?", -type => 'OKCancel');
if ($rc eq "Ok") {
$newname = "$correct";
}
}
my $ndpic = "$dir/$newname";
# check if new file name already exists
if (-f $ndpic) {
my $rc = $lb->Dialog( -title => "File exists",
-text => "$newname already exists!",
-buttons => ["Overwrite", 'Cancel'])->Show();
next if ($rc ne "Overwrite"); # skip this file
}
if (!rename ($dpic, $ndpic)) {
$lb->messageBox(-icon => 'warning', -message => "Could not rename $pic to $newname: $!",
-title => 'Error', -type => 'OK');
next;
}
# correct the searchDB
$searchDB{$ndpic} = $searchDB{$dpic}; # copy meta info in search database
delete $searchDB{$dpic}; # delete meta info of renamed pic in search database
renameCachedPic($dpic, $ndpic);
foreach (@resellist) { $_ = $ndpic if ($_ eq $dpic); }
if ($dpic eq $actpic) { $actpic = $ndpic; }
hlistEntryRename($lb, $dpic, $ndpic);
# change the displayed name
$lb->itemConfigure($ndpic, $lb->{thumbcol}, -text => getThumbCaption($newname));
$lb->itemConfigure($ndpic, $lb->{filecol}, -text => getAllFileInfo($ndpic));
# rename thumbnail
if (-f $thumb) {
if (!rename ($thumb, dirname($thumb)."/$newname")) {
$lb->messageBox(-icon => 'warning', -message => "Could not rename thumbnail $pic to $newname: $!",
-title => 'Error', -type => 'OK');
}
}
# rename exif info file, if any
if (-f "$dir/$exifdirname/$pic") {
if (!rename ("$actdir/$exifdirname/$pic", "$actdir/$exifdirname/$newname")) {
$lb->messageBox(-icon => 'warning', -message => "Could not rename exif info file $pic to $newname: $!",
-title => 'Error', -type => 'OK');
}
}
# rename backup file, if any
renameBackup($lb, $dpic, $newname, ASK);
}
progressWinEnd($pw);
reselect($lb, @resellist);
if ($lb == $picLB) {
setTitle();
$userinfo = "ready! ($i/".scalar @sellist." renamed)"; $userInfoL->update;
}
}
##############################################################
# renameNonJPEG - check if there are any non-JPEG files
# and rename them
##############################################################
# todo enhance this to cope with other formats
sub renameNonJPEG {
my $dpic = shift;
my $newname = shift;
foreach my $suf (split /\|/, $nonJPEGsuffixes) {
my $njpic = $dpic;
$njpic =~ s/(.*)\.jp(g|eg)$/$1.$suf/i;
if (-f $njpic) {
my $nnjpic = "$actdir/$newname";
$nnjpic =~ s/(.*)\.jp(g|eg)$/$1\.$suf/i;
my $rc = $top->messageBox(-icon => 'question', -message => "There is a non-JPEG file\n\"".basename($njpic)."\"\nOk to rename it to:\n\"".basename($nnjpic)."\"?",
-title => "Rename non-JPEG?", -type => 'OKCancel');
return 0 if ($rc !~ m/Ok/i);
if (!rename ("$njpic", "$nnjpic")) {
$top->messageBox(-icon => 'warning', -message => "Could not rename non-JPEG picture $njpic to $nnjpic: $!",
-title => 'Error', -type => 'OK');
}
}
}
return 1;
}
##############################################################
# showBackup
##############################################################
sub showBackup {
my @sellist = $picLB->info('selection');
if (@sellist != 1) {
$top->messageBox(-icon => 'info', -message => "Please select exacty one picture for this function.",
-title => "Wrong selection", -type => 'OK');
return;
}
my $bpic = buildBackupName($sellist[0]);
if (-f $bpic) {
showPicInOwnWin($bpic);
}
else {
$userinfo = 'Sorry, no backup "'.basename($bpic).'" found.'; $userInfoL->update;
}
}
##############################################################
# renameBackup - check if there is a backup file
# and rename it
##############################################################
sub renameBackup {
my $lb = shift;
my $dpic = shift;
my $newname = shift;
my $ask = shift;
return unless $config{RenameBackup};
my $bpic = buildBackupName($dpic);
return unless (-f $bpic); # no backup - no rename
my $dir = dirname($dpic);
my $pic = basename($dpic);
my $nbpic = basename(buildBackupName("$dir/$newname"));
my $rc = $nbpic;
if ((defined $ask) and ($ask == ASK)) {
$rc = myButtonDialog("Rename backup?", "Should I also rename the backup file ".basename($bpic)."?\nRename to:", undef, $nbpic, $pic, 'Cancel');
return if ($rc =~ m/Cancel/i);
}
my $new_bak_name = "$dir/$rc";
if (-f $new_bak_name) { # should not happen
$lb->messageBox(-icon => 'warning', -message => "Backup picture $bpic should be renamed to $new_bak_name. But $new_bak_name exists! Skipping rename action.",
-title => 'Error', -type => 'OK');
return;
}
if (rename ($bpic, $new_bak_name)) {
hlistEntryRename($lb, $bpic, $new_bak_name);
# change the displayed name
if ($lb->info("exists", $new_bak_name)) {
$lb->itemConfigure($new_bak_name, $picLB->{thumbcol}, -text => getThumbCaption($new_bak_name));
$lb->itemConfigure($new_bak_name, $picLB->{filecol}, -text => getAllFileInfo($new_bak_name));
}
# correct the searchDB
$searchDB{$new_bak_name} = $searchDB{$bpic}; # copy meta info in search database
delete $searchDB{$bpic};
# rename thumbnail
my $thumb = getThumbFileName($bpic);
if (-f $thumb) {
my $nthumb = getThumbFileName($new_bak_name);
if (!rename ($thumb, $nthumb)) {
$lb->messageBox(-icon => 'warning', -message => "Could not rename thumbnail $thumb to $nthumb: $!",
-title => 'Error', -type => 'OK');
}
}
} else {
$lb->messageBox(-icon => 'warning', -message => "Could not rename backup picture $bpic to $new_bak_name: $!",
-title => 'Error', -type => 'OK');
}
}
##############################################################
# getRenameFormat
##############################################################
sub getRenameFormat {
my $format = $config{FileNameFormat}; # copy to tmp variable
my $rc = myEntryDialog("Enter file name format",
'Please enter the file name format
%f = file name (without suffix) %xa = EXIF aperture
%y = year (yyyy) %xe = EXIF exposure time
%m = month (mm) %xm = EXIF camera model
%d = day (dd) %xr = EXIF artist
%h = hour (hh) %iw = image width
%M = Minute (MM) %ih = image height
%s = second (ss)
Examples:
"%y%m%d-%h%M%s" will rename all pictures to their internal EXIF
date e.g. 20061231-155959 (the file date will be used, if there
is no EXIF date).
If you select 3 pictures and enter "flower" as file name format,
the pics will be renamed to "flower.jpg", "flower-01.jpg" and
"flower-02.jpg".
The suffix ".jpg" will always be added.
Leave the format line below empty to use the default format
('.$config{FileNameFormatDef}.').', \$format);
return 'Cancel' if ($rc ne 'OK');
if ($format eq "") {
$format = $config{FileNameFormatDef};
}
if ($format =~ m/.*\/.*/) {
$top->messageBox(-icon => 'warning', -message => "Sorry, but a / is not allowed in a file name.",
-title => 'Error', -type => 'OK');
return 'Cancel';
}
$config{FileNameFormat} = $format; # save back to the config
return $rc;
}
##############################################################
# renameSmart - rename the selected pictures to e.g. the EXIF date
##############################################################
sub renameSmart {
my $lb = shift;
my @sellist = $lb->info('selection');
my @resellist = @sellist;
return unless checkSelection($lb, 1, 0, \@sellist);
my ($pic, $dir, $dpic, $ndpic, $rc, @datetime, @times, $time, @dates, $date, $n, $base);
my $doForAll = 0;
my $errors = "";
my $useFileDate = undef;
my @renamed;
$rc = getRenameFormat();
return if ($rc ne 'OK');
my $format = $config{FileNameFormat};
my $i = 0;
my $pw = progressWinInit($lb, "smart rename");
foreach $dpic (@sellist) {
last if progressWinCheck($pw);
$i++;
$pic = basename($dpic);
$dir = dirname($dpic);
progressWinUpdate($pw, "renaming ($i/".scalar @sellist.") ...", $i, scalar @sellist);
unless (-f $dpic) { # may happen when renaming backups
$errors .= "$pic: not found, seems to be an already renamed backup? - skipping\n";
next;
}
my $newname = "";
$rc = applyRenameFormat($dpic, $format, \$newname, \$doForAll);
next if ($rc eq "Skip this picture");
last if ($rc eq "Cancel all");
$newname = findNewName("$dir/$newname");
# todo: handle backup pics it should be possible to preserve the "-bak" part
$ndpic = "$dir/$newname";
if (-f $ndpic) { # just a safety check
$errors .= "$pic: new name $newname already exists - skipping\n";
next;
}
# rename the picture
if (renamePicInt($dpic, $ndpic, \$errors)) {
push @renamed, $ndpic;
# rename the hlist entry
hlistEntryRename($lb, $dpic, $ndpic);
# display the new file name
$lb->itemConfigure($ndpic, $lb->{thumbcol}, -text => getThumbCaption($ndpic));
$lb->itemConfigure($ndpic, $lb->{filecol}, -text => getAllFileInfo($ndpic));
foreach (@resellist) { $_ = $ndpic if ($_ eq $dpic); }
}
}
# fix the renaming of the first pic of a set (pic.jpg -> pic-00.jpg)
my $renamed = renameSmartFix(\$errors, @renamed);
foreach my $dpic (keys %{$renamed}) {
my $ndpic = $$renamed{$dpic};
# rename the hlist entry
hlistEntryRename($lb, $dpic, $ndpic);
# display the new file name
$lb->itemConfigure($ndpic, $lb->{thumbcol}, -text => getThumbCaption($ndpic));
$lb->itemConfigure($ndpic, $lb->{filecol}, -text => getAllFileInfo($ndpic));
foreach (@resellist) { $_ = $ndpic if ($_ eq $dpic); }
}
progressWinEnd($pw);
reselect($lb, @resellist);
if ($lb == $picLB) {
$userinfo = "ready! (renamed $i/".scalar @sellist.")"; $userInfoL->update;
setTitle();
}
if ($errors ne "") {
$errors = "These errors occured while renaming the ".scalar @sellist." selected pictures:\n$errors";
showText("Error while renaming", $errors, NO_WAIT);
}
$lb->focusForce;
}
##############################################################
# renamePicInt - rename a pic, the thumb, backup, exif, nonjpeg
# searchDB and cached pic
##############################################################
sub renamePicInt {
my $dpic = shift;
my $ndpic = shift;
my $errors = shift; # ref to error string
my $pic = basename($dpic);
my $dir = dirname($dpic);
my $npic = basename($ndpic);
my $rc = 0;
if (!rename ($dpic, $ndpic)) {
# rename failed
$$errors .= "Could not rename $pic to $npic: $!\n";
$rc = 0;
}
else {
# rename worked
# rename the thumbnail
my $thumbdir = dirname(getThumbFileName($dpic));
if (!rename ("$thumbdir/$pic", "$thumbdir/$npic")) {
$$errors .= "Could not rename thumbnail $pic to $npic: $!\n";
}
# rename exif info file, if any
if (-f "$dir/$exifdirname/$pic") {
if (!rename ("$dir/$exifdirname/$pic", "$dir/$exifdirname/$npic")) {
$$errors .= "Could not rename exif info file $pic to $npic: $!\n";
}
}
# rename backup file, if any
renameBackup($picLB, $dpic, $npic);
# rename non-JPEG file, if any
renameNonJPEG($dpic, $npic);
# correct the searchDB
$searchDB{$ndpic} = $searchDB{$dpic}; # copy meta info in search database
delete $searchDB{$dpic}; # delete meta info of renamed pic in search database
renameCachedPic($dpic, $ndpic);
$actpic = $ndpic if (($dpic eq $actpic) and (-f $ndpic));
$rc = 1;
}
return $rc;
}
##############################################################
# renameSmartFix - fix the renaming of renameSmart by adding
# "-00" to the first pic of a set
# e.g. pic1.jpg and pic1-01.jpg will become
# pic1-00.jpg and pic1-01.jpg
# todo: this really is an ugly solution
##############################################################
sub renameSmartFix {
my $errors = shift; # ref to scalar, errors will be added
my @piclist = @_;
return unless (@piclist);
my %hash;
$hash{$_} = 1 foreach (@piclist);
my %renamed; # hash of the renamed files (key: old name, value: new name)
# search the list for files matching file-01.jpg
foreach my $dpic (@piclist) {
if ($dpic =~ m/(.*)-01\.(.*)$/i) { # e.g. file-01.jpg
my $pic = "$1.$2";
my $npic = "$1-00.$2";
# if there is a file named file.jpg
if (defined $hash{$pic}) {
# and no file named file-00.jpg
unless (defined $hash{$npic}) {
print "renameSmartFix: rename $pic to $npic\n" if $verbose;
# we rename file.jpg to file-00.jpg
if (renamePicInt($pic, $npic, $errors)) {
$renamed{$pic} = $npic;
}
}
}
}
}
return \%renamed;
}
##############################################################
# applyRenameFormat
##############################################################
sub applyRenameFormat {
my $dpic = shift;
my $format = shift; # e.g. %y%m%d-%h%M%s
my $newname = shift; # reference to string
my $doForAll = shift; # reference to bool
my $pic = basename($dpic);
$$newname = $format;
# replace %f with the file name
if (($format =~ m/\%f/) and ($pic =~ /(.*)\.(.*)/)) {
my $name = $1; # $1 makes some problems in s///
$$newname =~ s/%f/$name/g;
}
# get the date and replace it, only when needed
if ($format =~ m/(\%y|\%m|\%d|\%h|\%M|\%s)/) {
my $datestr = "";
$datestr = getEXIFDate($dpic);
if ($datestr eq "") {
$datestr = getFileDate($dpic, NO_FORMAT);
$datestr = buildEXIFDateTime($datestr);
unless ($$doForAll) {
my $rc = checkDialog("Use file date?",
"$pic has no EXIF date, shall I use the file date ($datestr) instead?",
$doForAll,
"don't ask again",
getThumbFileName($dpic),
'OK', "Skip this picture", "Cancel all");
return $rc if (($rc eq "Skip this picture") or ($rc eq "Cancel all"));
}
}
my @datetime = split / /, $datestr;
my @times = split /:/, $datetime[1];
my @dates = split /:/, $datetime[0];
$$newname =~ s/%y/$dates[0]/g;
$$newname =~ s/%m/$dates[1]/g;
$$newname =~ s/%d/$dates[2]/g;
$$newname =~ s/%h/$times[0]/g;
$$newname =~ s/%M/$times[1]/g;
$$newname =~ s/%s/$times[2]/g;
}
# get EXIF data and replace it, only when needed
if ($format =~ m/(\%xa|\%xe|%xm|%xr)/) {
my $aperture = sprintf("%02.1f", getEXIFAperture($dpic, NUMERIC));
$$newname =~ s/%xa/$aperture/g;
my $exposure = sprintf("%.3f", getEXIFExposureTime($dpic, NUMERIC));
$$newname =~ s/%xe/$exposure/g;
my $model = getEXIFModel($dpic);
$model =~ tr/\000/ /; # remove null termination (\000) chars
$model =~ s/( )+/ /g; # replace more than one space with one
$model =~ s/\s+$//; # cut trailing whitespace
$$newname =~ s/%xm/$model/g;
my $artist = getEXIFArtist($dpic);
$$newname =~ s/%xr/$artist/g;
}
# get image data and replace it, only when needed
if ($format =~ m/(\%iw|\%ih)/) {
my ($w, $h) = getSize($dpic);
$$newname =~ s/%iw/$w/g;
$$newname =~ s/%ih/$h/g;
}
print "applyRenameFormat: $pic -> -$$newname- (format: $format)\n" if $verbose;
return 'OK';
}
##############################################################
# findNewName - find a unused name by adding a number
# e.g. name-03.jpg
# input: filename with dir! with or without suffix
# output: new filename - no dir!!!
##############################################################
sub findNewName {
my $dpic = shift;
my $dir = dirname($dpic);
my $pic = basename($dpic);
if ($pic !~ /(.*)(\.jp(g|eg))/i) {
$pic .= ".jpg"; # pic does not have a jpeg suffix - adding .jpg
}
$pic =~ /(.*)(\.jp(g|eg))/i; # now split again (we need $1 and $2)
my $base = $1;
my $new = $base;
my $suffix = $2;
# if a file with this name already exists, we add a number
for ( 1 .. 99 ) {
if (-f "$dir/$new$suffix") {
$new = sprintf "%s-%02d", $base, $_;
} else {
last;
}
}
print "findNewName: $pic -> $new$suffix\n" if $verbose;
return "$new$suffix";
}
##############################################################
# updateThumbsPlus - update and show the actual pic again
##############################################################
sub updateThumbsPlus {
updateThumbs();
showPic($actpic);
}
##############################################################
# updateThumbs - reads the pictures of the actual dir, shows the
# thumbnails, the given picture and generates
# the thumbnails
##############################################################
sub updateThumbs {
$userinfo = "loading thumbnails ...";
$top->update;
checkCachedPics();
canvasHide();
# delete all photo objects (thumbnnails)
foreach (keys %thumbs) {
print "updateThumbs: deleting thumbnail object of $_\n" if $verbose;
$thumbs{$_}->delete if (defined $thumbs{$_}); # delete photo object
delete $thumbs{$_}; # delete hash entry
}
if ($verbose) {
my @check = $top->imageNames;
print " there are ".scalar @check." pics left\n";
}
if (showThumbs()) {
$userinfo = "loading thumbnails ... ready"; $userInfoL->update;
generateThumbs(ASK, SHOW);
}
else {
$userinfo = "user abord (not all pictures are loaded!)"; $userInfoL->update;
}
showNrOf();
check_new_keywords();
}
##############################################################
# check_new_keywords - check if new keywords were found in the pictures and ask to add them to the catalog
##############################################################
sub check_new_keywords {
return unless ($config{CheckNewKeywords});
return if (keys %new_keywords <= 0);
return unless (get_new_keywords());
# open window
my $win = $top->Toplevel();
$win->title('New keywords');
$win->iconimage($mapiviicon) if $mapiviicon;
my $text = 'Found new keywords, please choose how to proceed.';
$win->Label(-textvariable => \$text)->pack(-expand => 0, -fill => 'x');
my $tlb = $win->Scrolled("HList",
-header => 1,
-separator => ';', # todo here we hope that ; will never be in a directory or file name
-pady => 0,
-columns => 2,
-scrollbars => 'osoe',
-selectmode => 'extended',
-width => 80,
-height => 30,
)->pack(-expand => 1, -fill => "both");
bindMouseWheel($tlb);
$tlb->header('create', 0, -text => 'Keyword', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
$tlb->header('create', 1, -text => 'Occurance', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
my $butF1 = $win->Frame()->pack(-fill =>'x', -padx => 3, -pady => 3);
my $butF2 = $win->Frame()->pack(-fill =>'x', -padx => 3, -pady => 3);
$butF1->Button(-text => 'add selected to keyword catalog',
-command => sub {
my @sellist = $tlb->info('selection');
return unless (@sellist);
add_new_keywords(\@sellist);
my $nr = show_new_keywords($tlb);
$win->destroy() if ($nr < 1);
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$butF1->Button(-text => 'add selected to ignore list',
-command => sub {
my @sellist = $tlb->info('selection');
return unless (@sellist);
foreach (@sellist) {
$ignore_keywords{$_} = 1;
delete $new_keywords{$_} if (defined $new_keywords{$_});
}
my $nr = show_new_keywords($tlb);
$win->destroy() if ($nr < 1);
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
my $Xbut = $butF2->Button(-text => 'Ask later',
-command => sub { $win->destroy();
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$win->bind('<Control-q>', sub { $Xbut->invoke; });
$win->bind('<Key-Escape>', sub { $Xbut->invoke; });
$win->bind('<Control-a>', sub { selectAll($tlb); } );
$win->Popup(-popover => 'cursor');
repositionWindow($win);
my $nr = show_new_keywords($tlb);
$text = "Found $nr new keywords, please choose how to proceed.";
$win->waitWindow;
}
##############################################################
# show_new_keywords - show a list of keywords in a hlist
##############################################################
sub show_new_keywords {
my $lb = shift; # the hlist widget
my @list = get_new_keywords();
$lb->delete('all');
foreach my $key (sort @list) {
$lb->add($key);
$lb->itemCreate($key, 0, -text => $key, -style => $comS);
$lb->itemCreate($key, 1, -text => $new_keywords{$key}, -style => $iptcS);
}
return (scalar @list);
}
##############################################################
# get_new_keywords - get new keywords from global hash, return list with new keywords (e.g. nature.animal.dog)
##############################################################
sub get_new_keywords {
my @new_keywords;
foreach my $key (keys %new_keywords) {
# skip if keyword is in the ignore list
next if (defined $ignore_keywords{$key});
# replace dot "." with slash "/" - that's the way they are stored in the prekeys list
my $keyS = $key;
$keyS =~ s|\.|\/|g;
# check if this is a new key (not in @prekeys list)
if (!isInList($keyS, \@prekeys)) {
# add new keyword to list
push @new_keywords, $key;
}
}
return @new_keywords;
}
##############################################################
# add_new_keywords - add new keywords to my keyword catalog (e.g. nature.animal.dog)
##############################################################
sub add_new_keywords {
my $new_keys_ref = shift;
foreach my $key (@{$new_keys_ref}) {
my $new_key = '';
# add hierarchical (joined) keywords e.g. nature.animal.dog as nature, nature.dog and nature.animal.dog
foreach (split /\./, $key) {
$new_key .= $_;
push @prekeys, $new_key unless (isInList($new_key, \@prekeys));
$new_key .= '/';
}
# remove from global hash
delete $new_keywords{$key};
}
# show in keyword window (if open)
if (Exists($keyw)) {
insertTreeList($keyw->{tree}, @prekeys);
}
}
##############################################################
# openWith
##############################################################
sub openWith {
# todo
$top->messageBox(-icon => 'warning', -message => '"Open with ..." is not yet implemented, sorry!',
-title => 'Error', -type => 'OK');
}
##############################################################
# deletePics - deletes selected pictures
# mode: trash|rm
# trash = move to $trashdir
# rm = remove
##############################################################
sub deletePics {
my $lb = shift; # the reference to the active listbox widget
my $mode = shift; # constant TRASH or REMOVE
my @sellist = $lb->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
my @childs = $lb->info('children');
my $all = 0; $all = 1 if (@childs == @sellist); # all pics are selected
my ($pic, $dpic, $thumb, $rc, $bakpic, $bakthumb, $njpic, $size, $str);
my @dummylist = ();
my $changed = 0;
my $update = 0;
my $lastOne;
# build the show and the delete list
foreach $dpic (@sellist) {
$pic = basename($dpic);
$size = getFileSize($dpic, FORMAT);
$str .= sprintf "%-40s %10s\n", $pic, $size;
# after deletion we select the one after the last one deleted
$lastOne = $dpic;
}
my $reselectPic = $lb->info('next', $lastOne);
if ($mode == REMOVE) { # remove mode
$rc = myButtonDialog("Really delete?",
"Please press Ok to delete these ".scalar @sellist." files.\nThere is no undelete!\n\nPath: $actdir\n\n$str",
undef,
'OK', 'Cancel');
return unless ($rc eq 'OK');
}
elsif ($mode == TRASH) { # remove to trash mode
# check if the trash dir is available
if (!-d $trashdir) {
$lb->messageBox(-icon => 'warning',
-message => "Trashdir $trashdir not found!\nPlease create this dir (shell: mkdir $trashdir) and retry.\n\nAborting.",
-title => "Delete pictures", -type => 'OK');
return;
}
# check if we are in the trash dir
if ($actdir eq $trashdir) {
$lb->messageBox(-icon => 'warning', -message => "Please use <Shift-Delete> to really remove files from the trash!",
-title => "Delete pictures", -type => 'OK');
return;
}
makeDir("$trashdir/$thumbdirname", NO_ASK);
}
else {
warn "deletePics called without or with a wrong mode ($mode). Aborting";
return;
}
my $errors = "";
my $i = 0;
my $pw = progressWinInit($lb, "Delete pictures");
foreach $dpic (@sellist) {
last if progressWinCheck($pw);
$i++;
$pic = basename($dpic);
$bakpic = $dpic;
$bakpic =~ s/(.*)(\.jp(g|eg))/$1-bak$2/i;
$thumb = getThumbFileName($dpic);
$bakthumb = $thumb;
$bakthumb =~ s/(.*)(\.jp(g|eg))/$1-bak$2/i;
progressWinUpdate($pw, "deleting ($i/".scalar @sellist.") ...", $i, scalar @sellist);
if ($mode == REMOVE) {
if ( removeFile($dpic) ) {
$changed++;
#delete $searchDB{$dpic}; # line is moved to removeFile()
deleteCachedPics($dpic);
$lb->delete('entry', $dpic) unless $all;
}
} else { # $mode == TRASH - move picture to trash
if (move ($dpic, $trashdir)) {
$changed++; # count nr of successfull moves
my $tpic = "$trashdir/$pic";
# change the location info in the search database
$searchDB{$tpic} = $searchDB{$dpic};
$searchDB{$tpic}{odir} = dirname($dpic);
delete $searchDB{$dpic};
deleteCachedPics($dpic);
$lb->delete('entry', $dpic) unless $all;
# only if move was successfull, we also move the thumbnail
if ((-d "$trashdir/$thumbdirname") and (-f $thumb)) {
if (!move ("$thumb", "$trashdir/$thumbdirname")) {
$errors .= "Could not move thumbnail \"$thumb\" to $trashdir/$thumbdirname: $!\n";
}
}
} else {
$errors .= "Could not move picture \"$pic\" to $trashdir: $!\n";
}
}
# if file is removed and a backup file exists and is not in the delete list,
# we offer to rename the backup to the original name
# todo this should be done in one dialog for all files at the end
if ((!-f $dpic) and (-f $bakpic) and !isInList($bakpic, \@sellist)) {
my $age = getAgeOfFile($bakpic);
$age = " (which is $age old)" unless ($age eq "");
my $bakname = basename($bakpic);
$rc = myButtonDialog('Restore backup?',
"Picture \"$pic\" has a backup file$age.\nShould I rename the backup \"$bakname\" to \"$pic\"?",
$bakthumb,
'Rename', 'Cancel', 'Cancel all');
last if ($rc eq 'Cancel all');
if ($rc eq 'Rename') {
if (!rename ("$bakpic", "$dpic")) {
$errors .= "Could not rename $bakpic to $pic: $!\n";
}
else {
$searchDB{$dpic} = $searchDB{$bakpic};
delete $searchDB{$bakpic};
# rename thumbnail
rename ("$bakthumb", "$thumb");
if ($lb->info("exists", $bakpic)) {
unless (hlistEntryRename($lb, $bakpic, $dpic)) { warn "error renaming hlist entry $bakpic to $dpic"; }
}
# if the backup is already visible we don't need an update
if ($lb->info("exists", $dpic)) {
# change the displayed name
$lb->itemConfigure($dpic, $lb->{thumbcol}, -text => getThumbCaption($pic));
$lb->itemConfigure($dpic, $lb->{filecol}, -text => getAllFileInfo($dpic));
}
else {
$update++;
}
}
}
}
if (!-f $dpic) {
# ask to delete non-JPEG file, if any
foreach my $suf (split /\|/, $nonJPEGsuffixes) {
$njpic = $dpic;
$njpic =~ s/(.*)\.jp(g|eg)$/$1.$suf/i;
if (-f $njpic) {
$rc = $lb->messageBox(-icon => 'question', -message => "There is a non-JPEG file\n\"".basename($njpic)."\"\nOk to delete it too?",
-title => "Delete non-JPEG?", -type => 'OKCancel');
last if ($rc !~ m/Ok/i);
if ($mode == REMOVE) {
if ( removeFile($njpic) ) {
}
} elsif ($mode == TRASH) {
if (!move ("$njpic", "$trashdir")) {
$errors .="Could not move \"".basename($njpic)."\" to $trashdir: $!\n";
}
}
}
}
}
} # foreach
progressWinEnd($pw);
$userinfo = "deleted $changed of ".scalar @sellist." pictures"; $userInfoL->update;
if ($errors ne "") {
$errors = "These errors occured while deleting the ".scalar @sellist." selected pictures:\n$errors";
showText("Error while deleting", $errors, NO_WAIT);
}
checkTrash() if ($changed > 0);
$update++ if $all;
if ($update > 0) {
if ($lb == $picLB) {
updateThumbs();
}
else {
$lb->delete("all");
}
}
unless ($reselectPic) {
my @childs = $lb->info('children');
$reselectPic = $childs[-1];
}
if ($lb->info("exists", $reselectPic)) {
if (($lb == $picLB) and $config{ShowNextPicAfterDel}) {
showPic($reselectPic);
}
else { # just select it
$actpic = $reselectPic if ($lb == $picLB);
selectThumb($lb, $reselectPic);
}
}
$lb->focus;
}
##############################################################
# getAgeOfFile - returns a string representing the age of the
# given file (with max two of the units:
# day, hour, minute, second)
##############################################################
sub getAgeOfFile {
my $file = shift;
return "" unless (-f $file);
my $diff = abs(time() - (lstat $file)[9]);
my @secs = qw/86400 3600 60/;
my @unit = qw/days hours minutes/;
my $str = "";
my $t;
my $count = 0;
for $t ( 0 .. $#secs) {
my $i = int($diff/$secs[$t]);
if ($i > 0) {
$str = "$str $i $unit[$t]";
$count++;
last if ($count >= 2); # two numbers are enough
}
$diff %= $secs[$t];
}
$str = "$str $diff seconds" if ($count < 2);
return "$str";
}
##############################################################
# findValidIndex - try to find a index to show e.g. after a
# delete
##############################################################
sub findValidIndex {
my $lb = shift;
my $i = shift; # startindex
my @pics = $lb->info('children');
if ((defined $i) and ($i > $#pics)) {
$i = $#pics;
}
# if possible show the pic following the last deleted one
while ((!$lb->info("exists", $i)) and ($i < $#pics)) {
$i++;
}
if ($i > $#pics) { $i = 0; }
return $i;
}
sub centerWindow {
####################################################
# Args: (0) window to center
# (1) [optional] desired width
# (2) [optional] desired height
#
# Returns: *nothing*
####################################################
my($window, $width, $height) = @_;
$window->idletasks;
$width = $window->reqwidth unless $width;
$height = $window->reqheight unless $height;
my $x = int(($window->screenwidth / 2) - ($width / 2));
my $y = int(($window->screenheight / 2) - ($height / 2));
$window->geometry($width . 'x' . $height . "+" . $x . "+" . $y);
}
##############################################################
# repositionWindow - reposition window to fit in the desktop
##############################################################
sub repositionWindow {
my $win = shift;
my $xoffset = shift; # optional x offset (1 or 0) reposition window by half the width
my $border = 40;
my $reposition = 0;
my $geo = $win->geometry;
my ($w, $h, $x, $y) = splitGeometry($geo);
print "geo $w $h $x $y\n" if $verbose;
$h = $win->screenheight if ($h > $win->screenheight);
$w = $win->screenwidth if ($w > $win->screenwidth);
if ( ($y+$h+$border) > $win->screenheight) {
$y = $y - ( ($y+$h+$border) - $win->screenheight );
$reposition = 1;
}
if ( ($x+$w+$border) > $win->screenwidth) {
$x = $x - ( ($x+$w+$border) - $win->screenwidth );
$reposition = 1;
}
if ($x < 0) {
$x = 0;
$reposition = 1;
}
if ($y < 0) {
$y = 0;
$reposition = 1;
}
if ($xoffset) {
if ($x > 400) {
$x -= int($w/2+10);
}
else {
$x += int($w/2+10);
}
$reposition = 1;
}
if ($reposition) {
print "reposing to $w $h $x $y\n" if $verbose;
$win->geometry($w . 'x' . $h . "+" . $x . "+" . $y);
$win->update;
}
}
##############################################################
# printlist
##############################################################
sub printlist {
print "---\n";
foreach (@_) {print "$_\n";}
print "---\n";
}
##############################################################
# printhash
##############################################################
sub printhash {
my $hash = shift;
foreach (sort keys %{$hash}) {
print "$$hash->{$_} = $_ \n";
}
}
##############################################################
# bindItem - binds the motion event to the picture
##############################################################
sub bindItem {
my $id = shift;
$c->bind($id, '<Button-1>' => sub {
($idx,$idy)=($Tk::event->x,$Tk::event->y);
});
# change the mouse pointer
$c->bind($id, '<ButtonRelease-1>' => sub {
# Color picker
# get mouse coordinates
my $x = $c->canvasx($Tk::event->x);
my $y = $c->canvasy($Tk::event->y);
# get and apply offset (because pic may be centered in canvas)
my ($x1, $y1, $x2, $y2) = $c->bbox($id);
$x -= $x1;
$y -= $y1;
$x = 1 if ($x < 1);
$y = 1 if ($y < 1);
$x = $x2-$x1-2 if ($x > $x2-$x1-2);
$y = $y2-$y1-2 if ($y > $y2-$y1-2);
# get the color information from the picture
my($r,$g,$b) = $c->itemcget($id, -image)->get($x, $y);
#convert to hex from decimal
$config{ColorPicker} = sprintf "#%.2x%.2x%.2x", $r, $g, $b;
$userinfo = "Color picker: $config{ColorPicker}";
$colorPickerInfo->configure(-background => $config{ColorPicker});
$userInfoL->update;
$c->configure(-cursor => "crosshair");
});
$c->bind($id, '<Enter>' => sub {
$c->configure(-cursor => "crosshair");
});
$c->bind($id, '<Leave>' => sub {
$c->configure(-cursor => "top_left_arrow");
});
# enable panning in the canvas (autoscroll)
$c->bind($id, '<B1-Motion>' => sub {
# actual mouse coordinates
$c->configure(-cursor => "fleur");
my ($mx,$my)=($Tk::event->x,$Tk::event->y);
my ($x1,$x2) = $c->xview;
my ($y1,$y2) = $c->yview;
return if ($x1 == 0 and $x2 == 1 and $y1 == 0 and $y2 == 1);
my $dx = 0; $dx = ($mx-$idx)/$width if ($width >= 1); # avoid division by zero
my $dy = 0; $dy = ($my-$idy)/$height if ($height >= 1); # avoid division by zero
$c->xviewMoveto($x1-$dx) unless ($x1 == 0 and $x2 == 1);
$c->yviewMoveto($y1-$dy) unless ($y1 == 0 and $y2 == 1);
($idx,$idy)=($mx,$my);
});
# show picture coordinates
$c->bind($id, '<Motion>' => sub {
return unless $config{ShowCoordinates};
my $zf = 1;
# get mouse coordinates
my $x = $c->canvasx($Tk::event->x);
my $y = $c->canvasy($Tk::event->y);
# get the actual zoom factor from the global variable $zoomFactorStr
if ($zoomFactorStr =~ m/(.*)%$/) { # cut off the % sign
return if ($1 eq "?");
$zf = $1; # get the zoom factor in % (e.g. 80%)
$zf /= 100; # the zoom factor as float (e.g. 0.8)
} else {
warn "zoomStep: zoomFactorStr not matching *% - returning!" if $verbose;
return;
}
return if ($zf <= 0);
# get and apply offset (because pic may be centered in canvas)
my ($x1, $y1, $x2, $y2) = $c->bbox($id);
$x -= $x1;
$y -= $y1;
# apply zoom factor
$x = int($x/$zf);
$y = int($y/$zf);
# set borders
$x = 0 if ($x < 0);
$y = 0 if ($y < 0);
$x = $width if ($x > $width);
$y = $height if ($y > $height);
$userinfo = "mouse coordinates: $x, $y"; $userInfoL->update;
});
}
##############################################################
# changeDir
##############################################################
sub changeDir {
my $newDir = shift;
return 0 unless defined $newDir;
if ( !chdir $newDir ) {
my $dialog = $top->Dialog(-title => "Changing to $newDir directory failed",
-text => "Can't change to $newDir directory: $!",
-buttons => ['OK']);
$dialog->Show();
warn "Can't change to $newDir directory: $!";
return 0;
}
return 1;
}
##############################################################
# getCorners - get the visible corners of an canvas
##############################################################
sub getCorners {
my $c = shift;
my(@xview) = $c->xview;
my(@yview) = $c->yview;
my(@scrollregion) = @{$c->cget(-scrollregion)};
($xview[0] * ($scrollregion[2]-$scrollregion[0]) + $scrollregion[0],
$yview[0] * ($scrollregion[3]-$scrollregion[1]) + $scrollregion[1],
$xview[1] * ($scrollregion[2]-$scrollregion[0]) + $scrollregion[0],
$yview[1] * ($scrollregion[3]-$scrollregion[1]) + $scrollregion[1],
);
}
##############################################################
# autozoom - zooms the given picture to fit into the available size
##############################################################
sub autoZoom {
if (!$config{AutoZoom}) {
#$zoomFactor = 1;
return "100%";
}
my $photo = shift; # reference to a photo object
my $dpic = shift; # the file including dir (e.g. /home/herrmann/Bild.jpg)
my $cw = shift; # the available width
my $ch = shift; # the available height
my ($pw, $ph) = getSize($dpic);
my ($wf, $hf, $zoom, $subsample, $max, $i);
return "" if (!$$photo);
return "" if (!-f $dpic);
return "" if (!defined($cw));
return "" if (!defined($ch));
print "autoZoom: place: $cw/$ch pic:$pw/$ph\n" if $verbose;
$wf = $pw/($cw - 6); # the offset (6) is needed, maybe because of the border?
$hf = $ph/($ch - 6);
$max = max($wf, $hf); # find the biggest zoom factor
#print "width factor = $wf h fac = $hf max = $max\n";
return "100%" if ($max <= 1);
# search for a zoom/subsample pair which will zoom the pic at least to the needed factor 1/$max
for ($i = 0; $i < (@frac - 2); $i += 2) {
if (($frac[$i]/$frac[$i+1]) < (1/$max)) {
last;
}
}
$zoom = $frac[$i];
$subsample = $frac[$i+1];
# show the user what's going on ...
my $zoomFactor = $subsample/$zoom;
$zoomFactor = int(1/$zoomFactor * 100)."%";
$userinfo = "zooming to $zoomFactor ..."; $userInfoL->update;
return "100%" if ($zoom == $subsample);
# open new photo object
my $zoomed = $top->Photo;
$zoomed->blank;
$zoomed->copy($$photo, -zoom => $zoom); # first zoom it
$$photo->delete;
$$photo = undef;
$$photo = $top->Photo;
#$$photo->blank;
$$photo->copy($zoomed, -subsample => $subsample); # then subsample it
$$photo->configure(-gamma => $config{Gamma});
$zoomed->delete;
$zoomed = undef;
print "autoZoom: $zoomFactor\n" if $verbose;
return $zoomFactor;
}
##############################################################
# getZoomAndSub - build a appropriate fraction for zoom and
# subsample from a zoomfactor (float)
##############################################################
sub getZoomAndSub {
my $targetfactor = shift; # the target zoom factor e.g. 0.66
my $step = shift; # -1 = stay beyond $targetfactor; +1 = return a bigger value than $targetfactor
my $i = 0;
my $dif = 1000; # difference to the targetfactor
my $diflast = $dif + 1; # last difference
# search the @frac array for the right fraction
for ($i = 0; $i < (@frac - 2); $i += 2) {
$dif = abs(($frac[$i]/$frac[$i+1]) - $targetfactor); # how far are we away?
#$dif *= -1 if ($dif < 0); # the difference must allways be positive
#printf " up %1.3f %2d %1.3f %2d/%-2d %1.3f\n", $targetfactor, $i, ($frac[$i]/$frac[$i+1]), $frac[$i], $frac[$i+1], $dif;
last if ( $dif > $diflast); # if the difference starts to grow we jump out
$diflast = $dif;
}
$i -= 2; # the last fraction had the lowest difference to the targetfactor
$i -= $step*2; # go to the next or previous fraction
# boundary checks (stay in the array)
$i = 0 if ($i < 0);
$i = @frac - 1 if ($i > @frac - 1);
return ($frac[$i], $frac[$i+1]);
}
##############################################################
# max - returns the biggest number in a list
##############################################################
sub max {
my $max = shift;
for(@_) {
$max = $_ if $max < $_;
}
return $max;
}
##############################################################
# zoomStep - increase/decrease the actual zoom factor
##############################################################
sub zoomStep {
my $step = shift; # +1 or -1
my $zoom = 1; # fallback value
my $subsample = 5; # fallback value
# get the actual zoom factor from the global variable $zoomFactorStr
if ($zoomFactorStr =~ m/(.*)%$/) { # cut off the % sign
print "matching *% $1\n" if $verbose;
my $zf = $1; # get the zoom factor in %
$zf /= 100; # the zoom factor as float
# find the next / previous zoom level
($zoom, $subsample) = getZoomAndSub($zf, $step);
print "z = $zoom s = $subsample for $zf\n" if $verbose;
} else {
warn "zoomStep: zoomFactorStr not matching *% - returning!" if $verbose;
return;
}
# zoom the picture
zoom ($zoom, $subsample);
}
##############################################################
# zoom - zooms the actual displayed picture to the given
# zoom and subsample values
##############################################################
sub zoom {
my ($zoom, $subsample) = @_;
print "zoom: $zoom $subsample\n" if $verbose;
my $dpic = $actpic;
# zoom the actual picture
return unless (defined $photos{$dpic});
$top->Busy;
$userinfo = "zooming to ".int($zoom/$subsample*100)."% ..."; $userInfoL->update();
$photos{$dpic}->delete;
delete $photos{$dpic};
print "reloading $actpic\n" if $verbose;
$photos{$dpic} = $top->Photo(-file => $dpic, -gamma => $config{Gamma});
my $zoomed = $top->Photo;
$zoomed->blank;
$zoomed->copy($photos{$dpic}, -zoom => $zoom);
# delete item from canvas
$c->delete('withtag', $dpic); # remove it from the canvas
#deleteCachedPics($dpic);
#$photos{$dpic} = undef;
#$photos{$dpic} = $top->Photo;
$photos{$dpic}->blank if $photos{$dpic};
$photos{$dpic}->copy($zoomed, -subsample => $subsample);
$photos{$dpic}->configure(-gamma => $config{Gamma});
$zoomed->delete;
$zoomed = undef;
# center pic in canvas, only when it's smaller
my $xoffset = 0; my $yoffset = 0;
$xoffset = int(($c->width - $photos{$dpic}->width) /2) if ($c->width > $photos{$dpic}->width);
$yoffset = int(($c->height - $photos{$dpic}->height)/2) if ($c->height > $photos{$dpic}->height);
# insert pic to the canvas
my $id = $c->createImage($xoffset, $yoffset, -image => $photos{$dpic}, -anchor => "nw", -tag => ["pic","$dpic"], -state => "hidden");
bindItem($id);
addToCachedPics($dpic);
$top->Unbusy;
showPic($dpic);
}
##############################################################
# makeButton
##############################################################
sub makeButton {
my $parentWidget = shift;
my $position = shift;
my $text = shift;
my $picName = shift;
my $func = shift;
my $pic = "$configdir/$picName";
my $image = $parentWidget->Photo(-file => $pic) if -f $pic;
if ($image) {
return $parentWidget->Button(-image => $image,
-borderwidth => 0,
-command => sub {
eval "$func";
}
)->pack(-side => $position,
-padx => 0,
-pady => 0);
}
else {
return $parentWidget->Button(-text => $text,
-command => sub {
eval "$func";
}
)->pack(-side => $position,
-padx => 0,
-pady => 0);
}
}
##############################################################
# layout - an sub, to change the layout of mapivi
##############################################################
sub layout {
my $withAdjuster = shift;
saveAdjusterPos() if $withAdjuster;
$config{Layout} = 0 if (($config{Layout} > 5) or ($config{Layout} < 0));
my $info = "";
if ($config{Layout} == 0) {
$info = "directories-thumbnails-picture";
$config{ShowDirTree} = 1;
$config{ShowThumbFrame} = 1;
$config{ShowPicFrame} = 1;
}
elsif ($config{Layout} == 1) {
$info = "directories-thumbnails";
$config{ShowDirTree} = 1;
$config{ShowThumbFrame} = 1;
$config{ShowPicFrame} = 0;
}
elsif ($config{Layout} == 2) {
$info = "thumbnails";
$config{ShowDirTree} = 0;
$config{ShowThumbFrame} = 1;
$config{ShowPicFrame} = 0;
}
elsif ($config{Layout} == 3) {
$info = "thumbnails-picture";
$config{ShowDirTree} = 0;
$config{ShowThumbFrame} = 1;
$config{ShowPicFrame} = 1;
}
elsif ($config{Layout} == 4) {
$info = "picture";
$config{ShowDirTree} = 0;
$config{ShowThumbFrame} = 0;
$config{ShowPicFrame} = 1;
}
elsif ($config{Layout} == 5) {
$info = "picture";
$config{ShowDirTree} = 1;
$config{ShowThumbFrame} = 0;
$config{ShowPicFrame} = 1;
}
else {
warn "error: toggle = ".$config{Layout}.", this should never happen!";
$config{Layout} = 0;
return;
}
if ($info ne "") { $userinfo = "layout $info"; $userInfoL->update; }
showHideFrames();
$top->update;
setAdjusterPos() if $withAdjuster;
$layoutOld = $config{Layout}; # save the actual Layout
}
##############################################################
# setAdjusterPos - set the position of the Adjusters according
# to the global hash values
##############################################################
sub setAdjusterPos {
my $x = $subF->width; # width of the surrounding frame
my $dirS = $dirA->slave;
my $thuS = $thumbA->slave;
my $min = 40; # min distance for safety
my $dirXnew = $min; # width of adjuser $dirA
my $thumbXnew = $min; # width of adjuser $thumbA
$x = $top->width if ($x == 1); # $x = 1 at startup, so we use the window width
if ($config{Layout} == 0) { # dirs thumbs picture
$dirXnew = int($config{Layout0dirX}*$x/100);
$thumbXnew = int($config{Layout0thumbX}*$x/100);
}
elsif ($config{Layout} == 1) { # dirs thumbs
$dirXnew = int($config{Layout1dirX}*$x/100);
$thumbXnew = int($x - $dirXnew);
}
elsif ($config{Layout} == 2) { }
elsif ($config{Layout} == 3) { # thumbs picture
$thumbXnew = int($config{Layout3thumbX}*$x/100);
}
elsif ($config{Layout} == 4) { }
elsif ($config{Layout} == 5) { # dirs picture
$dirXnew = int($config{Layout5dirX}*$x/100);
}
else {
warn "error: toggle = ".$config{Layout}.", this should never happen!";
$dirXnew = 1, $thumbXnew = 1; $config{Layout} = 0;
return;
}
print "layoutNew=".$config{Layout}." dirXnew=$dirXnew (".int($dirXnew/$x*100)."%) thumbXnew=$thumbXnew (".int($thumbXnew/$x*100)."%) x=$x dir=".$config{ShowDirTree}." thumb=".$config{ShowThumbFrame}." pic=".$config{ShowPicFrame}."\n" if $verbose;
$dirS->configure(-width => $dirXnew) if ($dirS->ismapped());
#print "[dirS]" if ($dirS->ismapped());
$thuS->configure(-width => $thumbXnew) if ($thuS->ismapped());
#print "[thuS]" if ($thuS->ismapped());print "\n";
$top->update;
}
##############################################################
# saveAdjusterPos - save the actual position of the Adjusters
# to the global hash
##############################################################
sub saveAdjusterPos {
my $x = $subF->width; # width of the surrounding frame
my $dirS = $dirA->slave;
my $thuS = $thumbA->slave;
return if ($x < 1);
my $dirX = 0;
my $thumbX = 0;
if ($dirS->ismapped()) {
# get the actual width of the dir frame
$dirX = $dirS->width;
# convert it to a percentual value
$dirX = $dirX / $x * 100;
# not too small not to wide (between 5% and 95%)
$dirX = 95 if ($dirX > 95);
$dirX = 5 if ($dirX < 5);
}
if ($thuS->ismapped()) {
# get the actual width of the thumb frame
$thumbX = $thuS->width;
# convert it to a percentual value
$thumbX = $thumbX / $x * 100;
# not too small not to wide (between 5% and 95%)
$thumbX = 95 if ($thumbX > 95);
$thumbX = 5 if ($thumbX < 5);
}
if ($layoutOld == 0) {
$config{Layout0dirX} = $dirX if ($dirS->ismapped());
$config{Layout0thumbX} = $thumbX if ($thuS->ismapped());
}
elsif ($layoutOld == 1) {
$config{Layout1dirX} = $dirX if ($dirS->ismapped());
}
elsif ($layoutOld == 3) {
$config{Layout3thumbX} = $thumbX if ($thuS->ismapped());
}
elsif ($layoutOld == 5) {
$config{Layout5dirX} = $dirX if ($dirS->ismapped());
}
print "layoutOld=$layoutOld dirX=$dirX% thumbX=$thumbX% x=$x\n" if $verbose;
}
##############################################################
# readConfig - read the configuration from file to hash
##############################################################
sub readConfig {
my $rcfile = shift;
my $configRef = shift;
print "readConfig: reading $rcfile\n" if $verbose;
if (!$rcfile) {
warn "readConfig: no file!"; return;
}
if (ref($configRef) ne 'HASH') {
warn "readConfig: $configRef is no hash ref!"; return;
}
return 0 if (!-f $rcfile);
my $file;
if (!open($file, "<$rcfile")) {
warn "readConfig: Couldn't open $rcfile: $!";
return 0;
}
my $errors = 0;
while (<$file>) {
chomp; # no newline
s/^#.*//; # no comments (lines starting with #)
s/^\s+//; # no leading white
s/\s+$//; # no trailing white
next unless length; # anything left?
my ($key, $value) = split(/\s*=\s*/, $_, 2); # split around the equal sign
$value =~ s/<br>/\n/g; # replace "<br>" by newline
if (!defined $configRef->{$key}) {
warn "readConfig: key $key (value: $value) should not belong to the config hash - removing\n" ;
$errors++;
next;
}
# save in global config hash, overwrite default value
$configRef->{$key} = $value;
}
close $file;
if (($errors > 0) and (-d $trashdir)) {
my $datetime = getDateTime();
# save a copy of the old config in the trash # todo: remove very old backups
warn "saving a backup of the config in the trash ($trashdir)\n";
mycopy($rcfile, $trashdir."/".basename($rcfile)."-$datetime", OVERWRITE);
}
return 1;
}
##############################################################
# saveConfig - save the configuration from hash to file
##############################################################
sub saveConfig {
my $rcfile = shift;
my $config = shift;
my $value;
print "saveConfig: writing $rcfile\n" if $verbose;
my $file;
if (!open($file, ">$rcfile")) {
warn "saveConfig: Couldn't open $rcfile: $!";
return 0;
}
print $file "\n# Configuration file for mapivi $version\n\n";
print $file "# last update: ", scalar localtime, "\n\n";
print $file "# This file will be overwritten each time you quit mapivi\n";
#print $file "# or call the \"Save config\" menu item.\n\n";
foreach (sort keys %{$config}) {
$value = $$config{$_};
$value =~ s/\n/<br>/g; # replace newline by "<br>"
print $file $_," = ", $value,"\n";
}
close $file;
return 1;
}
##############################################################
# readArrayFromFile - read an array from a file
##############################################################
sub readArrayFromFile {
my $file = shift;
my @list;
if (!$file) {
warn "readArrayFromFile: no file!"; return;
}
return () if (!-f $file);
my $fileH;
if (!open($fileH, "<$file")) {
warn "readArrayFromFile:: Couldn't open $file: $!";
return ();
}
while (<$fileH>) {
chomp; # no newline
s/^#.*//; # no comments (lines starting with #)
s/^\s+//; # no leading white
s/\s+$//; # no trailing white
next unless length; # anything left?
push @list, $_;
}
close $fileH;
return @list;
}
##############################################################
# saveArrayToFile - save a array to a file
##############################################################
sub saveArrayToFile {
my $file = shift;
my $listref = shift;
my $value;
my $fileH;
if (!open($fileH, ">$file")) {
warn "saveArrayToFile: Couldn't open $file: $!";
return 0;
}
foreach (@$listref) {
print $fileH "$_\n";
}
close $fileH;
return 1;
}
##############################################################
# showPicInOwnWin - displays a picture in a separate window
# a mouse click on the picture will close
# the window
##############################################################
sub showPicInOwnWin {
my $dpic = shift;
my $fullscreen = 0;
my $lb = 0;
if ((!defined $dpic) or ($dpic eq "") or (!-f $dpic)) {
# no picture given, take selection from main window
my @sellist = $picLB->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
$dpic = $sellist[0]; # simply take the first if there are more selected
$lb = $picLB;
}
if (!-f $dpic) {
$top->messageBox(-icon => 'warning', -message => "showPicinOwnWin: Error no file $dpic",
-title => 'Error', -type => 'OK');
return;
}
my $pic = basename($dpic);
$userinfo = "opening $pic in new window ..."; $userInfoL->update;
my $photo = $top->Photo(-file => $dpic, -gamma => $config{Gamma});
if (! $photo) {
$top->messageBox(-icon => 'warning', -message => "showPicinOwnWin: Error no photo $pic!",
-title => 'Error', -type => 'OK');
$userinfo = ""; $userInfoL->update;
return;
}
increasePicPopularity($dpic);
if (($config{trackPopularity}) and ($lb == $picLB)) {
updateOneRow($dpic, $lb); # update popularity (viewed x times) info
$lb->update;
}
my $zoomFactor = autoZoom(\$photo, $dpic, $top->screenwidth, $top->screenheight);
# open window
my $win = $top->Toplevel(-bg => "black");
#$win->withdraw;
$win->title("$pic $zoomFactor");
$win->iconname($pic);
# use the picture thumbnail as window icon
my $iconfile = getThumbFileName($dpic);
my $iconPhoto = $win->Photo(-file => $iconfile) if (-f $iconfile);
$win->idletasks if $EvilOS; # this line is crucial (at least on windows)
$win->iconimage($iconPhoto) if $iconPhoto;
my $but = $win->Button(-image => $photo,
-border => 0,
-relief => "flat",
-command => sub {
$win->grabRelease();
$win->withdraw();
$photo->delete;
$iconPhoto->delete if $iconPhoto;
$win->destroy();
},)->pack(-anchor => "center", -expand => 1, -padx => 0, -pady => 0);
my $balloonmsg = makeBalloonMsg($dpic);
$balloonmsg .= "\n\n(Click on picture to close window)";
$balloon->attach($but, -balloonposition => "mouse", -msg => \$balloonmsg);
$win->bind('<Key-q>', sub { $but->invoke; });
$win->bind('<Key-Escape>', sub { $but->invoke; });
# invoke $but when the window is closed by the window manager (x-button)
$win->protocol("WM_DELETE_WINDOW" => sub { $but->invoke; });
# key-desc,F11,toggle fullscreen mode when displaying picture in own window
$win->bind('<Key-F11>', sub
{
$fullscreen = ($fullscreen) ? 0 : 1;
fullscreen($win, $fullscreen);
});
# key-desc,o,overrideredirect (fullscreen mode - experimental) when displaying picture in own window
$win->bind('<Key-o>', sub
{
#print "override=".$config{Overrideredirect}."\n";
if ($config{Overrideredirect}) {
#print "no frame\n";
#fullscreen($win, 1);
#$but->bind('<Enter>',sub{$but->focusForce;$but->grabGlobal});
#$but->bind('<Leave>',sub{$but->grabRelease});
#$win->focusForce;
#$win->grabGlobal;
$config{Overrideredirect} = 0; # toggle
} else {
#print "frame\n";
#fullscreen($win, 0);
#$win->grabRelease();
$config{Overrideredirect} = 1; # toggle
}
#print "override=".$config{Overrideredirect}."\n";
fullscreen($win, $fullscreen);
$win->bind('<Enter>',sub{$win->focusForce;$win->grabGlobal;});
$win->bind('<Leave>',sub{$win->grabRelease});
}
);
#$win->deiconify;
#$win->raise;
fullscreen($win, $fullscreen);
$but->focusForce if (Exists($but));
$userinfo = "ready!"; $userInfoL->update;
}
##############################################################
# show_multiple_pics - displays several pictures in a separate window
# a mouse click on the picture will close
# the window
##############################################################
sub show_multiple_pics {
my $pic_list = shift; # reference to a picture list, each with full path
my $index = 0; $index = shift; # start index number, optional, defaults to first pic (index = 0)
unless (defined $pic_list) { warn "pic list undef"; return; }
unless (ref($pic_list) eq 'ARRAY') {warn "pic list is no array reference"; return; }
unless (@{$pic_list} >= 1) {warn "pic list is empty"; return; }
#my $fullscreen = 0;
my $balloon_addon = "\n\n(Click on picture to close window; use PgUp and PgDown for next/previous picture)";
my $dpic = @$pic_list[$index];
my $pic = basename($dpic);
my ($photo, $zoomFactor);
my $rc = load_zoom_pic($dpic, \$photo, \$zoomFactor);
return unless ($rc);
# open window
my $win = $top->Toplevel(-bg => "black");
#$win->withdraw;
$win->title(sprintf "(%d/%d) %s %s", ($index+1), ($#{@{$pic_list}}+1), $pic, $zoomFactor);
$win->iconname($pic);
# use the picture thumbnail as window icon
my $iconfile = getThumbFileName($dpic);
my $iconPhoto = $win->Photo(-file => $iconfile) if (-f $iconfile);
$win->idletasks if $EvilOS; # this line is crucial (at least on windows)
$win->iconimage($iconPhoto) if $iconPhoto;
my $but = $win->Button(-image => $photo,
-border => 0,
-relief => "flat",
-command => sub {
$win->grabRelease();
$win->withdraw();
$photo->delete;
$iconPhoto->delete if $iconPhoto;
$win->destroy();
},)->pack(-anchor => "center", -expand => 1, -padx => 0, -pady => 0);
my $balloonmsg = makeBalloonMsg($dpic).$balloon_addon;
if ($config{PicWinBalloon}) {
$balloon->attach($but, -balloonposition => "mouse", -msg => \$balloonmsg);
}
# the context menu
my $menu = $win->Menu(-title => "Menu");
$menu->checkbutton(-label => "Balloon popup info",
-variable => \$config{PicWinBalloon},
-command => sub {
if ($config{PicWinBalloon}) {
$balloon->attach($but, -balloonposition => "mouse", -msg => \$balloonmsg);
} else {
$balloon->detach($but);
}
});
$menu->command(-label => "next picture", -command => sub { print "use PageDown instead\n"; }); # todo
$menu->command(-label => "previous picture", -command => sub { print "use PageUp instead\n"; }); # todo
$menu->command(-label => "close window", -command => sub { $but->invoke; });
# mouse and button bindings
$win->bind('<ButtonPress-3>', sub {
$menu->Popup(-popover => "cursor", -popanchor => "nw");
} );
$win->bind('<Key-q>', sub { $but->invoke; });
$win->bind('<Key-Escape>', sub { $but->invoke; });
# invoke $but when the window is closed by the window manager (x-button)
$win->protocol("WM_DELETE_WINDOW" => sub { $but->invoke; });
$win->bind('<Key-Next>', sub {
$win->Busy;
$index++;
$index = 0 if ($index > $#{@{$pic_list}});
$dpic = @$pic_list[$index];
$pic = basename($dpic);
$win->title(sprintf "(%d/%d) loading %s ...", ($index+1), ($#{@{$pic_list}}+1), $pic);
my $rc = load_zoom_pic($dpic, \$photo, \$zoomFactor);
$but->invoke unless ($rc);
$win->title(sprintf "(%d/%d) %s %s", ($index+1), ($#{@{$pic_list}}+1), $pic, $zoomFactor);
$win->iconname($pic);
$but->configure(-image => $photo);
$balloonmsg = makeBalloonMsg($dpic).$balloon_addon;
$win->Unbusy;
});
$win->bind('<Key-Prior>', sub {
$win->Busy;
$index--;
$index = $#{@{$pic_list}} if ($index < 0);
$dpic = @$pic_list[$index];
$pic = basename($dpic);
$win->title(sprintf "(%d/%d) loading %s ...", ($index+1), ($#{@{$pic_list}}+1), $pic);
my $rc = load_zoom_pic($dpic, \$photo, \$zoomFactor);
$but->invoke unless ($rc);
$win->title(sprintf "(%d/%d) %s %s", ($index+1), ($#{@{$pic_list}}+1), $pic, $zoomFactor);
$win->iconname($pic);
$but->configure(-image => $photo);
$balloonmsg = makeBalloonMsg($dpic).$balloon_addon;
$win->Unbusy;
});
# key-desc,F11,toggle fullscreen mode when displaying picture in own window
#$win->bind('<Key-F11>', sub
# {
# $fullscreen = ($fullscreen) ? 0 : 1;
# fullscreen($win, $fullscreen);
# });
#$win->deiconify;
#$win->raise;
$but->focusForce if (Exists($but));
$userinfo = "ready!"; $userInfoL->update;
}
##############################################################
# load_zoom_pic - load and zoom a picture
# returns 1 on success and 0 on failure
##############################################################
sub load_zoom_pic {
my $dpic = shift;
my $photo = shift; # reference to photo object
my $zoomFactor = shift; # reference to zoom factor (string)
if (!-f $dpic) {
$top->messageBox(-icon => 'warning', -message => "load_zoom_pic: Error no file $dpic",
-title => 'Error', -type => 'OK');
return 0;
}
$userinfo = "opening $dpic in new window ..."; $userInfoL->update;
$$photo = $top->Photo(-file => $dpic, -gamma => $config{Gamma});
if (!$$photo) {
$top->messageBox(-icon => 'warning', -message => "load_zoom_pic: Error no photo $dpic!",
-title => 'Error', -type => 'OK');
$userinfo = ""; $userInfoL->update;
return 0;
}
increasePicPopularity($dpic);
if ($config{trackPopularity}) {
updateOneRow($dpic, $picLB); # update popularity (viewed x times) info - todo: will throw a warning if started somewhere else and dpic is not in this lb
$picLB->update;
}
$$zoomFactor = autoZoom(\$$photo, $dpic, $top->screenwidth, $top->screenheight);
return 1;
}
##############################################################
# showThumbList - displays a list of thumbs on a scrollable pane
##############################################################
sub showThumbList {
my $thumbs = shift; # reference on an array containing pictures
my $title = shift; # optinal window title
unless (@$thumbs) {
$userinfo = "$title: no pictures"; $userInfoL->update;
return;
}
my $nr = @$thumbs; # total number
$userinfo = "displaying $nr thumbs in new window ..."; $userInfoL->update;
#stopWatchStart();
# open window
my $win = $top->Toplevel(-bg => "black");
$win->withdraw;
$win->title("$title - $nr pictures");
# set the icon
$win->iconname("Pictures");
$win->iconimage($mapiviicon) if $mapiviicon;
my $topFrame = $win->Frame()->pack(-fill => 'both', -expand => 1);
my %tphotos; # local hash to store the thumbnail photo objects
$topFrame->Button(-text => "Close",
-command => sub { cleanUpAndClose($win, \%tphotos); })->pack(-side => 'left');
$win->{label} = "$nr pictures, 0 selected";
$topFrame->Label(-textvariable => \$win->{label})->pack(-side => 'left');
my $cols = 6;
$cols = $nr if ($nr < $cols);
my $maxrows = int($win->screenheight/($config{ThumbSize} + 20));
my $rows = int($nr/$cols) + 1;
$rows = $maxrows if ($rows > $maxrows);
print "tiler: nr:$nr col:$cols row:$rows maxroe:$maxrows\n" if $verbose;
my $tiler = $win->Scrolled("Tiler",
-columns => $cols,
-rows => $rows,
-scrollbars => 'oe',
)->pack(-fill => 'both', -expand => 1);
bindMouseWheel($tiler);
# list of all the window objects of $tiler
# special values are $a[$i]->{selected} a boolean value 1=selected 0=not selected
# and $a[$i]->{dpic} the path and the name of the displayed picture
my @a;
# the context menu
my $menu = $win->Menu(-title => "Menu");
############# selection menu
my $sel_menu = $menu->cascade(-label => "select ...");
$sel_menu->cget(-menu)->configure(-title => "Selection menu");
############# select all
$sel_menu->command(-label => "select all", -command => sub {
foreach (@a) { $_->{selected} = 1; }
my $sel = 0;
foreach (@a) { $sel++ if $_->{selected}; }
$win->{label} = "$nr pictures, $sel selected";
});
############# select none
$sel_menu->command(-label => "select none", -command => sub {
foreach (@a) { $_->{selected} = 0; }
my $sel = 0;
foreach (@a) { $sel++ if $_->{selected}; }
$win->{label} = "$nr pictures, $sel selected";
});
############# invert selection
$sel_menu->command(-label => "invert selection", -command => sub {
foreach (@a) { toggle(\$_->{selected}); }
my $sel = 0;
foreach (@a) { $sel++ if $_->{selected}; }
$win->{label} = "$nr pictures, $sel selected";
});
############# list selection
$sel_menu->command(-label => "list selection", -command => sub {
my @sel = ();
# get the selection
foreach (@a) { push @sel, $_->{dpic} if $_->{selected}; }
my $text = scalar @sel." pictures are selected:\n";
foreach (@sel) { $text .= "$_\n"; }
showText("selected pictures", $text, NO_WAIT);
});
$menu->separator;
############# open picture in main window
$menu->command(-label => "open picture in main window", -command => sub {
my @sel;
# get the selection
foreach (@a) { push @sel, $_->{dpic} if $_->{selected}; }
return unless checkSelection($win, 1, 1, \@sel);
my $dpic = $sel[0];
my $dir = dirname($dpic);
my $pic = basename($dpic);
if (!-d $dir) {
$win->messageBox(-icon => 'warning', -message => "Sorry, but the directory\n$dir\nis not availabale at the moment.\nMaybe you should clean your database\nor insert a removable media.",
-title => 'directory not found', -type => 'OK');
return;
}
$top->deiconify;
$top->raise;
$top->focus;
openDirPost($dir) if ($dir ne $actdir);
showPic($dpic);
});
############# add to light table
$menu->command(-label => "add to light table", -command => sub {
my @sel;
# get the selection
foreach (@a) { push @sel, $_->{dpic} if $_->{selected}; }
return unless (@sel);
light_table_add(\@sel);
});
############# copy selected
$menu->command(-label => "copy selected ...", -command => sub {
my @sel;
# get the selection
foreach (@a) { push @sel, $_->{dpic} if $_->{selected}; }
return unless (@sel);
my $targetdir = getDirDialog("Copy pictures to");
return unless (-d $targetdir);
makeDir(dirname(getThumbFileName("$targetdir/dummy.jpg")), ASK);
my ($pic, $dpic, $tpic, $thumbpic, $thumbtpic, $njpic);
my $pw = progressWinInit($win, "copy pictures");
my $i = 0;
my $rc = 1;
my $n = 0; # count successfull copied pictures
foreach $dpic (@sel) {
last if progressWinCheck($pw);
$pic = basename($dpic);
$i++;
progressWinUpdate($pw, "copy picture ($i/".scalar @sel.") ...", $i, scalar @sel);
$tpic = "$targetdir/$pic";
# if the pic exists, ask if the user wants to overwrite it
$rc = overwritePic($tpic, $dpic, (scalar(@sel) - $i + 1)) if ($rc != 2);
next if ($rc == 0);
last if ($rc == -1);
if (mycopy ("$dpic", "$tpic", OVERWRITE)) {
$n++;
$thumbpic = getThumbFileName($dpic);
$thumbtpic = getThumbFileName($tpic);
if ((-d dirname($thumbtpic)) and (-f $thumbpic)) {
mycopy ("$thumbpic","$thumbtpic", OVERWRITE)
}
}
} # foreach - end
progressWinEnd($pw);
});
############# show infos
$menu->command(-label => "show picture info", -command => sub {
my @sel;
foreach (@a) { push @sel, $_->{dpic} if $_->{selected}; }
return unless (@sel);
return unless askSelection(\@sel, 10, "picture info");
foreach my $dpic (@sel) {
my $info = makeBalloonMsg($dpic);
showText($dpic, $info, NO_WAIT, getThumbFileName($dpic));
} });
############# delete
$menu->command(-label => "delete selected pictures to trash", -command => sub {
delPicsToTrash($win, \@a, $thumbs, $title, \%tphotos);
}, -accelerator => '<Delete>');
$win->bind('<Key-Delete>', sub { delPicsToTrash($win, \@a, $thumbs, $title, \%tphotos); } );
# mouse and button bindings
$win->bind('<ButtonPress-3>', sub {
$menu->Popup(-popover => "cursor", -popanchor => "nw");
} );
my $i = 0;
my $frame;
my $pw = progressWinInit($picLB, "Show thumbnails");
foreach my $dpic (@$thumbs) {
last if progressWinCheck($pw);
progressWinUpdate($pw, "loading thumbnail (".($i+1)."/$nr) ...", ($i+1), $nr);
#if ( $i % $cols == 1 or $cols == 1 ) { # start new table row (modulo)
# $frame = $tiler->Frame()->pack();
#}
my $thumbFile = getThumbFileName($dpic);
$tphotos{$dpic} = $win->Photo(-file => $thumbFile, -gamma => $config{Gamma}) if (-f $thumbFile);
if (! $tphotos{$dpic}) {
#$top->messageBox(-icon => 'warning', -message => "showThumbList: Error no thumb for photo $dpic!",
# -title => 'Error', -type => 'OK');
$tphotos{$dpic} = $defaultthumbP if $defaultthumbP;
next unless $tphotos{$dpic};
}
my $j = $i; # we need a local copy here
$a[$i] = $tiler->Frame(-border => 1, -relief => "raised");
$a[$i]->{selected} = 0;
$a[$i]->{dpic} = $dpic;
my $check = $a[$i]->Checkbutton(-variable => \$a[$i]->{selected},
-border => 1,
-padx => 0, -pady => 0,
-command => sub {
my $sel = 0;
foreach (@a) { $sel++ if $_->{selected}; }
$win->{label} = "$nr pictures, $sel selected";
},)->pack(-side => "left", -expand => 0, -fill => "none", -anchor => "s", -padx => 0, -pady => 0);
my $but = $a[$i]->Button(-image => $tphotos{$dpic},
-border => 0,
-relief => "flat",
-padx => 0, -pady => 0,
-command => sub {
$check->invoke if (Exists($check));
},)->pack(-side => "left", -expand => 0, -fill => "none", -padx => 0, -pady => 0);
$but->bind('<ButtonPress-2>', sub { showPicInOwnWin($dpic); });
my $msg; # the balloon message is generated on demand later, to speed up the loading of the thumbs
$balloon->attach($but, -postcommand => sub { $msg = makeBalloonMsg($dpic); $msg .= "\n\nRight mouse button for context menu, middle mouse button to open picture";}, -balloonposition => "mouse", -msg => \$msg);
$tiler->Manage($a[$i]);
$i++;
}
progressWinEnd($pw);
$win->bind('<Key-Escape>', sub { cleanUpAndClose($win, \%tphotos); });
$win->bind('<Key-q>', sub { cleanUpAndClose($win, \%tphotos); });
$win->deiconify;
$win->raise;
#stopWatchStop("showThumbList");
$userinfo = "ready!"; $userInfoL->update;
}
##############################################################
# cleanUpAndClose - for showThumbList
##############################################################
sub cleanUpAndClose($$) {
my $win = shift;
my $hashref = shift;
$win->withdraw;
foreach (keys %{$hashref}) {
if ($$hashref{$_}) {
# do not delete the default thumbnail!
$$hashref{$_}->delete unless ($$hashref{$_} == $defaultthumbP);
}
}
Tk->break;
}
##############################################################
# delPicsToTrash
##############################################################
sub delPicsToTrash {
my ($win, $a, $thumbs, $title, $tphotos) = @_;
unless (defined $a) { warn "a undef"; return; }
unless (ref($a) eq 'ARRAY') {warn "a is no array"; return; }
unless (defined $thumbs) { warn "thumbs undef"; return; }
unless (ref($thumbs) eq 'ARRAY') {warn "thumbs is no array"; return; }
my @sel;
my $deleted = 0;
my $errors = "";
if (!-d $trashdir) {
$win->messageBox(-icon => 'warning',
-message => "Trashdir $trashdir not found!\nPlease create this dir (shell: mkdir $trashdir) and retry.\n\nAborting.",
-title => "Delete pictures", -type => 'OK');
return;
}
# check if we are in the trash dir
if ($actdir eq $trashdir) {
$win->messageBox(-icon => 'warning', -message => "Please use <Shift-Delete> to really remove files from the trash!",
-title => "Delete pictures", -type => 'OK');
return;
}
makeDir("$trashdir/$thumbdirname", NO_ASK);
foreach my $i (reverse 0 .. $#{$a}) {
if ($$a[$i]->{selected}) {
my $dpic = $$a[$i]->{dpic};
my $pic = basename($dpic);
if (move ($dpic, $trashdir)) {
$deleted++; # count nr of successfull moves
my $tpic = "$trashdir/$pic";
$searchDB{$tpic} = $searchDB{$dpic};
$searchDB{$tpic}{odir} = dirname($dpic);
delete $searchDB{$dpic};
deleteCachedPics($dpic);
my $thumb = getThumbFileName($dpic);
if ((-d "$trashdir/$thumbdirname") and (-f $thumb)) {
if (!move ($thumb, "$trashdir/$thumbdirname")) {
$errors .= "Could not move thumbnail \"$thumb\" to $trashdir/$thumbdirname: $!\n";
}
}
splice @$thumbs, $i, 1; # remove picture from list
} else { $errors .= "Could not move picture \"$dpic\" to $trashdir: $!\n"; }
}
}
# clean up and close window
if ($errors ne "") {
$errors = "These errors occured while deleting the selected pictures:\n$errors";
showText("Error while deleting", $errors, NO_WAIT);
}
$userinfo = "deleted $deleted pictures"; $userInfoL->update;
# while it's not possible to remove objects from Tk::Tiler we need to close the
# window and reload the function with the rest of the pictures
cleanUpAndClose($win, $tphotos);
# recursive call of this function
showThumbList($thumbs, $title);
}
##############################################################
# makeBalloonMsg
##############################################################
sub makeBalloonMsg {
my $dpic = shift;
return "$dpic\nis currently not available" if (!-f $dpic);
my $linktarget = "";
my $pic = basename($dpic);
my $dir = dirname($dpic);
my $fsize = getFileSize($dpic, FORMAT);
my $fdate = getFileDate($dpic, FORMAT);
my ($w, $h) = getSize($dpic);
my $exif = getShortEXIF($dpic, NO_WRAP);
if ($exif ne "") {
$exif = formatString($exif, 80);
$exif = "\nEXIF: ".$exif;
}
my $iptc = getIPTC($dpic, SHORT);
$iptc = formatString($iptc, 80); # needed for many joined keywords
if ($iptc ne '') {
$iptc = "\n\n".$iptc; # if IPTC is not empty, add a little distance
}
my $comment = getComment($dpic, LONG);
# show only the first 800 chars of the comment, else the balloon box is too full
$comment = cutString($comment, 797, "...");
$comment = formatString($comment, 80);
if ($comment ne "") {
$comment = "\n\n".$comment; # if comment is not empty, add a little distance
}
if (-l $dpic) {
$linktarget = "\nLink: links to: ".readlink($dpic);
}
return "File: $pic\nDir: $dir\nSize: $fsize (${w}x$h)\nDate: $fdate $linktarget$exif$iptc$comment";
}
##############################################################
# fullscreen
##############################################################
sub fullscreen {
my $win = shift;
#my $dpic = shift;
my $fullscreen = shift;
#my $geo;
if ($fullscreen) {
#saveOffsets($win);
#my $screenw = $top->screenwidth - 10;
#my $screenh = $top->screenheight - 30;
#$geo = "${screenw}x${screenh}+0+0";
print "fullscreen: full \n" if $verbose;
# this should olso work:
$win->packPropagate(0);
$win->FullScreen;
} else {
#my ($w, $h) = getSize($dpic);
$win->packPropagate(1);
#$geo = "${w}x${h}+${picwinx}+${picwiny}";
print "fullscreen: normal \n" if $verbose;
}
#$win->geometry($geo);
$win->update;
$win->overrideredirect($config{Overrideredirect}); # no window decoration, but also no key input possible?!
}
##############################################################
# saveOffsets
##############################################################
# sub saveOffsets {
# my $win = shift;
# my $geo = $win->geometry;
# my ($w, $h, $x, $y) = splitGeometry($geo);
# $picwinx = $x;
# $picwiny = $y;
# print "saveOffsets: $x $y\n" if $verbose;
# }
##############################################################
# systemInfo - show some infos about the system to the user
##############################################################
sub systemInfo {
my $string = "Here is a list of all external programs used by mapivi:\n\n";
foreach my $prog (sort keys %exprogs) {
if ($exprogs{$prog}) {
$string .= " ";
}
else {
$string .= " not ";
}
$string .= sprintf("available: %-12s - %s\n", $prog, $exprogscom{$prog});
}
showText("System Information", $string, WAIT, $mapiviiconfile);
}
##############################################################
# options
##############################################################
sub options {
if (Exists($ow)) {
$ow->deiconify;
$ow->raise;
return;
}
$ow = $top->Toplevel();
$ow->withdraw;
$ow->title("Mapivi options");
$ow->iconname("Options");
$ow->iconimage($mapiviicon) if $mapiviicon;
my $notebook =
$ow->NoteBook(-width => 500,
-background => $config{ColorBG}, # background of active page (including its tab)
-inactivebackground => $config{ColorEntry}, # tabs of inactive pages
-backpagecolor => $config{ColorBG}, # background behind notebook
)->pack(-expand => "yes",
-fill => "both",
-padx => 5, -pady => 5);
my $aF = $notebook->add("gen", -label => "General");
my $bF = $notebook->add("thumbs", -label => "Thumbnails");
my $cF = $notebook->add("view", -label => "Window");
my $eF = $notebook->add("col", -label => "Colors");
my $dF = $notebook->add("adv", -label => "Advanced");
$notebook->raise($config{OptionsLastPad});
my %tmpconf = %{ dclone(\%config) };
my $w = 37;
labeledEntry($aF,'top',20,"Copyright notice",\$tmpconf{Copyright});
my $sdbB =
$aF->Checkbutton(-variable => \$tmpconf{SaveDatabase},
-text => "Store the search database to a file")->pack(-anchor => 'w');
$balloon->attach($sdbB, -msg =>
"If this is enabled all image meta information
(Comments, EXIF, IPTC, file name) of all images
visited will be stored into a database.
The database can be used to search pictures.
It is highly recommended to enable this option.");
my $sexfeB =
$aF->Checkbutton(-variable => \$tmpconf{saveEXIFforEdit},
-text => "Save EXIF information before editing picture in The GIMP")->pack(-anchor => 'w');
$balloon->attach($sexfeB, -msg => "Some older picture editors (e.g. GIMP 1.3.15 and lower)
won't save the picture EXIF information.
With this option the EXIF info is saved
and you can restore it later.
(see menu Edit->EXIF info->restore)");
$aF->Checkbutton(-variable => \$tmpconf{ShowHiddenDirs},
-text => 'Show hidden directories (starting with a dot ".")')->pack(-anchor => 'w');
$aF->Checkbutton(-variable => \$tmpconf{AskGenerateThumb}, -text =>
"Ask before generating thumbnails")->pack(-anchor => 'w');
$aF->Checkbutton(-variable => \$tmpconf{AskDeleteThumb}, -text =>
"Ask before deleting thumbnails")->pack(-anchor => 'w');
$aF->Checkbutton(-variable => \$tmpconf{AskMakeDir},
-text => "Ask before making a directory (e.g. $thumbdirname)")->pack(-anchor => 'w');
$aF->Checkbutton(-variable => \$tmpconf{WarnBeforeResize},
-text => "Warn me before using change size/quality")->pack(-anchor => 'w');
my $cfnjB =
$aF->Checkbutton(-variable => \$tmpconf{CheckForNonJPEGs},
-text => "Check for non-JPEG pictures")->pack(-anchor => 'w');
$balloon->attach($cfnjB, -msg =>
"If this is enabled and there are some non-JPEGs
Mapivi will ask the user if they should be converted
to JPEGs. After the conversion the images can be
displayed by Mapivi. The originals (non-JPEGs) may
be left untouched or deleted.");
$aF->Checkbutton(-variable => \$tmpconf{ShowMoreEXIF}, -text =>
"Show detailed EXIF data (sharpness, contrast, artist, white balance, ...)")->pack(-anchor => 'w');
$aF->Checkbutton(-variable => \$tmpconf{BitsPixel}, -text =>
"Calculate and show picture compression in bit per pixel")->pack(-anchor => 'w');
$aF->Checkbutton(-variable => \$tmpconf{AspectRatio}, -text =>
"Calculate and show image aspect ratio (e.g. 4:3 or 3:2)")->pack(-anchor => 'w');
$aF->Checkbutton(-variable => \$tmpconf{ShowFileDate}, -text =>
"Show the file date in the size column")->pack(-anchor => 'w');
$aF->Checkbutton(-variable => \$tmpconf{RenameBackup}, -text =>
"Rename the backup file, if the file is renamed")->pack(-anchor => 'w');
my $trb =
$aF->Checkbutton(-variable => \$tmpconf{jpegtranTrim},
-text => "use the -trim switch when doing lossless rotation")->pack(-anchor => 'w');
$balloon->attach($trb, -msg =>
"The rotation operates rather oddly if the image dimensions are not a
multiple of the iMCU size (usually 8 or 16 pixels), because they can
only transform complete blocks in the desired way. jpegtran's default
behavior when transforming an odd-size image is designed to preserve
exact reversibility and mathematical consistency of the transformation
set.
For practical use, you may prefer to discard any untransformable
edge pixels using the -trim switch rather than having a
strange-looking strip along the right and/or bottom edges of a
transformed image.");
my $aFcp = labeledScale($aF, 'top', $w, "Max number of cached pictures", \$tmpconf{MaxCachedPics}, 2, 10, 1);
$balloon->attach($aFcp, -msg => "MaPiVi is able to cache some pictures.\nCached pictures can be displayed very fast, but eat up memory.");
my $aFtp = labeledScale($aF, 'top', $w, "Max number of displayed thumbnail", \$tmpconf{ThumbMaxLimit}, 10, 1000, 10);
$balloon->attach($aFtp, -msg => "Each thumbnail eats up a little bit of memory
(about 40kByte), so opening a directory
with a huge number of pictures may be dangerous.
With this option you are able to limit the
memory consumption of the thumbnails.
The remainding thumbnails will be displayed
with the default thumbnail.");
my $aFst = labeledScale($aF, 'top', $w, "Maximum size of trash (MB)", \$tmpconf{MaxTrashSize}, 1, 250, 5);
$balloon->attach($aFst, -msg => "The trash size is not really limited,
but there will be a warning,
when this limit is reached.");
labeledScale($aF, 'top', $w, "Slideshow pause time (sec)", \$tmpconf{SlideShowTime}, 1, 300, 1);
# ############### Thumbnail notepad ########################
my $abF = $bF->Frame()->pack(-fill => 'x', -expand => 0);
my $a1bF = $abF->Frame()->pack(-side => "left", -fill => 'x', -expand => 0);
my $a2bF = $abF->Frame()->pack(-side => "left", -fill => 'x', -expand => 0);
my $bFst =
$a1bF->Checkbutton(-variable => \$tmpconf{ShowThumbs},
-text => "Show thumbnail pictures")->pack(-anchor => 'w');
$balloon->attach($bFst, -msg => "Show thumbnails or nothing at all\n(disable this for compact view)");
my $bFuet =
$a1bF->Checkbutton(-variable => \$tmpconf{UseEXIFThumb},
-text => "Use EXIF thumbnails where available")->pack(-anchor => 'w');
$balloon->attach($bFuet, -msg => "Use the EXIF thumbnails where availabe,\nif not available a thumbnail is generated from the picture\n(very fast, but may not reflect a post processed picture).");
$a1bF->Checkbutton(-variable => \$tmpconf{RotateThumb},
-text => "Rotate EXIF thumbnail when rotating picture")->pack(-anchor => 'w');
my $bFudt =
$a1bF->Checkbutton(-variable => \$tmpconf{UseDefaultThumb},
-text => "Use default thumbnail")->pack(-anchor => 'w');
$balloon->attach($bFudt, -msg => "Show default thumbnail if no thumbnail available.");
my $example;
my $previewB;
if (-f $thumbExample) {
$example = $top->Photo(-file => "$thumbExample", -gamma => $config{Gamma});
if ($example) {
$a2bF->Label(-text => 'Click here for a preview')->pack();
$previewB =
$a2bF->Button(-image => $example,
-bd => $config{Borderwidth},
-command => sub {
my $thumb = "$trashdir/thumbExample.jpg";
my $com = makeCommandString(\%tmpconf);
$com .= " \"$thumbExample\" \"$thumb\" ";
$ow->Busy;
if ((system "$com") != 0) {
warn "$com failed: $!";
$ow->Unbusy;
return;
}
if (-f $thumb) {
my $prev = $top->Photo(-file => "$thumb", -gamma => $config{Gamma});
$previewB->configure(-image => $prev) if $prev;
}
$ow->Unbusy;
})->pack();
$balloon->attach($previewB, -msg => "Press here to update the thumbnail\nwith the choosen options");
}
}
$previewB->invoke if (Exists($previewB));
my $bFdt = labeledEntryButton($bF,'top',$w,"Path/name of default thumbnail",'Set',\$tmpconf{DefaultThumb});
$balloon->attach($bFdt, -msg => "This default thumbnail will be displayed when the real thumbnail\nis not available (e.g. while building the thumbnails).");
#my $bfF = $bF->Frame()->pack(-fill => 'x', -expand => "1");
my $bFstp = labeledScale($bF, 'top', $w, "Size (pixel)", \$tmpconf{ThumbSize}, 10, 200, 1);
$balloon->attach($bFstp, -msg => "This is the length and the heigt of the thumbnail.\nWith a value of e.g. 100 you will get a 100x100 thumbnail.");
my $bFqt = labeledScale($bF, 'top', $w, "Quality (%)", \$tmpconf{ThumbQuality}, 30, 100, 5);
qualityBalloon($bFqt);
#my $zF = $bF->Frame()->pack(-fill => 'x', -expand => "1");
my $zshS = labeledScale($bF, 'top', $w, "Sharpness (radius)", \$tmpconf{ThumbSharpen}, 0, 40, 0.1);
$balloon->attach($zshS, -msg => "The higher the value, the slower the conversion\n(suggestion: between 0 and 4)");
my $bFbs = labeledScale($bF, 'top', $w, "Frame size (pixel)", \$tmpconf{ThumbBorder}, 0, 50, 1);
$balloon->attach($bFbs, -msg => "Set the thumbnail frame size.");
$bF->Checkbutton(-variable => \$tmpconf{UseThumbShadow}, -text => "Add a shadow")->pack(-anchor => 'w');
my $bFbgc = labeledEntryColor($bF,'top',$w,"Thumbnail frame color",'Set',\$tmpconf{ColorThumbBG});
$balloon->attach($bFbgc, -msg => "Set the thumbnail frame color.");
my $bFnob = labeledScale($bF, 'top', 42, "Number of processes generating thumbnails", \$tmpconf{MaxProcs}, 1, 10, 1);
$balloon->attach($bFnob, -msg => "MaPiVi will generate the thumbnails in the background.\nChoose the maximum number of parallel executed processes.\nNumbers greater than one or two may only be appropriate on a muliprocessor plattform.");
# ############### window notepad ########################
$cF->Checkbutton(-variable => \$tmpconf{ShowClock},
-text => "Display a clock in the status bar")->pack(-anchor => 'w');
$cF->Checkbutton(-variable => \$tmpconf{ShowMenu},
-text => "Show menu bar")->pack(-anchor => 'w');
$cF->Checkbutton(-variable => \$tmpconf{ShowInfoFrame},
-text => "Show info frame on the upper side")->pack(-anchor => 'w');
$cF->Checkbutton(-variable => \$tmpconf{ShowDirTree},
-text => "Show directory tree on the left side")->pack(-anchor => 'w');
$cF->Checkbutton(-variable => \$tmpconf{ShowThumbFrame},
-text => "Show thumbnail list")->pack(-anchor => 'w');
$cF->Checkbutton(-variable => \$tmpconf{ShowPicFrame},
-text => "Show picture frame on the right side")->pack(-anchor => 'w');
my $aFe = $cF->Checkbutton(-variable => \$tmpconf{ShowEXIFField},
-text => "Show EXIF info and buttons in picture view")->pack(-anchor => 'w');
$balloon->attach($aFe, -msg => "show/hide the textfield containing the picture EXIF data\nand the EXIF- and IPTC-show buttons.\nThis field is usually located above the actual picture");
my $aFc = $cF->Checkbutton(-variable => \$tmpconf{ShowCommentField},
-text => "Display comment info in picture view")->pack(-anchor => 'w');
$balloon->attach($aFc, -msg => "show/hide the textfield containing the picture comments\nand the buttons to add, edit and remove a comment.\nThis field is usually located above the actual picture");
my $aFp = $cF->Checkbutton(-variable => \$tmpconf{ShowPicInfo},
-text => "Show picture info as a balloon on the actual picture")->pack(-anchor => 'w');
$balloon->attach($aFp, -msg => "if this is enabled and you move and hold your mouse pointer\nover the actual picture (right frame of the main window)\na balloon info box (with EXIF, comment, size, ...) will appear");
my $aIc = $cF->Checkbutton(-variable => \$tmpconf{ShowInfoInCanvas},
-text => "Overlap picture with picture info (EXIF, IPTC, ...)")->pack(-anchor => 'w');
$balloon->attach($aIc, -msg => "show/hide picture infos on the picture itself");
$cF->Checkbutton(-variable => \$tmpconf{AutoZoom},
-text => "Zoom big pictures to fit the canvas (auto zoom)")->pack(-anchor => 'w');
$cF->Checkbutton(-variable => \$tmpconf{ShowCoordinates},
-text => "Display the coordinates of the mouse cursor in the status bar")->pack(-anchor => 'w');
my $fontF = $cF->Frame(-bd => $config{Borderwidth}, -relief => 'groove')->pack(-expand => 1, -fill => 'x', -padx => 3, -pady => 3);
my $fontL = $fontF->Label(-text => "Font family: ", -bg => $config{ColorBG})->pack(-side => "left");
$fontF->Label(-textvariable => \$tmpconf{FontFamily}, -bg => $config{ColorBG})->pack(-side => "left");
$fontF->Button(-text => 'Set',
-command => sub {
my $font = $tmpconf{FontFamily};
my $rc = myFontDialog($ow, 'Select font family', \$font, $tmpconf{FontSize});
return unless $rc;
$tmpconf{FontFamily} = $font;
$ow->Busy;
my $font2 = $top->Font(-family => $tmpconf{FontFamily},
-size => $tmpconf{FontSize});
$fontL->configure(-font => $font2);
$fontL->update();
$ow->Unbusy;
})->pack(-side => "left");
$fontF->Label(-text => " Font size: ", -bg => $config{ColorBG})->pack(-side => "left");
$fontF->Scale(
-variable => \$tmpconf{FontSize},
-from => 5,
-to => 20,
-resolution => 1,
-sliderlength => 30,
-orient => 'horizontal',
-showvalue => 0,
-width => 15,
-bd => $config{Borderwidth},
-command => sub {
$ow->Busy;
my $font = $top->Font(-family => $tmpconf{FontFamily},
-size => $tmpconf{FontSize});
$fontL->configure(-font => $font);
$fontL->update();
$ow->Unbusy;
})->pack(-side => "left", -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$fontF->Label(-textvariable => \$tmpconf{FontSize})->pack(-side => "left");
my $tfontF = $cF->Frame(-bd => $config{Borderwidth}, -relief => 'groove')->pack(-expand => 1, -fill => 'x', -padx => 3, -pady => 3);
my $tfontL = $tfontF->Label(-text => "Thumbnail font size:", -bg => $config{ColorBG})->pack(-side => "left");
$tfontF->Scale(
-variable => \$tmpconf{ThumbCaptFontSize},
-from => 5,
-to => 20,
-resolution => 1,
-sliderlength => 30,
-orient => 'horizontal',
-showvalue => 0,
-width => 15,
-bd => $config{Borderwidth},
-command => sub {
$ow->Busy;
my $font = $top->Font(-family => $tmpconf{FontFamily},
-size => $tmpconf{ThumbCaptFontSize});
$tfontL->configure(-font => $font);
$tfontL->update();
$ow->Unbusy;
})->pack(-side => "left", -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$tfontF->Label(-textvariable => \$tmpconf{ThumbCaptFontSize})->pack(-side => "left");
# ############### color notepad ########################
$w = 36;
$eF->Label(-text => 'Please restart Mapivi to see all color changes')->pack();
my $presets = $eF->Frame()->pack(-fill =>'x', -padx => 0, -pady => 0);
$presets->Label(-text => 'Presets')->pack(-side => 'left', -anchor => 'w');
$presets->Button(-text => 'bright',
-command => sub {
$tmpconf{ColorBG} = "#efefef";
$tmpconf{ColorMenuBG} = "LightGoldenrod2";
$tmpconf{ColorMenuFG} = "black";
$tmpconf{ColorBG2} = "#e5e5e5";
$tmpconf{ColorBGCanvas} = "#efefef";
$tmpconf{ColorHlBG} = "#eeeeee";
$tmpconf{ColorActBG} = "LightGoldenrod1";
$tmpconf{ColorEntry} = "gray90";
$tmpconf{ColorSel} = "LightGoldenrod2";
$tmpconf{ColorSelBut} = "red3";
$tmpconf{ColorSelFG} = "black";
$tmpconf{ColorName} = "black";
$tmpconf{ColorComm} = "black";
$tmpconf{ColorIPTC} = "black";
$tmpconf{ColorEXIF} = "black";
$tmpconf{ColorFile} = "black";
$tmpconf{ColorDir} = "black";
$tmpconf{ColorThumbBG} = "azure3";
})->pack(-side => 'left');
$presets->Button(-text => 'white/yellow',
-command => sub {
$tmpconf{ColorBG} = "white";
$tmpconf{ColorMenuBG} = "LightGoldenrod3";
$tmpconf{ColorMenuFG} = "black";
$tmpconf{ColorBG2} = "#fff9d8";
$tmpconf{ColorBGCanvas} = "white";
$tmpconf{ColorHlBG} = "white";
$tmpconf{ColorActBG} = "LightGoldenrod1";
$tmpconf{ColorEntry} = "gray90";
$tmpconf{ColorSel} = "LightGoldenrod2";
$tmpconf{ColorSelBut} = "red3";
$tmpconf{ColorSelFG} = "black";
$tmpconf{ColorName} = "black";
$tmpconf{ColorComm} = "black";
$tmpconf{ColorIPTC} = "black";
$tmpconf{ColorEXIF} = "black";
$tmpconf{ColorFile} = "black";
$tmpconf{ColorDir} = "black";
$tmpconf{ColorThumbBG} = "LightGoldenrod1";
})->pack(-side => 'left');
$presets->Button(-text => 'blue',
-command => sub {
$tmpconf{ColorBG} = "SlateGray1";
$tmpconf{ColorMenuBG} = "SlateGray3";
$tmpconf{ColorMenuFG} = "black";
$tmpconf{ColorBG2} = "SlateGray2";
$tmpconf{ColorBGCanvas} = "SlateGray1";
$tmpconf{ColorHlBG} = "#e3f6ff";
$tmpconf{ColorActBG} = "DeepSkyBlue1";
$tmpconf{ColorEntry} = "SlateGray1";
$tmpconf{ColorSel} = "DeepSkyBlue1";
$tmpconf{ColorSelBut} = "red3";
$tmpconf{ColorSelFG} = "black";
$tmpconf{ColorName} = "black";
$tmpconf{ColorComm} = "black";
$tmpconf{ColorIPTC} = "black";
$tmpconf{ColorEXIF} = "black";
$tmpconf{ColorFile} = "black";
$tmpconf{ColorDir} = "black";
$tmpconf{ColorThumbBG} = "SlateGray3";
})->pack(-side => 'left');
$presets->Button(-text => 'bright/blue',
-command => sub {
$tmpconf{ColorBG} = "#efefef";
$tmpconf{ColorMenuBG} = "gray40";
$tmpconf{ColorMenuFG} = "white";
$tmpconf{ColorBG2} = "#e5e5e5";
$tmpconf{ColorBGCanvas} = "#efefef";
$tmpconf{ColorHlBG} = "#eeeeee";
$tmpconf{ColorActBG} = "#9fb6cd";
$tmpconf{ColorEntry} = "gray90";
$tmpconf{ColorSel} = "#9fb6cd";
$tmpconf{ColorSelBut} = "red3";
$tmpconf{ColorSelFG} = "black";
$tmpconf{ColorName} = "black";
$tmpconf{ColorComm} = "black";
$tmpconf{ColorIPTC} = "black";
$tmpconf{ColorEXIF} = "black";
$tmpconf{ColorSize} = "black";
$tmpconf{ColorDir} = "black";
$tmpconf{ColorThumbBG} = "gray85";
})->pack(-side => 'left');
$presets->Button(-text => 'gray',
-command => sub {
$tmpconf{ColorBG} = "#aeaeae";
$tmpconf{ColorMenuBG} = "#aaa";
$tmpconf{ColorMenuFG} = "black";
$tmpconf{ColorBG2} = "#c8c8c8";
$tmpconf{ColorBGCanvas} = "#222";
$tmpconf{ColorHlBG} = "#a1a1a1";
$tmpconf{ColorActBG} = "#ae6666";
$tmpconf{ColorEntry} = "#ccc";
$tmpconf{ColorSel} = "#9fb6cd";
$tmpconf{ColorSelBut} = "red3";
$tmpconf{ColorSelFG} = "#000";
$tmpconf{ColorName} = "#000060";
$tmpconf{ColorComm} = "#600000";
$tmpconf{ColorIPTC} = "#404000";
$tmpconf{ColorEXIF} = "#006000";
$tmpconf{ColorFile} = "#004040";
$tmpconf{ColorDir} = "#000060";
$tmpconf{ColorThumbBG} = "#ccc";
})->pack(-side => 'left');
labeledEntryColor($eF,'top',$w,"Background color: window",'Set',\$tmpconf{ColorBG});
labeledEntryColor($eF,'top',$w,"Background color: menu",'Set',\$tmpconf{ColorMenuBG});
labeledEntryColor($eF,'top',$w,"Background color: thumbnail table",'Set',\$tmpconf{ColorBG2});
labeledEntryColor($eF,'top',$w,"Background color: picture",'Set',\$tmpconf{ColorBGCanvas});
labeledEntryColor($eF,'top',$w,"Background color: highlight",'Set',\$tmpconf{ColorHlBG});
labeledEntryColor($eF,'top',$w,"Background color: active",'Set',\$tmpconf{ColorActBG});
labeledEntryColor($eF,'top',$w,"Background color: entry fields",'Set',\$tmpconf{ColorEntry});
labeledEntryColor($eF,'top',$w,"Background color: selections",'Set',\$tmpconf{ColorSel});
labeledEntryColor($eF,'top',$w,"Background color: selected button",'Set',\$tmpconf{ColorSelBut});
labeledEntryColor($eF,'top',$w,"Foreground color: selections",'Set',\$tmpconf{ColorSelFG});
labeledEntryColor($eF,'top',$w,"Font color: menu",'Set',\$tmpconf{ColorMenuFG});
labeledEntryColor($eF,'top',$w,"Font color: name",'Set',\$tmpconf{ColorName});
labeledEntryColor($eF,'top',$w,"Font color: comment",'Set',\$tmpconf{ColorComm});
labeledEntryColor($eF,'top',$w,"Font color: IPTC",'Set',\$tmpconf{ColorIPTC});
labeledEntryColor($eF,'top',$w,"Font color: EXIF",'Set',\$tmpconf{ColorEXIF});
labeledEntryColor($eF,'top',$w,"Font color: size",'Set',\$tmpconf{ColorFile});
labeledEntryColor($eF,'top',$w,"Font color: directory",'Set',\$tmpconf{ColorDir});
# ############### advanced notepad ########################
$w = 37;
$dF->Checkbutton(-variable => \$verbose,
-text => "verbose: print some debug info to STDOUT")->pack(-anchor => 'w');
$dF->Checkbutton(-variable => \$tmpconf{trackPopularity},
-text => "Track popularity of pictures (how often viewed in Mapivi)")->pack(-anchor => 'w');
$dF->Checkbutton(-variable => \$tmpconf{CheckForLinks},
-text => "Check if a file is a link before processing it")->pack(-anchor => 'w');
$dF->Checkbutton(-variable => \$tmpconf{AddMapiviComment},
-text => "add a comment to pictures created/processed by mapivi")->pack(-anchor => 'w');
$dF->Checkbutton(-variable => \$tmpconf{EXIFshowApp},
-text => "show App*-Info and MakerNotes and ColorComponents in EXIF info")->pack(-anchor => 'w');
$dF->Checkbutton(-variable => \$tmpconf{ShowUrgency},
-text => "show the rating (the IPTC urgency flag) in the status line (needs restart)")->pack(-anchor => 'w');
my $ctcb =
$dF->Checkbutton(-variable => \$tmpconf{CenterThumb},
-text => "center selected thumbnail")->pack(-anchor => 'w');
$balloon->attach($ctcb, -msg => "center the selected thumbnail,\nto show at least the next\nand the previous thumbnail");
$dF->Checkbutton(-variable => \$tmpconf{ShowNextPicAfterDel},
-text => "jump to next picture after delete")->pack(-anchor => 'w');
$dF->Checkbutton(-variable => \$tmpconf{BeepWhenLooping},
-text => "play a beep sound when jumping to the first e.g. last picture")->pack(-anchor => 'w');
my $ctdb =
$dF->Checkbutton(-variable => \$tmpconf{CentralThumbDB},
-text => "Store all thumbnails in a central place")->pack(-anchor => 'w');
$balloon->attach($ctdb, -msg => "If this is enabled all thumbnails will be\nstored in a central place (~/.maprogs/thumbDB),\nif disabled thumbnails will be stored\ndecentral in sub directories (.thumbs).");
my $tbb =
$dF->Checkbutton(-variable => \$tmpconf{ToggleBorder},
-text => "Remove the window border in fullscreen mode (experimental)")->pack(-anchor => 'w');
$balloon->attach($tbb, -msg => "Enable a real fullscreen mode,\nbut may not work as expected on all\noperating systems and window managers.\nTry it, switch to fullscreen (key: F11),\nif it works it's fine, if not just disable it again.");
my $fblfb =
$dF->Checkbutton(-variable => \$tmpconf{SlowButMoreFeatures},
-text => "enable some time intensive features (needs restart)")->pack(-anchor => 'w');
$balloon->attach($fblfb, -msg => "If this is selected, you will get e.g. some\nmore zoom levels.\nThis may slow down Mapivi a bit, so this option\nis only recommended for faster computers.");
$dF->Checkbutton(-variable => \$tmpconf{CheckNewKeywords},
-text => "Check for new keywords and ask to add them to my catalog")->pack(-anchor => 'w');
$dF->Checkbutton(-variable => \$tmpconf{UrgencyChangeWarning},
-text => "Show a warning when a rating/urgency has been changed")->pack(-anchor => 'w');
my $opfb = $dF->Checkbutton(-variable => \$tmpconf{supportOtherPictureFormats},
-text => "Show also other picture formats than just JPEG. Danger! (experimental feature)")->pack(-anchor => 'w');
$balloon->attach($opfb, -msg => "If this is selected, Mapivi will also show other picture formats (e.g. GIF and PNG),\nat least as thumbnails. But adding IPTC and other meta information is not possible.\nThis feature is not tested, so use it on your own risk.");
my $aspS = labeledScale($dF, 'top', $w, "Delta factor for aspect ratio (%)", \$tmpconf{AspectSloppyFactor}, 0, 5, 0.1);
$balloon->attach($aspS, -msg => "Adjust the accuracy of the aspect ratio display (rightmost column size).\nThis is the delta factor in percent when calculating the aspect ratio.\nFor example a picture with size 304x200 will still be displayed as a 3:2 picture,\nif the factor is equal or bigger than 1.4%.\nUse 0.0% if you need really exact values.\n3.0% is acceptable for me.");
labeledScale($dF, 'top', $w, "preview size in filter dialog (pixel)", \$tmpconf{FilterPrevSize}, 50, 500, 5);
labeledScale($dF, 'top', $w, "Comment text box height (lines)", \$tmpconf{CommentHeight}, 1, 50, 1);
labeledScale($dF, 'top', $w, "Gamma value, when displaying pictures", \$tmpconf{Gamma}, 0.1, 10.0, 0.01);
labeledScale($dF, 'top', $w, "Maximum number of lines of a comment", \$tmpconf{LineLimit}, 1, 20, 1);
labeledScale($dF, 'top', $w, "Maximum length of a comment line", \$tmpconf{LineLength}, 5, 80, 1);
labeledEntry($dF, 'top', $w, "External picture viewer",\$tmpconf{ExtViewer});
my $evmf =
$dF->Checkbutton(-variable => \$tmpconf{ExtViewerMulti},
-text => "External picture viewer can handle multiple files")->pack(-anchor => 'w');
$balloon->attach($evmf,
-msg => 'If the external viewer is able to handle multiple files enable this.
Example:
You have selected 3 pictures.
If this option is enabled one viewer will be started like this:
"viewer pic1.jpg pic2.jpg pic3.jpg",
if not 3 viewers will be started like this:
"viewer pic1.jpg" "viewer pic2.jpg" "viewer pic3.jpg".');
labeledEntry($dF, 'top', $w, "Tool to set the desktop background",\$tmpconf{ExtBGApp});
# ############### button frame ########################
my $butF =
$ow->Frame()->pack(-fill =>'x',
-padx => 3,
-pady => 3);
$butF->Button(-text => 'OK',
-command => sub {
%config = %{ dclone(\%tmpconf) };
applyConfig();
$example->delete if $example;
$config{OptionsLastPad} = $notebook->raised();
$ow->destroy();
}
)->pack(-side=>'left', -expand => 1, -fill =>'x');
$butF->Button(-text => "Apply",
-command => sub {
%config = %{ dclone(\%tmpconf) };
$previewB->invoke() if (Exists($previewB));
applyConfig();
}
)->pack(-side=>'left', -expand => 1, -fill =>'x');
my $Xbut = $butF->Button(-text => 'Cancel',
-command => sub {
$example->delete if $example;
$config{OptionsLastPad} = $notebook->raised();
$ow->destroy();
}
)->pack(-side=>'left', -expand => 1, -fill =>'x');
$ow->bind('<Control-q>', sub { $Xbut->invoke; });
$ow->bind('<Key-Escape>', sub { $Xbut->invoke; });
$ow->Popup;
}
##############################################################
# applyConfig
##############################################################
sub applyConfig {
$progressBar->configure(-blocks => $config{MaxProcs},
-to => $config{MaxProcs});
$dirtree->configure(-showhidden => $config{ShowHiddenDirs});
$comS->configure( -foreground=>$config{ColorComm}, -background=>$config{ColorBG2});
$iptcS->configure(-foreground=>$config{ColorIPTC}, -background=>$config{ColorBG});
$exifS->configure(-foreground=>$config{ColorEXIF}, -background=>$config{ColorBG2});
$fileS->configure(-foreground=>$config{ColorFile}, -background=>$config{ColorBG});
$dirS->configure( -foreground=>$config{ColorDir}, -background=>$config{ColorBG2});
toggleHeaders();
$top->optionAdd('*selectBackground', $config{ColorSel}, 'userDefault');
$picLB->configure(-selectbackground => $config{ColorSel});
# undocumented feature, but does not work (it stops the execution of the sub)
# $top->RecolorTree(-background => $config{ColorBG});
# we don't try to color everything, just a few widgets to give a visual feedback
$top->configure (-bg => $config{ColorBG});
$dirtree->configure(-bg => $config{ColorBG},
-selectbackground => $config{ColorSel});
$c->configure (-bg => $config{ColorBGCanvas});
$menubar->configure(-bg => $config{ColorBG});
my @wlist = $top->children;
foreach my $widget (@wlist) {
my $ref = ref($widget);
if ($ref eq "Tk::Frame" or $ref eq "Tk::Menu") {
$widget->configure(-bg => $config{ColorBG});
}
}
# don't know if this is very appropriate
$top->optionAdd('*selectBackground', $config{ColorSel}, 'userDefault');
$top->optionAdd("*highlightColor", $config{ColorSel}, 'userDefault');
$top->optionAdd("*highlightBackground", $config{ColorHlBG}, 'userDefault');
$top->optionAdd("*background", $config{ColorBG}, 'userDefault');
$top->optionAdd("*activeBackground", $config{ColorActBG}, 'userDefault');
# change font
my $font = $top->Font(-family => $config{FontFamily},
-size => $config{FontSize},
);
$top->optionAdd("*font", $font, "userDefault");
$top->Walk( sub {
print "changing widget font ",ref($_[0])," to $font\n" if $verbose;
eval { $_[0]->configure(-font => $font); }
});
showHideFrames();
$top->update;
setAdjusterPos();
startStopClock();
#print "Sortby Apply = ".$config{SortBy}."\n"; #???
}
##############################################################
# showHideFrames - pack or packForget the EXIF and Comment
# frame
##############################################################
sub showHideFrames {
# the pack command seems only to work, if we packforget all
# following widgets
# so we always remove them all - from the inner to the outer ones
# and pack them again according to the actual settings
foreach ($c, $comF, $exifF, $mainF, $thumbA, $thumbF, $dirA, $dirF, $subF, $infoF) {
$_->packForget if ($_->ismapped);
}
if ($config{ShowMenu}) {
$top->configure(-menu => $menubar);
}
else {
$top->configure(-menu => "");
}
if ($config{ShowInfoFrame}) {
$infoF->pack(-side => 'top', -anchor=>'w', -padx => 0, -pady => 0, -fill => 'x', -expand => "0");
}
$subF->pack(-side => 'top', -anchor=>'w', -padx => 0, -pady => 0, -fill => 'both', -expand => 1);
if ($config{ShowDirTree}) {
$dirF->pack(-side => "left", -anchor=>'w', -padx => 0, -pady => 0, -expand => 1, -fill => "both");
$dirA->packAfter($dirF, -side => "left", -padx => 3) if (($config{ShowThumbFrame}) or ($config{ShowPicFrame}));
}
if ($config{ShowThumbFrame}) {
$thumbF->pack(-side => "left", -anchor=>'w', -padx => 0, -pady => 0, -expand => 1, -fill => "both");
}
if ($config{ShowPicFrame}) {
$thumbA->packAfter($thumbF, -side => "left", -padx => 3) if ($config{ShowThumbFrame}) ;
$mainF->pack(-side => "left", -anchor=>'w', -padx => 0, -pady => 0, -ipadx => 0, -ipady => 0);
}
if ($config{ShowEXIFField}) {
$exifF->pack(-fill => 'x', -expand => 1, -padx => 0, -pady => 0);
}
if ($config{ShowCommentField}) {
$comF->pack(-fill => 'x',-expand => "1", -anchor=>'w', -padx => 0, -pady => 0) ;
}
$c->pack(-expand => 1, -fill => "both", -padx => 0, -pady => 0, -ipadx => 0, -ipady => 0);
}
##############################################################
# buttonComment
##############################################################
sub buttonComment {
my $widget = shift;
my $side = shift;
my $but = $widget->Checkbutton(-variable => \$config{AddMapiviComment},
-anchor => 'w',
-text => "Add comment"
)->pack(-side => $side, -anchor => 'w', -padx => 5, -pady => 3);
$balloon->attach($but, -msg => "Add a comment to pictures created\nor processed with Mapivi");
}
##############################################################
# buttonBackup
##############################################################
sub buttonBackup {
my $widget = shift;
my $side = shift;
my $but = $widget->Checkbutton(-variable => \$config{MakeBackup},
-anchor => 'w',
-text => "Create backup"
)->pack(-side => $side, -anchor => 'w', -padx => 5, -pady => 3);
$balloon->attach($but, -msg => "Create a backup of the original picture\nin the same directory named \"name-bak.jpg\"");
}
##############################################################
# labeledEntryButton - build a frame containing a labeled entry
# and a button with a file selector
##############################################################
sub labeledEntryButton {
# input values
my ($parentWidget, $position, $width, $label, $buttext, $varRef, $dir) = @_;
my $frame = labeledEntry($parentWidget, $position, $width, $label, $varRef);
setFileButton($frame,"right",$buttext,$label,$varRef, $dir);
return $frame;
}
##############################################################
# labeledEntryColor - build a frame containing a labeled entry
# and a button with a color selector
##############################################################
sub labeledEntryColor {
# input values
my ($parentWidget, $position, $width, $label, $buttext, $varRef) = @_;
my $frame = labeledEntry($parentWidget, $position, $width, $label, $varRef);
setColorButton($frame,"right",$buttext,$varRef);
return $frame;
}
##############################################################
# labeledEntry - build a frame containing a labeled entry
# for backward compability
##############################################################
sub labeledEntry {
# input values
my ($parentWidget, $position, $width, $label, $varRef, $width2) = @_;
labeledEntryFlex($parentWidget, $position, $width, $label, $varRef, "left", $width2);
}
##############################################################
# labeledEntryFlex - build a frame containing a labeled entry
##############################################################
sub labeledEntryFlex {
# input values
my ($parentWidget, $position, $width, $label, $varRef, $int_pos, $width2) = @_;
# $width2 is optional and the width of the entry field, defaults to the first width
$width2 = $width unless defined $width2;
my $frame =
$parentWidget->Frame()->pack(-side => $position, -expand => 0, -fill => 'x', -padx => 0, -pady => 3);
$frame->Label(-text => $label,
-width => $width,
-anchor => 'w',
)->pack(-side => $int_pos, -padx => 3, -fill => 'x');
my $entry;
if (MatchEntryAvail) {
# set the choice list to an empty list, if it's undefined
$entryHistory{$label} = [] unless (defined $entryHistory{$label});
$entry = $frame->MatchEntry(-textvariable => $varRef,
-choices => $entryHistory{$label},
-ignorecase => 0,
-maxheight => 20,
# add the new value to the list when enter or tab is pressed
-entercmd => sub { addItemToList($entry, $entryHistory{$label}, $varRef); },
-tabcmd => sub { addItemToList($entry, $entryHistory{$label}, $varRef); },
-width => $width2,
)->pack(-side => $int_pos, -expand => 1, -fill => 'x', -padx => 0);
}
else {
$entry = $frame->Entry(-textvariable => $varRef,
-width => $width2,
)->pack(-side => $int_pos, -expand => 1, -fill => 'x', -padx => 0);
}
$entry->xview('end');
$entry->icursor('end');
return $frame;
}
##############################################################
# addItemToList - add a new value to the list and remove double entries
##############################################################
sub addItemToList {
my $widget = shift;
my $listref = shift;
my $varref = shift;
return if (!defined $$varref);
return if ($$varref eq "");
# todo: remove double values and remove old values
push @{$listref}, $$varref;
my %d; # build a hash
foreach (@{$listref}) { $d{$_} = 1; }
@{$listref} = (sort { uc($a) cmp uc($b); } keys %d);
$widget->configure(-choices => $listref);
}
##############################################################
# labeledEntry2 - build a frame containing two labeled entrys
##############################################################
sub labeledEntry2 {
# input values
my ($parentWidget, $position, $width1, $width2, $label1, $varRef1, $label2, $varRef2) = @_;
my $frame =
$parentWidget->Frame()->pack(-side => $position, -expand => 0, -fill => 'x', -padx => 3, -pady => 3);
$frame->Label(-text => $label1,
-width => $width1,
-anchor => 'w',
-bg => $config{ColorBG},
)->pack(-side => "left", -padx => 3);
my $entry1 =
$frame->Entry(-textvariable => $varRef1,
-width => $width2,
)->pack(-side => "left", -fill => 'x', -expand => "1", -padx => 1);
$entry1->xview('end');
$entry1->icursor('end');
$frame->Label(-text => $label2,
-width => $width1,
-anchor => 'w',
-bg => $config{ColorBG},
)->pack(-side => "left", -padx => 3);
my $entry2 =
$frame->Entry(-textvariable => $varRef2,
-width => $width2,
)->pack(-side => "left", -fill => 'x', -expand => "1", -padx => 1);
$entry2->xview('end');
$entry2->icursor('end');
return $frame;
}
##############################################################
# labeledDoubleEntry - build a frame containing two labeled entrys
##############################################################
sub labeledDoubleEntry {
# input values
my ($parentWidget, $position, $width, $label, $label2, $dVarRef, $dBalloon, $tVarRef, $tBalloon) = @_;
my $fullframe =
$parentWidget->Frame()->pack(-side => $position, -fill => 'x', -expand => 0, -padx => 0, -pady => 0);
my $frame = labeledEntry($fullframe, 'left', $width, $label, $dVarRef, ($width+5));
$balloon->attach($frame, -msg => $dBalloon);
$frame = labeledEntry($fullframe, 'left', $width, $label2, $tVarRef, ($width+5));
$balloon->attach($frame, -msg => $tBalloon);
return $fullframe;
}
##############################################################
# labeledScale - build a frame containing a labeled scale
##############################################################
sub labeledScale {
# input values
my ($parentWidget, $position, $width, $label, $varRef, $from, $to, $res) = @_;
my $frame =
$parentWidget->Frame(-bd => 0)->pack(-side => $position, -fill => 'x', -padx => 3, -pady => 3);
$frame->Label(-text => $label,
-width => $width,
-anchor => 'w',
-bg => $config{ColorBG},
)->pack(-side => "left", -padx => 3);
my $scale = $frame->Scale(-variable => $varRef,
#-length => $width,
-from => $from,
-to => $to,
-resolution => $res,
-sliderlength => 30,
-orient => 'horizontal',
-width => 15,
-showvalue => 0,
)->pack(-side => "left", -fill => 'x', -expand => "1", -padx => 1);
$frame->Label(-textvariable => $varRef,
-width => 5,
-anchor => "e",
-bd => $config{Borderwidth},
-relief => "sunken",
-bg => $config{ColorBG},
)->pack(-side => "left", -padx => 1);
return $frame;
}
##############################################################
# setFileButton - open a file selector and set file or dir name
##############################################################
sub setFileButton {
# input values
my ($parentWidget, $position, $butlabel, $fileselLabel, $varRef, $dir) = @_;
# $dir is optional, if defined and true a dir will be selected instead of a file
$parentWidget->Button(-text => $butlabel,
-command => sub {
if ($EvilOS) { # windows
my $file = $parentWidget->getOpenFile();
if ((defined $file) and (-f $file)) {
$$varRef = $file;
}
if ((defined $dir) and ($dir == 1)) {
if (!-d $file) {
$$varRef = dirname($file);
}
}
}
else { # non windows system
my $fs = $parentWidget->FileSelect(-title => $fileselLabel,
-directory => dirname($$varRef),
-width => 30, -height => 30);
if ((defined $dir) and ($dir == 1)) {
$fs->configure(-verify => ['-d']);
}
my $file = $fs->Show;
if (defined $file and $file ne "") {
if (-f $file) {
$$varRef = $file;
}
if ((defined $dir) and ($dir == 1) and (-d $file)) {
$$varRef = $file;
}
}
}
},
)->pack(-side => $position);
}
##############################################################
# setColorButton - open a color selector and set the color
##############################################################
sub setColorButton {
# input values
my ($parentWidget, $position, $butlabel, $varRef) = @_;
my $ccbut;
$ccbut = $parentWidget->Button(-text => $butlabel,
-bg => $$varRef,
-command => sub {
my $rc = color_chooser();
if (defined $rc) {
$ccbut->configure(-bg => $rc);
$$varRef = $rc;
# this is needed when updating the button
if ($$varRef eq 'black') {
$ccbut->configure(-fg => 'white');
}
else {
$ccbut->configure(-fg => 'black');
}
}
})->pack(-side => $position);
# this is needed when drawing the button
if ($$varRef eq 'black') {
$ccbut->configure(-fg => 'white');
}
else {
$ccbut->configure(-fg => 'black');
}
}
##############################################################
# color_chooser - open a window and offer some colors to select
##############################################################
sub color_chooser {
my $title = 'Please select a color';
# open window
my $win = $top->Toplevel();
$win->withdraw;
$win->title($title);
$win->iconimage($mapiviicon) if $mapiviicon;
$win->iconname($title);
my $frame;
my $return_color = 0;
my $colP =
$win->Button(-text => 'Color picker',
-height => 0,
-width => 0,
-padx => 0,
-pady => 0,
-relief => "groove",
-background => $config{ColorPicker},
-command => sub {
$return_color = $config{ColorPicker};
}
)->pack(-padx => 0, -pady => 0);
$balloon->attach($colP, -msg => $config{ColorPicker});
my $colorF = $win->Frame()->pack(-fill => 'both', -expand => "1");
my $i = 0;
foreach (@allcolors) {
$i++;
if ($i == 1 or $i % 12 == 1) { # a frame for the first and every 12th button (modulo)
$frame = $colorF->Frame()->pack(-side => "left", -anchor => "n");
}
my $but;
$but =
$frame->Button(#-bitmap => "cbut",
-text => " ",
-height => 0,
-width => 0,
-padx => 0,
-pady => 0,
-relief => "groove",
-background => $_,
-command => sub {
my $col = $but->cget(-bg);
$return_color = $col;
}
)->pack(-padx => 0, -pady => 0);
$balloon->attach($but, -msg => $_);
}
my $xBut =
$win->Button(-text => "Close",
-command => sub {
print "returning: undef\n";
$return_color = undef;
},
)->pack(-fill => 'x');
# 50 ways to leave your window ;)
$win->bind('<Key-Escape>' , sub {$xBut->invoke;});
$win->bind('<Key-q>' , sub {$xBut->invoke;});
$win->protocol("WM_DELETE_WINDOW" => sub {$xBut->invoke;} );
$xBut->focus;
$win->Popup;
#repositionWindow($win);
$win->waitVariable(\$return_color);
$win->withdraw;
$win->destroy;
return $return_color;
}
##############################################################
# makeNewDir - get a new dir name from the user and create this
# new dir in the actual dir
##############################################################
sub makeNewDir {
my $path = shift;
my $tree = shift;
my $newDir = "newdir";
my $rc = myEntryDialog("Make a new directory","Enter name of new directory in $path",\$newDir);
return if ($rc ne 'OK' or $newDir eq "");
if (-d "$path/$newDir") {
$top->messageBox(-icon => 'warning', -message => "$newDir already exists!",
-title => 'Error', -type => 'OK');
return;
}
if (!mkdir "$path/$newDir", 0750) {
$top->messageBox(-icon => 'warning', -message => "error making dir $path/$newDir: $!",
-title => 'Error', -type => 'OK');
return;
}
dirSave("$path/$newDir");
exists &Tk::DirTree::chdir ? $tree->chdir("$path/$newDir") : $tree->set_dir("$path/$newDir");
exists &Tk::DirTree::chdir ? $dirtree->chdir("$path/$newDir") : $dirtree->set_dir("$path/$newDir");
}
##############################################################
# getRightDir - get the selected or the actual dir
##############################################################
sub getRightDir {
my $dir = "";
# if the dir frame is visible, try to get the selected dir
if ($dirF->ismapped()) {
$dir = ($dirtree->selectionGet())[0];
# normalize the path
if (defined $dir) {
$dir =~ s/\\/\//g; # replace Windows path delimiter with UNIX style \ -> /
$dir =~ s/\/+/\//g; # replace multiple slashes with one // -> /
}
}
# this is the fall back solution
$dir = $actdir if ((!defined $dir) or ($dir eq "") or (!-d $dir));
return $dir;
}
##############################################################
# cleanOneDir - remove the .thumbs and .exif subdir
##############################################################
sub cleanOneDir {
my $dir = shift;
my ($rc, $subdir);
my @subdirs = ("$dir/$thumbdirname", "$dir/$exifdirname");
foreach $subdir (@subdirs) {
if (-d $subdir) {
$rc = rmtree($subdir, 0, 1); # dir, 0 = no message for each file, 1 = skip write protected files
print "removed $rc elements in $subdir\n" if $verbose;
}
}
}
##############################################################
# deleteDir
##############################################################
sub deleteDir {
my $dir = getRightDir();
if (!-d $dir) {
$top->messageBox(-icon => 'warning', -message => "Sorry, but \"$dir\" does not exists!",
-title => 'Error', -type => 'OK');
return;
}
my $dirname = basename($dir);
my $rc = $top->messageBox(-icon => 'question',
-message => "Do you really want to delete directory \"$dirname\"\n($dir)?\nThere is no undelete!",
-title => "Delete directory?",
-type => 'OKCancel');
return if ($rc !~ m/Ok/i);
# get some infos about the dir
my $dirs = 0;
my $files = 0;
my $size = 0;
my $timeout = "";
my $start_time = Tk::timeofday();
$userinfo = "scanning directory ..."; $userInfoL->update;
$top->Busy;
find(sub {
# jump out after 5 seconds
if (Tk::timeofday()-$start_time > 5) {
$timeout = " at least (scanning stopped by timeout)";
$File::Find::prune = 1;
return; }
$dirs++ if (-d "$File::Find::name");
if (-f "$File::Find::name") {
$files++;
$size += getFileSize("$File::Find::name", NO_FORMAT);
}
}, "$dir");
$top->Unbusy;
$userinfo = "directory scanned!"; $userInfoL->update;
$size = computeUnit($size);
my $question = sprintf "There are%s\n%8d directories and\n%8d files with a total size of\n%8s in \"%s\".\nReally delete?", $timeout, $dirs, $files, $size, $dirname;
$rc = $top->messageBox(-icon => 'question',
-message => $question,
-title => "Delete directory?",
-type => 'OKCancel');
return if ($rc !~ m/Ok/i);
print "rmtree: dir = $dir\n" if $verbose;
rmtree($dir, 0, 1); # dir, 0 = no message for each file, 1 = skip write protected files
# remove the deleted pics from the search database
cleanDatabaseFolder($dir);
# refresh the dir tree
my $path = dirname($dir);
while (!-d $path) {
$path = dirname($dir);
last if ($path eq "");
}
my $slash = "";
$slash = "/" if ($Tk::VERSION < 800.025); # the additional slash is needed for older Tk!
# todo I don't know if 800.025 is really exactly the version the behavior changed
$dirtree->close("$slash$path");
$dirtree->open("$slash$path");
# open parent dir if we've deleted the actual dir
openDirPost($path) unless (-d $dir);
$userinfo = "ready! (removed directory \"$dirname\" with $files files)"; $userInfoL->update;
}
##############################################################
# renameDir
##############################################################
sub renameDir {
my $dir = getRightDir();
if (!-d $dir) { warn "dir $dir is no dir"; return; }
my $path = dirname($dir);
my $newDir = basename($dir);
my $rc = myEntryDialog("rename directory","Enter new name for directory $dir",\$newDir);
return if ($rc ne 'OK' or $newDir eq "");
if (-d "$path/$newDir") {
$top->messageBox(-icon => 'warning', -message => "$newDir already exists!",
-title => 'Error', -type => 'OK');
return;
}
if (!rename "$dir", "$path/$newDir") {
$top->messageBox(-icon => 'warning', -message => "error renameing directory $dir to $path/$newDir: $!",
-title => 'Error', -type => 'OK');
return;
}
# refresh the dir tree display
my $slash = "";
$slash = "/" if ($Tk::VERSION < 800.025); # the additional slash is needed for older Tk!
$dirtree->close("$slash$path");
$dirtree->open("$slash$path");
exists &Tk::DirTree::chdir ? $dirtree->chdir("$path/$newDir") : $dirtree->set_dir("$path/$newDir");
$dirtree->Subwidget("scrolled")->configure(-directory => "$path/$newDir");
if ($dirtree->info("exists", "$path/$newDir")) {
$dirtree->see("$path/$newDir");
}
# select the new dir
$dirtree->selectionSet("$slash$path/$newDir");
$actdir = "$path/$newDir" if (!-d $actdir);
}
##############################################################
# calcSize - calc new picture size
# considering the aspect ratio and landscape/portait
# mode
##############################################################
sub calcSize {
my ($w, $h, $ow, $oh) = @_;
my $aspect = $ow/$oh;
my ($nw, $nh);
if ($ow >= $oh) { # landscape
$nw = $w;
$nh = sprintf("%.0f",($nw/$aspect)); # int() does not round!
}
else { # portrait
$nh = $w;
$nw = sprintf("%.0f",($aspect*$nh));
}
return ($nw, $nh);
}
##############################################################
# qualityBalloon
##############################################################
sub qualityBalloon {
$balloon->attach(shift, -msg => "Quality of picture\nAppropriate settings are between 50% and 95%,\n80% is often a good tradeoff between size and quality for web and email\nfor further processing and best quality 95% is recommended\nValues over 95% just increase file size, not quality");
}
##############################################################
# changeSizeQuality - change the size and quality of all
# selected JPEG pictures
# based on code from Hans-Peter Rangol 10/13/2002.
# Needs mogrify from ImageMagick, preserves Exif-Data,
# depending on the version of mogrify (at least 5.1.1 does not!)
##############################################################
sub changeSizeQuality {
return if (!checkExternProgs("changeSizeQuality", "mogrify"));
my @sellist = $picLB->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
my $selected = @sellist;
my ($pic, $dpic, $dirthumb, $dirtpic, $i);
my $rc = 0;
if ($config{WarnBeforeResize}) {
my $rc = checkDialog("Change size quality",
"This function will change the size and/or quality\
of $selected selected pictures to a choosable value.\
The EXIF/IPTC and JPEG comment may be preserved,\
depending on your version of the program mogrify.\
So please make a test with a backup picture first.\
It's possible to save and restore the EXIF info with\
menu: \"EXIF info\"->\"save\".\n",
\$config{WarnBeforeResize},
"ask every time",
"",
'OK', 'Cancel');
return if ($rc ne 'OK');
}
# get the size of the first picture
my ($width, $height) = getSize($sellist[0]);
my $origW = $width;
my $origH = $height;
my $widthP = 100;
my $heightP = 100;
if ($height == 0) { # avoid division by zero
$top->messageBox(-message => "Sorry, but the size of ".basename($sellist[0])." is not available - Aborting.", -icon => 'warning', -title => "No size info", -type => 'OK');
return;
}
my $aspect = $width/$height;
my $PixPro = "pro";
# open dialog window
my $myDiag = $top->Toplevel();
$myDiag->title("Change size/quality");
$myDiag->iconimage($mapiviicon) if $mapiviicon;
$myDiag->Label(-text =>"Change the size and/or quality of $selected selected pictures",
-bg => $config{ColorBG}
)->pack(-anchor => 'w',-padx => 3,-pady => 3);
#my $scf = $myDiag->Frame()->pack(-expand => 1, -fill =>'both',-padx => 3,-pady => 3);
my $qS = labeledScale($myDiag, 'top', 18, "Quality (%)", \$config{PicQuality}, 10, 100, 1);
qualityBalloon($qS);
# check if the Imagemagick version supports the strip command
my $strip = 0;
$strip = 1 if (`mogrify` =~ m/.*-strip.*/);
# check, if the ImageMagick version supports the unsharp command
my $unsharp = 0;
$unsharp = 1 if (`mogrify` =~ m/.*-unsharp.*/);
my $keepaspect = 1;
my $csf1 = $myDiag->Frame()->pack(-fill =>'x',-padx => 3,-pady => 3);
$csf1->Button(-text => "original size",
-width => 12,
-command => sub {
$height = $origH;
$width = $origW;
$widthP = sprintf("%.0f",($width/$origW * 100));
$heightP = sprintf("%.0f",($height/$origH * 100));
})->pack(-side => "left", -padx => 0);
$csf1->Button(-text => "email preset",
-command => sub {
$PixPro = "pix";
$keepaspect = 1;
$config{PicQuality} = 80;
if ($unsharp) {
$config{Unsharp} = 1;
$config{PicSharpen} = 0;
}
else {
$config{Unsharp} = 0;
$config{PicSharpen} = 1;
}
$config{PicBlur} = 0;
($width, $height) = calcSize(640, 480, $origW, $origH);
$widthP = sprintf("%.0f",($width/$origW * 100));
$heightP = sprintf("%.0f",($height/$origH * 100));
})->pack(-side => "left", -padx => 0);
$csf1->Button(-text => "half",
-width => 9,
-command => sub {
$PixPro = "pro";
$keepaspect = 1;
$widthP = 50;
$heightP = 50;
$width = sprintf("%.0f",($origW * $widthP/100));
$height = sprintf("%.0f",($origH * $heightP/100));
})->pack(-side => "left", -padx => 0);
my $csf2 = $myDiag->Frame()->pack(-fill =>'x',-padx => 3,-pady => 3);
$csf2->Button(-text => "640x480",
-width => 9,
-command => sub {
$PixPro = "pix";
$keepaspect = 1;
($width, $height) = calcSize(640, 480, $origW, $origH);
$widthP = sprintf("%.0f",($width/$origW * 100));
$heightP = sprintf("%.0f",($height/$origH * 100));
})->pack(-side => "left", -padx => 0);
$csf2->Button(-text => "720x576",
-width => 9,
-command => sub {
$PixPro = "pix";
$keepaspect = 1;
($width, $height) = calcSize(720, 576, $origW, $origH);
$widthP = sprintf("%.0f",($width/$origW * 100));
$heightP = sprintf("%.0f",($height/$origH * 100));
})->pack(-side => "left", -padx => 0);
$csf2->Button(-text => "800x600",
-width => 9,
-command => sub {
$PixPro = "pix";
$keepaspect = 1;
($width, $height) = calcSize(800, 600, $origW, $origH);
$widthP = sprintf("%.0f",($width/$origW * 100));
$heightP = sprintf("%.0f",($height/$origH * 100));
})->pack(-side => "left", -padx => 0);
$csf2->Button(-text => "1024x768",
-width => 9,
-command => sub {
$PixPro = "pix";
$keepaspect = 1;
($width, $height) = calcSize(1024, 768, $origW, $origH);
$widthP = sprintf("%.0f",($width/$origW * 100));
$heightP = sprintf("%.0f",($height/$origH * 100));
})->pack(-side => "left", -padx => 0);
$csf2->Button(-text => "1280x960",
-width => 9,
-command => sub {
$PixPro = "pix";
$keepaspect = 1;
($width, $height) = calcSize(1280, 960, $origW, $origH);
$widthP = sprintf("%.0f",($width/$origW * 100));
$heightP = sprintf("%.0f",($height/$origH * 100));
})->pack(-side => "left", -padx => 0);
my $w = 20;
$myDiag->Checkbutton(-variable => \$keepaspect,
-anchor => 'w',
-text => "Keep aspect ratio (original size ${origW}x$origH)")->pack(-anchor => 'w');
$myDiag->Radiobutton(-text => "use absolute size (pixel)", -variable => \$PixPro, -value => "pix")->pack(-anchor => 'w');
my $labFw = labeledEntry($myDiag, 'top', $w, "Width (pixel)", \$width);
my $labFh = labeledEntry($myDiag, 'top', $w, "Height (pixel)", \$height);
$myDiag->Radiobutton(-text => "use relative size (%)", -variable => \$PixPro, -value => "pro")->pack(-anchor => 'w');
my $labFwp = labeledEntry($myDiag, 'top', $w, "Width (%)", \$widthP);
my $labFhp = labeledEntry($myDiag, 'top', $w, "Height (%)", \$heightP);
my $labEw = ($labFw->children)[1];
my $labEh = ($labFh->children)[1];
my $labEwp = ($labFwp->children)[1];
my $labEhp = ($labFhp->children)[1];
$labEw->bind('<FocusOut>', sub {
if ($keepaspect) {
$height = sprintf("%.0f",($width/$aspect)); # int() does not round!
}
$widthP = sprintf("%.0f",($width/$origW * 100));
$heightP = sprintf("%.0f",($height/$origH * 100));
$PixPro = "pix";
});
$labEh->bind('<FocusOut>', sub {
if ($keepaspect) {
$width = sprintf("%.0f",($aspect*$height));
}
$widthP = sprintf("%.0f",($width/$origW * 100));
$heightP = sprintf("%.0f",($height/$origH * 100));
$PixPro = "pix";
});
$labEwp->bind('<FocusOut>', sub {
if ($keepaspect) {
$heightP = $widthP; # int() does not round!
}
$width = sprintf("%.0f",($origW * $widthP/100));
$height = sprintf("%.0f",($origH * $heightP/100));
$PixPro = "pro";
});
$labEhp->bind('<FocusOut>', sub {
if ($keepaspect) {
$widthP = $heightP;
}
$width = sprintf("%.0f",($origW * $widthP/100));
$height = sprintf("%.0f",($origH * $heightP/100));
$PixPro = "pro";
});
my $filf = $myDiag->Frame()->pack(-fill =>'x',-padx => 3,-pady => 3);
$filf->Label(-text => "Resize filter", -bg => $config{ColorBG})->pack(-side => "left", -anchor => 'w');
$filf->Optionmenu(-options => [qw(Point Box Triangle Hermite Hanning Hamming Blackman Gaussian Quadratic Cubic Catrom Mitchell Lanczos Bessel Sinc)], -variable => \$config{ResizeFilter}, -textvariable => \$config{ResizeFilter})->pack(-side => "left", -anchor => 'w');
if ($strip) {
$myDiag->Checkbutton(-variable => \$config{PicStrip},
-anchor => 'w',
-text => "Strip all meta info (EXIF, IPTC, ...)")->pack(-anchor => 'w');
}
# option to sharpen the image with an unsharp mask operator
if ($unsharp) {
my $umF = $myDiag->Frame()->pack(-fill =>'x');
my $umcB = $umF->Checkbutton(-variable => \$config{Unsharp},
-anchor => 'w',
-text => "Unsharp mask")->pack(-side => "left", -anchor => 'w', -fill => 'x', -expand => 1);
$balloon->attach($umcB, -msg => "The unsharp option sharpens an image.
We convolve the image with a Gaussian operator of the given radius
and standard deviation (sigma).
For reasonable results, radius should be larger than sigma.
Use a radius of 0 to have the method select a suitable radius.");
$umF->Button(-text => "Options",
-anchor => 'w',
-command => sub { unsharpDialog(); })->pack(-side => "left", -anchor => 'w', -padx => 3);
}
my $sS = labeledScale($myDiag, 'top', 18, "Sharpness (radius)", \$config{PicSharpen}, 0, 10, 0.1);
$balloon->attach($sS, -msg => "Resizing a picture to a smaller size usually causes some blurring\nuse this function to sharpen the picture and reduce the blurring\nHowever if the unsharp mask option is available I recommend using it instead of sharpen\nThis function is deactivated when set to 0");
my $blS = labeledScale($myDiag, 'top', 18, "Blur (radius)", \$config{PicBlur}, 0, 10, 0.1);
$balloon->attach($blS, -msg => "Maybe used in conjunction with Sharpness");
buttonBackup($myDiag, 'top');
buttonComment($myDiag, 'top');
my $ButF = $myDiag->Frame()->pack(-fill =>'x',-padx => 3,-pady => 3);
my $OKB = $ButF->Button(-text => 'OK',
-command => sub {
$rc = 1;
$myDiag->withdraw();
$myDiag->destroy();
})->pack(-side => 'left',-expand => 1,-fill => 'x',-padx => 3,-pady => 3);
$ButF->Button(-text => 'Cancel',
-command => sub {
$rc = 0;
$myDiag->withdraw();
$myDiag->destroy();
}
)->pack(-side => 'left',-expand => 1,-fill => 'x',-padx => 3,-pady => 3);
$OKB->focus;
$myDiag->Popup;
$myDiag->waitWindow;
return if ($rc != 1);
# check if some files are links
return if (!checkLinks($picLB, @sellist));
return if (checkWriteableMulti(@sellist) eq 'Cancel All');
$userinfo = "changing the size/quality of $selected pictures ..."; $userInfoL->update;
my $pw = progressWinInit($top, "changing size/quality");
$i = 0;
foreach $dpic (@sellist) {
last if progressWinCheck($pw);
$i++;
$pic = basename($dpic);
$dirthumb = getThumbFileName($dpic);
# check if file is a link and get the real target
next if (!getRealFile(\$dpic));
next if (!checkWriteable($dpic));
next if (!makeBackup($dpic));
my ($w, $h) = getSize($dpic);
if ($PixPro eq "pro") {
if (($w == 0) or ($h == 0)) { # avoid division by zero
$top->messageBox(-message => "Sorry, but the size of $pic is not available - skipping picture.", -icon => 'warning', -title => "No size info", -type => 'OK');
next;
}
$width = sprintf("%.0f",($w * $widthP/100));
$height = sprintf("%.0f",($h * $heightP/100));
print "resizing to procent $w $h -> $width $height ($widthP $heightP)\n" if $verbose;
}
# call external command mogrify
# the comment option of mogrify overwrites all existing comments!
my $command = "mogrify";
$command .= " -blur ".$config{PicBlur} if ($config{PicBlur} > 0);
$command .= " -size ${width}x${height}";
$command .= " -geometry ${width}x${height}";
$command .= "\\\!" if (!$keepaspect);
$command .= " -filter ".$config{ResizeFilter};
$command .= " -strip ".$config{PicStrip} if ($config{PicStrip} and $strip);
$command .= " -sharpen ".$config{PicSharpen} if ($config{PicSharpen} > 0);
$command .= " -unsharp ".$config{UnsharpRadius}.'x'.$config{UnsharpSigma}."+".$config{UnsharpAmount}."+".$config{UnsharpThreshold}." " if ($config{Unsharp} and $unsharp);
$command .= " -quality ".$config{PicQuality}." \"$dpic\"";
print "changeSizeQuality: com = $command\n" if $verbose;
execute($command);
progressWinUpdate($pw, "changing size/quality ($i/$selected) ...", $i, $selected);
# touch the thumbnail pic (set actual time stamp), to suppress rebuilding the next time
print "new $width x $height old: $w x $h\n" if $verbose;
touch($dirthumb) if (($width == $w) and ($height == $h)); # only when the size changed
if ($config{AddMapiviComment}) {
$command =~ s/\"//g;
$command = "Picture processed by Mapivi ($mapiviURL):\n".$command;
addCommentToPic($command, $dpic, NO_TOUCH);
}
updateOneRow($dpic, $picLB);
showImageInfo($dpic) if ($dpic eq $actpic);
} # foreach end
progressWinEnd($pw);
$userinfo = "ready! ($i of $selected changed)"; $userInfoL->update;
generateThumbs(ASK, SHOW);
}
##############################################################
# dragPic - enable panning of an object in a canvas
# needs $c->{picWidth} and $c->{picHeight} to be
# set to the object (picture) width and height
##############################################################
sub dragPic {
my $c = shift; # the canvas
my $i = shift; # the item to drag
$c->bind($i, '<Button-1>' => sub {
($c->{idx}, $c->{idy})=($Tk::event->x,$Tk::event->y);
});
$c->bind($i, '<B1-Motion>' => sub {
# actual mouse coordinates
$c->configure(-cursor => "fleur");
my ($mx,$my) = ($Tk::event->x,$Tk::event->y);
my ($x1,$x2) = $c->xview;
my ($y1,$y2) = $c->yview;
return if ($x1 == 0 and $x2 == 1 and $y1 == 0 and $y2 == 1);
my $dx = 0; $dx = ($mx-$c->{idx})/$c->{picWidth} if ($c->{picWidth} >= 1); # avoid division by zero
my $dy = 0; $dy = ($my-$c->{idy})/$c->{picHeight} if ($c->{picHeight} >= 1); # avoid division by zero
$c->xviewMoveto($x1-$dx) unless ($x1 == 0 and $x2 == 1);
$c->yviewMoveto($y1-$dy) unless ($y1 == 0 and $y2 == 1);
($c->{idx},$c->{idy}) = ($mx,$my);
});
}
##############################################################
# filterPic - apply a image filter to the picture
##############################################################
sub filterPic {
if (Exists($filterW)) {
$filterW->deiconify;
$filterW->raise;
return;
}
my $fdir = $actdir;
return if (!checkExternProgs("filterPic", "mogrify"));
# check, if a new version of ImageMagick's mogrify with the unsharp and level option is available
my $unsharp = 0;
my $level = 0;
my $usage = `mogrify`;
$unsharp = 1 if ($usage =~ m/.*-unsharp.*/);
$level = 1 if ($usage =~ m/.*-level.*/);
my @sellist = $picLB->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
# check if some files are links
return if (!checkLinks($picLB, @sellist));
my ($pic, $dpic, $dirtpic, $i);
$userinfo = "image processing: preparing preview ..."; $userInfoL->update;
# take the first picture as preview picture
$dpic = $sellist[0];
$pic = basename($dpic);
# open dialog window
$filterW = $top->Toplevel();
$filterW->withdraw(); # hide window while populating
$filterW->title("Image processing $pic");
$filterW->iconimage($mapiviicon) if $mapiviicon;
my $p = $filterW;
my $lF = $p->Frame()->pack(-anchor => "n", -side => "left");
my $rF = $p->Frame()->pack(-anchor => "n", -side => "left");
my $leftF = $lF->Frame(-bd => $config{Borderwidth}, -relief => 'groove')->pack(-expand => 1, -fill => "both", -side => "left");
my $rightF = $lF->Frame(-bd => $config{Borderwidth}, -relief => 'groove')->pack(-expand => 1, -fill => "both", -side => "right");
$leftF->Label (-text => "Original")->pack(-fill => 'x');
$rightF->Label(-text => "Processed")->pack(-fill => 'x');
my %filters = (
"equalize" => 0,
"normalize" => 0,
"despeckle" => 0,
"grayscale" => 0,
"enhance" => 0,
"negate" => 0,
"antialias" => 0,
"contrast" => 0,
);
# try to get the saved filter settings
if (-f "$configdir/filters") {
my $hashRef = retrieve("$configdir/filters");
warn "could not retrieve filter settings" unless defined $hashRef;
%filters = %{$hashRef};
}
# layout infos:
# leftF rightF
# original processed
# $icon($thumb) $thumbicon($thumbnew)
# $photo($actdir/pic) $previewP($prevpic)
my @xy = (0, 0);
my $pc;
my $icon;
my $thumbicon;
my $previewP;
# the preview thumb
my $thumb = "$trashdir/$thumbdirname/$pic.jpg";
my $thumbnew = "$trashdir/$thumbdirname/$pic";
my $thumbPreviewB;
return if (!mycopy ("$fdir/$pic", "$thumb", OVERWRITE));
return if (!resizePic("$thumb", $config{FilterPrevSize}, $config{FilterPrevSize}, $config{PicQuality}));
# the cropped preview pic
my $prevpic = "$trashdir/$pic";
my $previewB;
return if (!mycopy ("$fdir/$pic", $prevpic, OVERWRITE));
return if (!cropPic($prevpic, $config{FilterPrevSize}, $config{FilterPrevSize},0,0, $config{PicQuality}));
if ((defined $thumb) and (-f $thumb)) {
$icon = $top->Photo(-file => "$thumb", -gamma => $config{Gamma});
if ($icon) {
$leftF->Label(-image => $icon
)->pack(-padx => 3, -pady => 3,-anchor => "e");
$thumbPreviewB =
$rightF->Button(-image => $icon,
-command => sub {
return if !mycopy("$thumb" , "$thumbnew", OVERWRITE);
return if !mycopy("$fdir/$pic", "$prevpic" , OVERWRITE);
# we need to recrop everytime, because the crop sector may be changed by the user
@xy = getCorners($pc); # get the crop offset
return if !cropPic($prevpic, $config{FilterPrevSize},$config{FilterPrevSize},$xy[0],$xy[1], $config{PicQuality});
$filterW->Busy;
applyFilter("$thumbnew", \%filters, PREVIEW);
if ($thumbicon) { # if the photo object is already defined we just need to configure it
$thumbicon->configure(-file => "$thumbnew", -gamma => $config{Gamma});
}
else { # else we define it
$thumbicon = $top->Photo(-file => "$thumbnew", -gamma => $config{Gamma});
$thumbPreviewB->configure(-image => $thumbicon);
}
applyFilter("$prevpic", \%filters, PREVIEW);
if ($previewP) { # if the photo object is already defined we just need to configure it
$previewP->configure(-file => "$prevpic", -gamma => $config{Gamma});
}
else { # else we define it
$previewP = $top->Photo(-file => "$prevpic", -gamma => $config{Gamma});
$previewB->configure(-image => $previewP);
}
$filterW->Unbusy;
})->pack(-padx => 3, -pady => 3,-anchor => 'w');
$balloon->attach($thumbPreviewB, -msg => "Press on the thumbnail or the Preview-button\nto see how the settings affect the picture");
}
}
# load the original picture in original size into a scrollable canvas
# to set the crop frame
$pc = $leftF->Scrolled("Canvas",
-scrollbars => 'osoe',
-width => $config{FilterPrevSize},
-height => $config{FilterPrevSize},
-relief => 'sunken',
#-cursor => "fleur",
-bd => $config{Borderwidth})->pack(-expand => 1, -fill => "both");
# this is needed for dragPic()
($pc->{picWidth}, $pc->{picHeight}) = getSize("$fdir/$pic");
$top->Busy;
my $photo = $top->Photo(-file => "$fdir/$pic", -gamma => $config{Gamma});
my $id = $pc->createImage(0, 0, -image => $photo, -anchor => "nw");
dragPic($pc, $id); # enable panning of the pic in the canvas
my ($x1, $y1, $x2, $y2) = $pc->bbox($id);
$pc->configure(-scrollregion => [0, 0, $x2-$x1, $y2-$y1]);
# load the croped preview picture
$previewP = $top->Photo(-file => "$prevpic", -gamma => $config{Gamma});
if ($previewP) {
$previewB =
$rightF->Button(-image => $previewP,
-command => sub {$thumbPreviewB->invoke();},
)->pack(-expand => 1, -fill => "both", -padx => 0, -pady => 0, -anchor => "nw");
$balloon->attach($previewB, -msg => "Press on the picture or the Preview-button\nto see how the settings affect the picture");
}
$top->Unbusy;
my $mF = $rF->Frame()->pack(-expand => 1, -fill => "both");
my $lbf = $mF->Frame()->pack(-expand => 1, -fill => "both", -side => "left");
my $rbf = $mF->Frame()->pack(-expand => 1, -fill => "both", -side => "right");
foreach (sort keys %filters) {
$lbf->Checkbutton(-variable => \$filters{$_},
-anchor => 'w',
-text => "$_")->pack(-anchor => 'w');
}
#my $scF = $rF->Frame()->pack(-fill =>'x', -expand => "1");
my $qS = labeledScale($rF, 'top', 12, "Quality (%)", \$config{PicQuality}, 10, 100, 1);
qualityBalloon($qS);
my $sS = labeledScale($rF, 'top', 12, "Sharpness", \$config{PicSharpen}, 0, 10, 0.1);
$balloon->attach($sS, -msg => "appropriate settings are between 0 (no sharpen) and 4,\nthe higher the value the slower the conversion");
my $colF = $rF->Frame()->pack(-fill =>'x');
my $colcB = $colF->Checkbutton(-variable => \$config{ColorAdj},
-anchor => 'w',
-text => "Color adjustment")->pack(-side => "left", -anchor => 'w', -fill => 'x', -expand => 1);
$balloon->attach($colcB, -msg => "Adjust brightness, hue,\nsaturation and gamma");
$colF->Button(-text => "Options",
-anchor => 'w',
-command => sub { colorDialog(); })->pack(-side => "left", -anchor => 'w', -padx => 3);
# sharpen the image with an unsharp mask operator
if ($unsharp) {
my $umF = $rF->Frame()->pack(-fill =>'x');
my $umcB = $umF->Checkbutton(-variable => \$config{Unsharp},
-anchor => 'w',
-text => "Unsharp mask")->pack(-side => "left", -anchor => 'w', -fill => 'x', -expand => 1);
$balloon->attach($umcB, -msg => "The -unsharp option sharpens an image.
We convolve the image with a Gaussian operator of the given radius
and standard deviation (sigma).
For reasonable results, radius should be larger than sigma.
Use a radius of 0 to have the method select a suitable radius.");
$umF->Button(-text => "Options",
-anchor => 'w',
-command => sub { unsharpDialog(); })->pack(-side => "left", -anchor => 'w', -padx => 3);
}
if ($level) {
my $lvF = $rF->Frame()->pack(-fill =>'x');
my $lvB = $lvF->Checkbutton(-variable => \$config{Level},
-anchor => 'w',
-text => "Level")->pack(-side => "left", -anchor => 'w', -fill => 'x', -expand => 1);
$balloon->attach($lvB, -msg => "Level adjusts the levels of an image by scaling
the colors falling between specified white and
black points to the full available quantum range.");
$lvF->Button(-text => "Options",
-anchor => 'w',
-command => sub { levelDialog(); })->pack(-side => "left", -anchor => 'w', -padx => 3);
}
my $decoF = $rF->Frame()->pack(-fill =>'x');
$decoF->Checkbutton(-variable => \$config{FilterDeco},
-anchor => 'w',
-text => "Add border or text")->pack(-side => "left", -anchor => 'w', -fill => 'x', -expand => 1);
$decoF->Button(-text => "Options",
-anchor => 'w',
-command => sub {decorationDialog(scalar @sellist,0);})->pack(-side => "left", -anchor => 'w', -padx => 3);
buttonBackup($rF, 'top');
buttonComment($rF, 'top');
my $ButF =
$rF->Frame()->pack(-fill =>'x');
$ButF->Button(-text => "Preview",
-command => sub {$thumbPreviewB->invoke();}
)->pack(-side => 'left',-expand => 1,-fill => 'x',-padx => 3,-pady => 3);
my $OKB =
$ButF->Button(-text => 'OK',
-command => sub {
# save the filter settings
store(\%filters, "$configdir/filters") or warn "could not store filter settings in file";
$uw->withdraw if (Exists($uw));
$lw->withdraw if (Exists($lw));
$colw->withdraw if (Exists($colw));
$decoW->withdraw if (Exists($decoW));
$filterW->withdraw(); # close window
my $pw = progressWinInit($top, "Process pictures");
my $nr = 0;
foreach my $dpic (@sellist) {
last if progressWinCheck($pw);
$pic = basename($dpic);
next if (!checkWriteable($dpic));
last if (!makeBackup($dpic));
$nr++;
progressWinUpdate($pw, "processing ($nr/".scalar @sellist.") ...", $nr, scalar @sellist);
# we need to reread the picture to show the effect,
# so we should clear the cachedPics list first
deleteCachedPics($dpic);
applyFilter($dpic, \%filters, NO_PREVIEW, "processing ($nr/".scalar @sellist.") ...");
updateOneRow($dpic, $picLB);
# redisplay the processed picture if it is the actual picture
showPic($dpic) if ($dpic eq $actpic);
}
progressWinEnd($pw);
reselect($picLB, @sellist);
$userinfo = "ready! ($nr of ".scalar @sellist." processed)"; $userInfoL->update;
generateThumbs(ASK, SHOW);
$filterW->destroy;
})->pack(-side => 'left',-expand => 1,-fill => 'x',-padx => 3,-pady => 3);
my $Xbut =
$ButF->Button(-text => 'Cancel',
-command => sub { $filterW->destroy if (Exists($filterW));
$uw->destroy if (Exists($uw));
$lw->destroy if (Exists($lw));
$colw->destroy if (Exists($colw));
$decoW->destroy if (Exists($decoW));
}
)->pack(-side => 'left',-expand => 1,-fill => 'x',-padx => 3,-pady => 3);
$filterW->bind('<Key-q>', sub { $Xbut->invoke; });
$filterW->bind('<Key-Escape>', sub { $Xbut->invoke; });
$OKB->focus;
$filterW->Popup;
$userinfo = "image processing: preview ready!"; $userInfoL->update if (Exists($userInfoL));
$filterW->waitWindow;
$userinfo = "image processing: cleaning up ..."; $userInfoL->update if (Exists($userInfoL));
$icon->delete if $icon;
$photo->delete if $photo;
$thumbicon->delete if $thumbicon;
$previewP->delete if $previewP;
$uw->destroy if (Exists($uw));
$lw->destroy if (Exists($lw));
$colw->destroy if (Exists($colw));
$decoW->destroy if (Exists($decoW));
removeFile($prevpic);
removeFile($thumb);
removeFile($thumbnew);
$userinfo = "image processing ready!"; $userInfoL->update if (Exists($userInfoL));
}
##############################################################
# applyFilter
##############################################################
sub applyFilter {
my $dpic = shift;
my $filters = shift;
my $preview = shift; # PREVIEW = preview mode, NO_PREVIEW = real conversion
my $info = shift; # optional, user info text
$info = "processing ".basename($dpic)." ..." if (!defined $info);
$userinfo = $info; $userInfoL->update;
# check if file is a link and get the real target
return if (!getRealFile(\$dpic));
# call external command mogrify
my $command = "mogrify ";
foreach (keys %{$filters}) {
if ($_ eq "grayscale") {
$command .= "-colorspace GRAY -colors 256 " if $$filters{$_};
}
else {
$command .= "-$_ " if $$filters{$_};
}
}
$command .= "-sharpen ".$config{PicSharpen}." " if ($config{PicSharpen} > 0);
$command .= "-gamma ".$config{PicGamma}." " if (($config{PicGamma} != 1.0) and ($config{ColorAdj}));
$command .= "-modulate ".$config{PicBrightness}.",".$config{PicSaturation}.",".$config{PicHue}." " if ($config{ColorAdj});
$command .= makeDrawOptions($dpic) if ((!$preview) and ($config{FilterDeco})); # do not add a border or a text in the preview
$command .= "-unsharp ".$config{UnsharpRadius}.'x'.$config{UnsharpSigma}."+".$config{UnsharpAmount}."+".$config{UnsharpThreshold}." " if $config{Unsharp};
$command .= "-level \"".$config{LevelBlack}."%/".$config{LevelWhite}."%/".$config{LevelGamma}."\" " if $config{Level};
$command .= "-quality ".$config{PicQuality};
execute($command." \"$dpic\" ");
addDropShadow($dpic) if ($config{FilterDeco});
if ($config{AddMapiviComment}) {
$command =~ s/\"//g;
$command = "Picture processed by Mapivi ($mapiviURL):\n".$command;
addCommentToPic($command, $dpic, NO_TOUCH);
}
$userinfo = "image processing ready!"; $userInfoL->update;
}
##############################################################
# removeFile - delete a file
##############################################################
sub removeFile {
my $file = shift;
return 1 if (!-f $file);
if ( unlink($file) != 1) { # unlink returns the number of successfull removed files
$top->messageBox(-icon => 'warning', -message => "Could not delete file \"$file\": $!",
-title => 'Error', -type => 'OK');
return 0;
}
else {
# remove file from search database, if it exists
delete $searchDB{$file};
}
return 1;
}
##############################################################
# resizePic
##############################################################
sub resizePic {
my ($dpic, $x, $y, $quality) = @_;
unless (-f $dpic) {
warn "no picture $dpic found!";
return 0;
}
my $command = "mogrify -size ${x}x${y} -geometry ${x}x${y} -quality $quality \"$dpic\" ";
execute($command);
return 1;
}
##############################################################
# crop - crop pictures in a lossless way
##############################################################
sub crop {
if (!checkExternProgs("crop", "jpegtran")) {
$top->messageBox(-icon => 'warning', -message => "Could not find jpegtran, so there is no support for lossless JPEG cropping!\nYou will get jpegtran here: http://jpegclub.org\nNote: Download and install the jpegtran version with crop patch.\nNormal cropping is however possible.",
-title => "No jpegtran available", -type => 'OK');
}
else {
# check if jpegtran supports lossless cropping
my $usage = `jpegtran -? 2>&1`;
if ($usage !~ m/.*-crop.*/) {
$top->messageBox(-icon => 'warning', -message => "Sorry, but your version of jpegtran does not support lossless cropping!\nTry to get the lossless crop patch from http://jpegclub.org.\nNormal cropping is however possible.",
-title => "Wrong jpegtran version", -type => 'OK');
}
}
my $lb = shift; # the reference to the active listbox widget
my @sellist = $lb->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
my ($pic, $dpic, $w, $h, $wo, $ho, $x, $y);
my $i = 0;
my $doforall = 0;
my $askDifSize = 1;
my $first = $sellist[0];
my ($wm, $hm) = getSize($first);
my $pw = progressWinInit($lb, "Crop pictures");
foreach $dpic (@sellist) {
last if progressWinCheck($pw);
$i++;
progressWinUpdate($pw, "cropping picture ($i/".scalar @sellist.") ...", $i, scalar @sellist);
$pic = basename($dpic);
# check if file is a link and get the real target
next if (!getRealFile(\$dpic));
next if (!checkWriteable($dpic));
($wo, $ho) = getSize($dpic);
if ($wo == 0 or $ho == 0) {
$top->messageBox(-icon => 'warning', -message => "Sorry, picture $pic has no correct size (${wo}x$ho)!",
-title => "Crop file", -type => 'OK');
next;
}
if ($doforall and $askDifSize and (($wo != $wm) or ($ho != $hm))) {
my $rc = $top->messageBox(-icon => 'question',
-message => "Picture $pic has not the same size as the preview picture.\nShould I continue and adjust the crop range if necessary?\nNote:\nThis will be done for all following pictures too!",
-title => "Question",
-type => 'OKCancel');
if ($rc !~ m/Ok/i) {
$i--;
last;
}
else {
$askDifSize = 0;
}
}
if (!$doforall) {
($w, $h) = calcAspectSize($wo, $ho);
$x = 0;
$y = 0;
last if (!cropDialog($dpic, \$x, \$y, \$w, \$h, $wo, $ho, \$doforall, scalar @sellist));
}
# save crop frame offset before adjusting to small pics
my $xsave = $x; my $ysave = $y;
if (($x + $w) > $wo) { # crop frame outside the picture
$x = $wo - $w;
if ($x < 0) {
$top->messageBox(-icon => 'warning', -message => "Skipping picture $pic!\nThe width ($wo) is too small for the crop frame ($w).",
-title => "Picture too small", -type => 'OK');
# restore crop frame offset after adjusting to small pics
$x = $xsave; $y = $ysave;
next;
}
}
if (($y + $h) > $ho) { # crop frame outside the picture
$y = $ho - $h;
if ($y < 0) {
$top->messageBox(-icon => 'warning', -message => "Skipping picture $pic!\nThe height ($ho) is too small for the crop frame ($h).",
-title => "Picture too small", -type => 'OK');
# restore crop frame offset after adjusting to small pics
$x = $xsave; $y = $ysave;
next;
}
}
printf "cropping $pic %4dx%4d+%4d+%4d\n", $w, $h, $x, $y if $verbose;
next if (!makeBackup($dpic));
# crop the picture
$top->Busy;
cropPic($dpic,$w,$h,$x,$y,95);
$top->Unbusy;
# check if crop has the right size
# due to the 8 pixel blocks, sometimes the size is too big (a few pixels)
my ($nw, $nh) = getSize($dpic);
if (($nw > $w) or ($nh > $h)) {
# but a recrop will help ...
$top->Busy;
cropPic($dpic,$w,$h,0,0,95);
$top->Unbusy;
print "recropping $pic w:$nw > $w h: $nh > $h n" if $verbose;
}
# restore crop frame offset after adjusting to small pics
$x = $xsave; $y = $ysave;
addCommentToPic("Picture lossless cropped by Mapivi ($mapiviURL)", $dpic, NO_TOUCH) if ($config{AddMapiviComment});
updateOneRow($dpic, $lb);
deleteCachedPics($dpic);
showPic($dpic) if ($dpic eq $actpic); # redisplay the picture if it is the actual one
} # foreach end
progressWinEnd($pw);
reselect($lb, @sellist);
$userinfo = "ready! ($i of ".scalar @sellist." cropped)"; $userInfoL->update;
generateThumbs(ASK, SHOW);
}
##############################################################
# calcAspectSize
##############################################################
sub calcAspectSize {
my $w = shift; # width
my $h = shift; # height
my $m = shift; # (optional) master ('w' if the width is the master or "h" for height)
# calculate new size
if ($config{CropAspect} != 0) { # if there is no aspect ratio there is nothing to do
if (defined $m) { # master defined
if ($m eq 'w') { # width is master
if ($w >= $h) { # landscape image
$h = sprintf "%.0f", ($w / $config{CropAspect}); # int() does not round!
} else { # portait image
$h = sprintf "%.0f", ($w * $config{CropAspect});
}
} else { # height is master
if ($w >= $h) { # landscape image
$w = sprintf "%.0f", ($h * $config{CropAspect});
} else { # portait image
$w = sprintf "%.0f", ($h / $config{CropAspect});
}
}
} else { # no master defined
if ($w >= $h) { # landscape image
if (($h != 0) and ($w/$h >= $config{CropAspect})) { # too wide
$w = sprintf "%.0f", ($h * $config{CropAspect});
} else { # too high
$h = sprintf "%.0f", ($w / $config{CropAspect});
}
} else { # portait image
if (($h != 0) and ($w/$h >= 1/$config{CropAspect})) { # too wide
$w = sprintf "%.0f", ($h / $config{CropAspect});
} else { # too high
$h = sprintf "%.0f", ($w * $config{CropAspect});
}
}
}
}
return ($w, $h);
}
##############################################################
# setNewAspect
##############################################################
sub setNewAspect {
my $c = shift;
my $info_ref = shift;
my $w = $c->{m_x2} - $c->{m_x1};
my $h = $c->{m_y2} - $c->{m_y1};
($w, $h) = calcAspectSize($w, $h);
$c->{m_x2} = $c->{m_x1} + $w;
$c->{m_y2} = $c->{m_y1} + $h;
$c->{m_aspect} = getAspectRatio($w, $h);
drawFrame($c);
}
##############################################################
#bindForResize
##############################################################
sub bindForResize {
my $canvas = shift;
# Drag requests:
# 0 = No drag requested in this direction.
# 1 = Drag top (for y) or left (for x) edge of rectangle.
# -1 = Drag bottom (for y) or right (for x) edge of rectangle.
my ( $dx, $dy ) = ( 0, 0 );
# Drag mode: NO_ACTIVE_MODE, MOVE_MODE, or RESIZE_MODE.
use constant NO_ACTIVE_MODE => 0;
# use constant MOVE_MODE => 1;
use constant RESIZE_MODE => 1;
my $mode = NO_ACTIVE_MODE;
# How close to the edge we have to be to initiate a resize (instead
# of a move) drag. Expressed in percentage of overall
# height/width.
my $resize_within = 0.05; # Within 5% of edge to resize.
# Initial location of mouse pointer.
my ($oldx, $oldy) = (0) x 2;
# ID of rectangle that we're resizing.
my $rect;
# Bind left-mouse clicks (<1>) over any widget with a 'RECT' tag to
# do...
$canvas->bind( 'RECT' => '<1>' =>
sub {
my ( $x, $y ) = ( $Tk::event->x, $Tk::event->y );
my $id = $canvas ->find( qw|withtag current| );
my ( $x0, $y0, $x1, $y1 ) = $canvas->coords( $id );
my ( $width, $height ) = ( $x1 - $x0, $y1 - $y0 );
#my $rrrrx = $canvas->width * $canvas->{m_xzoom};
#my $rrrry = $canvas->height * $canvas->{m_yzoom};
#print "canvas $canvas->width,$canvas->height $rrrrx, $rrrry\n";
# Determine if the user wants to size in the x direction. If
# the user clicks within $resize_within of the edge, then he
# wants to resize.
$dx = 0;
if( $x < ( $x0 + $resize_within * $width ) ) { $dx = 1; }
elsif( $x > ( $x1 - $resize_within * $width ) ) { $dx = -1; }
# Do the same for the y direction.
$dy = 0;
if( $y < ( $y0 + $resize_within * $width ) ) { $dy = 1; }
elsif( $y > ( $y1 - $resize_within * $width ) ) { $dy = -1; }
# If resizing in either direction, set resize mode.
# $mode = ( $dx || $dy ) ? RESIZE_MODE : MOVE_MODE;
$mode = RESIZE_MODE;
( $oldx, $oldy, $rect ) = ( $x, $y, $id );
# Create the red-outlined rectangle that shows the resize as
# it occurs.
# if( $mode == RESIZE_MODE ) {
$canvas->createRectangle( $x0, $y0, $x1, $y1,
-outline => 'red',
#-dash => [6,4,2,4],
-tags => ['TEMP'] );
#$canvas->createRectangle( $x0, $y0, $x1, $y1,
# -outline => 'white',
# -dash => [2,6,2,4],
# -tags => ['TEMP'] );
# }
return;
}
);
# Bind motion with the left mouse button down (<B1-Motion>) over a
# widget with a 'RECT' tag to do...
$canvas->bind( 'RECT' => '<B1-Motion>' =>
sub {
my ( $x, $y ) = ( $Tk::event->x, $Tk::event->y );
if( $mode == RESIZE_MODE ) {
# Get coordinates of resizing rectangle. Note that we
# tagged it with 'TEMP' in the createRectangle call.
my ( $x0, $y0, $x1, $y1 ) = $canvas->coords( 'TEMP' );
# Resize logic. If we're moving the left border, then
# change the coordinates of the left edge ($x0) to be the
# current mouse position's x position ($x), else set the
# rectangle's right edge.
if( $dx == 1 ) { $x0 = $x; }
elsif( $dx == -1 ){ $x1 = $x; }
if( $dy == 1 ) { $y0 = $y; }
elsif( $dy == -1 ){ $y1 = $y; }
$x0 = 0 if ($x0 < 0);
$x1 = $canvas->width if ($x1 > $canvas->width);
$y0 = 0 if ($y0 < 0);
$y1 = $canvas->height if ($y1 > $canvas->height);
# Set the coordinates of the temporary resizing rectangle.
$canvas->coords( 'TEMP', $x0, $y0, $x1, $y1 );
}
}
);
# Set to false when we've changed the cursor. Tells us we want to
# reset the cursor when we leave a rectangle.
my $cursor_is_normal = 1;
# Maps cursor position to cursor shape.
# 0 = middle of shape, 1 = left/top edge, 2 = right/bottom edge.
# [$x][$y]
my @cursors = (
# [ (0,0), (0,1), (0,2) ]
[ 'target', 'top_side', 'bottom_side' ],
# [ (1,0), (1,1), (1,2) ]
[ 'left_side', 'top_left_corner', 'bottom_left_corner' ],
# [ (2,0), (2,1), (2,2) ]
[ 'right_side', 'top_right_corner', 'bottom_right_corner' ]
);
my @old_cursors = ( 3, 3 ); # ( x, y )
$canvas->CanvasBind( '<B1-ButtonRelease>' =>
sub {
my @coords = $canvas->coords( 'TEMP' );
$canvas->delete( 'TEMP' );
$canvas->coords( $rect => @coords );
$mode = NO_ACTIVE_MODE;
$canvas->configure( -cursor => 'left_ptr' );
@old_cursors = ( 3, 3 );
$cursor_is_normal = 1;
drawFrame($canvas, @coords);
$canvas->raise($rect);
}
);
# Update the mouse cursor based on where the pointer is on the
# canvas. If it's not over a rectangle, set it to the default
# ('left_ptr'). If it's over a rectangle, set to a target cursor
# if the pointer is in the drag region (center) else to a resize
# cursor.
$canvas->CanvasBind( '<Motion>' =>
sub {
my $id = $canvas->find( qw|withtag current| );
my @tags = $canvas->gettags($id);
#for (0 .. $#tags) { print "$_ $tags[$_]\n"; }
# Bail if we're not over a rectangle.
if ( (!defined $id) or (!isInList('RECT', \@tags)) ) {
unless( $cursor_is_normal ) {
$canvas->configure( -cursor => 'left_ptr' );
@old_cursors = ( 3, 3 );
$cursor_is_normal = 1;
}
return;
}
# Don't update the cursor once we've started a drag or resize
# operation.
return unless $mode == NO_ACTIVE_MODE;
my ( $x, $y ) = ( $Tk::event->x, $Tk::event->y );
my ( $x0, $y0, $x1, $y1 ) = $canvas->coords( $id );
return unless (defined $x0 and defined $y0 and defined $x1 and defined $y1);
my( $width, $height ) = ( $x1 - $x0, $y1 - $y0 );
# Now figure out where we are in the widget.
my ( $px, $py ) = ( 0, 0 );
# Determine if the user wants to size in the x direction. If
# the user clicks within $resize_within of the edge, then he
# wants to resize.
if ( $x > ( $x1 - $resize_within * $width ) ) {
$px = 2;
} elsif ( $x < ( $x0 + $resize_within * $width ) ) {
$px = 1;
}
# Do the same for the y direction.
if ( $y > ( $y1 - $resize_within * $width ) ) {
$py = 2;
}
if ( $y < ( $y0 + $resize_within * $width ) ) {
$py = 1;
}
# Don't update cursor unless it's changed.
return if ( $px == $old_cursors[0] and $py == $old_cursors[1] );
$canvas->configure( -cursor => $cursors[$px][$py] );
@old_cursors = ( $px, $py );
$cursor_is_normal = 0;
}
);
}
##############################################################
# cropDialog - let the user set the crop offset
##############################################################
sub cropDialog {
my ($dpic, $xr, $yr, $wr, $hr, $wo, $ho, $doforallr, $nr) = @_;
# $xr, $yr, $wr $hr x,y-offset and width and height of crop frame (type: reference on scalar)
# $wo, $ho width and height of original picture (type: scalar)
# $doforallr bool (type: reference on scalar)
# $nr number of pics to crop
my $rc;
my $pc; # the canvas widget
my $x2 = $$xr + $$wr;
my $y2 = $$yr + $$hr;
$userinfo = "crop: creating preview picture ..."; $userInfoL->update;
my $zpic = "$trashdir/".basename($dpic);
warn "copy error" if (!mycopy($dpic, $zpic, OVERWRITE));
my $per = 0.75; # preview pic should be 75% of the min screen size
my $cropPreviewSize = int($per * $top->screenwidth);
$cropPreviewSize = int($per * $top->screenheight) if ($top->screenheight < $top->screenwidth);
# just shrink big pictures, do not blow up small ones
my $command = 'mogrify -geometry "'.$cropPreviewSize.'x'.$cropPreviewSize.'>" -quality 80 "'.$zpic.'"';
print "croppreview: $command\n" if $verbose;
$top->Busy;
(system $command) == 0 or warn "$command failed: $!";
$top->Unbusy;
$userinfo = "ready!"; $userInfoL->update;
if (!-f $zpic) {
$top->messageBox(-icon => 'warning', -message => "Sorry, error zooming $dpic!",
-title => "Crop file", -type => 'OK');
return 0;
}
# open window
my $cropW = $top->Toplevel();
$cropW->title("Crop picture (lossless)");
$cropW->iconimage($mapiviicon) if $mapiviicon;
my $cropFL = $cropW->Frame()->pack(-side => "left", -anchor => 'w');
my $cropFR = $cropW->Frame()->pack(-side => "left", -anchor => 'n');
my ($zpicx, $zpicy) = getSize($zpic);
my $fc = $cropFL->Frame()->pack();
$pc = $fc->Canvas(-width => $zpicx,
-height => $zpicy,
-relief => 'sunken',
-bd => $config{Borderwidth})->pack(-side => "left", -padx => 3);
# store some values in the canvas hash
$pc->{m_aspect} = "[x:y]";
$pc->{m_wo} = $wo;
$pc->{m_ho} = $ho;
my $fF = $cropFR->Frame(-bd => $config{Borderwidth}, -relief => 'groove' )->pack(-anchor => 'w', -padx => 3, -pady => 3, -expand => 0, -fill => 'x');
$fF->Label(-text => "Help")->pack(-expand => 0, -fill => 'x');
my $rotext = $fF->ROText(-wrap => "word", -bg => $config{ColorBG},
-bd => "0", -width => 26, -height => 7)->pack(-expand => 0, -fill => 'x', -anchor => 'w');
$rotext->insert('end', "Use right mouse button to open and drag a crop frame and the left mouse button to adjuste this frame");
my $iF = $cropFR->Frame(-bd => $config{Borderwidth}, -relief => 'groove' )->pack(-anchor => 'w', -padx => 3, -pady => 3, -expand => 0, -fill => 'x');
$iF->Label(-text => "Info")->pack(-expand => 0, -fill => 'x');
$iF->Label(-text => "File: ".basename($dpic), -bg => $config{ColorBG})->pack(-anchor => 'w');
$iF->Label(-text => "old size: ${wo} x ${ho}", -bg => $config{ColorBG})->pack(-anchor => 'w');
my $lf = $iF->Frame()->pack(-anchor => 'w');
$lf->Label(-text => "new size:", -bg => $config{ColorBG})->pack(-side => "left", -anchor => 'w');
$lf->Label(-textvariable => \$pc->{m_w}, -bg => $config{ColorBG})->pack(-side => "left", -anchor => 'w');
$lf->Label(-text => 'x', -bg => $config{ColorBG})->pack(-side => "left", -anchor => 'w');
$lf->Label(-textvariable => \$pc->{m_h}, -bg => $config{ColorBG})->pack(-side => "left", -anchor => 'w');
my $caF = $iF->Frame()->pack(-anchor => 'w');
$caF->Label(-text => "crop area:", -bg => $config{ColorBG})->pack(-side => "left", -anchor => 'w');
$caF->Label(-textvariable => \$pc->{m_xyxy}, -bg => $config{ColorBG})->pack(-side => "left", -anchor => 'w');
my $cropRect;
my @cropRectCoords;
#$pc->bind('<Any-Enter>' => sub { $pc->Tk::focus });
$pc->CanvasBind('<3>' => sub {
my $x = $pc->canvasx($Tk::event->x);
my $y = $pc->canvasy($Tk::event->y);
$pc->delete('withtag', 'RECT');
@cropRectCoords = ($x, $y, $x, $y);
$cropRect = $pc->createRectangle(@cropRectCoords,
-tags => ['RECT'], -outline => 'red',
);
});
$pc->CanvasBind('<B3-Motion>' => sub {
@cropRectCoords[2,3] = ($pc->canvasx($Tk::event->x),
$pc->canvasy($Tk::event->y));
$pc->coords($cropRect => @cropRectCoords);
});
$pc->CanvasBind( '<B3-ButtonRelease>' =>
sub {
my @coords = $pc->coords('RECT');
drawFrame($pc, @coords);
$pc->raise($cropRect);
}
);
bindForResize($pc);
my $zpicP = $cropFL->Photo(-file => "$zpic", -gamma => $config{Gamma}) if (-f $zpic);
if (!$zpicP) {
$top->messageBox(-icon => 'warning', -message => "Error displaying $zpic!",
-title => "Crop file", -type => 'OK');
return 0;
}
# insert pic
my $id = $pc->createImage(0, 0, -image => $zpicP, -anchor => "nw", -tags =>"PIC") if $zpicP;
my ($px1, $py1, $px2, $py2) = $pc->bbox($id);
print "cropDialog: x1 $px1 x2 $px2 y1 $py1 y2 $py2 $wo $ho\n" if $verbose;
if (($px1 == $px2) or ($py1 == $py2)) {
$top->messageBox(-icon => 'warning', -message => "Error displaying $zpic!",
-title => "Crop file", -type => 'OK');
return 0;
}
# calculate the x and y zoom factor
my $xz = $wo/($px2-$px1);
my $yz = $ho/($py2-$py1);
# store info in canvas widget
$pc->{m_xzoom} = $xz;
$pc->{m_yzoom} = $yz;
$pc->{m_step} = 16; # resolution/step width for lossless crop must be 16 or 8, depends on picture encoding
plusMinusEntry($iF, \$pc->{m_y1}, \$pc->{m_step}, 0, $ho, \&drawFrame, $pc, 'h');
my $iF1 = $iF->Frame()->pack();
my $iF11 = $iF1->Frame()->pack(-side => 'left');
my $iF12 = $iF1->Frame()->pack(-side => 'left');
plusMinusEntry($iF11, \$pc->{m_x1}, \$pc->{m_step}, 0, $wo, \&drawFrame, $pc, 'w');
plusMinusEntry($iF12, \$pc->{m_x2}, \$pc->{m_step}, 0, $wo, \&drawFrame, $pc, 'w');
plusMinusEntry($iF, \$pc->{m_y2}, \$pc->{m_step}, 0, $ho, \&drawFrame, $pc, 'h');
my $stepF = $iF->Frame()->pack(-anchor => 'w');
$stepF->Label(-text => "step width")->pack(-side => 'left', -anchor => 'w');
$stepF->Radiobutton(-variable => \$pc->{m_step},
-anchor => 'w',
-text => "1",
-value => 1,
)->pack(-side => 'left', -anchor => 'w');
$stepF->Radiobutton(-variable => \$pc->{m_step},
-anchor => 'w',
-text => "8",
-value => 8,
)->pack(-side => 'left', -anchor => 'w');
$stepF->Radiobutton(-variable => \$pc->{m_step},
-anchor => 'w',
-text => "16",
-value => 16,
)->pack(-side => 'left', -anchor => 'w');
my $aF = $cropFR->Frame(-bd => $config{Borderwidth}, -relief => 'groove' )->pack(-anchor => 'w', -padx => 3, -pady => 3, -expand => 0, -fill => 'x');
$aF->Label(-text => "Aspect ratio")->pack(-expand => 0, -fill => 'x');
my $aspF = $aF->Frame()->pack(-anchor => 'w');
$aspF->Label(-text => "actual aspect ratio:", -bg => $config{ColorBG})->pack(-side => "left", -anchor => 'w');
$aspF->Label(-textvariable => \$pc->{m_aspect}, -width => 8, -bg => $config{ColorBG})->pack(-side => "left", -anchor => 'w');
$aF->Radiobutton(-text => "X:Y (any aspect ratio)", -variable => \$config{CropAspect}, -value => 0,
-command => sub { setNewAspect($pc); }
)->pack(-side => 'top', -anchor => 'w');
$aF->Radiobutton(-text => "3:2 (e.g. 10x15)", -variable => \$config{CropAspect}, -value => 3/2,
-command => sub { setNewAspect($pc); }
)->pack(-side => 'top', -anchor => 'w');
$aF->Radiobutton(-text => "4:3", -variable => \$config{CropAspect}, -value => 4/3,
-command => sub { setNewAspect($pc); }
)->pack(-side => 'top', -anchor => 'w');
$aF->Radiobutton(-text => "5:4 (PAL)", -variable => \$config{CropAspect}, -value => 5/4,
-command => sub { setNewAspect($pc); }
)->pack(-side => 'top', -anchor => 'w');
$aF->Radiobutton(-text => "7:5 (e.g. 13x18)", -variable => \$config{CropAspect}, -value => 7/5,
-command => sub { setNewAspect($pc); }
)->pack(-side => 'top', -anchor => 'w');
$aF->Radiobutton(-text => "16:9", -variable => \$config{CropAspect}, -value => 16/9,
-command => sub { setNewAspect($pc); }
)->pack(-side => 'top', -anchor => 'w');
$aF->Radiobutton(-text => "1:1", -variable => \$config{CropAspect}, -value => 1/1,
-command => sub { setNewAspect($pc); }
)->pack(-side => 'top', -anchor => 'w');
# my $portLandB =
# $aF->Button(-text => "portrait/landscape",
# -command => sub {
# my $tmp = $$wr;
# $$wr = $$hr;
# $$hr = $tmp;
# if ($$wr+$$xr > $wo) {
# $$wr = $wo - $$xr;
# ($$wr, $$hr) = calcAspectSize($$wr, $$hr);
# }
# if ($$hr+$$yr > $ho) {
# $$hr = $ho - $$yr;
# ($$wr, $$hr) = calcAspectSize($$wr, $$hr);
# }
# $x2 = $$xr + $$wr;
# $y2 = $$yr + $$hr;
# #$xyxy = sprintf "%d,%d - %d,%d", $$xr, $$yr, ($$xr + $$wr), ($$yr + $$hr);
# #$aspect = getAspectRatio($$wr, $$hr);
# drawFrame($pc, $$xr, $$yr, $$wr, $$hr, $xz, $yz);
# })->pack(-fill => 'x', -padx => 3, -pady => 3);
# $balloon->attach($portLandB, -msg => "Switch crop frame between portrait and landscape mode");
buttonBackup($cropFR, 'top');
buttonComment($cropFR, 'top');
if ($nr > 1) {
$cropFR->Checkbutton(-variable => \$$doforallr,
-anchor => 'w',
-text => "use this setting for all pics"
)->pack(-anchor => 'w');
}
my $ButF =
$cropFR->Frame()->pack(-fill =>'x', -expand => 1, -padx => 0, -pady => 2);
my $OKB =
$ButF->Button(-text => 'OK',
-command => sub {
$$xr = $pc->{m_x1};
$$yr = $pc->{m_y1};
$$wr = $pc->{m_x2} - $pc->{m_x1};
$$hr = $pc->{m_y2} - $pc->{m_y1};
$cropW->withdraw();
$cropW->destroy();
$rc = 1;
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
my $Xbut =
$ButF->Button(-text => 'Cancel',
-command => sub { $rc = 0;
$cropW->withdraw();
$cropW->destroy();
})->pack(-side => 'left', -expand => 0, -fill => 'x', -padx => 3, -pady => 3);
$cropW->bind('<Control-q>', sub { $Xbut->invoke; });
$cropW->bind('<Key-Escape>', sub { $Xbut->invoke; });
$cropW->Popup;
$cropW->waitWindow;
# clean up
$zpicP->delete;
removeFile($zpic);
return $rc;
}
##############################################################
# plusMinusEntry
##############################################################
sub plusMinusEntry {
my ($widget, $value, $step, $min, $max, $callback, $cb_para1, $cb_para2) = @_;
$$value = 0 unless (defined $$value);
my $frame = $widget->Frame(-relief => 'sunken')->pack();
$frame->Label(-textvariable => $value, -bg => $config{ColorBG}, -width => 6)->pack(-side => 'left', -anchor => 'w');
my $r_frame = $frame->Frame()->pack(-side => 'left', -padx => 0, -pady => 0);
$r_frame->Button(-bitmap => "plusbut", -padx => 0, -pady => 0, -command => sub {
$$value += $$step;
$$value = $min if ($$value < $min);
$$value = $max if ($$value > $max);
$callback->($cb_para1, $cb_para2);
})->pack(-anchor => 'w', -padx => 0, -pady => 0);
$r_frame->Button(-bitmap => "minusbut", -padx => 0, -pady => 0, -command => sub {
$$value -= $$step;
$$value = $min if ($$value < $min);
$$value = $max if ($$value > $max);
$callback->($cb_para1, $cb_para2);
})->pack(-anchor => 'w', -padx => 0, -pady => 0);
}
##############################################################
# normalizeCoords - assign coordinates to allowed values (stepwidth)
##############################################################
sub normalizeCoords {
my $canvas = shift;
foreach my $coord qw(m_x1 m_x2 m_y1 m_y2) {
# assign it to the step width
$canvas->{$coord} = sprintf "%.0f", ($canvas->{$coord}/$canvas->{m_step});
$canvas->{$coord} *= $canvas->{m_step};
# check lower bound
$canvas->{$coord} = 0 if ($canvas->{$coord} < 0);
}
# check upper bound
foreach my $coord qw(m_x1 m_x2) {
$canvas->{$coord} = $canvas->{m_wo} if ($canvas->{$coord} > $canvas->{m_wo});
}
foreach my $coord qw(m_y1 m_y2) {
$canvas->{$coord} = $canvas->{m_ho} if ($canvas->{$coord} > $canvas->{m_ho});
}
}
##############################################################
# drawFrame
##############################################################
sub drawFrame {
my $canvas = shift;
my @coords;
my $direction = 'h';
if (@_ == 4) { # canvas coordinates are given
@coords = @_;
$canvas->{m_x1} = int($coords[0] * $canvas->{m_xzoom});
$canvas->{m_y1} = int($coords[1] * $canvas->{m_yzoom});
$canvas->{m_x2} = int($coords[2] * $canvas->{m_xzoom});
$canvas->{m_y2} = int($coords[3] * $canvas->{m_yzoom});
normalizeCoords($canvas);
}
elsif (@_ == 0) { # use the real coordinates
normalizeCoords($canvas);
$coords[0] = int($canvas->{m_x1} / $canvas->{m_xzoom});
$coords[1] = int($canvas->{m_y1} / $canvas->{m_yzoom});
$coords[2] = int($canvas->{m_x2} / $canvas->{m_xzoom});
$coords[3] = int($canvas->{m_y2} / $canvas->{m_yzoom});
}
elsif (@_ == 1) { # optional direction h or w
$direction = shift;
normalizeCoords($canvas);
}
else {
warn "drawFrame:: error wrong number of args ".scalar @_."\n";
return;
}
my $w = $canvas->{m_x2} - $canvas->{m_x1};
my $h = $canvas->{m_y2} - $canvas->{m_y1};
($w, $h) = calcAspectSize($w, $h, $direction);
#($w, $h) = calcAspectSize($w, $h);
$canvas->{m_x2} = $canvas->{m_x1} + $w;
$canvas->{m_y2} = $canvas->{m_y1} + $h;
$canvas->{m_xyxy} = $canvas->{m_x1}.",".$canvas->{m_y1}." - ".$canvas->{m_x2}.",".$canvas->{m_y2};
$canvas->{m_w} = $w;
$canvas->{m_h} = $h;
$canvas->{m_aspect} = getAspectRatio($w, $h);
$coords[0] = int($canvas->{m_x1} / $canvas->{m_xzoom});
$coords[1] = int($canvas->{m_y1} / $canvas->{m_yzoom});
$coords[2] = int($canvas->{m_x2} / $canvas->{m_xzoom});
$coords[3] = int($canvas->{m_y2} / $canvas->{m_yzoom});
$canvas->delete('withtag', 'FRAME');
# draw a pseudo transparent box around the crop frame
$canvas->createRectangle( 1, 1, $coords[0], $canvas->height-1,
-tags => ['FRAME'],
-outline => undef,
-fill => 'black',
-stipple => 'transp',
);
$canvas->createRectangle( $coords[0], 1, $canvas->width-1, $coords[1],
-tags => ['FRAME'],
-outline => undef,
-fill => 'black',
-stipple => 'transp',
);
$canvas->createRectangle( $coords[2], $coords[1], $canvas->width-1, $canvas->height-1,
-tags => ['FRAME'],
-outline => undef,
-fill => 'black',
-stipple => 'transp',
);
$canvas->createRectangle( $coords[0], $coords[3], $coords[2], $canvas->height-1,
-tags => ['FRAME'],
-outline => undef,
-fill => 'black',
-stipple => 'transp',
);
$canvas->delete('withtag', 'RECT');
$canvas->createRectangle(@coords, -tags => ['RECT'], -outline => 'red');
#my $rect = $canvas->find('withtag', 'RECT');
#$canvas->coords( $rect => @coords );
$canvas->raise('RECT');
# black dashed line
# $canvas->createRectangle( @coords,
# -tags => ['RECT'],
# -outline => "black",
# -dash => [6,4,2,4],
# );
# white dashed line
# $canvas->createRectangle( @coords,
# -tags => ['RECT'],
# -outline => "white",
# -dash => [2,6,2,4],
# );
}
##############################################################
# cropPic - cut a rect out of the pic
# needs a geometry (e.g. 200x200+33+66)
# overwrites the given file!!!
# returns true if it worked
##############################################################
sub cropPic {
my $dpic = shift; return 0 if (!-f $dpic); # pic will be overwritten!!!
my $w = shift; # width
my $h = shift; # height
my $x = shift; # x offset
my $y = shift; # y offset
my $qua = shift; # quality
my ($pw, $ph) = getSize($dpic);
#return 1 if (($pw <= $w) and ($ph <= $h));
# if the requested size is bigger than the pic we adapt to the real pic size
$w = $pw if ($w > $pw);
$h = $ph if ($h > $ph);
my $geo = "${w}x${h}+${x}+${y}";
my $command = "";
# try to use lossless cropping for JPEGs if available
if (is_a_JPEG($dpic) and checkExternProgs("crop", "jpegtran")) {
# check if jpegtran supports lossless cropping
my $usage = `jpegtran -? 2>&1`;
if ($usage =~ m/.*-crop.*/) {
$command = "jpegtran -copy all -crop $geo -outfile \"$dpic\" \"$dpic\"";
print "$dpic: cropping lossless using jpegtran\n" if $verbose;
}
}
# the fallback solution
if ($command eq "") {
$command = "mogrify -crop $geo -quality $qua \"$dpic\"";
print "$dpic: cropping with loss using mogrify\n" if $verbose;
}
if ((system $command) != 0) {
warn "$command failed: $!";
return 0;
}
else {
return 1;
}
}
##############################################################
# mycopy
##############################################################
sub mycopy {
my $from = shift;
my $to = shift;
my $overwrite = shift; # OVERWRITE = overwrite without asking ASK_OVERWRITE = ask before overwrite
if (!-f $from) {
$top->messageBox(-icon => 'warning', -message => "file $from not found!",
-title => "Copy file", -type => 'OK');
return 0;
}
return 1 if ($from eq $to); # no need to copy a file on itself
# if target exists and ask overwrite modus on
if ((-f $to) and ($overwrite == ASK_OVERWRITE)) {
my $rc =
$top->messageBox(-icon => 'warning', -message => "file $to exist. Ok to overwrite?",
-title => "Copy file", -type => 'OKCancel');
return 0 if ($rc !~ m/Ok/i);
}
if (!copy ("$from", "$to")) {
$top->messageBox(-icon => 'warning', -message => "Could not copy $from to $to: $!",
-title => "Copy file", -type => 'OK');
return 0;
}
return 1;
}
##############################################################
# mylink
##############################################################
sub mylink {
my $old = shift;
my $new = shift;
my $overwrite = shift; # 1 = overwrite without asking 0 = ask before overwrite
return 0 if $EvilOS; # sorry, no links on non-UNIX system, use Linux instead ;)
if (!-f $old) {
$top->messageBox(-icon => 'warning', -message => "file $old not found!",
-title => "Link file", -type => 'OK');
return 0;
}
if ((-f $new) and !$overwrite) {
my $rc =
$top->messageBox(-icon => 'warning', -message => "file $new exist. Ok to overwrite?",
-title => "Link file", -type => 'OKCancel');
return 0 if ($rc !~ m/Ok/i);
}
if (!symlink ("$old", "$new")) {
$top->messageBox(-icon => 'warning', -message => "Could not link $old to $new: $!",
-title => "Link file", -type => 'OK');
return 0;
}
return 1;
}
##############################################################
# checkLinks - check if there are links, count them and ask
# whether to proceed
##############################################################
sub checkLinks {
my $lb = shift; # listbox ref
my @list = @_;
my $selected = @list;
return 1 unless ($config{CheckForLinks});
if (@list < 1) {
warn "checkLinks: uops, list is empty. Aborting!";
return 0;
}
my $dpic;
my $links = 0;
foreach $dpic (@list) {
if (-l $dpic) {
$links++;
}
}
if ($links > 0) {
my $rc = $top->messageBox(-message => "$links of $selected selected pictures are links.\nDo you really want to change them?",
-icon => 'question', -title => "Work on linked files?", -type => 'OKCancel');
if ($rc eq "Ok") {
return 1;
}
else {
return 0;
}
}
return 1; # no links, Ok to continue ...
}
##############################################################
# getBitPix - calculate picture compression in bit per pixel
##############################################################
sub getBitPix {
my $dpic = shift;
return $quickSortHashBitsPixel{$dpic} if ($quickSortSwitch and defined $quickSortHashBitsPixel{$dpic});
my $b = getFileSize($dpic, NO_FORMAT); # in Bytes
$b *= 8; # Bytes * 8 = bits
my $p = getPixels($dpic);
# avoid division by zero
if ($p == 0) {
$p = 1;
$b = 0;
}
$quickSortHashBitsPixel{$dpic} = ($b/$p) if $quickSortSwitch;
return ($b/$p);
}
##############################################################
# getPixels - get the number of pixels of a picture
##############################################################
sub getPixels {
my $dpic = shift;
return $quickSortHashPixel{$dpic} if ($quickSortSwitch and defined $quickSortHashPixel{$dpic});
my $x = $searchDB{$dpic}{PIXX};
my $y = $searchDB{$dpic}{PIXY};
$quickSortHashPixel{$dpic} = int($x*$y) if $quickSortSwitch;
return int($x*$y);
}
##############################################################
# getSize - get the image size of a picture
##############################################################
sub getSize {
my $dpic = shift;
my $meta = shift; # optional, the Image::MetaData::JPEG object of $dpic if available
if ((!defined $dpic) or ($dpic eq "")) {
warn "getSize: Sorry, but there is no file!";
return (0, 0);
}
if (!-f $dpic) {
warn "Sorry, but \"$dpic\" is no file!";
return (0, 0);
}
my $w = 0;
my $h = 0;
if (is_a_JPEG($dpic)) {
$meta = getMetaData($dpic, "SOF", 'FASTREADONLY') unless (defined($meta));
($w, $h) = $meta->get_dimensions() if $meta;
}
else {
my $info = image_info($dpic);
if (my $error = $info->{error}) {
warn "getSize: Can't parse image info: $error\n";
}
($w, $h) = dim($info);
}
$w = 0 unless (defined $w);
$h = 0 unless (defined $h);
return ($w, $h);
}
##############################################################
# getSuffix - return the file suffix or undef
##############################################################
sub getSuffix {
my $file = shift;
if ($file =~ m/(.*)\.(.*)$/) {
return $2;
}
return undef;
}
##############################################################
# is_a_JPEG - returns true (1) if the given file is a JPEG/JFIF
##############################################################
sub is_a_JPEG($) {
my $dpic = shift;
return 0 unless ($dpic);
return 0 unless (-f $dpic);
my @c;
# open file and read the first 3 bytes
return 0 unless (open FILE,"<$dpic");
for my $i (0 .. 2) {
read(FILE, $c[$i], 1);
}
close FILE;
# JPEG JFIF files start with 0xFF 0xD8 0xFF
# todo: this check is necessary but not sufficent
if ( (ord($c[0]) == 0xFF) && (ord($c[1]) == 0xD8) && (ord($c[2]) == 0xFF) ) {
return 1;
}
else {
return 0;
}
}
##############################################################
# makeConfigDir
##############################################################
sub makeConfigDir {
if (!-d $configdir) {
# ask the user for permission to create a configdir
my $rc = $top->messageBox(-icon => 'question',
-message => "MaPiVi would like to create a directory \"$configdir\" in your home directory to store the configuration of Mapivi and some button and background pictures.",
-title => "Mapivi installation", -type => 'OKCancel');
return if ($rc !~ m/Ok/i);
}
# make config dir
if (!-d $maprogsdir) {
if ( !mkdir $maprogsdir, 0700 ) { # 0700 = only for the user
$top->messageBox(-icon => 'warning', -message => "Error making $maprogsdir: $!",
-title => "Mapivi installation", -type => 'OK');
return;
}
}
if (!-d $configdir) {
if ( !mkdir $configdir, 0700 ) {
$top->messageBox(-icon => 'warning', -message => "Error making configdir $configdir: $!",
-title => "Mapivi installation", -type => 'OK');
return;
}
}
if (!-d $trashdir) {
if ( !mkdir $trashdir, 0755 ) {
$top->messageBox(-icon => 'warning', -message => "Error making trashdir $trashdir: $!",
-title => "Mapivi installation", -type => 'OK');
return;
}
}
if (!-d "$trashdir/$thumbdirname") {
if ( !mkdir "$trashdir/$thumbdirname", 0755 ) {
$top->messageBox(-icon => 'warning', -message => "Error making trashthumbdir $trashdir/$thumbdirname: $!",
-title => "Mapivi installation", -type => 'OK');
return;
}
}
if (!-d $plugindir) {
if ( !mkdir "$plugindir", 0755 ) {
$top->messageBox(-icon => 'warning', -message => "Error making PlugIn dir $plugindir: $!",
-title => "Mapivi installation", -type => 'OK');
return;
}
}
}
##############################################################
# copyConfigPics
##############################################################
sub copyConfigPics {
return if (!-d $configdir);
# try to find the pictures in the actual dir and in the dir where mapivi is located
my $searchdir = dirname($0)."/pics";
my @pics;
my @searchDirList = ("$actdir/pics", dirname($0)."/pics");
foreach $searchdir (@searchDirList) {
print "searching $searchdir ...\n" if $verbose;
next if (!-d $searchdir);
@pics = getFiles($searchdir); # mapivi should be startet as mapivi or mapivi .
# so $actdir points to the dir where mapivi is stored
last if (@pics > 0);
}
if (@pics <= 0) {
my $rc = $top->messageBox(-icon => 'warning', -message => "Error could not find any pictures! Please stop mapivi, change to the directory where mapivi is installed and restart mapivi",
-title => "Mapivi installation", -type => 'OKCancel');
#todo $config{NrOfRuns}-- if ($rc =~ m/Ok/i);
return;
}
# copy the pictures to the config dir
foreach (@pics) {
if (-f "$configdir/$_") {
my $rc = $top->Dialog(-text => "I found a button/icon picture \"$_\" in the mapivi config directory (seem like there was another mapivi version installed before). Ok to overwrite?",
-title => "Mapivi installation",
-width => 40,
-buttons => ['OK', 'Cancel', "Cancel all"])->Show();
next if ($rc eq 'Cancel');
last if ($rc eq "Cancel all");
}
mycopy ("$searchdir/$_", "$configdir/$_", OVERWRITE);
}
}
##############################################################
# copyOtherStuff - this will copy some mapivi files to
# the config dir (all optional)
##############################################################
sub copyOtherStuff {
return if (!-d $configdir);
my @files = qw/Changes.txt License.txt Tips.txt FAQ/;
my $dir = dirname($0);
# copy the files to the config dir
foreach (@files) {
if (-f "$dir/$_") {
mycopy ("$dir/$_", "$configdir/$_", OVERWRITE);
}
}
}
##############################################################
# copyPlugIns
##############################################################
sub copyPlugIns {
return if (!-d $plugindir);
# try to find the PlugIns in the actual dir and in the dir where mapivi is located
my $searchdir = dirname($0)."/PlugIns";
my @plugs;
my @searchDirList = ("$actdir/PlugIns", dirname($0)."/PlugIns");
foreach $searchdir (@searchDirList) {
print "searching $searchdir ...\n" if $verbose;
next if (!-d $searchdir);
@plugs = getFiles($searchdir); # mapivi should be startet as mapivi or mapivi .
# so $actdir points to the dir where mapivi is stored
last if (@plugs > 0);
}
if (@plugs <= 0) {
my $rc = $top->messageBox(-icon => 'warning', -message => "Error could not find any PlugIns! Please stop mapivi, change to the directory where mapivi is installed and restart mapivi",
-title => "Mapivi installation", -type => 'OKCancel');
# todo $config{NrOfRuns}-- if ($rc =~ m/Ok/i);
return;
}
# copy the PlugIns to the plugin dir
foreach (@plugs) {
if (-f "$plugindir/$_") {
my $rc = $top->messageBox(-icon => 'question', -message => "I found a PlugIn\n $_\nin the mapivi PlugIn directory (seem like there was another mapivi version installed before).\n\nOk to overwrite?",
-title => "Mapivi installation", -type => 'OKCancel');
next if ($rc !~ m/Ok/i);
}
if (!copy ("$searchdir/$_", "$plugindir/$_")) {
$top->messageBox(-icon => 'warning', -message => "Could not copy $_ to $plugindir: $!",
-title => "Mapivi installation", -type => 'OK');
}
}
}
##############################################################
# checkGeometry
##############################################################
sub checkGeometry($) {
my $geoRef = shift;
my ($w, $h, $x, $y) = splitGeometry($$geoRef);
my $screenx = $top->screenwidth;
my $screeny = $top->screenheight;
my $tw = $top->reqwidth;
my $th = $top->reqheight;
print "checkGeometry: geo = $w ($tw) x $h ($th) + $x + $y ($screenx x $screeny)\n" if $verbose;
if ((($w + $x) > $screenx) or (($h + $y) > $screeny)) {
warn "MaPiVi: window is out of screen, resizing!\n";
$screenx -= 20;
$screeny -= 80;
$$geoRef = "${screenx}x${screeny}+0+0";
}
else { warn "geo ok" if $verbose; }
}
##############################################################
# splitGeometry - returns width, height, x, y of the geomtry
##############################################################
sub splitGeometry {
my $geo = shift;
my @tmp = split /x/, $geo;
my $w = $tmp[0];
@tmp = split /\+/, $tmp[1];
return ($w, $tmp[0], $tmp[1], $tmp[2]);
}
##############################################################
# checkAdjusterGeometry
##############################################################
sub checkAdjusterGeometry {
my $geoRef = shift;
my $adj1Ref = shift;
my $adj2Ref = shift;
my $letterWidth = $top->fontMeasure($nrofL->cget(-font), "0");
if ($letterWidth < 8) {warn "letterWidth $letterWidth < 8!!!\n"; $letterWidth = 8; }
my $x1 = $$adj1Ref * $letterWidth;
my $x2 = $$adj2Ref * $letterWidth;
my $wx;
($wx, undef, undef, undef) = splitGeometry($$geoRef);
print "$x1 + $x2 letter: $letterWidth windowW: $wx?\n" if $verbose;
if (($x1 + $x2 + 120) > $wx) { # add x for scrollbars and safety
warn "Adjuster need to much place, changing back to minimum!";
$$adj1Ref = 10;
$$adj2Ref = 10;
}
else { warn "Adjuster ok" if $verbose; }
}
##############################################################
# checkSystem
##############################################################
sub checkSystem {
# UNIX and Windows have different PATH separators und suffixes
my $sep = ":";
$sep = ";" if $EvilOS;
my $suffix = "";
$suffix = ".exe" if $EvilOS;
# check if the external programs listet in the global hash %exprogs are available
my @path = split /$sep/, $ENV{PATH};
my ($dir, $prog);
foreach $dir (@path) {
foreach $prog (keys %exprogs) {
next if ($exprogs{$prog} > 0); # already found it somewhere else
if (-x "$dir/$prog$suffix") {
$exprogs{$prog}++;
#print " $prog in $dir found!\n";
}
}
}
}
##############################################################
# checkExternProgs - checks if the external programs needed
# for a certain function exist
##############################################################
sub checkExternProgs {
my $sub = shift; # name of the calling sub
my @neededProgs = @_; # list of needed external programs
my @missingProgs = missingProgs($sub, @neededProgs);
if (@missingProgs > 0) {
my $msg = "";
$msg .= explainMissingProg($sub, $_) foreach (@missingProgs);
$top->messageBox(-icon => 'warning',
-message => $msg,
-title => "Extern program(s) not available",
-type => 'OK');
return 0; # if just one prog is missing we better abort
}
return 1; # everything seems to be there
}
##############################################################
# missingProgs - given a list of required external programs,
# return a list of those that are missing
##############################################################
sub missingProgs {
my $sub = shift; # name of the calling sub
my @neededProgs = @_; # list of needed external programs
my @missingProgs;
if (@neededProgs <= 0) {
warn "missingProgs called from sub $sub with no progs to check!";
} else {
foreach (@neededProgs) {
if (!defined $exprogs{$_}) {
warn "missingProgs called from sub $sub with program $_, which is not in the exprogs hash!";
push @missingProgs, $_;
} elsif ($exprogs{$_} < 1) {
push @missingProgs, $_;
}
}
}
return @missingProgs
}
##############################################################
# explainMissingProg - returns info about a missing program
##############################################################
sub explainMissingProg {
my $sub = shift;
my $missingProg = shift;
my $com = "";
my $res = "";
if (defined $exprogscom{$missingProg}) {
$com = "$missingProg is needed to ".$exprogscom{$missingProg}."\n";
}
if (defined $exprogsres{$missingProg}) {
$res = "$missingProg resource: ".$exprogsres{$missingProg}."\n";
}
return "Sorry, but to run $sub you need the external program $missingProg. I could not find $missingProg in your PATH.\n${com}${res}Aborting.";
}
##############################################################
# hlistEntryRename - rename the entrypath of an hlist entry
##############################################################
sub hlistEntryRename($$$) {
my ($hlist, $old, $new ) = @_;
return 0 unless ($hlist->info('exists', $old));
return 0 if ($hlist->info('exists', $new));
hlistCopy($hlist, $old, $new);
$hlist->delete('entry', $old) if ($hlist->info('exists', $new));
return 1;
}
##############################################################
# hlistCopy - copy an item of a hlist to another position
##############################################################
sub hlistCopy {
my($hl, $from_entry, $to_entry) = @_;
if ($hl->info('exists', $to_entry)) {
return;
}
my @entry_args;
foreach ($hl->entryconfigure($from_entry)) {
push @entry_args, $_->[0] => $_->[4] if defined $_->[4];
}
my $next = $hl->info('next', $from_entry);
if ($next) {$hl->add($to_entry, @entry_args, -before => $next);}
else {$hl->add($to_entry, @entry_args);}
foreach my $col (1 .. $hl->cget(-columns)-1) {
my @item_args;
foreach ($hl->itemConfigure($from_entry, $col)) {
push @item_args, $_->[0] => $_->[4] if defined $_->[4];
}
$hl->itemCreate($to_entry, $col, @item_args);
}
}
##############################################################
# startStopClock - starts and stops the clock, display
# and remove the clock label
##############################################################
sub startStopClock {
if ($config{ShowClock}) {
$clocktimer = $top->repeat(5000, \&showTime) if !$clocktimer; # 5000ms = 5 seconds
$clockL->pack(-side => "left");
showTime();
}
else {
$clocktimer->cancel if $clocktimer;
$time = "";
$clockL->packForget() if (Exists($clockL));
}
}
##############################################################
# getDateTime - returns the actual local time as a string
##############################################################
sub getDateTime {
my (undef,$m,$h,$d,$M,$y,undef,undef,undef,undef) = localtime(time());
$y += 1900;
$M++;
my $datetime = sprintf "%04d%02d%02d-%02d%02d", $y, $M, $d, $h, $m;
return $datetime;
}
##############################################################
# showTime - calculate actual time and display it
##############################################################
sub showTime {
return unless (Exists($clockL));
my (undef,$m,$h,$d,$M,$y,$wd,undef, undef,undef) = localtime(time());
my @workday = qw/Sun Mon Tue Wed Thu Fri Sat/;
$y += 1900;
$M++;
$time = sprintf "%02d:%02d", $h, $m;
$date = sprintf "%3s, %02d.%02d.%04d", $workday[$wd], $d, $M, $y;
$clockL->update;
}
my $htmlW; # global make-html window widget
my $htmlInfo;
##############################################################
# makeHTML - build HTML web pages from the selected pictures
##############################################################
sub makeHTML {
if (Exists($htmlW)) {
$htmlW->deiconify;
$htmlW->raise;
return;
}
my $lb = shift;
my @sellist = $lb->info('selection');
return unless checkSelection($lb, 1, 0, \@sellist);
my $selected = @sellist;
my ($pic);
# open make html window
$htmlW = $lb->Toplevel();
$htmlW->title("Build web pages");
$htmlW->iconimage($mapiviicon) if $mapiviicon;
$htmlInfo = "Build HTML web pages of $selected selected pictures";
$htmlW->Label(-textvariable =>\$htmlInfo,-bg => $config{ColorBG}
)->pack(-side => 'top',-fill => 'x',-padx => 3,-pady => 3);
my $w = 30;
my $l1 = labeledEntry($htmlW, 'top', $w, "Title of Gallery", \$config{HTMLGalleryTitle});
my $l2 = labeledEntry($htmlW, 'top', $w, "Link to gallery index page", \$config{HTMLGalleryIndex});
my $l3 = labeledEntry($htmlW, 'top', $w, "Link to homepage", \$config{HTMLHomepage});
my $l4 = labeledEntry($htmlW, 'top', $w, "HTML footer", \$config{HTMLFooter});
my $l5 = labeledEntryButton($htmlW,'top',$w,"HTML target directory",'Set',\$config{HTMLTargetDir},1);
my $l6 = labeledEntryButton($htmlW,'top',$w,"HTML template file",'Set', \$config{HTMLTemplate});
$balloon->attach($l1, -msg => "The content of this entry will be\ninserted in the <!-- mapivi-galtitle --> field.");
$balloon->attach($l2, -msg => "The content of this entry will be\ninserted in the <!-- mapivi-gallery-index --> field.");
$balloon->attach($l3, -msg => "The content of this entry will be\ninserted in the <!-- mapivi-home --> field.");
$balloon->attach($l4, -msg => "The content of this entry will be\ninserted in the <!-- mapivi-footer --> field.\nIt may contain a link to your homepage\nand your email address.");
$balloon->attach($l5, -msg => "Mapivi will save the generated\npages and pictures in this directory.");
$balloon->attach($l6, -msg => "This is the used HTML template.\nThere are some example templates\nin the Mapivi package.");
#labeledEntry($htmlW, 'top', $w, "Background of picture", \$config{HTMLBGcolor});
my $picF;
$htmlW->Checkbutton(-variable => \$config{HTMLnoPicChange},
-anchor => 'w',
-text => "Leave pictures untouched (just copy them)",
-command => sub {
my $state = 'normal';
$state = "disabled" if ($config{HTMLnoPicChange});
setChildState($picF, $state);
})->pack(-anchor => 'w');
$picF = $htmlW->Frame(-bd => $config{Borderwidth}, -relief => 'groove')->pack(-fill => 'x', -padx => 3, -pady => 3);
$picF->Label(-text =>"HTML pictures",-bg => $config{ColorBG}, -anchor => 'w'
)->pack(-side => 'top',-fill => 'x',-padx => 3,-pady => 3);
#my $picF2 = $picF->Frame ()->pack(-expand => 1, -fill => 'x', -padx => 0, -pady => 0);
my $sS = labeledScale($picF, 'top', $w, "Size (pixel)", \$config{HTMLPicSize}, 100, 2000, 1);
$balloon->attach($sS, -msg => "This is the length of the longest side.\nWith a value of 500 a 1000x800 picture will be resized to 500x400.");
my $qS = labeledScale($picF, 'top', $w, "Quality (%)", \$config{HTMLPicQuality}, 10, 100, 1);
qualityBalloon($qS);
my $shS = labeledScale($picF, 'top', $w, "Sharpness (radius)", \$config{HTMLPicSharpen}, 0, 10, 0.1);
$balloon->attach($shS, -msg => "The higher the value, the slower the conversion\n0 means no sharping.\n(suggestion: between 0 and 4)");
my $cof = $picF->Frame()->pack(-anchor => 'w');
$cof->Checkbutton(-variable => \$config{HTMLPicCopyright},
-anchor => 'w',
-text => "Add some decorations (border, copyright)")->pack(-side => "left", -anchor => 'w');
$cof->Button(-text => "Options",
-anchor => 'w',
-command => sub {decorationDialog($selected,0);})->pack(-side => "left", -anchor => 'w');
$picF->Checkbutton(-variable => \$config{HTMLPicEXIF},
-anchor => 'w',
-text => "Leave EXIF info in HTML pictures")->pack(-anchor => 'w');
labeledScale($htmlW, 'top', $w, "Number of thumbnail columns", \$config{HTMLcols}, 1, 10, 1);
$htmlW->Checkbutton(-variable => \$config{HTMLaddComment},
-anchor => 'w',
-text => "Show JPEG comments")->pack(-anchor => 'w');
$htmlW->Checkbutton(-variable => \$config{HTMLaddEXIF},
-anchor => 'w',
-text => "Show EXIF infos")->pack(-anchor => 'w');
$htmlW->Checkbutton(-variable => \$config{HTMLaddIPTC},
-anchor => 'w',
-text => "Show IPTC infos")->pack(-anchor => 'w');
my $ButF =
$htmlW->Frame()->pack(-fill =>'x',-padx => 3,-pady => 3);
my $OKB =
$ButF->Button(-text => "Make HTML",
-command => sub {
return if ( !checkHTMLSettings() );
return if ( !makeHTMLSubdirs($config{HTMLTargetDir}) );
$lb->update;
#my @pics ;
#foreach (@sellist){
#push @pics, basename($_);
#}
# because the building of web galleries should also work
# within the search dialog we can't throw away the path here
cleanHTMLDirs($config{HTMLTargetDir}, @sellist);
return if ( !makeHTMLPics (\%config, @sellist) );
$lb->update;
return if ( !copyHTMLThumbs($config{HTMLTargetDir}, @sellist) );
my $table = makeHTMLIndex (\%config, @sellist);
makeHTMLPages ($table, \%config, @sellist);
$htmlInfo = "make web pages - Ready!"; $htmlW->update;
$htmlW->messageBox(-icon => 'info',
-message => "Finished building web pages and pictures!",
-title => "make HTML", -type => 'OK');
# bring the make html dialog window in front
$htmlW->deiconify;
$htmlW->raise;
}
)->pack(-side => 'left',-expand => 1,-fill => 'x',-padx => 3,-pady => 3);
$ButF->Button(-text => "Close",
-command => sub {
$htmlW->withdraw();
$htmlW->destroy();
}
)->pack(-side => 'left',-expand => 1,-fill => 'x',-padx => 3,-pady => 3);
$htmlW->bind('<Key-Escape>', sub { $htmlW->destroy; } );
my $state = 'normal';
$state = "disabled" if ($config{HTMLnoPicChange});
setChildState($picF, $state);
$OKB->focus;
$htmlW->Popup;
$htmlW->waitWindow;
}
##############################################################
# checkHTMLSettings
##############################################################
sub checkHTMLSettings {
my $targetDir = $config{HTMLTargetDir};
print "checkHTMLSettings: $targetDir\n" if $verbose;
if (!-d $targetDir) {
my $rc = $htmlW->messageBox(-icon => 'question', -message => "$targetDir does not exists!\nShould I create it?!",
-title => "check HTML settings", -type => 'OKCancel');
if ($rc !~ m/Ok/i) {
return 0;
}
if ( !mkdir "$targetDir", 0755 ) {
$htmlW->messageBox(-icon => 'warning', -message => "can not create $targetDir: $!",
-title => 'Error', -type => 'OK');
return 0;
}
}
return 1;
}
##############################################################
# copyHTMLThumbs
##############################################################
sub copyHTMLThumbs {
my $targetDir = shift;
my @pics = @_;
my ($sthumb, $tthumb);
# copy the pictures to the config dir
foreach my $dpic (@pics) {
my $pic = basename($dpic);
$sthumb = getThumbFileName($dpic);
$tthumb = "$targetDir/$HTMLThumbDir/$pic";
if (!-f $sthumb) {
$htmlW->messageBox(-icon => 'warning', -message => "$sthumb not found! Stopping!",
-title => "copy thumbs", -type => 'OK');
return 0;
}
if (!aNewerThanb($sthumb,$tthumb)) {
print "skip thumb $pic (it is up to date)\n" if $verbose;
next;
}
else {
print "copy thumb $pic\n" if $verbose;
}
$htmlInfo = "copy thumb $pic for HTML page ..."; $htmlW->update;
mycopy("$sthumb", "$tthumb", OVERWRITE);
}
return 1;
}
##############################################################
# makeHTMLSubdirs
##############################################################
sub makeHTMLSubdirs {
my $tdir = shift;
# make pic and thumb dir
foreach my $dir ($HTMLPicDir, $HTMLThumbDir) {
my $sdir = "$tdir/$dir";
if (!-d $sdir) {
if ( !mkdir "$sdir", 0755 ) {
$htmlW->messageBox(-icon => 'warning', -message => "makeThumbSubdirs: can not create $sdir: $!",
-title => 'Error', -type => 'OK');
return 0;
}
}
}
return 1;
}
##############################################################
# makeHTMLPics
##############################################################
sub makeHTMLPics {
my $tmpconfR = shift;
my @pics = @_;
my ($pic, $dpic, $tpic, $command);
my $targetDir = $tmpconfR->{'HTMLTargetDir'};
my $i = 0;
my $nrpics = @pics;
foreach $dpic (@pics) {
$i++;
$pic = basename($dpic);
$tpic = "$targetDir/$HTMLPicDir/$pic";
if (!-f $dpic) {
warn "makeHTMLPics: $dpic does not exist!";
return 0;
}
if (!aNewerThanb($dpic,$tpic)) {
warn "makeHTMLPics: $tpic is up to date - skipping\n" if $verbose;
next;
}
else {
warn "makeHTMLPics: converting $pic\n" if $verbose;
}
# just copy the pics ...
if ($tmpconfR->{'HTMLnoPicChange'}) {
$htmlInfo = "copy $pic ($i/$nrpics) for HTML page ..."; $htmlW->update;
mycopy("$dpic", "$tpic", OVERWRITE);
}
# ... or convert them
else {
# adding -size XxY speeds up the convertion! (Dan Eble)
$command = " convert -size \"$tmpconfR->{'HTMLPicSize'}x$tmpconfR->{'HTMLPicSize'}\" -geometry \"$tmpconfR->{'HTMLPicSize'}x$tmpconfR->{'HTMLPicSize'}>\" -quality $tmpconfR->{'HTMLPicQuality'} ";
if ($tmpconfR->{HTMLPicSharpen} > 0) { # ! Sharpen is the most time consuming option, when building thumbnails!
$command .= "-sharpen $tmpconfR->{'HTMLPicSharpen'} " # the higher the value the slower the conversion
}
if ($tmpconfR->{HTMLPicCopyright} > 0) {
$command .= makeDrawOptions($dpic);
}
$command .= " \"$dpic\" \"$tpic\" ";
$htmlInfo = "converting $pic ($i/$nrpics) for HTML page ..."; $htmlW->update;
#(system "$command") == 0 or warn "$command failed: $!";
execute($command);
addDropShadow($tpic);
if ($tmpconfR->{HTMLPicEXIF}) {
# copy the EXIF header from the original pic to the html pic
copyEXIF( $dpic, $tpic );
}
else {
# remove the EXIF header and thumb from the HTML pic
my $errors = "";
removeEXIF($tpic, 'all', \$errors);
}
}
}
return 1;
}
##############################################################
# makeHTMLIndex
##############################################################
sub makeHTMLIndex {
my $tmpconfR = shift;
my @pics = @_;
my $targetDir = $tmpconfR->{'HTMLTargetDir'};
my ($pic, $dpic, $opic, $picNoSuffix, $lthumb, $htmlfile, $title, $size, $table, $tx, $ty);
$table = "<table class=\"darkbox\">\n";
my $i = 0;
$htmlInfo = "building HTML thumbnail index ..."; $htmlW->update;
foreach $opic (@pics) {
$i++;
$pic = basename($opic);
if ( $i % $tmpconfR->{HTMLcols} == 1 or $tmpconfR->{HTMLcols} == 1 ) { # start new table row (modulo)
$table .= "<tr>\n";
}
#$lpic = "$HTMLPicDir/$pic";
$dpic = "$targetDir/$HTMLPicDir/$pic";
$lthumb = "$HTMLThumbDir/$pic";
$size = getFileSize($dpic, FORMAT);
($tx, $ty)= getSize("$targetDir/$lthumb");
$picNoSuffix = $pic;
# cut off trailing ".jpg"
$picNoSuffix =~ s/\..*$//i; # this is the name of the picture without .jpg suffix
$title = getIPTCObjectName($opic);
$title = "$picNoSuffix" if ($title eq "");
$title .= " ($size)";
# replace (german) umlaute by corresponding HTML-tags
$title =~ s/([$umlauteHTML])/$umlauteHTML{$1}/g;
$htmlfile = ($i == 1) ? "index.html" : "$picNoSuffix.html";
$table .= "<td>\n";
$table .= "<a href=\"$htmlfile\">\n";
$table .= " <img src=\"$lthumb\" alt=\"$pic\" title=\"$title\" width=\"$tx\" height=\"$ty\" vspace=\"1\" border=\"0\" />\n";
$table .= "</a>\n";
$table .= "</td>\n";
if ( $i % $tmpconfR->{HTMLcols} == 0 ) { # end table row (modulo)
$table .= "</tr>\n";
}
}
$table .= "</table>\n";
return $table;
}
##############################################################
# createReplacementHashForPic
##############################################################
sub createReplacementHashForPic {
my $tmpconfR = shift;
my $opic = shift;
my $pic = basename($opic);
my $targetDir = $tmpconfR->{'HTMLTargetDir'};
my $dpic = "$targetDir/$HTMLPicDir/$pic";
my $tpic = "$targetDir/$HTMLThumbDir/$pic";
my $picNoSuffix = $pic;
$picNoSuffix =~ s/\..*$//i;
my $size = getFileSize($dpic, FORMAT);
my ($w, $h) = getSize($dpic);
my ($thumbw, $thumbh)= getSize($tpic);
my $title = getIPTCObjectName($opic);
$title = $picNoSuffix if ($title eq "");
my $IPTCheadline = getIPTCHeadline($opic);
my $headline = $IPTCheadline;
$headline = $title if ($headline eq "");
my $com = "";
if ($tmpconfR->{'HTMLaddComment'}) {
# only the first comment is copied by jhead, so we use the comment(s) of the original picture
$com = getComment($opic, 3); # allows big comments (up to 1000 chars)
$com =~ s/\n/<br>/g; # replace newline with the corresponding html tag
}
my $IPTCcaption = getIPTCCaption($opic);
$IPTCcaption =~ s/\n/<br>/g; # replace newline with the corresponding html tag
# caption comes from either the IPTC caption or the JPEG comment
my $caption = $IPTCcaption;
$caption = $com if ($caption eq "");
my $byline = getIPTCByLine($opic);
my $bylinetitle = getIPTCByLineTitle($opic);
$bylinetitle .= ": " if ($bylinetitle ne "");
$byline = $bylinetitle.$byline if ($byline ne "");
my $location = getIPTCSublocation($opic);
my $city = ""; $city = getIPTCCity($opic);
if ($city ne "") {
$location .= ", " if ($location ne "");
$location .= $city;
}
my $province = ""; $province = getIPTCProvince($opic);
my $country = ""; $country = getIPTCAttr($opic, "Country/PrimaryLocationName");#getIPTCCountryCode($opic);
if ($country ne "") {
$province .= ", " if ($province ne "");
$province .= $country;
}
if ($province ne "") {
if ($location ne "") {
$location .= " ($province)";
} else {
$location = $province;
}
}
my $exif = "";
$exif = getShortEXIF($opic, NO_WRAP) if ($tmpconfR->{'HTMLaddEXIF'});
$exif =~ s/\[t\]//g; # remove thumbnail indicator [t]
$exif =~ s/\[s\]//g; # remove saved exif indicator [s]
my $iptc = "";
$iptc = getShortIPTC($opic, LONG) if ($tmpconfR->{'HTMLaddIPTC'});
# Escape special HTML characters, except in file names
# and in purely numeric values (e.g. width). (by Dan Eble)
foreach ($pic, $byline, $caption, $com, $exif, $size, $headline, $iptc,
$IPTCcaption, $IPTCheadline, $location, $time, $title) {
$_ =~ s/([$htmlChars])/$htmlChars{$1}/g;
}
my %replace;
$replace{'<!-- mapivi-alt -->'} = $pic;
$replace{'<!-- mapivi-byline -->'} = $byline;
$replace{'<!-- mapivi-caption -->'} = $caption;
$replace{'<!-- mapivi-comment -->'} = $com;
$replace{'<!-- mapivi-exif -->'} = $exif;
$replace{'<!-- mapivi-file-no-suffix -->'}= $picNoSuffix;
$replace{'<!-- mapivi-filesize-kB -->'} = $size;
$replace{'<!-- mapivi-headline -->'} = $headline;
$replace{'<!-- mapivi-height -->'} = $h;
$replace{'<!-- mapivi-iptc -->'} = $iptc;
$replace{'<!-- mapivi-iptc-caption -->'} = $IPTCcaption;
$replace{'<!-- mapivi-iptc-headline -->'} = $IPTCheadline;
$replace{'<!-- mapivi-location -->'} = $location;
$replace{'<!-- mapivi-pic -->'} = "$HTMLPicDir/$pic";
$replace{'<!-- mapivi-thumb-height -->'} = $thumbh;
$replace{'<!-- mapivi-thumb-pic -->'} = "$HTMLThumbDir/$pic";
$replace{'<!-- mapivi-thumb-width -->'} = $thumbw;
$replace{'<!-- mapivi-time -->'} = $time;
$replace{'<!-- mapivi-title -->'} = $title;
$replace{'<!-- mapivi-width -->'} = $w;
return %replace;
}
##############################################################
# makeHTMLPages
##############################################################
sub makeHTMLPages {
my $table = shift;
my $tmpconfR = shift;
my @pics = @_;
my $targetDir = $tmpconfR->{'HTMLTargetDir'};
my ($pic, $htmlpage, $page, $next, $prev, $galtitle, %bigrep, $maxwidth, $maxheight);
my $sum = @pics;
$maxwidth = 0;
$maxheight = 0;
$galtitle = $tmpconfR->{HTMLGalleryTitle};
$galtitle =~ s/ / /g; # replace space by html tag non-breakable space
my $index = 0;
foreach my $dpic (@pics) {
$pic = basename($dpic);
$htmlInfo = "extracting data from $pic ..."; $htmlW->update;
my %replace = createReplacementHashForPic($tmpconfR, $dpic);
if ($replace{'<!-- mapivi-height -->'} > $maxheight) {
$maxheight = $replace{'<!-- mapivi-height -->'};
}
if ($replace{'<!-- mapivi-width -->'} > $maxwidth) {
$maxwidth = $replace{'<!-- mapivi-width -->'};
}
# Next and previous pages wrap around from end to beginning.
my $previndex = ($index - 1) % $sum;
my $nextindex = ($index + 1) % $sum;
# File names for previous, current, and next page.
# The first is "index.html" to simplify the URL of the album.
$prev = $previndex ? basename($pics[$previndex]) : "index.html";
$htmlpage = $index ? basename($pics[$index]) : "index.html";
$next = $nextindex ? basename($pics[$nextindex]) : "index.html";
# change extensions to ".html"
foreach ($prev, $htmlpage, $next) {
$_ =~ s/\..*$/\.html/i;
}
$replace{'<!-- mapivi-pic-index -->'} = $index+1;
$replace{'<!-- mapivi-next -->'} = $next;
$replace{'<!-- mapivi-this -->'} = $htmlpage;
$replace{'<!-- mapivi-prev -->'} = $prev;
$bigrep{$pic} = \%replace;
$index++;
}
my ($s,$m,$ho,$d,$mo,$y) = localtime(time());
$y += 1900; $mo++; # do some adjustments
# build up the date time string
my $date = sprintf "%02d.%02d.%04d", $d, $mo, $y;
my $time = sprintf "%02d:%02d", $ho, $m;
my $datetime = sprintf "%02d.%02d.%04d %02d:%02d", $d, $mo, $y, $ho, $m;
my %globalReplace;
$globalReplace{'<!-- mapivi-date -->'} = $date;
$globalReplace{'<!-- mapivi-datetime -->'} = $datetime;
$globalReplace{'<!-- mapivi-footer -->'} = $tmpconfR->{HTMLFooter};
$globalReplace{'<!-- mapivi-gallery-index -->'}= $tmpconfR->{HTMLGalleryIndex};
$globalReplace{'<!-- mapivi-galtitle -->'} = $galtitle;
$globalReplace{'<!-- mapivi-home -->'} = $tmpconfR->{HTMLHomepage};
$globalReplace{'<!-- mapivi-info -->'} = $mapiviInfo;
$globalReplace{'<!-- mapivi-max-height -->'} = $maxheight;
$globalReplace{'<!-- mapivi-max-index -->'} = $sum;
$globalReplace{'<!-- mapivi-max-width -->'} = $maxwidth;
$globalReplace{'<!-- mapivi-thumbtable -->'} = $table;
foreach my $dpic (@pics) {
$pic = basename($dpic);
$htmlpage = $bigrep{$pic}{'<!-- mapivi-this -->'};
print "xxx pic=$pic html=$htmlpage ($dpic)\n";
$htmlInfo = "building page $htmlpage ..."; $htmlW->update;
$page = openTemplate($tmpconfR->{HTMLTemplate});
# do global substitutions first so that they will not have
# to be replaced for each expansion of <mapivi:foreachpic>
$page = doSubstitutions($page, \%globalReplace);
my $re;
my @left = ('(','');
my @right = (')','');
$_ = $page;
# find the text inside of <mapivi:foreachpic> sections
($re=$_)=~s/((<mapivi:foreachpic>)|(<\/mapivi:foreachpic>)|.)/$right[!$3]\Q$1\E$left[!$2]/gs;
my @inside = (eval{/$re/},$@!~/unmatched/i);
# find the text outside of <mapivi:foreachpic> sections
($re=$_)=~s/((<mapivi:foreachpic>)|(<\/mapivi:foreachpic>)|.)/$right[!$2]\Q$1\E$left[!$3]/gs;
$re = "(" . $re . ")";
my @outside = (eval{/$re/},$@!~/unmatched/i);
# if the <mapivi:foreachpic> sections were parsed without error,
# process the templates inside the tags
if ($inside[-1] && $outside[-1] && ($#inside+1 == $#outside)) {
$page = "";
for (0..$#inside-1)
{
$page .= $outside[$_] . substituteForEachPic($tmpconfR, $inside[$_], \%bigrep, @pics);
}
$page .= $outside[-2];
}
$page = doSubstitutions($page, $bigrep{$pic});
writePage("$targetDir/$htmlpage", $page);
$top->update;
}
}
##############################################################
# doSubstitutions
# Input: the pageContent string (from template), followed by hash of
# substitutions to make
##############################################################
sub doSubstitutions {
my ($pageContent, $replaceR )= @_;
my($tag, $replacement);
while (($tag, $replacement) = each(%$replaceR)) {
warn "doSubstitutions: tag not defined" unless defined $tag;
warn "doSubstitutions: $tag replacement not defined" unless defined $replacement;
$pageContent =~ s/$tag/$replacement/g;
}
# replace (german) umlaute by corresponding html-tags
$pageContent =~ s/([$umlauteHTML])/$umlauteHTML{$1}/g;
return $pageContent;
}
##############################################################
# substituteForEachPic
##############################################################
sub substituteForEachPic {
my $tmpconfR = shift;
my $template = shift;
my $bigrepR = shift;
my @pics = @_;
my $result = "";
my $pic;
foreach my $dpic (@pics) {
$pic = basename($dpic);
$result .= doSubstitutions($template, $$bigrepR{$pic});
}
return $result;
}
##############################################################
# openTemplate - open, read and return template
##############################################################
sub openTemplate {
my $template = shift;
my $file;
if (!open ($file, $template)) {
die ("cannot open template $template for reading: ($!)");
}
my $pageContent = (join '', <$file>);
close ($file) || bail ("can't close template: ($!)");
return $pageContent;
}
##############################################################
# writePage - input path of page to render, not including $root
##############################################################
sub writePage {
# Spits out a page of HTML.
my($file, $pageContent) = @_;
my $outfile;
open ($outfile, ">$file") or die "Couldn't open $file: $!";
print $outfile $pageContent;
close($outfile);
}
##############################################################
# cleanHTMLDirs - delete all files which are not needed anymore
##############################################################
sub cleanHTMLDirs {
my $targetDir = shift;
my @dpics = @_;
my @picsAct;
my @toDelete;
my $rc;
my $pictures;
# clean html files
my @htmlfiles = grep {m/.*\.html$/i} getFiles($targetDir);
if (@htmlfiles >= 1) {
$rc = $htmlW->messageBox(-icon => 'question',
-message => scalar @htmlfiles." HTML pages should be deleted in $targetDir.\nOk, to delete?",
-title => "clean up HTML directories",
-type => 'OKCancel');
if ($rc eq "Ok") {
foreach (@htmlfiles) {
removeFile("$targetDir/$_");
}
}
}
# clean pictures and thumbs
foreach my $dir ("$targetDir/$HTMLPicDir", "$targetDir/$HTMLThumbDir") {
@picsAct = getPics($dir, JUST_FILE); # no sort needed
my @pics;
# now we need the pics list without path
push @pics, basename($_) foreach (@dpics);
@toDelete = diffList(\@picsAct, \@pics);
next if (@toDelete < 1);
# choose the right word depending on the dir
$pictures = "pictures";
$pictures = "thumbnails" if ($dir =~ m/$HTMLThumbDir$/);
$rc = $htmlW->messageBox(-icon => 'question',
-message => scalar @toDelete." $pictures should be deleted in\n$dir\nOk, to delete?",
-title => "clean up HTML directories",
-type => 'OKCancel');
if ($rc !~ m/Ok/i) {
next;
}
foreach (@toDelete) {
removeFile ("$dir/$_");
}
}
}
##############################################################
# compareLists
##############################################################
sub compareLists {
my ($first, $second) = @_;
no warnings; # silence spurious -w undef complaints
return 0 unless @$first == @$second;
for ( 0 .. $#{@$first}) {
return 0 if $first->[$_] ne $second->[$_];
}
return 1;
}
##############################################################
# diffList - returns a list containing all elements of list1
# which are not in list2
##############################################################
sub diffList {
my $list1Ref = shift; # reference to first list
my $list2Ref = shift; # reference to second list
my %d;
# build a hash
foreach (@{$list1Ref}) {
$d{$_} = 1;
}
# delete all elements, which are in list2
foreach (@{$list2Ref}) {
delete $d{$_};
}
return (keys %d);
}
##############################################################
# listIntersection - returns a list containing all elements
# of list1 which are also in list2
##############################################################
sub listIntersection {
my $list1Ref = shift; # reference to first list
my $list2Ref = shift; # reference to second list
my (@intersection, %count, $element);
foreach $element (@{$list1Ref}, @{$list2Ref}) { $count{$element}++ }
foreach $element (keys %count) {
push @intersection, $element if ($count{$element} > 1);
}
return @intersection;
}
##############################################################
# dirDiffWindow
##############################################################
sub dirDiffWindow {
if (Exists($ddw)) {
$ddw->deiconify;
$ddw->raise;
$ddw->focus;
return;
}
# open window
$ddw = $top->Toplevel();
$ddw->withdraw;
$ddw->title("Compare two directories");
$ddw->iconimage($mapiviicon) if $mapiviicon;
my $f1 = $ddw->Frame(-relief => 'groove')->pack(-fill => 'x', -padx => 3, -pady => 3);
my $f1a = $f1->Frame()->pack(-side => "left", -fill => 'x', -expand => 1, -padx => 0, -pady => 0);
my $f1b = $f1->Frame()->pack(-side => "left", -fill => "y", -padx => 0, -pady => 0);
my $f2 = $ddw->Frame()->pack(-fill => 'x', -padx => 2, -pady => 3);
my $f2a = $f2->Frame(-relief => 'groove')->pack(-side => "left", -fill => "y", -expand => 0, -padx => 1, -pady => 0);
my $f2b = $f2->Frame(-relief => 'groove')->pack(-side => "left", -fill => "both", -expand => 1, -padx => 1, -pady => 0);
#my $f3 = $ddw->Frame()->pack(-fill => 'x', -padx => 3, -pady => 3);
my $ddlb;
$ddw->Label(-textvariable => \$ddw->{label}, -anchor => 'w', -bg => $config{ColorBG})->pack(-padx => 3, -anchor => 'w');
$ddw->{label} = 'Choose directories to compare and press the "Compare" button.';
labeledEntryButton($f1a,'top',12,"directory A",'Set',\$config{dirDiffDirA},1);
labeledEntryButton($f1a,'top',12,"directory B",'Set',\$config{dirDiffDirB},1);
$ddlb = $ddw->Scrolled("HList",
-header => 1,
-separator => ';', # todo here we hope that ; will never be in a directory or file name
-pady => 0,
-columns => 12,
-scrollbars => 'osoe',
-selectmode => "extended",
-background => $config{ColorBG}, #8fa8bf
-width => 40,
-height => 20,
)->pack(-expand => 1, -fill => "both");
bindMouseWheel($ddlb);
$balloon->attach($ddlb, -msg => "left click : select\nmiddle click: open picture in new window\nright click : open context menu");
my $col = 0;
$ddlb->header('create', $col, -text => 'Differences', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
$ddlb->{diffcol} = $col; $col++;
$ddlb->header('create', $col, -text => 'Name', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
$ddlb->{namecol} = $col; $col++;
$ddlb->header('create', $col, -text => 'Thumbnail A', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
$ddlb->{thumbAcol} = $col; $col++;
$ddlb->header('create', $col, -text => 'Thumbnail B', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
$ddlb->{thumbBcol} = $col; $col++;
$ddlb->header('create', $col, -text => 'Size A', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
$ddlb->{sizeAcol} = $col; $col++;
$ddlb->header('create', $col, -text => 'Size B', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
$ddlb->{sizeBcol} = $col; $col++;
$ddlb->header('create', $col, -text => 'IPTC A', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
$ddlb->{iptcAcol} = $col; $col++;
$ddlb->header('create', $col, -text => 'IPTC B', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
$ddlb->{iptcBcol} = $col; $col++;
$ddlb->header('create', $col, -text => 'EXIF A', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
$ddlb->{exifAcol} = $col; $col++;
$ddlb->header('create', $col, -text => 'EXIF B', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
$ddlb->{exifBcol} = $col; $col++;
$ddlb->header('create', $col, -text => 'Comments A', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
$ddlb->{comAcol} = $col; $col++;
$ddlb->header('create', $col, -text => 'Comments B', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
$ddlb->{comBcol} = $col; $col++;
my $progress = 0;
$f1b->Button(-text => "Compare",
-command => sub {
# check both dirs first
foreach ($config{dirDiffDirA}, $config{dirDiffDirB}) {
unless (-d $_) {
$ddw->messageBox(-icon => 'warning', -message => "Directory \"$_\" is not valid!",
-title => 'Error', -type => 'OK');
return;
}
}
if ($config{dirDiffDirA} eq $config{dirDiffDirB}) {
$ddw->messageBox(-icon => 'warning', -message => "Please choose two different directories!",
-title => 'Error', -type => 'OK');
return;
}
$ddw->Busy;
$ddlb->delete("all"); # clear listbox
my (@onlyInDirA, @onlyInDirB, @intersec);
dirDiff($config{dirDiffDirA}, $config{dirDiffDirB}, \@onlyInDirA, \@onlyInDirB, \@intersec);
$ddw->{label} = "found ".scalar @onlyInDirA." unique pictures in dir A, ".scalar @onlyInDirB." unique pictures in dir B and ".scalar @intersec." matching pictures";
$ddw->update;
my $pics = @onlyInDirA + @onlyInDirB + @intersec;
my $pic;
my $last_time;
my $i = 0;
foreach $pic (sort @onlyInDirA) {
my $dpic = $config{dirDiffDirA}."/$pic";
ddInsertPic($ddlb, $dpic, "", "only in dir A");
$i++;
# show progress and found pics every 0.5 seconds - idea from Slaven
if (!defined $last_time || Tk::timeofday()-$last_time > 0.5) {
$progress = int($i/$pics*100); $ddw->update;
$last_time = Tk::timeofday();
}
}
foreach $pic (sort @onlyInDirB) {
my $dpic = $config{dirDiffDirB}."/$pic";
ddInsertPic($ddlb, "", $dpic, "only in dir B");
$i++;
# show progress and found pics every 0.5 seconds - idea from Slaven
if (!defined $last_time || Tk::timeofday()-$last_time > 0.5) {
$progress = int($i/$pics*100); $ddw->update;
$last_time = Tk::timeofday();
}
}
my $inter = 0;
foreach $pic (sort @intersec) {
my $dpicA = $config{dirDiffDirA}."/$pic";
my $dpicB = $config{dirDiffDirB}."/$pic";
my $differences = "";
if (compareTwoPics($dpicA, $dpicB, \$differences)) {
ddInsertPic($ddlb, $dpicA, $dpicB, $differences);
$inter++;
}
$i++;
# show progress and found pics every 0.5 seconds - idea from Slaven
if (!defined $last_time || Tk::timeofday()-$last_time > 0.5) {
$progress = int($i/$pics*100); $ddw->update;
$last_time = Tk::timeofday();
}
}
$progress = 100;
$ddw->{label} = "found ".scalar @onlyInDirA." unique pictures in dir A, ".scalar @onlyInDirB." unique pictures in dir B and ".scalar @intersec." matching pictures ($inter of them differ).";
$ddw->Unbusy;
})->pack(-fill => "y", -side => "left");
$f1b->Button(-text => "Close",
-command => sub {
$ddw->destroy;
})->pack(-fill => "y", -side => "left");
$f2a->Label(-text => "compare by ", -anchor => 'w', -bg => $config{ColorBG})->pack(-side => "left", -padx => 3);
$f2a->Checkbutton(-variable => \$config{dirDiffSize}, -text => "files size")->pack(-side => "left");
$f2a->Checkbutton(-variable => \$config{dirDiffPixel}, -text => "pixel size")->pack(-side => "left");
$f2a->Checkbutton(-variable => \$config{dirDiffComment}, -text => "comment")->pack(-side => "left");
$f2a->Checkbutton(-variable => \$config{dirDiffEXIF}, -text => "EXIF")->pack(-side => "left");
$f2a->Checkbutton(-variable => \$config{dirDiffIPTC}, -text => "IPTC")->pack(-side => "left");
$f2b->Button(-text => "Copy A->B",
-command => sub {
return unless ($ddlb->info('children'));
my @sellist = $ddlb->info('selection');
return unless (@sellist);
my $i = 0; my $rc = 1; my $n = 0;
foreach (@sellist) {
my $pic = $ddlb->itemCget($_, $ddlb->{namecol}, -text);
$i++;
$ddw->{label} = "copy ($i/".scalar @sellist.") ... "; $ddw->update;
my $dpic = $config{dirDiffDirA}."/$pic";
next unless (-f $dpic);
my $tpic = $config{dirDiffDirB}."/$pic";
# if the pic exists, ask if the user wants to overwrite it
$rc = overwritePic($tpic, $dpic, (scalar(@sellist) - $i + 1)) if ($rc != 2);
next if ($rc == 0);
last if ($rc == -1);
if (mycopy ($dpic, $tpic, OVERWRITE)) { # copy pic
$n++;
my $thumbpic = getThumbFileName($dpic);
my $thumbtpic = getThumbFileName($tpic);
if ((-d dirname($thumbtpic)) and (-f $thumbpic)) {
mycopy ($thumbpic,$thumbtpic, OVERWRITE) # copy thumbnail
}
$ddlb->delete("entry", $_); # remove entry from list box
}
} # foreach - end
$ddw->{label} = "ready! ($n/".scalar @sellist." copied)"; $ddw->update;
})->pack(-fill => 'x', -side => "left", -padx => 2, -pady => 2);
$f2b->Button(-text => "Copy A<-B",
-command => sub {
return unless ($ddlb->info('children'));
my @sellist = $ddlb->info('selection');
return unless (@sellist);
my $i = 0; my $rc = 1; my $n = 0;
foreach (@sellist) {
my $pic = $ddlb->itemCget($_, $ddlb->{namecol}, -text);
$i++;
$ddw->{label} = "copy ($i/".scalar @sellist.") ... "; $ddw->update;
my $dpic = $config{dirDiffDirB}."/$pic";
next unless (-f $dpic);
my $tpic = $config{dirDiffDirA}."/$pic";
# if the pic exists, ask if the user wants to overwrite it
$rc = overwritePic($tpic, $dpic, (scalar(@sellist) - $i + 1)) if ($rc != 2);
next if ($rc == 0);
last if ($rc == -1);
if (mycopy ($dpic, $tpic, OVERWRITE)) { # copy pic
$n++;
my $thumbpic = getThumbFileName($dpic);
my $thumbtpic = getThumbFileName($tpic);
if ((-d dirname($thumbtpic)) and (-f $thumbpic)) {
mycopy ($thumbpic, $thumbtpic, OVERWRITE) # copy thumbnail
}
$ddlb->delete("entry", $_); # remove entry from list box
}
} # foreach - end
$ddw->{label} = "ready! ($n/".scalar @sellist." copied)"; $ddw->update;
})->pack(-fill => 'x', -side => "left", -padx => 2, -pady => 2);
$f2b->Button(-text => "Delete A",
-command => sub {
return unless ($ddlb->info('children'));
my @sellist = $ddlb->info('selection');
return unless (@sellist);
my $rc = $ddw->messageBox(-message => "Really delete ".scalar @sellist." pictures in directory ".$config{dirDiffDirA}."?",
-icon => 'question', -title => "Really delete?", -type => 'OKCancel');
return unless ($rc =~ m/Ok/i);
my $i = 0; my $n = 0;
foreach (@sellist) {
my $pic = $ddlb->itemCget($_, $ddlb->{namecol}, -text);
$i++;
$ddw->{label} = "deleting ($i/".scalar @sellist.") ... "; $ddw->update;
my $dpic = $config{dirDiffDirA}."/$pic";
unless (-f $dpic) { print "$dpic not found!\n"; next;}
if (move ($dpic, $trashdir)) { # move pic to trash
$n++;
my $tpic = "$trashdir/$pic";
# change the location info in the search database
$searchDB{$tpic} = $searchDB{$dpic};
delete $searchDB{$dpic};
deleteCachedPics($dpic);
# todo move thumbnail?
# todo deleting the entry is wrong, if picture exists in both dirs
$ddlb->delete("entry", $_); # remove entry from list box
}
} # foreach - end
$ddw->{label} = "ready! ($n/".scalar @sellist." deleted)"; $ddw->update;
})->pack(-fill => 'x', -side => "left", -padx => 2, -pady => 2);
$f2b->Button(-text => "Delete B",
-command => sub {
return unless ($ddlb->info('children'));
my @sellist = $ddlb->info('selection');
return unless (@sellist);
my $rc = $ddw->messageBox(-message => "Really delete ".scalar @sellist." pictures in directory ".$config{dirDiffDirB}."?",
-icon => 'question', -title => "Really delete?", -type => 'OKCancel');
return unless ($rc =~ m/Ok/i);
my $i = 0; my $n = 0;
foreach (@sellist) {
my $pic = $ddlb->itemCget($_, $ddlb->{namecol}, -text);
$i++;
$ddw->{label} = "deleting ($i/".scalar @sellist.") ... "; $ddw->update;
my $dpic = $config{dirDiffDirB}."/$pic";
unless (-f $dpic) { print "$dpic not found!\n"; next;}
if (move ($dpic, $trashdir)) { # move pic to trash
$n++;
my $tpic = "$trashdir/$pic";
# change the location info in the search database
$searchDB{$tpic} = $searchDB{$dpic};
delete $searchDB{$dpic};
deleteCachedPics($dpic);
# todo move thumbnail?
# todo deleting the entry is wrong, if picture exists in both dirs
$ddlb->delete("entry", $_); # remove entry from list box
}
} # foreach - end
$ddw->{label} = "ready! ($n/".scalar @sellist." deleted)"; $ddw->update;
})->pack(-fill => 'x', -side => "left", -padx => 2, -pady => 2);
$f2b->Label(-text => "progress: ", -anchor => 'w', -bg => $config{ColorBG})->pack(-side => "left", -padx => 3);
my $progBar =
$f2b->ProgressBar(-takefocus => 0,
-borderwidth => 1,
-relief => 'sunken',
-length => 100,
-height => 5,
-padx => 0,
-pady => 0,
-variable => \$progress,
-colors => [0 => $config{ColorProgress}],
-resolution => 1,
-blocks => 10,
-anchor => 'w',
-from => 0,
-to => 100,
)->pack(-side => 'left', -expand => 1, -fill => "both", -padx => 3, -pady => 3);
my $ws = 0.7;
my $w = int($ws * $ddw->screenwidth);
my $h = int($ws * $ddw->screenheight);
my $x = int(((1 - $ws) * $ddw->screenwidth)/3);
my $y = int(((1 - $ws) * $ddw->screenheight)/3);
#print "geo==${w}x${h}+${x}+${y}\n";
$ddw->geometry("${w}x${h}+${x}+${y}");
$ddw->Popup;
$ddw->waitWindow;
}
##############################################################
# compareTwoPics
##############################################################
sub compareTwoPics {
my $dpicA = shift;
my $dpicB = shift;
my $diff = shift; # Ref to differences
my $rc = 0; # 0 = no difference 1 = pics are different
if ($config{dirDiffSize} and (-s $dpicA != -s $dpicB)) {
my $diff_bytes = getFileSize($dpicB, NO_FORMAT) - getFileSize($dpicA, NO_FORMAT);
my $sign = '-';
$sign = '+' if ($diff_bytes > 0);
if (abs($diff_bytes) > 1024) {
$diff_bytes = computeUnit(abs($diff_bytes));
} else {
$diff_bytes = abs($diff_bytes).'B';
}
$$diff .= "file size ($sign$diff_bytes)\n";
$rc = 1;
}
if ($config{dirDiffComment} and (getComment($dpicA, LONG) ne getComment($dpicB, LONG))) {
$$diff .= "comment\n";
$rc = 1;
}
if ($config{dirDiffEXIF} and (getShortEXIF($dpicA, NO_WRAP) ne getShortEXIF($dpicB, NO_WRAP))) {
$$diff .= "EXIF\n";
$rc = 1;
}
if ($config{dirDiffIPTC} and (getIPTC($dpicA, SHORT) ne getIPTC($dpicB, SHORT))) {
$$diff .= "IPTC\n";
$rc = 1;
}
if ($config{dirDiffPixel}) {
my ($wa, $ha) = getSize($dpicA);
my ($wb, $hb) = getSize($dpicB);
if (($wa != $wb) or ($ha != $hb)) {
$$diff .= "pixel size\n";
$rc = 1;
}
}
return $rc;
}
##############################################################
# ddInsertPic - insert a row in the dir diff list
##############################################################
sub ddInsertPic {
my $lb = shift;
my $dpicA = shift; # the dir A pic, empty string if non
my $dpicB = shift; # the dir B pic, empty string if non
my $reason = shift; # the difference
if ((!-f $dpicA) and (!-f $dpicB)) { warn "both pics are missing!"; return; }
my @childs = $lb->info('children');
my $count = 0;
$count = @childs if (@childs);
# create new row
$lb->add($count);
my (%ddthumbs, $sizeA, $sizeB, $comA, $comB, $exifA, $exifB, $iptcA, $iptcB);
if (-f $dpicA) {
$comA = getComment($dpicA, SHORT);
$exifA = getShortEXIF($dpicA, WRAP);
$iptcA = getShortIPTC($dpicA, SHORT);
$sizeA = getAllFileInfo($dpicA);
my $thumbA = getThumbFileName($dpicA);
if (-f $thumbA) {
$ddthumbs{$thumbA} = $lb->Photo(-file => $thumbA, -gamma => $config{Gamma});
if (defined $ddthumbs{$thumbA}) {
$lb->itemCreate($count, $lb->{thumbAcol}, -image => $ddthumbs{$thumbA}, -itemtype => "image");
}
}
}
if (-f $dpicB) {
$comB = getComment($dpicB, SHORT);
$exifB = getShortEXIF($dpicB, WRAP);
$iptcB = getShortIPTC($dpicB, SHORT);
$sizeB = getAllFileInfo($dpicB);
my $thumbB = getThumbFileName($dpicB);
if (-f $thumbB) {
$ddthumbs{$thumbB} = $lb->Photo(-file => $thumbB, -gamma => $config{Gamma});
if (defined $ddthumbs{$thumbB}) {
$lb->itemCreate($count, $lb->{thumbBcol}, -image => $ddthumbs{$thumbB}, -itemtype => "image");
}
}
}
my $pic;
if (-f $dpicA) { $pic = basename($dpicA); } else { $pic = basename($dpicB); }
$lb->itemCreate($count, $lb->{diffcol}, -text => $reason, -style => $comS);
$lb->itemCreate($count, $lb->{namecol}, -text => $pic, -style => $fileS);
$lb->itemCreate($count, $lb->{sizeAcol}, -text => $sizeA, -style => $comS);
$lb->itemCreate($count, $lb->{sizeBcol}, -text => $sizeB, -style => $exifS);
$lb->itemCreate($count, $lb->{comAcol}, -text => $comA, -style => $comS);
$lb->itemCreate($count, $lb->{comBcol}, -text => $comB, -style => $exifS);
$lb->itemCreate($count, $lb->{exifAcol}, -text => $exifA, -style => $comS);
$lb->itemCreate($count, $lb->{exifBcol}, -text => $exifB, -style => $exifS);
$lb->itemCreate($count, $lb->{iptcAcol}, -text => $iptcA, -style => $comS);
$lb->itemCreate($count, $lb->{iptcBcol}, -text => $iptcB, -style => $exifS);
}
##############################################################
# dirDiff
##############################################################
sub dirDiff {
my $dir1 = shift;
my $dir2 = shift;
my $only1 = shift; # ref to array
my $only2 = shift; # ref to array
my $inter = shift; # ref to array
return unless (-d $dir1);
return unless (-d $dir2);
my $tmp = $config{CheckForNonJPEGs}; # save the option to a temp variable
$config{CheckForNonJPEGs} = 0; # switch the option off
my @pics1 = getPics($dir1, JUST_FILE); # no sort needed
my @pics2 = getPics($dir2, JUST_FILE); # no sort needed
$config{CheckForNonJPEGs} = $tmp; # restore the option
@{$only1} = diffList(\@pics1, \@pics2);
@{$only2} = diffList(\@pics2, \@pics1);
@{$inter} = listIntersection(\@pics2, \@pics1);
}
##############################################################
# showkeys - show the key bindings
##############################################################
sub showkeys {
my $file;
# open the file mapivi
if (!open($file, "<$0")) {
warn "could not open $0 for read access!: $!";
return;
}
my @lines = <$file>; # read the complete file into the array lines
close $file;
my @keys;
foreach my $line (@lines) {
$line =~ s/\s+$//; # cut trailing whitespace
$line =~ s/^\s+//; # cut leading whitespace
# look for lines containing "key-desc"
if ($line =~ m/.*key-desc.*/) {
push @keys, $line;
}
}
my $text;
# sort the keys alphabetical
foreach (sort { uc($a) cmp uc($b); } @keys) {
my @a = split /,/, $_;
if (@a != 3) { print "showKeys: suspicious line: $_\n"; next; }
chomp($a[2]);
$text .= sprintf "%-13s ... %s\n",$a[1], $a[2];
}
my $title = "Keys shortcuts for mapivi $version";
showText($title, $text, NO_WAIT, $mapiviiconfile);
}
##############################################################
# buildDatabase - scans through all subdirectories of
# the actual dir an collects JPEG files
# let the user select in which dirs
# mapivi should build/refresh thumbnails
##############################################################
sub buildDatabase {
my $mydir = getRightDir();
my $rc = checkDialog( 'Add pictures to database in all sub directories',
'MaPiVi will create a list of all sub directories of directory "'.basename($mydir).'" containing JPEG files.
You are then able to select directories from the list.',
\$config{SearchDBOnlyNew},
"add only new pictures",
"",
'OK', 'Cancel');
return if ($rc ne 'OK');
my $tmp = $config{CheckForNonJPEGs}; # save the option to a temp variable
$config{CheckForNonJPEGs} = 0; # switch the option off
$userinfo = "searching sub directories ..."; $userInfoL->update;
my @dirlist;
my %nr_of_pics_in_dir;
my @pictestlist;
my $pic_count = 0;
my $pw = progressWinInit($top, "Collect sub directories");
my $i = 0;
my $break = 0;
find(sub {
if (progressWinCheck($pw)) { $break = 1; $File::Find::prune = 1; }
$i++; $i = 0 if ($i > 10);
progressWinUpdate($pw, "collecting directories, found ".scalar @dirlist." ...", $i, 10);
# search in dirs, but not in .thumbs/ .xvpics/ etc.
if (-d and ($_ ne $thumbdirname) and ($_ ne ".xvpics") and ($_ ne $exifdirname)) {
@pictestlist = getPics($File::Find::name, JUST_FILE); # no sorting needed
if (@pictestlist > 0) {
$pic_count += scalar @pictestlist;
$nr_of_pics_in_dir{$File::Find::name} = scalar @pictestlist;
push @dirlist, $File::Find::name;
$userinfo = "found ".scalar @dirlist." sub directories ..."; $userInfoL->update;
}
}
}, $mydir);
progressWinEnd($pw);
if ($break) {
$userinfo = "user break while counting directories";
return;
}
$config{CheckForNonJPEGs} = $tmp; # restore the option
$userinfo = "found ".@dirlist." sub directories with $pic_count JPEGs"; $userInfoL->update;
@dirlist = sort @dirlist;
my @sellist;
return if (!mySelListBoxDialog("Select directories",
"Found ".scalar @dirlist." directories with $pic_count JPEG pictures.\nThe database will be updated with the pictures of the selected directories.",
"add to database", \@sellist, @dirlist));
# copy the selected elements into the @sel_dirs list
my @sel_dirs;
$pic_count = 0;
foreach (@sellist) {
push @sel_dirs, $dirlist[$_];
$pic_count += $nr_of_pics_in_dir{$dirlist[$_]}
}
my ($dir, $dirshort, @dpics, $pic, $dpic, $com, $exif, $iptcL);
$tmp = $config{CheckForNonJPEGs}; # save the option to a temp variable
$config{CheckForNonJPEGs} = 0; # switch the option off
$pw = progressWinInit($top, "building search database");
$i = 0;
my $new = 0;
foreach $dir (@sel_dirs) {
last if progressWinCheck($pw);
$dirshort = cutString($dir, -40, "...");
print "build database recursive in $dir\n" if $verbose;
@dpics = getPics($dir, WITH_PATH); # no sorting needed
foreach (@dpics) {
last if progressWinCheck($pw);
$i++;
# todo $pic_count is not correct if not all directories have been selected
progressWinUpdate($pw, "adding picture ($i/$pic_count) in directory $dirshort", $i, $pic_count);
next if ($config{SearchDBOnlyNew} and exists $searchDB{$_});
addToSearchDB($_);
$new++;
}
}
progressWinEnd($pw);
$config{CheckForNonJPEGs} = $tmp; # restore the option
$userinfo = "database updated (scanned $i pictures, $new added)"; $userInfoL->update;
check_new_keywords();
}
##############################################################
# cleanDatabase - remove all database entries of non existing
# files
##############################################################
sub cleanDatabase {
my $count = 0;
my $pics;
my $ignoreText = "";
my $ignoreCount = 0;
my $keys = keys %searchDB;
my %ignorePaths = qw(
/mnt/cdrom/ 1
);
# try to get the saved ignore paths
if (-f "$configdir/ignorePaths") {
my $hashRef = retrieve("$configdir/ignorePaths");
warn "could not retrieve ignorePaths" unless defined $hashRef;
%ignorePaths = %{$hashRef};
}
my $rc = editHashDialog('Edit ignore paths',
'This function will remove all invalid and outdated entries from the search database.
When cleaning the database, all entries without an corresponding file will be removed.
It is possible to exclude entries from cleaning depending on their path.
This could be done e.g. for pictures on removable media like CDROMs or DVDs.
Please add or remove paths from this list according to your file system.
A typical entry for a linux system could be /mnt/cdrom',
\%ignorePaths,
'Clean database',
'Cancel',
1 );
return if ($rc ne 'OK');
store(\%ignorePaths, "$configdir/ignorePaths") or warn "could not store ignorePaths";
$userinfo = "cleaning database - please wait ..."; $userInfoL->update;
my $pw = progressWinInit($top, "cleaning search database");
my $i = 0;
# loop through all database entries
foreach my $pic (sort keys %searchDB) {
last if progressWinCheck($pw);
$i++;
progressWinUpdate($pw, "checking ($i/$keys) ...", $i, $keys);
# if the pic path matches a path of @ignorePaths we skip the entry
# this can be used to leave pictures in the database which are
# located on removable media like CDs
my $ignore = 0;
foreach my $ipath (keys %ignorePaths) {
if ($pic =~ m/^$ipath/) {
$ignore = 1;
$ignoreCount++;
$ignoreText .= "(ignoring $pic)\n";
last;
}
}
next if $ignore;
# delete the picture from the database if it does not exists
if (!-f $pic) {
delete $searchDB{$pic};
$pics .= "$pic\n";
$count++;
}
}
progressWinEnd($pw);
$userinfo = "cleaning database - ready"; $userInfoL->update;
my $text = "clean picture info database:\n\n";
if ($count > 0) {
$text .= "Removed $count entries of non existing pictures:\n\n$pics";
}
else {
$text .= "Nothing to clean - database is up to date!\n\n";
}
$keys = keys %searchDB;
my $size = getFileSize("$configdir/SearchDataBase", FORMAT);
$text .= "There are $keys entries in the database (file size: $size)\n\n";
$text .= "The following $ignoreCount entries have been ignored, because their path\nmatches a entry in the \%ignorePaths hash:\n\n$ignoreText" if ($ignoreText ne "");
showText("Clean database", $text, WAIT);
}
##############################################################
# cleanDatabaseFolder - clean the database in one directory
##############################################################
sub cleanDatabaseFolder {
my $directory = shift;
$userinfo = "updating database - please wait ..."; $userInfoL->update;
my $pw = progressWinInit($top, "updating search database");
my $i = 0;
my $keys = keys %searchDB;
# loop through all database entries
foreach my $pic (sort keys %searchDB) {
last if progressWinCheck($pw);
$i++;
progressWinUpdate($pw, "checking ($i/$keys) ...", $i, $keys);
# if the pic path matches the given path
# delete the picture from the database if it does not exists
if (($pic =~ m/^$directory/) and (!-f $pic)) {
#print "deleting pic $pic from DB\n";
delete $searchDB{$pic};
#$pics .= "$pic\n";
#$count++;
}
}
progressWinEnd($pw);
$userinfo = "database updated!"; $userInfoL->update;
}
##############################################################
# editEntryHistory
##############################################################
sub editEntryHistory {
my $buttext = "Remove";
my $text = "The left list shows all used entry fields, if you select one, the right listbox will show you all elements, that have been typed into this entry field. Select one or multiple element from the right listbox and press the $buttext button to delete them.";
my $rc;
# open window
my $ew = $top->Toplevel();
$ew->title("Edit entry history");
$ew->iconimage($mapiviicon) if $mapiviicon;
my $height = ($text =~ tr/\n//);
$height += 2;
$height = 10 if ($height > 10); # not to big, we have scrollbars
my $rotext = $ew->Scrolled("ROText",
-scrollbars => 'osoe',
-wrap => 'word',
-tabs => '4',
-width => 110,
-height => $height,
-relief => "flat",
-bg => $config{ColorBG},
-bd => "0"
)->pack(-expand => "0", -padx => 3, -pady => 3,-anchor => 'w');
$rotext->insert('end', $text);
my $size = getFileSize($file_Entry_values, FORMAT);
my $info = "File size of $file_Entry_values: $size";
my $lbf = $ew->Frame()->pack(-fill =>'x');
my $listBox =
$lbf->Scrolled('Listbox',
-scrollbars => 'osoe',
-selectmode => 'single',
-exportselection => 0,
-width => 30,
-height => 25,
)->pack(-side => 'left', -expand => 1, -fill =>'both', -padx => 3, -pady => 3);
bindMouseWheel($listBox);
my @ekeys = sort keys %entryHistory;
$listBox->insert('end', @ekeys);
my $lbfr = $lbf->Frame()->pack(-side => 'left', -expand => 1, -fill =>'both');
my $listBox2 =
$lbfr->Scrolled('Listbox',
-scrollbars => 'osoe',
-selectmode => 'extended',
-exportselection => 0,
#-width => 80,
-height => 25,
)->pack(-side => 'top', -expand => 1, -fill =>'both', -padx => 3, -pady => 3);
bindMouseWheel($listBox2);
$listBox->bind('<ButtonPress-1>', sub {
my @sel = $listBox->curselection();
my $key = $ekeys[$sel[0]];
my @list = @{$entryHistory{$key}};
$listBox2->delete(0, 'end');
$listBox2->insert('end', @list);
});
my $labF = $ew->Frame()->pack(-anchor => 'w', -padx => 3, -pady => 3);
$labF->Label(-textvariable => \$info, -bg => $config{ColorBG})->pack(-side => "left");
$lbfr->Button(-text => $buttext,
-command => sub {
my @sel = $listBox->curselection();
my $key = $ekeys[$sel[0]];
foreach (reverse $listBox2->curselection()) {
my $path = $listBox2->get($_);
#print "deleting key $key element $_ ".${$entryHistory{$key}}[$_]."\n";
splice @{$entryHistory{$key}}, $_, 1; # remove it from list
$listBox2->delete($_);
}
}
)->pack(-expand => 1, -fill =>'x', -anchor => 'w', -padx => 3, -pady => 3);
my $ButF = $ew->Frame()->pack(-fill =>'x');
my $OKB = $ButF->Button(-text => 'OK',
-command => sub { $rc = 'OK'; }
)->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$OKB->bind('<Return>', sub { $OKB->invoke; } );
$OKB->focus;
$ew->Popup(-popover => 'cursor');
repositionWindow($ew);
$ew->waitVariable(\$rc);
$ew->withdraw;
$ew->destroy;
}
##############################################################
# database_info - show infos and statistics about search database
##############################################################
sub database_info {
# first create a chronological statistic (number of pics for each month)
my %chrono_hash;
my $pic_count = 0;
my $error_count = 0;
my $i = 0;
my $keys = keys %searchDB;
my $pw = progressWinInit($top, "Calculating statistic (chronological distribution)");
foreach my $dpic (keys %searchDB) {
last if progressWinCheck($pw);
$i++;
progressWinUpdate($pw, "adding picture ($i/$keys) ...", $i, $keys);
if ($searchDB{$dpic}{TIME}) {
my ($s,$m,$h,$d,$mo,$y) = localtime $searchDB{$dpic}{TIME};
$y += 1900; $mo++; # do some adjustments
my $key = sprintf "%04d%02d", $y, $mo; # key = yyyymm
$chrono_hash{$key}++;
$pic_count++;
}
else {
$error_count++;
}
}
progressWinEnd($pw);
#print "found $error_count pictures without date info.\n" if ($error_count > 0);
#print "found $pic_count pictures with date info.\n";
# fill up empty months in hash with zero
my @chrono_list;
foreach (sort keys %chrono_hash) { push @chrono_list, $_; }
my $first_ymonth = $chrono_list[0];
my $last_ymonth = $chrono_list[-1];
my $first_month = substr($first_ymonth, 4 , 2);
my $last_month = substr($last_ymonth, 4 , 2);
my $first_year = substr($first_ymonth, 0 , 4);
my $last_year = substr($last_ymonth, 0 , 4);
for my $year ($first_year .. $last_year) {
for my $month (1 .. 12) {
next if (($year == $first_year) and ($month < $first_month));
last if (($year == $last_year) and ($month > $last_month));
my $yyyymm = sprintf "%04d%02d", $year, $month;
if ($chrono_hash{$yyyymm}) {
#print "$yyyymm is defined\n";
}
else {
#print "$yyyymm is not defined\n";
$chrono_hash{$yyyymm} = 0;
}
}
}
my $month_nr = keys %chrono_hash;
#print "found $month_nr differnt month; max. pics $max_pics_per_month in month $max_month. first: $first_ymonth ($first_year $first_month) last: $last_ymonth ($last_year $last_month)\n";
# open window
my $win = $top->Toplevel();
$win->title("Database Information - Timeline (Chronological Picture Distribution)");
$win->iconimage($mapiviicon) if $mapiviicon;
# canvas size
#my $h = int(0.3 * $win->screenheight);
#my $w = int(0.9 * $win->screenwidth);
my $w = 0; my $h = 0; my $h_scale_factor =1;
my $month_w = $w/$month_nr;
my $butF = $win->Frame()->pack(-expand => 0, -fill => 'y');
my $canvas = $win->Scrolled('Canvas',
-scrollbars => 'osoe',
#-width => $w,
#-height => $h+26,
-width => 10,
-height => 10,
-relief => 'sunken',
)->pack(-side => 'top', -expand => 1, -fill => 'both', -padx => 3, -pady => 3);
$canvas->configure(-scrollregion => [0, 0, 10, 10]);
$butF->Button(-text => ' -- ', -command => sub {
$w = $canvas->Subwidget("scrolled")->width - $ScW; # $ScW = scrollbar width
$month_w = $w/$month_nr if ($month_w < 1);
$month_w -= 5;
$month_w = 1 if ($month_w < 1);
database_info_update($canvas, \%chrono_hash, $month_w);
})->pack(-side => 'left', -padx => 3, -pady => 3);
$butF->Button(-text => ' - ', -command => sub {
$w = $canvas->Subwidget("scrolled")->width - $ScW; # $ScW = scrollbar width
$month_w = $w/$month_nr if ($month_w < 1);
$month_w--;
$month_w = 1 if ($month_w < 1);
database_info_update($canvas, \%chrono_hash, $month_w);
})->pack(-side => 'left', -padx => 3, -pady => 3);
$butF->Button(-text => ' + ', -command => sub {
$w = $canvas->Subwidget("scrolled")->width - $ScW; # $ScW = scrollbar width
$month_w = $w/$month_nr if ($month_w < 1);
$month_w++;
database_info_update($canvas, \%chrono_hash, $month_w);
})->pack(-side => 'left', -padx => 3, -pady => 3);
$butF->Button(-text => '++', -command => sub {
$w = $canvas->Subwidget("scrolled")->width - $ScW; # $ScW = scrollbar width
$month_w = $w/$month_nr if ($month_w < 1);
$month_w += 5;
database_info_update($canvas, \%chrono_hash, $month_w);
})->pack(-side => 'left', -padx => 3, -pady => 3);
$butF->Button(-text => 'minimum', -command => sub {
$month_w = 1;
database_info_update($canvas, \%chrono_hash, $month_w);
})->pack(-side => 'left', -padx => 3, -pady => 3);
$butF->Button(-text => 'medium', -command => sub {
$month_w = 16;
database_info_update($canvas, \%chrono_hash, $month_w);
})->pack(-side => 'left', -padx => 3, -pady => 3);
$butF->Button(-text => 'large', -command => sub {
$month_w = 36;
database_info_update($canvas, \%chrono_hash, $month_w);
})->pack(-side => 'left', -padx => 3, -pady => 3);
$butF->Button(-text => 'fit', -command => sub {
$win->update;
#$w = $canvas->Subwidget("scrolled")->width;
#$h = $canvas->Subwidget("scrolled")->height;
#$month_w = $w/$month_nr;
$month_w = 0;
database_info_update($canvas, \%chrono_hash, $month_w);
})->pack(-side => 'left', -padx => 3, -pady => 3);
$butF->Button(-text => 'Info', -command => sub {
my $text = "Chronological distribution of pictures per month in the search database.\nThis chart uses the picture EXIF date when available.\n$pic_count pictures with and $error_count pictures without date info in database.\nIf you click on a box the pictures of that month will be shown.\nSome information will appear, if mouse hovers above a box.";
showText("Information", $text, NO_WAIT);
})->pack(-side => 'left', -padx => 3, -pady => 3);
my $msg = '';
$balloon->attach($canvas,
-postcommand => sub {
my @curr = $canvas->find('withtag', 'current');
my @tags = $canvas->gettags($curr[0]);
my $yyyymm = '';
foreach (@tags) {
next if ($_ eq 'current');
$yyyymm = $_;
}
return if (length($yyyymm) != 6);
my $act_month = substr($yyyymm, 4 , 2);
my $act_year = substr($yyyymm, 0 , 4);
$msg = "$act_month/$act_year: $chrono_hash{$yyyymm} pictures";
},
-balloonposition => "mouse",
-msg => \$msg);
$canvas->CanvasBind( '<B1-ButtonRelease>' =>
sub {
my @curr = $canvas->find('withtag', 'current');
my @tags = $canvas->gettags($curr[0]);
my $yyyymm = '';
foreach (@tags) {
next if ($_ eq 'current');
$yyyymm = $_;
}
return if (length($yyyymm) != 6);
my $act_month = substr($yyyymm, 4 , 2);
my $act_year = substr($yyyymm, 0 , 4);
my $rc = $win->messageBox(-icon => 'question',
-title => "Show $chrono_hash{$yyyymm} pictures from $act_month/$act_year?",
-message => "Press OK to display $chrono_hash{$yyyymm} pictures from $act_month/$act_year.",
-type => 'OKCancel');
return if ($rc !~ m/Ok/i);
my @list;
my $start_time = buildUnixTime(sprintf "01.%02d.%04d", $act_month, $act_year);
my $next_month = $act_month + 1;
my $next_year= $act_year;
if ($next_month > 12) { $next_month = 1; $next_year++; }
my $end_time = buildUnixTime(sprintf "01.%02d.%04d", $next_month, $next_year) - 1;
#print "xxx-start: $start_time .. end: $end_time act:$act_month, $act_year next: $next_month, $next_year\n";
my $i = 0;
my $db_keys = keys %searchDB;
my $pw = progressWinInit($win, "Searching pictures database");
foreach my $dpic (keys %searchDB) {
last if progressWinCheck($pw);
$i++;
progressWinUpdate($pw, "searching ($i/$db_keys) ...", $i, $db_keys);
my $time = $searchDB{$dpic}{TIME};
next unless (defined $time);
next if ($time < $start_time);
next if ($time > $end_time);
push @list, $dpic;
}
progressWinEnd($pw);
sortPics('exifdate', 1, \@list);
showThumbList(\@list, "$act_month/$act_year");
});
$butF->Button(-text => "Close",
-command => sub { $win->destroy(); }
)->pack(-side => 'left',-expand => 0,-fill => 'x',-padx => 3,-pady => 3);
$win->bind('<Key-Escape>', sub { $win->destroy; } );
$win->Popup;
my $ww = int(0.8 * $top->screenwidth);
my $wh = int(0.3 * $top->screenheight);
$win->geometry("${ww}x${wh}+10+10");
$win->update;
database_info_update($canvas, \%chrono_hash, $month_w);
}
##############################################################
# database_info_update - draw diagram
##############################################################
sub database_info_update {
my $canvas = shift;
#my $w = shift;
#my $h = shift;
my $chrono_hash = shift;
#my $pic_count = shift;
#my $error_count = shift;
my $month_w = shift;
#my $month_nr = shift;
#my $h_scale_factor = shift;
my $month_nr = keys %{$chrono_hash};
my $w = $canvas->Subwidget("scrolled")->width - $ScW; # $ScW = scrollbar width
my $h = $canvas->Subwidget("scrolled")->height - $ScW;
# search the maximum number of pictures per month
my $max_pics_per_month = 0;
foreach (keys %{$chrono_hash}) {
if ($chrono_hash->{$_} > $max_pics_per_month) {
$max_pics_per_month = $chrono_hash->{$_};
}
}
my $axis_h = 30; # height for x axis and month and year numbers
my $h_scale_factor = $max_pics_per_month/($h - $axis_h);
$month_w = $w/$month_nr if ($month_w == 0);
$canvas->delete('all');
#$canvas->configure(-scrollregion => [0, 0, $month_nr*$month_w-10, $h+26]);
$canvas->configure(-scrollregion => [0, 0, $month_nr*$month_w, $h]);
my $x = 2; my $step = 0;
foreach my $yyyymm (sort keys %{$chrono_hash}) {
my $act_month = substr($yyyymm, 4 , 2);
my $act_year = substr($yyyymm, 0 , 4);
# draw a box for each month
my $id = $canvas->createRectangle( $x, $h-$axis_h, int($x+$month_w-1), $h-$axis_h-int($chrono_hash->{$yyyymm}/$h_scale_factor),
-fill => $config{ColorActBG},
-outline => $config{ColorSel},
-tags => $yyyymm,
-width => 1,
);
# mark month border
$canvas->createLine( $x, $h-$axis_h, $x, $h-int(0.5*$axis_h), -fill => $config{ColorFG});
# mark year border
if ($act_month eq '01') {
$canvas->createLine( $x, $h-$axis_h, $x, $h, -fill => $config{ColorFG});
}
# write month if more then 16 pixel available
if ($month_w >= 16) {
$canvas->createText($x+int($month_w/2), $h-$axis_h+6, -font => $small_font, -text => $act_month, -anchor => 'n', -justify => 'center', -fill => $config{ColorFG});
}
# write number of pics if enough space
if ($month_w > length($chrono_hash->{$yyyymm})*8) {
my $h = $h-$axis_h-int($chrono_hash->{$yyyymm}/$h_scale_factor);
$h = 14 if ($h < 14);
$canvas->createText($x+int($month_w/2), $h, -font => $small_font, -text => $chrono_hash->{$yyyymm}, -anchor => 's', -justify => 'center', -fill => $config{ColorFG});
}
# write year
if ($act_month eq '07') {
$canvas->createText($x, $h, -font => $small_font, -text => $act_year, -anchor => 's', -justify => 'center', -fill => $config{ColorFG});
}
$step++;
$x = int($month_w * $step);
}
# draw x axis
$canvas->createLine( 0, $h-$axis_h, $month_nr*$month_w, $h-$axis_h, -fill => $config{ColorFG});
}
##############################################################
# keyword_browse - browse picture collection by keywords (tagclouds)
##############################################################
sub keyword_browse {
# list of keywords to constraint the browsing/searching
my @search_keys;
# list of keywords to exclude from browsing/searching
my @exclude_keys;
# get stored values
if ($config{KeywordExclude}) {
@exclude_keys = split / /, $config{KeywordExclude};
}
# open window
my $win = $top->Toplevel();
$win->title('Keyword browser (tag cloud)');
$win->iconimage($mapiviicon) if $mapiviicon;
my $cc;
my $butF = $win->Frame()->pack(-fill =>'x', -padx => 3, -pady => 3);
my $butF2 = $win->Frame()->pack(-fill =>'x', -padx => 3, -pady => 3);
my $butF3 = $win->Frame(-relief => 'groove');
if ($config{KeywordMore}) {
$butF3->pack(-after => $butF2, -expand => 0, -fill => 'x', -padx => 4, -pady => 3);
}
else { $butF3->packForget(); }
my $add_mode = 1;
my $label = '';
my $hb = $butF->Button(-text => 'home',
-command => sub {
# reset search_keys
@search_keys = ();
$label = '';
show_keywords($win, \@search_keys, \@exclude_keys);
})->pack(-side => 'left');
$balloon->attach($hb, -msg => "Restart\nShow all keywords");
my $bb = $butF->Button(-text => 'back',
-command => sub {
return unless (@search_keys);
# remove last element of array search_keys
pop @search_keys;
$label = '';
$label .= "$_ " foreach (@search_keys);
show_keywords($win, \@search_keys, \@exclude_keys);
})->pack(-side => 'left');
$balloon->attach($bb, -msg => "Go back\nRemove last keyword from list");
$butF->Label(-textvariable => \$label,
)->pack(-side => 'left', -expand => 0, -fill => 'x', -padx => 1, -pady => 1);
my $addB = $butF->Checkbutton(-text => 'add mode', -variable => \$add_mode)->pack(-side => 'left');
$balloon->attach($addB, -msg => 'If add mode is enabled, keywords will be added
and the search is narrowed to pictures
containing all displayed keywords.
If add mode is disabled, each click on a keyword
will start a new search for this keyword.');
my $Xbut = $butF->Button(-text => 'Close',
-command => sub {
# store excluded keywords for next session
$config{KeywordExclude} = '';
$config{KeywordExclude} .= "$_ " foreach (@exclude_keys);
# clode window
$win->destroy();
})->pack(-side => 'right');
$balloon->attach($Xbut, -msg => 'Close window (key: ESC)');
$win->bind('<Control-q>', sub { $Xbut->invoke; });
$win->bind('<Key-Escape>', sub { $Xbut->invoke; });
$butF2->Button(-text => 'show',
-command => sub {
my @list = get_pics_with_keywords(\@search_keys, \@exclude_keys);
showThumbList(\@list, $label);
})->pack(-side => 'left');
my $lab2 = $butF2->Label(-textvariable => \$win->{label2},
)->pack(-side => 'left', -expand => 0, -fill => 'x', -padx => 1, -pady => 1);
$balloon->attach($lab2, -msg => "x pictures\nx = number of pictures with the selected keywords\ny/z keywords\n = number of displayed keywords\nz = number of all matching keywords");
my $more_button;
$more_button = $butF2->Checkbutton(-variable => \$config{KeywordMore},
-text => 'more',
-command => sub {
if ($config{KeywordMore}) {
$butF3->pack(-after => $butF2, -expand => 0, -fill => 'x', -padx => 4, -pady => 3);
}
else { $butF3->packForget(); }
})->pack(-side => 'right', -padx => 5);
$balloon->attach($more_button, -msg => 'Click here to see some more options');
my $label_ex = ''; $label_ex .= "$_ " foreach (@exclude_keys);
my $butF3i = $butF3->Frame()->pack(-fill =>'x', -padx => 3, -pady => 3);
my $ceb = $butF3i->Button(-text => 'clear',
-command => sub {
# reset exclude_keys
@exclude_keys = ();
$label_ex = '';
show_keywords($win, \@search_keys, \@exclude_keys);
})->pack(-side => 'left');
$balloon->attach($ceb, -msg => "Clear all keywords from exclude list");
$butF3i->Label(-text => 'Excluded:',
)->pack(-side => 'left', -expand => 0, -fill => 'x', -padx => 1, -pady => 1);
$butF3i->Label(-textvariable => \$label_ex,
)->pack(-side => 'left', -expand => 0, -fill => 'x', -padx => 1, -pady => 1);
my $lib = $butF3->Checkbutton(-variable => \$config{KeywordLimit},
-text => 'Limit to 100 keywords',
-command => sub {show_keywords($win, \@search_keys, \@exclude_keys);}
)->pack(-anchor => 'w');
$balloon->attach($lib, -msg => 'Limit to a maximum of the 100 most popular keywords.');
$butF3->Label(-text => 'Right click to select a keyword, left click to exclude it')->pack(-anchor => 'w');
$cc = $win->Scrolled('Canvas',
-scrollbars => 'osoe',
-width => 700,
-height => 400,
-relief => 'sunken'
)->pack(-expand => 1, -fill => 'both', -padx => 1, -pady => 1);
$cc->configure(-scrollregion => [0, 0, 700, 400]);
$win->{canvas} = $cc;
$win->Popup(-popover => 'cursor');
show_keywords($win, \@search_keys, \@exclude_keys);
# reaction for clicking on a keyword (tag)
$cc->CanvasBind('<Button-1>' => sub {
my @curr = $cc->find('withtag', 'current');
my @tags = $cc->gettags($curr[0]);
foreach (@tags) {
next if ($_ eq 'current');
if ($add_mode) {
# add new keyword to list, if it is not already there
push @search_keys, $_ unless (isInList($_, \@search_keys));
}
else {
# clear list and add just the new selected keyword
@search_keys = ();
push @search_keys, $_;
}
}
$label = '';
$label .= "$_ " foreach (@search_keys);
show_keywords($win, \@search_keys, \@exclude_keys);
});
# reaction for right clicking on a keyword (tag)
$cc->CanvasBind('<Button-3>' => sub {
my @curr = $cc->find('withtag', 'current');
my @tags = $cc->gettags($curr[0]);
foreach (@tags) {
next if ($_ eq 'current');
push @exclude_keys, $_ unless (isInList($_, \@exclude_keys));
}
$label_ex = '';
$label_ex .= "$_ " foreach (@exclude_keys);
show_keywords($win, \@search_keys, \@exclude_keys);
});
# wait for the close button
$win->waitWindow;
}
##############################################################
# show_keywords - add keyword cloud to a canvas
##############################################################
sub show_keywords {
my $win = shift; # canvas
my $search_keys = shift; # list reference for keywords which must be contained
my $exclude_keys = shift; # list reference for keywords which must not be contained
$win->Busy;
# get the keywords according to the search keyword list ($search_keys)
my ($count, %keyword_hash) = get_keywords($search_keys, $exclude_keys);
my $all_keys = keys %keyword_hash;
my $cc = $win->{canvas};
# clear canvas
$cc->delete('all');
# limit the number of keywords to the 100 most popular keywords
# todo 100 should not be a fixed value
my $max_keys = 100;
my $key_count = 0;
if (($config{KeywordLimit}) and ((keys %keyword_hash) > $max_keys)) {
my %new_hash;
# sort hash by size of value (number of pictures with this keyword)
foreach my $key (sort {$keyword_hash{$b} <=> $keyword_hash{$a}} keys %keyword_hash) {
# copy the first 100 to a new hash
$new_hash{$key} = $keyword_hash{$key};
$key_count++;
last if ($key_count >= $max_keys);
}
# empty the original hash
undef %keyword_hash;
# copy the shortened hash back
%keyword_hash = %new_hash;
}
$win->{label2} = "$count pictures (".keys(%keyword_hash)."/$all_keys keywords)";
# find max an min numbers
my $min = 10000; my $max = 0;
foreach (keys %keyword_hash) {
$min = $keyword_hash{$_} if ($keyword_hash{$_} < $min);
$max = $keyword_hash{$_} if ($keyword_hash{$_} > $max);
}
# to have a nice size distribution we need the log function
my $diff = 1;
$diff = log($max - $min) if ($max != $min);
#print "max $max min $min diff $diff\n";
# maximum and minimum font size for tag cloud
my $font_min = 9;
my $font_max = 20;
my $font_middle = int(($font_max-$font_min)/2 + $font_min);
# h and v space between tags/keywords
my $x_space = 5;
my $y_space = 3;
my $x_max = 0;
my $x = $x_space;
my $y = $y_space + int($font_max/2);
# sort keywords alphabetical
foreach my $key (sort keys %keyword_hash) {
my $size = $font_middle;
# to have a nice size distribution we need the log function
$size = int(log($keyword_hash{$key} - $min + 1)/$diff * ($font_max-$font_min) + $font_min) if ($max != $min);
#printf "%-20s %5d %2.2f size: %2d", $key, $keyword_hash{$key}, log($keyword_hash{$key})/$diff, $size;
# safety check
$size = $font_max if ($size > $font_max);
$size = $font_min if ($size < $font_min);
#print " $size\n";
# bold style for the bigger fonts
my $style = 'normal';
$style = 'bold' if ($size >= $font_middle);
my $font = $top->Font(-family => $config{FontFamily}, -size => $size, -weight => $style);
# the more often a keyword is used there brighter it is displayed
my $color_percent = 100;
$color_percent = int(log($keyword_hash{$key} - $min + 1)/$diff * 100) if ($max != $min);
my $color = $win->Darken('blue', $color_percent);
# add the keyword (tag) to the canvas
my $id = $cc->createText($x, $y, -text => $key, -fill => $color, -font => $font, -anchor => 'w', -tags => [$key]);
# get the needed canvas space
my ($x1, $y1, $x2, $y2) = $cc->bbox($id);
# calculate next coordinates
$x += ($x2 - $x1) + $x_space;
if ($x > 600) { $x_max = $x if ($x > $x_max); $x = $x_space; $y += ($font_max + $y_space); }
}
# adjust the canvas scrollbars to the used space
$cc->configure(-scrollregion => [0, 0, $x_max, ($y + int($font_max/2) + $y_space)]);
$win->Unbusy;
}
##############################################################
# get_keywords - get all keywords from the searchDB (may be restriced by a keyword list ($search_keys))
##############################################################
sub get_keywords {
my $search_keys = shift; # list reference for keywords which must be contained
my $exclude_keys = shift; # list reference for keywords which must not be contained
my %keyword_hash;
my $count = 0;
# build keyword/tag hash
#stopWatchStart();
# loop through all pictures in the DB
foreach my $dpic (keys %searchDB) {
# skip if no keywords info in picture
next unless (defined $searchDB{$dpic}{KEYS});
# check if any items of the exclude_keys list are contained in this keyword string
my $wrong = 0;
foreach (@{$exclude_keys}) {
$wrong++ if ($searchDB{$dpic}{KEYS} =~ m/$_/);
last if ($wrong > 0);
}
next if ($wrong > 0);
# check if all items of the search_keys list are contained in this keyword string
$wrong = 0;
foreach (@{$search_keys}) {
$wrong++ unless ($searchDB{$dpic}{KEYS} =~ m/$_/);
last if ($wrong > 0);
}
next if ($wrong > 0);
# count number of pictures matching all keywords of the search keyword list
$count++;
# the keywords are stored as a space separated string so we need to split up
my @keys = split / /, $searchDB{$dpic}{KEYS};
foreach my $key (@keys) {
# hierarchical keywords are joined by an period "." todo this may cause problems
my @subkeys = split /\./, $key;
foreach (@subkeys) {
# add keyword to hash and count how often it was found
if (defined $keyword_hash{$_}) {
$keyword_hash{$_}++;
}
else {
$keyword_hash{$_} = 1;
}
}
}
}
#stopWatchStop('building keyword hash');
#print "done\nFound ".keys(%keyword_hash)." different keywords in $count pictures (database: ".keys(%searchDB).").\n";
#foreach (sort {$keyword_hash{$b} <=> $keyword_hash{$a}} keys %keyword_hash) {
#printf "%5d %-s\n", $keyword_hash{$_}, $_;
#}
return ($count, %keyword_hash);
}
##############################################################
# get_pics_with_keywords - returns a list of pictures with the
# given keywords (source: searchDB)
##############################################################
sub get_pics_with_keywords {
my $search_keys = shift; # list reference
my $exclude_keys = shift; # list reference for keywords which must not be contained
my @pic_list;
# build keyword/tag hash
#stopWatchStart();
foreach my $dpic (keys %searchDB) {
# skip if no keywords in picture
next unless (defined $searchDB{$dpic}{KEYS});
# check if any items of the exclude_keys list are contained in this keyword string
my $wrong = 0;
foreach (@{$exclude_keys}) {
$wrong++ if ($searchDB{$dpic}{KEYS} =~ m/$_/);
last if ($wrong > 0);
}
next if ($wrong > 0);
# check if all items of the search_keys list are contained in this keyword string
$wrong = 0;
foreach (@{$search_keys}) {
$wrong++ unless ($searchDB{$dpic}{KEYS} =~ m/$_/);
last if ($wrong > 0);
}
next if ($wrong > 0);
# collect matching pics in a list
push @pic_list, $dpic;
}
#stopWatchStop('collecting pics');
#print "done\nFound ".scalar @pic_list." pictures\n";
return @pic_list;
}
##############################################################
# editDatabase
##############################################################
sub editDatabase {
my $buttext = "Remove picture(s) from database";
my $text = "This list shows all pictures of the search database.\nYou may select any number of pictures and remove them with the \"$buttext\" button.\nThe pictures won't be deleted, only the entry in the database is removed.\nIt's recommended to call the function \"clean database\" first, because it will remove all invalid entries for you.";
my $rc;
# open window
my $ew = $top->Toplevel();
$ew->title("Edit search database");
$ew->iconimage($mapiviicon) if $mapiviicon;
my $height = ($text =~ tr/\n//);
$height += 2;
$height = 10 if ($height > 10); # not to big, we have scrollbars
my $rotext = $ew->Scrolled("ROText",
-scrollbars => 'osoe',
-wrap => 'word',
-tabs => '4',
-width => 110,
-height => $height,
-relief => "flat",
-bg => $config{ColorBG},
-bd => "0"
)->pack(-expand => "0", -padx => 3, -pady => 3,-anchor => 'w');
$rotext->insert('end', $text);
my $size = getFileSize("$configdir/SearchDataBase", FORMAT);
my $keys = keys %searchDB;
my $info = "$keys entries in the database (file size: $size)";
my $listBoxY = $keys;
$listBoxY = 25 if ($listBoxY > 25); # not higher than 30 entries
my $listBox =
$ew->Scrolled('Listbox',
-scrollbars => 'osoe',
-selectmode => 'extended',
-exportselection => 0,
#-width => 80,
-height => $listBoxY,
)->pack(-expand => 1, -fill =>'both', -padx => 3, -pady => 3);
bindMouseWheel($listBox);
$listBox->insert('end', (sort keys %searchDB));
my $labF = $ew->Frame()->pack(-anchor => 'w', -padx => 3, -pady => 3);
$labF->Label(-textvariable => \$info, -bg => $config{ColorBG})->pack(-side => "left");
$ew->Button(-text => $buttext,
-command => sub {
foreach (reverse $listBox->curselection()) {
my $path = $listBox->get($_);
delete $searchDB{$path}; # delete key from hash
$listBox->delete($_);
}
$keys = keys %searchDB; # display the ne wnumber of database entries
$info = "$keys entries in the database";
}
)->pack(-anchor => 'w', -padx => 3, -pady => 3);
my $filter;
my $ef = $ew->Frame()->pack(-fill => 'x', -padx => 3, -pady => 3);
$ef->Label(-text => "Show only keys matching:",
-anchor => 'w',
-bg => $config{ColorBG},
)->pack(-side => "left", -padx => 3);
my $entry = $ef->Entry(-textvariable => \$filter,
-width => 20,
)->pack(-fill => 'x', -padx => 3, -pady => 3);
$entry->bind('<Return>', sub {
return if (!defined $filter);
$listBox->delete(0, 'end');
$keys = keys %searchDB; # display the ne wnumber of database entries
if ($filter eq "") {
$listBox->insert('end', (sort keys %searchDB));
$info = "$keys entries in the database (all visible)";
}
else {
my $count = 0;
$filter = makePattern($filter); # create a windows like pattern
foreach (sort keys %searchDB) {
if ($_ =~ m!$filter!i) {
$listBox->insert('end', $_);
$count++;
}
}
$info = "$keys entries in the database ($count visible)";
}
} );
my $ButF =
$ew->Frame()->pack(-fill =>'x');
my $OKB =
$ButF->Button(-text => 'OK',
-command => sub { $rc = 'OK'; }
)->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$OKB->bind('<Return>', sub { $OKB->invoke; } );
$OKB->focus;
$ew->Popup(-popover => 'cursor');
repositionWindow($ew);
$ew->waitVariable(\$rc);
$ew->withdraw;
$ew->destroy;
}
##############################################################
# checkDatabase - check the comment and iptc fields of all
# database entries for problematic chars
# will e.g. complain about the copyright sign
##############################################################
sub checkDatabase {
my ($com, $iptc, $text);
my $i = 0;
foreach my $dpic (sort keys %searchDB) {
$i++;
$com = $searchDB{$dpic}{COM};
$iptc = $searchDB{$dpic}{IPTC};
if ($com =~ m/[^\x00-\x7f]/) {
$text .= "comment of $dpic\n";
}
if ($iptc =~ m/[^\x00-\x7f]/) {
$text .= "IPTC of $dpic\n";
}
}
$text = "Check finished.\nFound these problematic chars in $i pictures:\n\n$text";
showText("Check database", $text, WAIT);
}
##############################################################
# searchDupName - search duplicate pics in the database by
# same file name
##############################################################
sub searchDupsName {
my %pics; # hash of all file names key: file name or size value: directory+pic
my $dpics = shift; # ref to hash of all file names key: file name value: list of dirs+pic containing this pic
my $ignore_links = shift;
my $filter = shift;
undef %$dpics;
#$userinfo = "searching duplicates by file name ..."; $userInfoL->update;
# loop through all database entries
foreach my $dpic (sort keys %searchDB) {
next if (($filter ne '') and ($dpic !~ m!$filter!i));
next if ($ignore_links and -l $dpic);
my $pic = basename($dpic);
# new entry
if (!defined $pics{$pic}) {
$pics{$pic} = $dpic;
}
# duplicate found
else {
# if not defined in the dups hash, add first dir (was saved before)
if (!defined $$dpics{$pic}) {
$$dpics{$pic} = [$pics{$pic}];
}
# and add the actual dir and pic
push @{$$dpics{$pic}}, $dpic;
}
}
}
##############################################################
# searchDupSize - search duplicate pics in the database by
# same file size
##############################################################
sub searchDupsSize {
my %pics; # hash of all file names key: file name or size value: directory+pic
my $dpics = shift; # ref to hash of all file names key: file size value: list of dirs+pic containing this pic
my $ignore_links = shift;
my $filter = shift;
undef %$dpics;
#$userinfo = "searching duplicates by file size ..."; $userInfoL->update;
# loop through all database entries
foreach my $dpic (sort keys %searchDB) {
next if (($filter ne '') and ($dpic !~ m!$filter!i));
next unless ($ignore_links and -f $dpic);
next if (-l $dpic);
my $size = $searchDB{$dpic}{SIZE}; # size in Bytes
# new entry
if (!defined $pics{$size}) {
$pics{$size} = $dpic;
}
# duplicate found
else {
# if not defined in the dups hash, add first dir (was saved before)
if (!defined $$dpics{$size}) {
$$dpics{$size} = [$pics{$size}];
}
# and add the actual dir and pic
push @{$$dpics{$size}}, $dpic;
}
}
}
##############################################################
# findDups - find duplicate pics in the database
##############################################################
sub findDups {
if (Exists($dupw)) {
$dupw->deiconify;
$dupw->raise;
$dupw->focus;
return;
}
my $pic;
my $dir;
my %dpics; # hash of all file names key: file name or size value: list of dirs+pic containing this pic
my $searchForDups = "Name";
my $ignore_links = 0;
my $filter = '';
# open window
$dupw = $top->Toplevel();
$dupw->title("Duplicate pictures");
$dupw->iconimage($mapiviicon) if $mapiviicon;
my %dupthumbs;
my $subF = $dupw->Frame()->pack(-fill => 'x', -expand => 0, -pady => 1);
my $subF2 = $dupw->Frame()->pack(-fill => 'x', -expand => 0, -pady => 1);
my $dbsize = getFileSize("$configdir/SearchDataBase", FORMAT);
my $progress = 0;
my $progBar =
$subF->ProgressBar(-takefocus => 0,
-borderwidth => 1,
-relief => 'sunken',
-length => 100,
-padx => 0,
-pady => 0,
-variable => \$progress,
-colors => [0 => $config{ColorProgress}],
-resolution => 1,
-blocks => 10,
-anchor => 'w',
-from => 0,
-to => 100,
)->pack(-side => 'left', -fill => 'both', -expand => 0, -padx => 2, -pady => 0);
my $stop = 0;
my $stopB = $subF->Button(-text => "Stop",
-command => sub { $stop = 1; }
)->pack(-side => 'left', -anchor => 'w', -expand => 0,-padx => 1,-pady => 1);
my $stopImg = $top->Photo(-file => "$configdir/StopPic.gif") if (-f "$configdir/StopPic.gif");
$stopB->configure(-image => $stopImg, -borderwidth => 0) if $stopImg;
$stopB->configure(-state => "disabled");
my $label = "";
$subF->Label(-textvariable => \$label, -justify => "left",-bg => $config{ColorBG})->pack(-side => "left", -anchor => 'w', -padx => 2);
labeledEntry($subF2, 'left', 33, "Show only path filenames matching", \$filter);
my $duplb = $dupw->Scrolled("HList",
-header => 1,
-separator => ';', # todo here we hope that ; will never be in a directory or file name
-pady => 0,
-columns => 4,
-scrollbars => 'osoe',
-selectmode => "extended",
-background => $config{ColorBG}, #8fa8bf
-width => 40,
-height => 200,
)->pack(-fill => "both");
bindMouseWheel($duplb);
my $col = 0;
$duplb->{thumbcol} = $col; # save the colomn numbers in the list box widget ref
$duplb->header('create', $col++, -text => 'Thumbnail', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
$duplb->{namecol} = $col;
$duplb->header('create', $col++, -text => 'Name', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
$duplb->{filecol} = $col;
$duplb->header('create', $col++, -text => 'File info', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
$duplb->{dircol} = $col; # save the colomn number of the directory in the list box widget ref
$duplb->header('create', $col, -text => 'Folder', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
$balloon->attach($duplb, -msg => "left click : select\nmiddle click: open picture in new window\nright click : open context menu");
$subF->Button(-text => "Search",
-command => sub {
# clean up
$duplb->delete("all");
$label = 'cleaning up ...';
$duplb->update;
# clean up memory - delete all found thumbnail photo objects
foreach (keys %dupthumbs) {
print "findDups: deleting thumb $_\n" if $verbose;
$dupthumbs{$_}->delete if (defined $dupthumbs{$_});
delete $dupthumbs{$_};
}
$label = 'searching duplicates in database ...';
$duplb->update;
my $filterP = makePattern($filter); # create a windows like pattern
if ($searchForDups eq 'Name') {
searchDupsName(\%dpics, $ignore_links, $filterP);
} elsif ($searchForDups eq 'Size') {
searchDupsSize(\%dpics, $ignore_links, $filterP);
} elsif ($searchForDups eq 'Cancel') {
return;
} else {
warn "wrong searchForDups: $searchForDups\n";
return;
}
my $keys = keys %dpics;
$label = " $keys duplicates are found in the database (file size: $dbsize).";
my $last_time;
my $pcount = 0; # pic count = keys %dpics
my $dcount = 0; # dir count (if each pic has one duplicate this number is $pcount * 2)
my ($dpic, $size, $date, $dir, $pic, $thumb);
my $style = $iptcS;
$stopB->configure(-state => 'normal');
# insert duplicates in hlist
foreach my $item (sort keys %dpics) {
last if $stop;
$pcount++;
foreach my $dpic (@{$dpics{$item}}) {
last if $stop;
#$dir =~ s!^([a-z]:)/!$1\\!i if $EvilOS; # replace E:/ with E:\ else Win will fire an error message that E: is not mounted
$dir = dirname($dpic);
$pic = basename($dpic);
$thumb = getThumbFileName($dpic);
# create new row
$duplb->add($dpic);
if (-f $thumb) {
$dupthumbs{$thumb} = $duplb->Photo(-file => $thumb, -gamma => $config{Gamma});
if (defined $dupthumbs{$thumb}) {
$duplb->itemCreate($dpic, $duplb->{thumbcol}, -image => $dupthumbs{$thumb}, -itemtype => 'image');
}
}
if ($searchForDups eq "size") {
$size = $item;
} else {
$size = "n.a."; # default value
if ((-d $dir) and (-f $dpic)) {
$size = getFileSize($dpic, NO_FORMAT); # size in Bytes
}
}
$date = "n.a."; # default value
if ((-d $dir) and (-f $dpic)) {
$date = getFileDate($dpic, FORMAT); # date in exif format
}
$duplb->itemCreate($dpic, $duplb->{namecol}, -text => $pic, -style => $style);
$duplb->itemCreate($dpic, $duplb->{filecol}, -text => "$size bytes\n$date", -style => $comS);
$duplb->itemCreate($dpic, $duplb->{dircol}, -text => $dir, -style => $style);
$dcount++;
# show progress and found pics every 0.5 seconds - idea from Slaven
if (!defined $last_time || Tk::timeofday()-$last_time > 0.5) {
$progress = int($pcount/$keys*100);
$label = " displaying duplicates $progress% ($pcount/$keys)";
$duplb->update();
$last_time = Tk::timeofday();
}
}
# toggle style of name col
if ($style == $iptcS) { $style = $comS } else {$style = $iptcS };
}
$progress = 100 if ($pcount >= $keys); # sometimes there is a little gap
$stopB->configure(-state => "disabled");
$label = " found $pcount duplicates in $dcount files.";
$duplb->update();
})->pack(-side => "left", -anchor => 'w', -fill => "both", -padx => 1,-pady => 1);
$subF->Label(-text => "duplicates by same file", -bg => $config{ColorBG})->pack(-side => "left", -anchor => 'w', -fill => "both");
$subF->Optionmenu(-options => [qw(Name Size)], -variable => \$searchForDups, -textvariable => \$searchForDups)->pack(-side => "left", -anchor => 'w', -fill => "both");
$subF->Checkbutton(-text => 'ignore links', -variable => \$ignore_links)->pack(-side => "left", -anchor => 'w', -fill => "both", -padx => 1,-pady => 1);
my $Xbut = $subF->Button(-text => "Close",
-command => sub {
$dupw->withdraw();
$dupw->destroy();
# clean up memory - delete all found thumbnail photo objects
foreach (keys %dupthumbs) {
print "findDups: deleting thumb $_\n" if $verbose;
$dupthumbs{$_}->delete if (defined $dupthumbs{$_});
delete $dupthumbs{$_};
}
}
)->pack(-side => "left", -anchor => 'w', -fill => "both", -expand => 1, -padx => 1,-pady => 1);
# the context menu
my $menu = $dupw->Menu(-title => "Duplicate pictures menu");
############# open pic
$menu->command(-label => "open picture in new window", -accelerator => "Middle Mouse Button",
-command => sub {
my @pics = $duplb->info('children');
return unless (@pics);
my @sellist = $duplb->info('selection');
if (@sellist != 1) {
$dupw->messageBox(-icon => 'warning', -message => "Please select exactly one picture!",
-title => "Wrong selection", -type => 'OK');
return;
}
my $dpic = $sellist[0];
my $dir = dirname($dpic);
if (!-d $dir) {
$dupw->messageBox(-icon => 'warning', -message => "Sorry, but the directory\n$dir\nis not availabale at the moment.\nMaybe you should clean your database\nor insert a removable media.",
-title => "directory not found", -type => 'OK');
return;
}
$dupw->Busy;
showPicInOwnWin($dpic);
$dupw->Unbusy;
});
############# open dir
$menu->command(-label => "open directory and show picture", -command => sub {
my @pics = $duplb->info('children');
return unless (@pics);
my @sellist = $duplb->info('selection');
if (@sellist != 1) {
$dupw->messageBox(-icon => 'warning', -message => "Please select exactly one picture!",
-title => "Wrong selection", -type => 'OK');
return;
}
my $dpic = $sellist[0];
my $dir = dirname($dpic);
if (!-d $dir) {
$dupw->messageBox(-icon => 'warning', -message => "Sorry, but the directory\n$dir\nis not availabale at the moment.\nMaybe you should clean your database\nor insert a removable media.",
-title => "directory not found", -type => 'OK');
return;
}
$top->deiconify;
$top->raise;
$top->focus;
openDirPost($dir) if ($dir ne $actdir);
showPic($dpic);
});
############# ignore dir
$menu->command(-label => "ignore directory ...", -command => sub {
my @pics = $duplb->info('children');
return unless (@pics);
my @sellist = $duplb->info('selection');
if (@sellist != 1) {
$dupw->messageBox(-icon => 'warning', -message => "Please select exactly one picture!",
-title => "Wrong selection", -type => 'OK');
return;
}
my $ignoredir = dirname($sellist[0]);
my $rc = myEntryDialog("Ignore directory", "Ignore all directories matching this pattern:", \$ignoredir);
return if ($rc ne 'OK' or $ignoredir eq "");
my $count = 0;
foreach my $i (@pics) {
next unless ($duplb->info("exists", $i));
my $dir = dirname($i);
if ($dir =~ m!$ignoredir!) {
$count++;
$label = "removing $dir ($count) ...";
#print "$dir remove $i $ignoredir\n";
$duplb->delete("entry", $i);
}
}
$label = "removed $count directories.";
});
############# select all
$menu->command(-label => "selected all", -command => sub {
my @pics = $duplb->info('children');
return unless (@pics);
$duplb->selectionSet($pics[0], $pics[-1]); # 'end' does not work with HList
} );
$menu->separator;
############# delete to trash
$menu->command(-label => "delete picture to trash", -command => sub {
deletePics($duplb, TRASH);
$label = "pictures deleted";
} );
############# copy
$menu->command(-label => "copy selected pictures ...", -command => sub {
copyPicsDialog(COPY, $duplb);
$label = "ready! (pictures copied)"; $dupw->update;
} );
############# move
$menu->command(-label => "move selected pictures ...", -command => sub {
movePicsDialog($duplb);
$label = "ready! (pictures moved)"; $dupw->update;
} );
# mouse and button bindings
$duplb->bind('<ButtonPress-3>', sub {
$menu->Popup(-popover => "cursor", -popanchor => "nw");
} );
$duplb->bind('<ButtonRelease-2>', sub {
return unless ($duplb->info('children'));
my $dpic = getNearestItem($duplb);
my $dir = dirname($dpic);
if (!-d $dir) {
$dupw->messageBox(-icon => 'warning', -message => "Sorry, but the directory\n$dir\nis not availabale at the moment.\nMaybe you should clean your database\nor insert a removable media.",
-title => "directory not found", -type => 'OK');
return;
}
$dupw->Busy;
showPicInOwnWin($dpic);
$dupw->Unbusy;
} );
$dupw->bind('<Control-q>', sub { $Xbut->invoke; });
$dupw->bind('<Key-Escape>', sub { $Xbut->invoke; });
my $w = int(0.7 * $dupw->screenwidth);
my $h = int(0.7 * $dupw->screenheight);
$dupw->geometry("${w}x${h}+10+10");
$duplb->update();
$dupw->waitWindow;
}
##############################################################
# editHashDialog - let the user add or remove keys from a hash
##############################################################
sub editHashDialog {
my $title = shift;
my $text = shift;
my $hr = shift; # hash reference
my $okB = shift; # Ok button text
my $cancelB = shift; # Cancel button text ("" means no Cancel button)
my $addB = shift; # bool - show a path entry and a Add Path button
my $entry = "";
my $rc;
# open window
my $ew = $top->Toplevel();
$ew->title($title);
$ew->iconimage($mapiviicon) if $mapiviicon;
my $height = ($text =~ tr/\n//);
$height += 2;
$height = 10 if ($height > 10); # not to big, we have scrollbars
my $rotext = $ew->Scrolled("ROText",
-scrollbars => 'osoe',
-wrap => 'word',
-tabs => '4',
-width => 80,
-height => $height,
-relief => "flat",
-bg => $config{ColorBG},
-bd => "0"
)->pack(-expand => "0", -padx => 3, -pady => 3);
$rotext->insert('end', $text);
my $keys = keys %{$hr};
my $listBoxY = $keys;
$listBoxY = 30 if ($listBoxY > 30); # not higher than 30 entries
my $listBox =
$ew->Scrolled('Listbox',
-scrollbars => 'osoe',
-selectmode => 'extended',
-exportselection => 0,
-width => 80,
-height => $listBoxY,
)->pack(-expand => 1, -fill =>'both', -padx => 3, -pady => 3);
$listBox->insert('end', (sort keys %{$hr}));
my $labF = $ew->Frame()->pack(-anchor => 'w', -padx => 3, -pady => 3);
$labF->Label(-textvariable => \$keys, -bg => $config{ColorBG})->pack(-side => "left");
$labF->Label(-text => " entries", -bg => $config{ColorBG})->pack(-side => "left");
$ew->Button(-text => "Remove marked",
-command => sub {
foreach (reverse $listBox->curselection()) {
my $path = $listBox->get($_);
delete $$hr{$path}; # delete key from hash
$listBox->delete($_);
}
# refresh listbox
#$listBox->delete(0, 'end');
#$listBox->insert('end', (sort keys %{$hr}));
$keys = keys %{$hr}; # display the ne wnumber of database entries
}
)->pack(-anchor => 'w', -padx => 3, -pady => 3);
if ($addB) {
my $entryF = $ew->Frame()->pack(-fill =>'x');
$entryF->Entry(-textvariable => \$entry,
-width => 40)->pack(-side => "left", -fill => 'x', -padx => 3, -pady => 3);
$entryF->Button(-text => "Add path",
-command => sub {
$$hr{"$entry"} = 1;
$listBox->delete(0, 'end');
$listBox->insert('end', (sort keys %{$hr}));
})->pack(-side => 'left', -padx => 3, -pady => 3);
}
my $ButF =
$ew->Frame()->pack(-fill =>'x');
my $OKB =
$ButF->Button(-text => $okB,
-command => sub {
$rc = 'OK',
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$OKB->bind('<Return>', sub { $OKB->invoke; } );
if ($cancelB ne "") {
$ButF->Button(-text => $cancelB,
-command => sub {
$rc = 'Cancel';
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
}
$OKB->focus;
$ew->Popup(-popover => 'cursor');
repositionWindow($ew);
$ew->waitVariable(\$rc);
$ew->withdraw;
$ew->destroy;
return $rc;
}
##############################################################
# checkDateFormat - check if date string matches dd.mm.yyyy
# and day is between 1..31 and month 1..12
##############################################################
sub checkDateFormat($) {
my $date = shift;
my $rc = 0;
if ($date =~ /^(\d\d)\.(\d\d)\.(\d\d\d\d)$/) { # check format
if ($1 >= 1 and $1 <= 31) { # check day range
if ($2 >= 1 and $2 <= 12) { # check month range
if ($3 >= 1901 and $3 <= 2038) { # check year range, 1901 and 2038 are save boundaries for 32 bit systems
# check for valid dates (e.g. 31.02.2000 is invalid)
eval { timelocal(0, 0, 0, $1, $2-1, $3-1900); };
$rc = 1 unless ($@);
}
}
}
}
return $rc;
}
##############################################################
# checkNumberFormat - check if the argument is a number
##############################################################
sub checkNumberFormat($) {
my $nr = shift;
my $rc = 0;
if ($nr =~ /^\d+$/) { # check format
if ($nr >= 0 and $nr <= 99999) { # check range
$rc = 1;
}
}
return $rc;
}
##############################################################
# buildUnixTime - dd.mm.yyyy to UNIX date/time
##############################################################
sub buildUnixTime {
my $date_str = shift;
my $time;
if ($date_str =~ m/(\d\d)\.(\d\d)\.(\d\d\d\d)/) {
my $mon = $2;
my $year = $3;
$mon--;
$year -= 1900;
# check for valid dates (e.g. 31.02.2000 is invalid)
eval { timelocal(0, 0, 0, $1, $mon, $year); };
if ($@) {
warn "buildUnixTime: $date_str is invalid, date does not exists.\n";
$time = 0;
}
else { # valid
$time = timelocal(0, 0, 0, $1, $mon, $year);
}
}
else {
warn "buildUnixTime: wrong string format $date_str, should be dd.mm.yyyy\n";
$time = 0;
}
return $time;
}
##############################################################
# buildDateTime - UNIX date/time to dd.mm.yyyy hh:mm:ss
##############################################################
sub buildDateTime {
my $ctime = shift;
my ($s,$m,$h,$d,$mo,$y) = localtime $ctime;
$y += 1900; $mo++; # do some adjustments
# build up the date time string, similar to the EXIF format
return sprintf "%02d.%02d.%04d %02d:%02d:%02d", $d, $mo, $y, $h, $m, $s;
}
##############################################################
# buildEXIFDateTime - UNIX date/time to yyyy:mm:dd hh:mm:ss
##############################################################
sub buildEXIFDateTime {
my $ctime = shift;
my ($s,$m,$h,$d,$mo,$y) = localtime $ctime;
$y += 1900; $mo++; # do some adjustments
# build up the date time string, similar to the EXIF format
return sprintf "%04d:%02d:%02d %02d:%02d:%02d", $y, $mo, $d, $h, $m, $s;
}
##############################################################
# searchFileName
##############################################################
sub searchFileName {
my $lb = shift;
my @sellist = $lb->info('selection');
return unless checkSelection($lb, 1, 1, \@sellist);
my $fileName = basename($sellist[0]);
#resetAllSearchOptions(); # todo: write this sub
$config{SearchPattern} = $fileName;
$config{SearchName} = 1;
searchMetaInfo();
}
##############################################################
# searchMetaInfo
##############################################################
sub searchMetaInfo {
use bytes;
use locale;
if (Exists($sw)) {
$sw->deiconify;
$sw->raise;
$sw->focus;
$sw->{entry}->focus;
$sw->{entry}->selectionRange(0,'end'); # select all
return;
}
my $start_dir = getRightDir();
my $pattern = $config{SearchPattern};
my $exclude = $config{SearchExPattern};
my $pat = "";
my $exl = "";
my $OKB;
my $keys = keys %searchDB;
my $size = getFileSize("$configdir/SearchDataBase", FORMAT);
my $stop = 0;
my $stopB;
if (!$config{SaveDatabase}) {
my $rc =
$top->messageBox(-message => "The save database to file option is off. The search will only cover the directories visited during this session.\nShould I switch the save option on?\nYou can change this option also in the options dialog.",
-icon => 'question', -title => "Switch save option", -type => 'OKCancel');
$config{SaveDatabase} = 1 if ($rc =~ m/Ok/i);
}
# open window
$sw = $top->Toplevel();
$sw->withdraw;
$sw->title("Search picture database");
$sw->iconimage($mapiviicon) if $mapiviicon;
#$sw->Label(-text => "Search in the picture database for a pattern:", -justify => "left",-bg => $config{ColorBG})->pack(-anchor => 'w');
my $topF = $sw->Frame()->pack(-fill => 'x', -expand => 0, -pady => 1);
my $leftF = $topF->Frame()->pack(-fill => 'x', -side => 'left', -padx => 3, -pady => 3);
my $pf1 = $leftF->Frame()->pack(-fill => 'x', -padx => 3, -pady => 3);
$pf1->Label(-text => "Search pattern", -width => 15, -anchor => 'w', -bg => $config{ColorBG})->pack(-side => "left", -padx => 3);
$sw->{entry} = $pf1->Entry(-textvariable => \$pattern, -width => 25)->pack(-side => "left", -fill => 'x', -expand => "1", -padx => 1);
my $pf2 = $leftF->Frame()->pack(-fill => 'x', -padx => 3, -pady => 3);
$pf2->Label(-text => "Exclude pattern", -width => 15, -anchor => 'w', -bg => $config{ColorBG})->pack(-side => "left", -padx => 3);
my $exentry = $pf2->Entry(-textvariable => \$exclude, -width => 25)->pack(-side => "left", -fill => 'x', -expand => "1", -padx => 1);
#$pf2->Button(-text => "clear", -command => sub {$exclude = "";})->pack(-side => "left", -padx => 3, -pady => 0);
$balloon->attach($sw->{entry}, -msg => 'Use * for zero or more chars, ? for exactly one char.
Use \* to search for the star sign (*) and \? to search for a questionmark (?) itself.
To search for a backslash (\) use two backslashes (\\\).
Examples:
"I * home" will match e.g. "I go home", "I run home" but also "I do not go home"
"Tr?ck" will match "Trick" or "Track"
"who\?" will match "who?"
"\*\* Party \*\*" will match "** Party **"');
$balloon->attach($exentry, -msg => 'Enter the patterns to exclude here.
Separate them with one space.
All patterns will be joined by or.
Hint:
Use an empty search pattern and the exlude pattern "?*"
to search for pictures without comments, EXIF or IPTC infos.');
$sw->{entry}->bind('<Return>', sub { $OKB->invoke; } );
$exentry->bind('<Return>', sub { $OKB->invoke; } );
$sw->{entry}->focus;
$sw->{entry}->selectionRange(0,'end'); # select all
# what to search: keywords, IPTC, comments, ...
my $f1 = $topF->Frame(-relief => 'groove', -bd => $config{Borderwidth})->pack(-side => "left", -anchor => "n", -fill =>'both',-padx => 3,-pady => 5);
# different search options
my $f0 = $leftF->Frame()->pack(-anchor => 'w', -padx => 0,-pady => 0);
# local search + more options
my $locSF = $leftF->Frame(-relief => 'groove')->pack(-fill => 'x', -padx => 3, -pady => 5);
$locSF->Checkbutton(-variable => \$config{SearchOnlyInDir}, -text => "local search in")->pack(-side => 'left', -anchor => 'w', -padx => 4, -padx => 2);
$locSF->Label(-textvariable => \$start_dir)->pack(-side => 'left', -anchor => 'w', -padx => 4, -padx => 2);
setFileButton($locSF,'left','Set','Select folder to search in',\$start_dir, 1);
$balloon->attach($locSF, -msg =>
'When this option is enabled, the search will only take place
in directories matching the displayed string.
When the option is disabled a global search will take place.');
my ($addMF, $addF);
$locSF->Checkbutton(-variable => \$config{SearchMore},
-text => 'more options',
-command => sub {
if ($config{SearchMore}) {
$addF->pack(-in => $addMF, -side => 'left', -expand => 0);# if (!ismapped($addF));
}
else {
$addF->packForget();# if (ismapped($addF));
}
})->pack(-side => 'right', -padx => 5);
my $ButF = $f0->Frame(-relief => 'groove', -bd => $config{Borderwidth})->pack(-side => "left", -anchor => "n", -expand => 1, -fill =>'both',-padx => 3,-pady => 0);
$balloon->attach($f1, -msg => "Search in JPEG comments, EXIF info,\nIPTC info, IPTC keywords, file name and/or in folder name");
my $f2 = $f0->Frame(-relief => 'groove', -bd => $config{Borderwidth})->pack(-side => "left", -anchor => "n", -fill =>'both',-padx => 3,-pady => 0);
my $f3 = $f0->Frame(-relief => 'groove', -bd => $config{Borderwidth})->pack(-side => "left", -anchor => "n", -fill =>'both',-padx => 3,-pady => 0);
my $f4 = $f0->Frame(-relief => 'groove', -bd => $config{Borderwidth})->pack(-side => "left", -anchor => "n", -fill =>'both',-padx => 3,-pady => 0);
$f1->Checkbutton(-variable => \$config{SearchKeys}, -text => "Keywords")->pack(-anchor => 'w');
$f1->Checkbutton(-variable => \$config{SearchIptc}, -text => "IPTC info")->pack(-anchor => 'w');
$f1->Checkbutton(-variable => \$config{SearchCom}, -text => "comments")->pack(-anchor => 'w');
$f1->Checkbutton(-variable => \$config{SearchExif}, -text => "EXIF info")->pack(-anchor => 'w');
$f1->Checkbutton(-variable => \$config{SearchName}, -text => "file name")->pack(-anchor => 'w');
$f1->Checkbutton(-variable => \$config{SearchDir}, -text => "folder name")->pack(-anchor => 'w');
my $sep = $f1->Checkbutton(-variable => \$config{SearchJoin}, -text => "join fields")->pack(-anchor => "nw");
$balloon->attach($sep, -msg =>
"If this option is selected all selected fields (keywords, IPTC,
comments, ...) of a picture will be joined before the search
starts, so it's e.g. possible to find a picture with keyword
\"Tom\" and the comment \"at the beach\".
If it is not selected, a all-search for \"Tom\" and \"Tim\"
will only match, if all patterns are in one field
(e.g. Tom and Tim are both in the keywords).");
my $sc1 = $f2->Checkbutton(-variable => \$config{SearchCase}, -text => "case sensitive")->pack(-anchor => "nw");
$balloon->attach($sc1, -msg => "Toggle between case sensitive/insensitive searching");
my $sw1 = $f2->Checkbutton(-variable => \$config{SearchWord}, -text => "complete word")->pack(-anchor => "nw");
$balloon->attach($sw1, -msg => "search only for complete words, not for parts");
my $stf = $f2->Frame()->pack(-anchor => 'w');
$stf->Label(-text => "match", -bg => $config{ColorBG})->pack(-side => "left", -anchor => 'w');
my $st1 = $stf->Optionmenu(-variable => \$config{SearchType}, -textvariable => \$config{SearchType}, -options => [qw(exactly all any)] )->pack(-side => "left", -anchor => 'w');
$balloon->attach($st1, -msg => 'Match search pattern exactly, match all words or
try to match any of the given words.
e.g. "Tim Tom" with search type
match exactly will find all pictures containing exactly this string (string-search)
match all will find this but also "Tom Tim" or "Tim and Tom" (and-search)
match any will find all pictures containing "Tim" or "Tom" or both (or-search)');
my $urgF = $f3->Frame()->pack(-anchor=>'w', -padx => 0, -pady => 0);
$urgF->Checkbutton(-variable => \$config{SearchUrgencyOn}, -text => "urgency")->pack(-side => "left", -anchor => 'w');
$urgF->Optionmenu(-variable => \$config{SearchUrgencyRel}, -textvariable => \$config{SearchUrgencyRel}, -options => [ qw(= <= >=) ] )->pack(-side => "left", -anchor => 'w');
# 0 must be first, because it's the default
my $dummy;
$urgF->Optionmenu(-variable => \$config{SearchUrgency}, -options => [ ["0 None" => 0], ["1 High" => 1], 2,3,4,["5 Normal" => 5],6,7, ["8 Low" => 8], ], -variable => \$config{SearchUrgency}, -textvariable => \$dummy)->pack(-side => "left", -anchor => 'w');
# todo search for empty urgency tags: , [Empty => ""]
$balloon->attach($urgF, -msg => "Search only for pictures with this IPTC urgency.\nYou can use the urgency flag to set the priority\nof the picture (1 = high to 8 = low).");
#$f3->Checkbutton(-variable => \$config{SearchUrgencyIg}, -text => "ignore pictures without urgency")->pack(-anchor => "nw");
my $popF = $f3->Frame()->pack(-anchor=>'w', -padx => 0, -pady => 0);
$popF->Checkbutton(-variable => \$config{SearchPopOn}, -text => "viewed ")->pack(-side => "left", -anchor => 'w');
$popF->Optionmenu(-variable => \$config{SearchPopRel}, -textvariable => \$config{SearchPopRel}, -options => [ qw(= <= >=) ] )->pack(-side => "left", -anchor => 'w');
my $popE = $popF->Entry(-textvariable => \$config{SearchPop}, -width => 10, -validate => 'focus', -validatecommand => sub { checkNumberFormat($_[0]); }, -invalidcommand => sub {$config{SearchPop} = 5; $sw->messageBox(-icon => 'warning', -message => 'Please enter a natural number (0,1,2,3,...) in the viewed field', -title => "Wrong format", -type => 'OK');})->pack(-side => "left", -fill => 'x', -expand => 1, -padx => 1);
$balloon->attach($popF, -msg => "Search only for pictures with have been viewed\nthis numer of times.");
my $justCount = 0;
my $countOp = $f3->Checkbutton(-variable => \$justCount, -text => "just count pictures")->pack(-anchor => "nw");
$balloon->attach($countOp, -msg => "Just count the matching pictures, do not display them.\nWith this option the search is much faster.");
$f4->Checkbutton(-variable => \$config{SearchDate}, -text => "search by EXIF date", -width => 19, -anchor => 'w')->pack(-anchor => 'w');
my $datetext = 'Please use date format: dd.mm.yyyy
and check if you entered a valid date.
dd (day) is between 01 and 31
mm (month) is between 01 and 12
yyyy (year) is between 1901 and 2038
Example 25.02.2006';
my $fromF = $f4->Frame()->pack(-anchor => 'w');
$fromF->Button(-text => 'from', -anchor => 'w', -width => 4, -command => sub { setFromTo(); } )->pack(-side => "left", -anchor => 'w', -padx => 3);
my $fromdate = $fromF->Entry(
-textvariable => \$config{SearchDateStart},
-width => 11,
-validate => 'focus',
-validatecommand => sub { checkDateFormat($_[0]); },
-invalidcommand => sub {
$config{SearchDateStart} = "01.01.2004";
$sw->messageBox(-icon => 'warning', -message => $datetext, -title => "Wrong date format", -type => 'OK');
}
)->pack(-side => "left", -padx => 3);
my $toF = $f4->Frame()->pack(-anchor => 'w');
$toF->Button(-text => 'to', -anchor => 'w', -width => 4, -command => sub { setFromTo(); } )->pack(-side => "left", -anchor => 'w', -padx => 3);
my $todate = $toF->Entry(
-textvariable => \$config{SearchDateEnd},
-width => 11,
-validate => 'focus',
-validatecommand => sub { checkDateFormat($_[0]); },
-invalidcommand => sub {
$config{SearchDateEnd} = "01.01.2007";
$sw->messageBox(-icon => 'warning', -message => $datetext, -title => "Wrong date format", -type => 'OK');
}
)->pack(-side => "left", -padx => 3);
$balloon->attach($fromdate, -msg => "Search only for pictures with a creation date\nwith or after this date.\nFormat: dd.mm.yyyy (example: 21.12.2001)");
$balloon->attach($todate, -msg => "Search only for pictures with a creation date\nbefore or with this date.\nFormat: dd.mm.yyyy (example: 31.01.2006)");
$addMF = $sw->Frame()->pack(-fill => 'x', -expand => 0, -pady => 0, -padx => 3);
# this empty frame is needed, else the frame won't shrink after removing the other content
my $empty_frame = $addMF->Frame()->pack();
$addF = $addMF->Frame();
# pixel size
my $pixF = $addF->Frame()->pack(-anchor=>'w', -padx => 0, -pady => 0);
$pixF->Checkbutton(-variable => \$config{SearchPixelOn}, -text => "pixel size")->pack(-side => "left", -anchor => 'w');
$pixF->Optionmenu(-variable => \$config{SearchPixelRel}, -textvariable => \$config{SearchPixelRel}, -options => [ qw(= <= >=) ] )->pack(-side => "left", -anchor => 'w');
$pixF->Entry(-width => 8,-textvariable => \$config{SearchPixel})->pack(-side => 'top', -anchor => 'w', -padx => 8);
if ($config{SearchMore}) {
$addF->pack(-in => $addMF, -side => 'left', -expand => 0);# if (!ismapped($addF));
}
else {
$addF->packForget();# if (ismapped($addF));
}
my $label = "$keys pictures are stored in the database (size: $size).";
my $subF = $sw->Frame()->pack(-fill => 'x', -expand => 0, -pady => 1);
my $progress = 0;
my $progBar =
my $progB =
$subF->ProgressBar(-takefocus => 0,
-borderwidth => 1,
-relief => 'sunken',
-length => 100,
-padx => 0,
-pady => 0,
-variable => \$progress,
-colors => [0 => $config{ColorProgress}],
-resolution => 1,
-blocks => 10,
-anchor => 'w',
-from => 0,
-to => 100,
)->pack(-side => 'left', -fill => 'both', -expand => 0, -padx => 8, -pady => 0);
$balloon->attach($progB, -msg => "Displays the search progress");
$subF->Label(-textvariable => \$label, -justify => "left",-bg => $config{ColorBG})->pack(-side => "left", -anchor => 'w', -padx => 8);
my $findLB = makeThumbListbox($sw);
$balloon->attach($findLB, -msg => "left click : select\nmiddle click: open picture in new window\nright click : open context menu");
addCommonKeyBindings($findLB, $findLB);
$findLB->bind('<Key-Delete>', sub { deletePics($findLB, TRASH); } );
$findLB->bind('<Shift-Delete>', sub { deletePics($findLB, REMOVE); } );
# the context menu
my $menu = $sw->Menu(-title => "Search menu");
############# select all
$menu->command(-label => "selected all",
-command => sub {selectAll($findLB);},
-accelerator => "<Ctrl-a>" );
$menu->separator;
############# file operations
addFileActionsMenu($menu, $findLB);
$menu->separator;
############# remove pictures from searchDB
$menu->command(-label => "remove pictures from search database", -command => sub {
my @sellist = getSelection($findLB);
return unless checkSelection($top, 1, 0, \@sellist);
my $rc = $sw->messageBox(-icon => 'question',
-message => "Please press OK to remove the ".scalar @sellist." selected picture(s) from the search data base.\nThe picture file(s) won't be deleted. They may be added to the search database again anytime.",
-title => "Remove ".scalar @sellist." picture(s) from search database?", -type => 'OKCancel');
return if ($rc !~ m/Ok/i);
foreach (@sellist) {
delete $searchDB{$_};
}
});
############# open pic
$menu->command(-label => "show pictures in new window", -command => sub {
my @sellist = getSelection($findLB);
return unless checkSelection($top, 1, 0, \@sellist);
show_multiple_pics(\@sellist, 0);
});
############# open dir
$menu->command(-label => "open picture in main window", -command => sub {
my @pics = $findLB->info('children');
return unless (@pics);
my @sellist = $findLB->info('selection');
return unless checkSelection($sw, 1, 1, \@sellist);
my $dpic = $sellist[0];
my $dir = dirname($dpic);
my $pic = basename($dpic);
if (!-d $dir) {
$sw->messageBox(-icon => 'warning', -message => "Sorry, but the directory\n$dir\nis not availabale at the moment.\nMaybe you should clean your database\nor insert a removable media.",
-title => "directory not found", -type => 'OK');
return;
}
$top->deiconify;
$top->raise;
$top->focus;
openDirPost($dir) if ($dir ne $actdir);
showPic($dpic);
});
############# open in external viewer
$menu->command(-label => "open pictures in external viewer", -command => sub {
openPicInViewer($findLB); }, -accelerator => "<v>");
$menu->separator;
############# display IPTC
$menu->command(-label => "show IPTC", -command => sub {
displayIPTCData($findLB); }, -accelerator => "<i>");
############# edit IPTC
$menu->command(-label => "edit IPTC ...", -command => sub {
editIPTC($findLB); }, -accelerator => "<Ctrl-i>");
addRatingMenu($menu, $findLB);
$menu->command(-label => "add/remove keywords ...", -command => sub { editIPTCKeywords($findLB); }, -accelerator => '<Ctrl-k>');
$menu->command(-label => "add/remove categories ...", -command => sub { editIPTCCategories($findLB); } , -accelerator => '<Ctrl-t>');
$menu->separator;
############# add comment
$menu->command(-label => "add comment ...", -command => sub {
addComment($findLB); }, -accelerator => "<a>");
############# edit comment
$menu->command(-label => "edit comment ...", -command => sub {
editComment($findLB); }, -accelerator => "<e>");
############# search/replace comment
$menu->command(-label => "search/replace comment ...", -command => sub {
replaceComment($findLB); }, );
$menu->separator;
############# sort - todo
my $sort_menu = $menu->cascade(-label => "sort by ...");
$menu->separator;
$menu->command(-label => "add to light table", -command => sub {light_table_add_from_lb($findLB);}, -accelerator => "<Ctrl-l>");
$sort_menu->command(-label => "file name", -command => sub {
my @pics = $findLB->info('children');
$findLB->delete("all");
searchThumbsDelete();
sortPics("name", 0, \@pics);
foreach (@pics) {
insertPic($findLB, $_);
}
}, );
$sort_menu->command(-label => "urgency", -command => sub {
my @pics = $findLB->info('children');
$findLB->delete("all");
searchThumbsDelete();
sortPics("urgency", 0, \@pics);
foreach (@pics) {
insertPic($findLB, $_);
}
}, );
$sort_menu->command(-label => "file date", -command => sub {
my @pics = $findLB->info('children');
$findLB->delete("all");
searchThumbsDelete();
sortPics("date", 0, \@pics);
foreach (@pics) {
insertPic($findLB, $_);
}
}, );
$sort_menu->command(-label => "EXIF date", -command => sub {
my @pics = $findLB->info('children');
$findLB->delete("all");
searchThumbsDelete();
sortPics("exifdate", 0, \@pics);
foreach (@pics) {
insertPic($findLB, $_);
}
}, );
# mouse and button bindings
$findLB->bind('<ButtonPress-3>', sub {
$menu->Popup(-popover => "cursor", -popanchor => "nw");
} );
$findLB->bind('<ButtonRelease-2>', sub {
return unless ($findLB->info('children'));
my $dpic = getNearestItem($findLB);
my $dir = dirname($dpic);
if (!-d $dir) {
$sw->messageBox(-icon => 'warning', -message => "Sorry, but the directory\n$dir\nis not availabale at the moment.\nMaybe you should clean your database\nor insert a removable media.",-title => "directory not found", -type => 'OK');
return;
}
$sw->Busy;
showPicInOwnWin($dpic);
$sw->Unbusy;
} );
my $SButF = $ButF->Frame(-bd => 0)->pack(-side => 'top', -anchor => "n", -expand => 1, -fill =>'both',-padx => 0,-pady => 0);
$OKB =
$SButF->Button(-text => "Search",
-command => sub {
my $searchStart = Tk::timeofday();
my $count = 0;
my ($thumb, $thumbP, $last_time, $start_time, $end_time);
if (($config{SearchCom} == 0 and
$config{SearchName} == 0 and
$config{SearchDir} == 0 and
$config{SearchExif} == 0 and
$config{SearchKeys} == 0 and
$config{SearchIptc} == 0)) {
$sw->messageBox(-icon => 'warning',
-message => 'Please select at least on field (keywords, comments, ...) to search in.',
-title => "No search field selected", -type => 'OK');
return;
}
unless (checkNumberFormat($config{SearchPop})) {
$config{SearchPop} = 5;
$sw->messageBox(-icon => 'warning',
-message => 'Please enter a natural number (0,1,2,3,...) in the viewed field',
-title => "Wrong format", -type => 'OK');
return;
}
# store the patterns before we process them
$config{SearchPattern} = $pattern;
$config{SearchExPattern} = $exclude;
# replace (german) umlaute by corresponding letters
$pattern =~ s/([$umlaute])/$umlaute{$1}/g if ($config{ConvertUmlaut});
$exclude =~ s/([$umlaute])/$umlaute{$1}/g if ($config{ConvertUmlaut});
$label = "searching pattern in $keys pictures."; $sw->update;
$pat = makePattern($pattern);# support windows like search patterns
$exl = makePattern($exclude);# support windows like search patterns
if ($config{SearchWord}) {
$pat = "\\b$pat";
$pat =~ s/\s+/\\b \\b/g; # replace one or more whitespaces with \b \b the word boundary
$pat .= "\\b";
}
if ($config{SearchType} eq 'any') { # or-function "Tim Tom" -> "Tim|Tom"
$pat =~ s/\s+/|/g; # replace one or more whitespaces with |
}
elsif ($config{SearchType} eq 'all') {
$pat = "(?=.*".$pat; # and-function with look-ahead
$pat =~ s/\s+/)(?=.*/g; # replace one or more whitespaces with )(?=.*
$pat .= ")"; # "Tom Tim" is now: "(?=.*Tom)(?=.*Tim)"
}
else { # do nothing (normal string search)
}
#my $qrpat; # todo, but seems not to work with and searches
#if ($config{SearchCase}) { $qrpat = qr/'$pat'2/io; } else { $qrpat = qr/'$pat'/o; }
#print "pat = $pat qrpat = $qrpat\n";
# the exclude patterns are always combined with or
$exl =~ s/ /|/g; # or-function "Tim Tom" -> "Tim|Tom"
print "searchMetaInfo: pattern: $pattern -> -$pat-\n" if $verbose;
print "searchMetaInfo: exclude pattern: $exclude -> -$exl-\n" if $verbose;
if ($config{SearchDate}) {
if (!checkDateFormat($config{SearchDateStart})) {
$sw->messageBox(-icon => 'warning', -message => $datetext, -title => "Wrong from-date", -type => 'OK');
return;
}
if (!checkDateFormat($config{SearchDateEnd})) {
$sw->messageBox(-icon => 'warning', -message => $datetext, -title => "Wrong to-date", -type => 'OK');
return;
}
$start_time = buildUnixTime($config{SearchDateStart});
$end_time = buildUnixTime($config{SearchDateEnd});
#print "$start_time .. $end_time\n";
if ($end_time < $start_time) {
$sw->messageBox(-icon => 'warning',
-message => 'Search from date must be before search to date',
-title => "Wrong search date", -type => 'OK');
return;
}
}
$findLB->delete("all"); # clear listbox
$sw->Busy;
my $case = "i"; $case = "" if $config{SearchCase};
$stopB->configure(-state => 'normal'); $stopB->update();
my $i = 0;
####################################################
# loop through all database entries
foreach my $dpic (sort keys %searchDB) {
last if $stop;
$i++;
# show progress and found pics every 0.5 seconds - idea from Slaven
if (!defined $last_time || Tk::timeofday()-$last_time > 0.5) {
$progress = int($i/$keys*100); $sw->update;
$last_time = Tk::timeofday();
}
if ($config{SearchOnlyInDir}) { # search only in subdirs of actual/selected dir
next unless ($dpic =~ m/^$start_dir/);
}
if ($config{SearchUrgencyOn}) { # ignore pics without a urgency setting
next unless (defined($searchDB{$dpic}{URG}));
}
# fill in the POP key if it's missing (will cost about 6 Bytes per picture in the searchDB
$searchDB{$dpic}{POP} = 0 unless (defined $searchDB{$dpic}{POP});
my $urg = $searchDB{$dpic}{URG};
my $time = $searchDB{$dpic}{TIME};
# skip if wrong urgency
if ($config{SearchUrgencyOn} and (defined $urg)) {
if ($config{SearchUrgencyRel} eq "=") { # equal
next if ($urg != $config{SearchUrgency});
}
else { # handle bigger and lower
$urg = 9 if ($urg == 0); # urgency 0 means none, which is less than 8 (low)
if ($config{SearchUrgencyRel} eq ">=") { # bigger
next if ($urg < $config{SearchUrgency});
}
if ($config{SearchUrgencyRel} eq "<=") { # lower
next if ($urg > $config{SearchUrgency});
}
}
}
# skip if wrong pixel sum size
if ($config{SearchPixelOn}) {
next unless (defined $searchDB{$dpic}{PIXX});
next unless (defined $searchDB{$dpic}{PIXY});
my $pixy = $searchDB{$dpic}{PIXX} * $searchDB{$dpic}{PIXY};
if ($config{SearchPixelRel} eq "=") { # equal
next if ($pixy != $config{SearchPixel});
}
else { # handle bigger and lower
if ($config{SearchPixelRel} eq ">=") { # bigger
next if ($pixy < $config{SearchPixel});
}
if ($config{SearchPixelRel} eq "<=") { # lower
next if ($pixy > $config{SearchPixel});
}
}
}
# skip if wrong numer of views (popularity)
if ($config{SearchPopOn}) {
if ($config{SearchPopRel} eq "=") { # equal
next if ($searchDB{$dpic}{POP} != $config{SearchPop});
}
else { # handle bigger and lower
if ($config{SearchPopRel} eq ">=") { # bigger
next if ($searchDB{$dpic}{POP} < $config{SearchPop});
}
if ($config{SearchPopRel} eq "<=") { # lower
next if ($searchDB{$dpic}{POP} > $config{SearchPop});
}
}
}
# skip if wrong date
if ($config{SearchDate} and defined($time)) {
next if ($time < $start_time);
next if ($time > $end_time);
}
my $com = $searchDB{$dpic}{COM};
my $exif = $searchDB{$dpic}{EXIF};
my $iptc = $searchDB{$dpic}{IPTC};
my $keys = $searchDB{$dpic}{KEYS};
# replace newlines with space
$com =~ s/\n/ /g if (defined $com);
$exif =~ s/\n/ /g if (defined $exif);
$iptc =~ s/\n/ /g if (defined $iptc);
my $allMeta = "";
if ($config{SearchJoin}) { # join all selected meta info with a space
$allMeta = $com if ($config{SearchCom} and $com);
$allMeta .= " ".$exif if ($config{SearchExif} and $exif);
$allMeta .= " ".$iptc if ($config{SearchIptc} and $iptc);
$allMeta .= " ".$keys if ($config{SearchKeys} and $keys);
$allMeta .= " ".basename($dpic) if ($config{SearchName});
$allMeta .= " ".dirname($dpic) if ($config{SearchDir});
$allMeta =~ s/\n/ /g; # replace newlines with space
}
if ((($config{SearchJoin} and ($allMeta ne "") and ($allMeta =~ m/(?$case).*$pat.*/) ) ) or
(($config{SearchCom} and (defined $com) and ($com =~ m/(?$case).*$pat.*/)) or
($config{SearchExif} and (defined $exif) and ($exif =~ m/(?$case).*$pat.*/)) or
($config{SearchIptc} and (defined $iptc) and ($iptc =~ m/(?$case).*$pat.*/)) or
($config{SearchKeys} and (defined $keys) and ($keys =~ m/(?$case).*$pat.*/)) or
($config{SearchName} and (basename($dpic) =~ m/(?$case).*$pat.*/)) or
($config{SearchDir} and (dirname($dpic) =~ m/(?$case).*$pat.*/)))) {
# skip if exclude pattern matches
if ((defined $exl) and ($exl ne "")) {
next if ((($config{SearchJoin} and ($allMeta ne "") and ($allMeta =~ m/(?$case).*$exl.*/ )) ) or
(($config{SearchCom} and (defined $com) and ($com =~ m/(?$case).*$exl.*/)) or
($config{SearchExif} and (defined $exif) and ($exif =~ m/(?$case).*$exl.*/)) or
($config{SearchIptc} and (defined $iptc) and ($iptc =~ m/(?$case).*$exl.*/)) or
($config{SearchKeys} and (defined $keys) and ($keys =~ m/(?$case).*$exl.*/)) or
($config{SearchName} and (basename($dpic) =~ m/(?$case).*$exl.*/)) or
($config{SearchDir} and (dirname($dpic) =~ m/(?$case).*$exl.*/))));
}
unless ($justCount) {
insertPic($findLB, $dpic);
}
$count++;
$label = "found pattern in $count pictures.";
}
} # foreach
####################################################
$stopB->configure(-state => "disabled");
$progress = 100; $findLB->update;
my $searchDuration = sprintf "%.2f", (Tk::timeofday() - $searchStart);
if ($count == 0) {
my $msg = "Found no pictures containing \"$pattern\"";
$msg .= " with urgency ".$config{SearchUrgencyRel}." ".$config{SearchUrgency} if ($config{SearchUrgencyOn});
$msg .= " with pixel size ".$config{SearchPixelRel}." ".$config{SearchPixel} if ($config{SearchPixelOn});
$msg .= " with views ".$config{SearchPopRel}." ".$config{SearchPop} if ($config{SearchPopOn});
$msg .= " dated between ".$config{"SearchDateStart"}." and ".$config{"SearchDateEnd"} if ($config{"SearchDate"} != 0);
$msg .= " in directories matching $start_dir" if ($config{"SearchOnlyInDir"} != 0);
$msg .= " in the database.";
$sw->messageBox(-icon => 'warning', -message => $msg,
-title => "Pattern not found", -type => 'OK');
$label = "pattern not found (duration: $searchDuration sec).";
$sw->Unbusy;
$stop = 0;
return;
}
$sw->Unbusy;
$label = "Search finished: found $count pictures (duration: $searchDuration sec).";
$stop = 0;
})->pack(-side => 'left', -anchor => 'w', -expand => 1,-fill => 'x',-padx => 1,-pady => 1);
$stopB = $SButF->Button(-text => "Stop",
-command => sub { $stop = 1; }
)->pack(-side => 'left', -anchor => 'w', -expand => 0,-padx => 1,-pady => 1);
my $stopImg = $top->Photo(-file => "$configdir/StopPic.gif") if (-f "$configdir/StopPic.gif");
$stopB->configure(-image => $stopImg, -borderwidth => 0) if $stopImg;
$stopB->configure(-state => "disabled");
# would be usefull here, but needs to much space
#$ButF->Button(-text => "Clean database ...",
# -command => sub {cleanDatabase();})->pack(-side => 'top', -anchor => 'w', -expand => 1,-fill => 'x',-padx => 1,-pady => 1);
my $Xbut =
$ButF->Button(-text => "Close",
-command => sub {
$stop = 1;
$config{SearchGeometry} = $sw->geometry;
$sw->withdraw;
searchThumbsDelete();
$sw->destroy;
}
)->pack(-side => 'top', -anchor => 'w', -expand => 1,-fill => 'x',-padx => 1,-pady => 1);
$sw->bind('<Control-q>', sub { $Xbut->invoke; });
$sw->bind('<Key-Escape>', sub { $Xbut->invoke; });
$sw->bind('<H>', sub { showHistogram($findLB); });
$sw->Popup;
checkGeometry(\$config{SearchGeometry});
$sw->geometry($config{SearchGeometry});
$sw->waitWindow;
}
##############################################################
# searchThumbsDelete
##############################################################
sub searchThumbsDelete {
# clean up memory - delete all found thumbnail photo objects
foreach (keys %searchthumbs) {
print "searchMetaInfo: deleting thumb $_\n" if $verbose;
$searchthumbs{$_}->delete if (defined $searchthumbs{$_});
delete $searchthumbs{$_};
}
}
##############################################################
# insertPic
##############################################################
sub insertPic($$) {
my $lb = shift;
my $dpic = shift;
my $thumb = getThumbFileName($dpic);
# create new row
$lb->add($dpic);
my $pic = basename($dpic);
if (-f $thumb) {
$searchthumbs{$thumb} = $lb->Photo(-file => $thumb, -gamma => $config{Gamma});
if (defined $searchthumbs{$thumb}) {
$lb->itemCreate($dpic, $lb->{thumbcol}, -image => $searchthumbs{$thumb}, -itemtype => "imagetext", -text => getThumbCaption($dpic), -style => $thumbS);
}
}
else {
$lb->itemCreate($dpic, $lb->{thumbcol}, -itemtype => "imagetext", -text => $pic, -style => $thumbS);
print "insertPic: no thumb for $dpic ($thumb)\n" if $verbose;
}
my $dir = dirname($dpic);
my $iptc;
$iptc = displayIPTC($dpic);
my $com = formatString($searchDB{$dpic}{COM}, 30); # format the comment for the list
my $exif = formatString($searchDB{$dpic}{EXIF}, 30); # format the EXIF info for the list
$iptc = formatString($iptc, 30); # format the IPTC info for the list
my $size = basename($dpic)."\n\n";
$size .= int($searchDB{$dpic}{SIZE}/1024)."kB\n" if (defined $searchDB{$dpic}{SIZE});
$size .= $searchDB{$dpic}{PIXX}.'x'.$searchDB{$dpic}{PIXY}."\n" if (defined $searchDB{$dpic}{PIXX});
$size .= buildDateTime($searchDB{$dpic}{MOD}) if (defined $searchDB{$dpic}{MOD});
$size .= "\nviewed ".$searchDB{$dpic}{POP}." times" if (defined $searchDB{$dpic}{POP});
$lb->itemCreate($dpic, $lb->{filecol}, -text => $size, -style => $fileS);
$lb->itemCreate($dpic, $lb->{iptccol}, -text => $iptc, -style => $iptcS);
$lb->itemCreate($dpic, $lb->{comcol}, -text => $com, -style => $comS);
$lb->itemCreate($dpic, $lb->{exifcol}, -text => $exif, -style => $exifS);
$lb->itemCreate($dpic, $lb->{dircol}, -text => $dir, -style => $dirS);
}
##############################################################
# makePattern - create a regex from windows like search patterns
# * for zero or more chars
# ? for exactly one char
# \* to search for the star sign (*)
# \? to search for a questionmark (?)
# . for a point (.)
##############################################################
sub makePattern {
my $pattern = shift;
$pattern =~ s/\(/\\(/g; # replace ( with \(
$pattern =~ s/\)/\\)/g; # replace ) with \)
$pattern =~ s/\[/\\[/g; # replace ( with \(
$pattern =~ s/\]/\\]/g; # replace ) with \)
$pattern =~ s/\{/\\{/g; # replace ( with \(
$pattern =~ s/\}/\\}/g; # replace ) with \)
$pattern =~ s/\./\\./g; # replace . with \. (a point)
$pattern =~ s/\\\*/\377/g; # replace \* with \377 (\377 is an unlikly char)
$pattern =~ s/\*/.*/g; # replace * with .* (zero or more chars)
$pattern =~ s/\377/\\*/g; # replace \377 with \* (the star iteself)
$pattern =~ s/\\\?/\377/g; # replace \? with \377
$pattern =~ s/\?/.{1}/g; # replace ? with .{1} (one char) must be after { -> \{
$pattern =~ s/\377/\\?/g; # replace \377 with \? (the questionmark iteself)
$pattern =~ s/\+/\\+/g; # replace + with \+
$pattern =~ s/\^/\\^/g; # replace ^ with \^
$pattern =~ s/\$/\\\$/g; # replace $ with \$
$pattern =~ s/\|/\\|/g; # replace | with \|
#print "makePattern: $pattern\n";
return $pattern;
}
##############################################################
# getMemoryUsage - get the actual memory usage of mapivi in Bytes
##############################################################
sub getMemoryUsage {
my $size = 0;
my $t = new Proc::ProcessTable;
foreach my $p (@{$t->table}) {
#if ($p->{pid} == $$) { # todo this would be the better way, but $p->{pid} is 0 on solaris
if ($p->{fname} eq "mapivi") {
$size = $p->{size};
last;
}
}
return $size;
}
##############################################################
# about - display some infos about the application
##############################################################
sub about {
my $title = "About Mapivi $version";
my @date = split / /, '$Date: 2006/10/31 03:20:58 $ ';
my @datum = split /\//, $date[1];
my $nrs = $config{NrOfRuns};
my $sec = time() - $^T;
my $min = 0;
my $hou = 0;
my $day = 0;
# some modula calculations
if ($sec > 59) { $min = int($sec / 60); $sec = $sec % 60; } # modulo
if ($min > 59) { $hou = int($min / 60); $min = $min % 60; }
if ($hou > 24) { $day = int($hou / 24); $hou = $hou % 24; }
my $uptime = sprintf "%d day(s) %02d:%02d:%02d", $day, $hou, $min, $sec;
my $perlversion = sprintf "%vd",$^V;
my $about = << "EOA";
MaPiVi - Martin\'s Picture Viewer and Organizer
A JPEG picture viewer with EXIF/IPTC/Comment support.
Mapivi Version: $version
Date of last change: $datum[2].$datum[1].$datum[0]
Mapivi config dir: $configdir
Author: Martin Herrmann
email:<Martin-Herrmann\@gmx.de>
www: $mapiviURL
download: http://sourceforge.net/projects/mapivi
You have used Mapivi $nrs times
Perl version: $perlversion
Perl/Tk version: $Tk::VERSION
Tcl/Tk version: $Tk::version
Tcl/Tk patch level: $Tk::patchLevel
Tk::JPEG version: $Tk::JPEG::VERSION
MetaData version: $Image::MetaData::JPEG::VERSION
Perl executable: $^X
System (OS): $^O
Process ID (PID): $$
Running since: $uptime
EOA
my $procTabAvail = (eval "require Proc::ProcessTable") ? 1 : 0 ;
my $mem = int(getMemoryUsage()/(1024*1024))."MB" if $procTabAvail;
$about .= " memory usage: ".$mem."\n" if $procTabAvail;
$about .= " OS type: ".$ENV{OS}."\n" if ($ENV{OS});
$about .= " OS: ".$ENV{PC_OS}."\n" if ($ENV{PC_OS});
$about .= " OS type: ".$ENV{OSTYPE}."\n" if ($ENV{OSTYPE});
$about .= " System name: ".$ENV{HOSTNAME}."\n" if ($ENV{HOSTNAME});
$about .= " System name: ".$ENV{COMPUTERNAME}."\n" if ($ENV{COMPUTERNAME});
$about .= " System type: ".$ENV{HOSTTYPE}."\n" if ($ENV{HOSTTYPE});
$about .= " # of processors: ".$ENV{NUMBER_OF_PROCESSORS}."\n" if ($ENV{NUMBER_OF_PROCESSORS});
$about .= " Processor: ".$ENV{CPU}."\n" if ($ENV{CPU});
$about .= " Processor: ".$ENV{PROCESSOR_ARCHITECTURE}."\n" if ($ENV{PROCESSOR_ARCHITECTURE});
$about .= " Processor type: ".$ENV{PROCESSOR_IDENTIFIER}."\n" if ($ENV{PROCESSOR_IDENTIFIER});
$about .= " Processor type: ".$ENV{MACHTYPE}."\n" if ($ENV{MACHTYPE});
$about .= " Processor rev.: ".$ENV{PROCESSOR_REVISION}."\n" if ($ENV{PROCESSOR_REVISION});
$about .= '
Mapivi is free software, if you want you may make a donation,
see http://herrmanns-stern.de/software/donations.shtml
Your donation of any amount will encourage me to continue the
development.';
$about .= "\n\n I am always happy to receive some feedback about Mapivi!\n";
showText($title, $about, WAIT, $mapiviiconfile);
}
##############################################################
# checkTrash
##############################################################
sub checkTrash {
my @files = getFiles($trashdir);
my $sum = 0;
foreach (@files) {
$sum += getFileSize("$trashdir/$_", NO_FORMAT); # get size in Bytes
}
my $msum = sprintf "%.1f", $sum/(1024*1024); # size in MB
return if ($msum < $config{MaxTrashSize});
my $dialog = $top->Dialog(-title => "Trash full!",
-text => "The trash contains $msum MB in ".scalar @files." files!",
-buttons => ["Do nothing", "Show me the trash", "Empty trash"]);
my $rc = $dialog->Show();
if ($rc eq "Do nothing") {
$top->focusForce;
return;
}
elsif ($rc eq "Show me the trash") {
openDirPost($trashdir);
$top->focusForce;
return;
}
elsif ($rc eq "Empty trash") {
emptyTrash();
}
else {
warn "this should never be reached!";
}
$top->focusForce;
}
##############################################################
# emptyTrash - remove all files from the trash
##############################################################
sub emptyTrash {
my @files = getFiles($trashdir);
# open window
my $win = $top->Toplevel();
$win->title('Empty trash?');
$win->iconimage($mapiviicon) if $mapiviicon;
my $w = int($top->screenwidth * 0.5);
my $h = int($top->screenheight * 0.90);
$win->geometry("${w}x${h}+0+0");
my $text = "loading ...";
$win->Label(-textvariable => \$text)->pack(-expand => 0, -fill => 'x');
my $tlb = $win->Scrolled("HList",
-header => 1,
-separator => ';', # todo here we hope that ; will never be in a directory or file name
-pady => 0,
-columns => 4,
-scrollbars => 'osoe',
-selectmode => 'extended',
-background => $config{ColorBG}, #8fa8bf
-width => 80,
-height => 30,
)->pack(-expand => 1, -fill => "both");
bindMouseWheel($tlb);
$tlb->header('create', 0, -text => 'Thumbnail', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
$tlb->header('create', 1, -text => 'Name', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
$tlb->header('create', 2, -text => 'Size', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
$tlb->header('create', 3, -text => 'Original folder', -headerbackground => $config{ColorEntry}, -borderwidth => $config{Borderwidth});
my $butF = $win->Frame()->pack(-fill =>'x', -padx => 3, -pady => 3);
$butF->Button(-text => 'Empty trash',
-command => sub {
my @sellist = $tlb->info('selection');
print "sel: $_\n" foreach (@sellist);
foreach (@files) {
removeFile("$trashdir/$_");
}
updateThumbsPlus() if ($actdir eq $trashdir);
$win->destroy;
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$butF->Button(-text => 'Remove selected',
-command => sub {
my @sellist = $tlb->info('selection');
foreach (@sellist) {
removeFile($_);
$tlb->delete('entry', $_);
}
#updateThumbsPlus() if ($actdir eq $trashdir);
#$win->destroy;
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$butF->Button(-text => 'Restore selected',
-command => sub {
my @sellist = $tlb->info('selection');
my $error = '';
foreach my $dpic (@sellist) {
# if original dir (odir) is defined and not unknown and the folder exists, we move the picture back
if ($searchDB{$dpic}{odir} and
($searchDB{$dpic}{odir} ne 'unknown') and
( -d $searchDB{$dpic}{odir})) {
my @list; # we need a dummy list here with one element
push @list, $dpic;
#print "moving $dpic to $searchDB{$dpic}{odir}\n";
movePics($searchDB{$dpic}{odir}, $tlb, @list);
#$tlb->delete('entry', $dpic) unless (-f $dpic);
}
else {
$error .= "Could not restore $dpic (no folder information available)\n";
}
}
if ($error ne '') {
$error = "Errors while restoring selected pictures:\n$error";
showText("Errors", $error, NO_WAIT);
}
#updateThumbsPlus() if ($actdir eq $trashdir);
#$win->destroy;
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
my $Xbut = $butF->Button(-text => 'Close',
-command => sub {
$win->destroy();
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$win->bind('<Control-q>', sub { $Xbut->invoke; });
$win->bind('<Key-Escape>', sub { $Xbut->invoke; });
$win->bind('<Control-a>', sub { selectAll($tlb); } );
$win->bind('<ButtonPress-2>', sub {
return if (!$tlb->info('children'));
my $dpic = getNearestItem($tlb);
showPicInOwnWin($dpic); });
$win->Popup(-popover => 'cursor');
repositionWindow($win);
my $sum = 0;
my %thumbs;
foreach my $pic (sort { uc($a) cmp uc($b); } @files) {
my $dpic = "$trashdir/$pic";
$sum += getFileSize($dpic, NO_FORMAT); # get size in Bytes
my $size = getFileSize($dpic, FORMAT);
my $thumb = getThumbFileName($dpic);
my $odir = 'unknown';
$odir = $searchDB{$dpic}{odir} if ($searchDB{$dpic}{odir});
$tlb->add($dpic);
if (-f $thumb) {
$thumbs{$thumb} = $top->Photo(-file => $thumb, -gamma => $config{Gamma});
if (defined $thumbs{$thumb}) {
$tlb->itemCreate($dpic, 0, -image => $thumbs{$thumb}, -itemtype => 'imagetext', -style => $thumbS);
}
}
$tlb->itemCreate($dpic, 1, -text => $pic, -style => $comS);
$tlb->itemCreate($dpic, 2, -text => $size, -style => $iptcS);
$tlb->itemCreate($dpic, 3, -text => $odir, -style => $comS);
}
my $msum = sprintf "%.1f", $sum/(1024*1024); # size in MB
$text = "Please press Ok to delete all files ($msum MB in ".scalar @files." files) in the trash.\nThere is no undelete!\n\nPath: $trashdir";
$win->waitWindow;
foreach (keys %thumbs) { $thumbs{$_}->delete if (defined $thumbs{$_}); } # free memory
}
##############################################################
# setFromTo - dialog to set search from and search to date
##############################################################
sub setFromTo {
# open window
my $win = $top->Toplevel();
$win->title('Set from/to search dates');
$win->iconimage($mapiviicon) if $mapiviicon;
my @fdate = split /\./, $config{SearchDateStart};
my $from_day = $fdate[0];
my $from_month = $fdate[1];
my $from_year = $fdate[2];
my @tdate = split /\./, $config{SearchDateEnd};
my $to_day = $tdate[0];
my $to_month = $tdate[1];
my $to_year = $tdate[2];
# ranges
my (@day, @month, @year);
push @day, sprintf "%02d",$_ for ( 1 .. 31);
push @month, sprintf "%02d",$_ for ( 1 .. 12);
push @year, sprintf "%4d", $_ for ( 1990 .. 2010);
# it is still possible to add other year numbers in the search window itself!
my $f1 = $win->Frame()->pack(-fill =>'x', -padx => 3, -pady => 3);
$f1->Label(-text => 'from', -width => 4)->pack(-side => "left", -anchor => 'w');
$f1->Optionmenu(-variable => \$from_day, -textvariable => \$from_day, -options => \@day)->pack(-side => "left", -anchor => 'w');
$f1->Optionmenu(-variable => \$from_month, -textvariable => \$from_month, -options => \@month)->pack(-side => "left", -anchor => 'w');
$f1->Optionmenu(-variable => \$from_year, -textvariable => \$from_year, -options => \@year)->pack(-side => "left", -anchor => 'w');
$f1->Button(-text => 'today', -command => sub {
my (undef,undef,undef,$d,$M,$y,undef,undef,undef,undef) = localtime(time());
$y += 1900;
$M++;
$from_day = sprintf "%02d", $d;
$from_month = sprintf "%02d", $M;
$from_year = sprintf "%4d", $y;})->pack(-side => "left", -anchor => 'w');
my $f2 = $win->Frame()->pack(-fill =>'x', -padx => 3, -pady => 3);
$f2->Label(-text => 'to', -width => 4)->pack(-side => "left", -anchor => 'w');
$f2->Optionmenu(-variable => \$to_day, -textvariable => \$to_day, -options => \@day)->pack(-side => "left", -anchor => 'w');
$f2->Optionmenu(-variable => \$to_month, -textvariable => \$to_month, -options => \@month)->pack(-side => "left", -anchor => 'w');
$f2->Optionmenu(-variable => \$to_year, -textvariable => \$to_year, -options => \@year)->pack(-side => "left", -anchor => 'w');
$f2->Button(-text => 'today', -command => sub {
my (undef,undef,undef,$d,$M,$y,undef,undef,undef,undef) = localtime(time());
$y += 1900;
$M++;
$to_day = sprintf "%02d", $d;
$to_month = sprintf "%02d", $M;
$to_year = sprintf "%4d", $y;})->pack(-side => "left", -anchor => 'w');
my $butF = $win->Frame()->pack(-fill =>'x', -padx => 3, -pady => 3);
my $OKB =
$butF->Button(-text => 'OK',
-command => sub {
$config{SearchDateStart} = "$from_day.$from_month.$from_year";
$config{SearchDateEnd} = "$to_day.$to_month.$to_year";
$win->destroy;
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
my $Xbut = $butF->Button(-text => 'Cancel',
-command => sub {
$win->destroy();
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$win->bind('<Control-q>', sub { $Xbut->invoke; });
$win->bind('<Key-Escape>', sub { $Xbut->invoke; });
$win->bind('<Control-x>', sub { $OKB->invoke; });
$win->Popup(-popover => 'cursor');
repositionWindow($win);
$win->waitWindow;
}
##############################################################
# showFile
##############################################################
sub showFile {
my $file = shift;
return if (!-f $file);
my $fileH;
if (!open($fileH, "<$file")) {
warn "Sorry, I couldn't open the file $file: $!";
return;
}
my $buffer;
read $fileH, $buffer, 32768;
close($fileH);
$buffer =~ s/\r//g;
showText(basename($file), $buffer, WAIT) if ($buffer ne "");
}
##############################################################
# showText
##############################################################
sub showText {
my $title = shift;
my $text = shift;
my $wait = shift; # WAIT = wait for the window to close or NO_WAIT
my $thumbnail = shift; # optional
my $icon;
$text = " " if ((!defined $text) or ($text eq ""));
# open window
my $win = $top->Toplevel();
$win->withdraw;
$win->title($title);
$win->iconname($title);
$win->iconimage($mapiviicon) if $mapiviicon;
my $xBut =
$win->Button(-text => "Close",
-command => sub {
$icon->delete if $icon;
$win->withdraw();
$win->destroy();
},
)->pack(-fill => 'x');
# 50 ways to leave your window ;)
$win->bind('<Key-Escape>' , sub {$xBut->invoke;});
$win->bind('<Key-q>' , sub {$xBut->invoke;});
$win->protocol("WM_DELETE_WINDOW" => sub {$xBut->invoke;} );
my $f = $win->Frame()->pack(-fill => 'both', -expand => "1");
my $fl = $f->Frame()->pack(-anchor => "n", -side => "left");
my $fr = $f->Frame()->pack(-anchor => "n", -side => "left", -fill => 'both', -expand => "1");
if ((defined $thumbnail) and (-f $thumbnail)) {
$icon = $win->Photo(-file => "$thumbnail", -gamma => $config{Gamma});
if ($icon) {
$fl->Label(-image => $icon, -bg => $config{ColorBG}, -relief => "sunken",
)->pack(-padx => 1, -pady => 2);
}
}
# determine the height of the textbox by counting the number of lines
my $height = ($text =~ tr/\n//);
$height += 3;
$height = 50 if ($height > 50); # not to big, we have scrollbars
my $rotext = $fr->Scrolled("ROText",
-scrollbars => 'oe',
-wrap => 'word',
-tabs => '4',
-width => 90,
-height => $height,
)->pack(-fill => 'both', -expand => "1");
$rotext->insert('end', "$text");
bindMouseWheel($rotext);
$xBut->focus;
$win->Popup;
repositionWindow($win);
$win->waitWindow if ($wait == WAIT);
}
##############################################################
# exportFilelist
##############################################################
sub exportFilelist {
my @sellist = $picLB->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
my ($pic, $dpic);
my $addPath = 0;
my $useQuotes = 0;
# open window
my $myDiag = $top->Toplevel();
$myDiag->title("Export file list");
$myDiag->iconimage($mapiviicon) if $mapiviicon;
$myDiag->Label(-text => "Write a filelist containing the ".scalar @sellist." selected pictures",
-bg => $config{ColorBG}
)->pack(-fill => 'x', -padx => 3, -pady => 3);
labeledEntryButton($myDiag,'top',37,"path/name of file list",'Set',\$config{PicListFile});
$myDiag->Checkbutton(-variable => \$addPath, -text => "add the complete path to every file")->pack(-anchor=>'w');
$myDiag->Checkbutton(-variable => \$useQuotes, -text => "add quotes around each file")->pack(-anchor=>'w');
my $ButF =
$myDiag->Frame()->pack(-fill =>'x', -padx => 3, -pady => 3);
my $OKB =
$ButF->Button(-text => 'OK',
-command => sub {
if (-f $config{PicListFile}) {
my $rc =
$myDiag->messageBox(-icon => 'warning', -message => "file $config{'PicListFile'} exist. Ok to overwrite?",
-title => "Export file list", -type => 'OKCancel');
return if ($rc !~ m/Ok/i);
}
my $exfile;
if (!open($exfile, ">$config{'PicListFile'}")) {
warn "exportFilelist: Couldn't open $config{'PicListFile'}: $!";
return;
}
foreach $dpic (@sellist) {
$pic = basename($dpic);
print $exfile "\"" if $useQuotes;
print $exfile "$actdir/" if $addPath;
print $exfile "$pic";
print $exfile "\"" if $useQuotes;
print $exfile ", ";
}
close $exfile;
$myDiag->withdraw();
$myDiag->destroy();
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
#$balloon->attach($OKB, -msg => "You can press Control-x to close the dialog");
$ButF->Button(-text => 'Cancel',
-command => sub {
$myDiag->withdraw();
$myDiag->destroy();
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$myDiag->Popup(-popover => 'cursor');
repositionWindow($myDiag);
$myDiag->waitWindow;
$userinfo = "ready!"; $userInfoL->update;
}
##############################################################
# GIMPedit
##############################################################
sub GIMPedit {
my @sellist = $picLB->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
return unless askSelection(\@sellist, 10, "GIMP");
my ($pic, $dpic, $i, $exifthumb);
if ($EvilOS) {
return if (!checkExternProgs("GIMPedit", "gimp-win-remote"));
}
else {
if (!checkExternProgs("GIMPedit", "gimp-remote")){
$dpic = $sellist[0];
$pic = basename($dpic);
my $rc = $top->messageBox(-icon => "question",
-message => "Should Mapivi start a new GIMP with the first selected picture ($pic)?\nEXIF info will not be saved!\nUse Edit->EXIF info->save first!",
-title => "Open picture with GIMP", -type => 'OKCancel');
return if ($rc !~ m/Ok/i);
my $command = "gimp \"$dpic\" 2>&1 1>/dev/null &";
(system "$command") == 0 or warn "$command failed: $!";
return;
}
}
EXIFsave() if $config{saveEXIFforEdit};
$i = 0;
foreach $dpic (@sellist) {
$i++;
$userinfo = "opening picture in GIMP ($i/".scalar @sellist.")"; $userInfoL->update;
# check if file is a link and get the real target
next if (!getRealFile(\$dpic));
my $command = "gimp-remote -n \"$dpic\" ";
#$command = "gimp-win-remote \"$dpic\" " if $EvilOS; # GIMP <= 2.0
$command = "gimp-win-remote gimp-2.2.exe \"$dpic\" " if $EvilOS; # GIMP > 2.0
$command .= "2>&1 1>/dev/null &" if (!$EvilOS);
(system "$command") == 0 or warn "$command failed: $!";
#execute($command); # does not work for Windows
}
$top->after(800, sub { $userinfo = "ready!"; $userInfoL->update; });
}
##############################################################
# getSelection - get the selected items from a Canvas or a HList
##############################################################
sub getSelection {
my $widget = shift;
my @sellist;
if (ref($widget) eq 'Tk::Canvas') {
my @sel = $widget->find('withtag', 'THUMBSELECT_MH');
foreach my $id (@sel) { push @sellist, get_path_from_id($id); }
}
else {
@sellist = $widget->info('selection');
}
return @sellist;
}
##############################################################
# openPicInViewer
##############################################################
sub openPicInViewer {
my $lb = shift; # the reference to the active listbox widget
my @sellist = getSelection($lb);
return unless checkSelection($top, 1, 0, \@sellist);
my $maxnr = 20;
if (!$config{ExtViewerMulti} and (@sellist > $maxnr)) {
my $rc = $lb->messageBox(-icon => "question",
-message => "You have selected more than $maxnr pictures.\nPlease confirm to start ".scalar @sellist." pictures viewer processes.\nPlease press Ok to continue.",
-title => "Start a lot of viewers?", -type => 'OKCancel');
return if ($rc !~ m/Ok/i);
}
my ($dpic, $i, $exifthumb, $piclist);
$i = 0;
foreach $dpic (@sellist) {
$i++;
$userinfo = "opening picture in viewer ($i/".scalar @sellist.")"; $userInfoL->update;
increasePicPopularity($dpic);
updateOneRow($dpic, $lb) if (($config{trackPopularity}) and (ref($lb) ne 'Tk::Canvas'));
$dpic =~ s/\//\\/g if $EvilOS; # windows needs backslashes
if ($config{ExtViewerMulti}) {
$piclist .= "\"$dpic\" ";
}
else {
my $command = $config{ExtViewer}." \"$dpic\" ";
# instead of the & for UNIX windows needs a "start" in front of the application to run in the background
if ($EvilOS) {
$command = "start $command";
}
else {
$command .= "2>&1 1>/dev/null &";
}
(system "$command") == 0 or warn "$command failed: $!";
#execute($command); this is no good choice, because it waits for the viewer to finish
}
}
if ($config{ExtViewerMulti}) {
my $command = $config{ExtViewer}." $piclist";
# instead of the & for UNIX windows needs a "start" in front of the application to run in the background
if ($EvilOS) {
$command = "start $command";
}
else {
$command .= "2>&1 1>/dev/null &";
}
(system "$command") == 0 or warn "$command failed: $!";
}
$top->after(800, sub { $userinfo = "ready!"; $userInfoL->update; });
}
##############################################################
# setBackground - set the current picture as desktop background
##############################################################
sub setBackground {
my @sellist = $picLB->info('selection');
if (@sellist != 1) {
$top->messageBox(-icon => 'warning', -message => "Please select exactly one picture.",
-title => "set desktop background", -type => 'OK');
return;
}
my $dpic = $sellist[0];
my $pic = basename($dpic);
$userinfo = "setting $pic as desktop background ..."; $userInfoL->update;
# check if file is a link and get the real target
next if (!getRealFile(\$dpic));
my $command = $config{ExtBGApp}." \"$dpic\" ";
execute($command);
$userinfo = "ready!"; $userInfoL->update;
}
##############################################################
# identifyPic - display the output of identify
##############################################################
sub identifyPic {
return if (!checkExternProgs("identifyPic", "identify"));
my @sellist = $picLB->info('selection');
if (@sellist != 1) {
$top->messageBox(-icon => 'warning', -message => "Please select exactly one picture.",
-title => "Show picture infos", -type => 'OK');
return;
}
my $dpic = $sellist[0];
my $pic = basename($dpic);
my $thumb = getThumbFileName($dpic);
$userinfo = "getting infos about $pic ..."; $userInfoL->update;
# check if file is a link and get the real target
next if (!getRealFile(\$dpic));
my $command = "identify -verbose \"$dpic\" ";
my $buffer = `$command`;
showText("Informations about $pic", $buffer, NO_WAIT, $thumb);
$userinfo = "ready!"; $userInfoL->update;
}
##############################################################
# showSegments
##############################################################
sub showSegments {
my @sellist = $picLB->info('selection');
if (@sellist != 1) {
$top->messageBox(-icon => 'warning', -message => "Please select exactly one picture.",
-title => "Show segments", -type => 'OK');
return;
}
my $dpic = $sellist[0];
my $pic = basename($dpic);
my $thumb = getThumbFileName($dpic);
# check if file is a link and get the real target
next if (!getRealFile(\$dpic));
my $meta = getMetaData($dpic); # get all segments
return unless ($meta);
my $segments = $meta->{segments};
my $win = $top->Toplevel();
$win->withdraw;
$win->title("JPEG segments of $pic");
$win->iconimage($mapiviicon) if $mapiviicon;
my $xBut = $win->Button(-text => "Close", -command =>
sub { $win->destroy(); })->pack(-fill => 'x');
foreach (@$segments) {
my $segInfo = $_->get_description();
my $segname = $_->{name};
my $title = sprintf "%-16s %8s Bytes",$segname,$_->size();
$win->Button(-text => $title, -anchor => "nw",
-command => sub {
showText("Segment $segname of $pic", $segInfo, NO_WAIT);
})->pack(-fill => 'x');
}
$xBut->focus;
$win->Popup;
}
##############################################################
# showHistogram - display the histogram of a picture
##############################################################
sub showHistogram($) {
return if (!checkExternProgs("showHistogram", "convert"));
my $lb = shift;
my @sellist = $lb->info('selection');
if (@sellist != 1) {
$lb->messageBox(-icon => 'warning', -message => "Please select exactly one picture.",
-title => "Show picture histogram", -type => 'OK');
return;
}
my $dpic = $sellist[0];
my $pic = basename($dpic);
my $thumb = getThumbFileName($dpic);
$userinfo = "building histogram of $pic ..."; $userInfoL->update;
# check if file is a link and get the real target
next if (!getRealFile(\$dpic));
my $hist = getHistogram($lb, $dpic);
if (($hist eq "") or (!-f $hist)) {
$userinfo = "Error building histogram of $pic!"; $userInfoL->update;
return;
}
$userinfo = "ready!"; $userInfoL->update;
my $but = "Save histogram";
my $rc = myPicDialog("Histogram", "Histogram of $pic", $but, $thumb, $hist);
if ($rc eq $but) {
my $file = $lb->FileSelect(-title => "Save histogram of $pic (GIF format)",
-directory => $actdir,
-initialfile => basename($hist),
-create => 1,
-width => 30, -height => 30)->Show;
if ((defined $file) and ($file ne "")) {
if (mycopy($hist, $file, ASK_OVERWRITE)) { # ask before overwrite
$userinfo = "histogram saved!";
}
else {
$userinfo = "error while saving histogram";
}
}
}
removeFile($hist);
}
##############################################################
# getHistogram - generate a histogram of the given picture
# returns the path and file to the histogram
# file or "" if no success
##############################################################
sub getHistogram($$) {
my $widget = shift;
my $dpic = shift;
my $rc = "";
return $rc unless (-f $dpic);
my $pic = basename($dpic);
# temp PNM or GIF file in the trash directory
my $hist = "$trashdir/histogram.pnm"; # exchange pnm with gif if needed
if (-f $hist) {
my $urc = $top->messageBox(-icon => 'question',
-message => "Histgram file $hist exists already.\nShould I overwrite it?",
-title => "Overwrite?", -type => 'OKCancel');
return $rc if ($urc !~ m/Ok/i);
}
# with the -comment "" option the file size of the histogram shrinks from ~1MB to ~5kB
# because convert saves the complete color table in the comment (at least when GIF format is used)
my $command = "convert \"$dpic\" HISTOGRAM:- | convert -comment \"\" - \"$hist\" ";
$widget->Busy;
execute($command);
$widget->Unbusy;
$rc = $hist if (-f $hist);
return $rc;
}
##############################################################
# showHistogram2 - display the histogram of a picture with builtin histogram function
##############################################################
sub showHistogram2($) {
return if (!checkExternProgs("showHistogram", "convert"));
my $lb = shift;
my @sellist = $lb->info('selection');
if (@sellist != 1) {
$lb->messageBox(-icon => 'warning', -message => "Please select exactly one picture.",
-title => "Show picture histogram", -type => 'OK');
return;
}
my $dpic = $sellist[0];
my $pic = basename($dpic);
my $thumb = getThumbFileName($dpic);
$userinfo = "building histogram of $pic ..."; $userInfoL->update;
# check if file is a link and get the real target
next if (!getRealFile(\$dpic));
buildHistogram($dpic);
}
##############################################################
# buildHistogram
##############################################################
sub buildHistogram {
my $dpic = shift;
my $photo = $top->Photo(-file => $dpic); # no gamma correction here!
my (@red, @green, @blue);
foreach (0 .. 255) { $red[$_] = 0; }
foreach (0 .. 255) { $green[$_] = 0; }
foreach (0 .. 255) { $blue[$_] = 0; }
my $w = $photo->width;
my $h = $photo->height;
# if the picture is to big, it will take very long, so we shrink them first.
# some color information may be lost this way!
my $subsample = int($w*$h/500000);
print "$dpic: subsample: $subsample\n" if $verbose;
if ($subsample > 1) {
my $zoomed = $top->Photo;
$zoomed->blank;
$zoomed->copy($photo, -zoom => 1);
$photo->delete;
$photo = undef;
$photo = $top->Photo;
$photo->copy($zoomed, -subsample => $subsample);
$zoomed->delete;
$zoomed = undef;
$w = $photo->width;
$h = $photo->height;
print "$dpic new size: $w x $h\n" if $verbose;
}
if ($w <= 0 or $h <= 0) { warn "buildHistogram: wrong size: $w $h\n"; return; }
#stopWatchStart();
my $pw = progressWinInit($top, "Calculating histogram of ".$w*$h." pixels");
# get and add rgb values of each pixel
foreach my $x (0 .. $w-1) {
last if progressWinCheck($pw);
progressWinUpdate($pw, "calculating column ($x/$w) ...", $x, $w);
foreach my $y (0 .. $h-1) {
my @rgb = $photo->get($x,$y);
$red[$rgb[0]]++;
$green[$rgb[1]]++;
$blue[$rgb[2]]++;
}
}
progressWinEnd($pw);
# find the maximal value
my $max = 0;
foreach (0 .. 255) { $max = $red[$_] if ($red[$_] > $max);
$max = $green[$_] if ($green[$_] > $max);
$max = $blue[$_] if ($blue[$_] > $max); };
# open window
my $win = $top->Toplevel();
$win->title("Histogram of $dpic");
$win->iconimage($mapiviicon) if $mapiviicon;
$h = 255; # height is now the height of the canvas
my $canvas = $win->Canvas(-width => 256,
-height => $h+1,
-background => 'black',
-relief => 'sunken',
-bd => $config{Borderwidth})->pack(-side => 'top', -padx => 3, -pady => 3);
# draw a line for red, green and blue
foreach my $x (0 .. 255) {
$canvas->createLine( $x, $h, $x, $h-int($h*$red[$x]/$max), -fill => 'red');
$canvas->createLine( $x, $h, $x, $h-int($h*$green[$x]/$max), -fill => 'green', -stipple => 'transp2');
$canvas->createLine( $x, $h, $x, $h-int($h*$blue[$x]/$max), -fill => 'blue', -stipple => 'transp3');
}
$win->Button(-text => "Close",
-command => sub {
$win->destroy();
}
)->pack(-side => 'top',-expand => 1,-fill => 'x',-padx => 3,-pady => 3);
$win->bind('<Key-Escape>', sub { $win->destroy; } );
$win->Popup;
#stopWatchStop("Histogram of $dpic");
}
##############################################################
# checkSelection
##############################################################
sub checkSelection {
my $win = shift;
my $min = shift;
my $max = shift; # use 0 for any number
my $listref = shift;
my $plural = '';
$plural = 's' if ($min > 1);
if (($min == $max) and (@$listref != $min)) {
$win->messageBox(-icon => 'warning', -message => "Please select exactly $min item$plural!",
-title => "Wrong selection", -type => 'OK');
return 0;
}
if (@$listref < $min) {
$win->messageBox(-icon => 'warning', -message => "Please select at least $min item$plural!",
-title => "Wrong selection", -type => 'OK');
return 0;
}
if (($max != 0) and (@$listref > $max)) {
$win->messageBox(-icon => 'warning', -message => "Please select not more than $max items!",
-title => "Wrong selection", -type => 'OK');
return 0;
}
return 1;
}
##############################################################
# askSelection
##############################################################
sub askSelection {
my $listRef = shift;
my $max = shift;
my $text = shift;
# ask only for more than $max pictures
return 1 if (@{$listRef} < $max);
my $rc = $top->messageBox(-icon => "question",
-message => "You have selected ".scalar @{$listRef}." pictures. This function will open an $text window for each selected picture.\nPlease press Ok to continue.",
-title => "Show $text of ".scalar @{$listRef}." pictures",
-type => 'OKCancel');
if ($rc =~ m/Ok/i) {
return 1;
}
return 0;
}
##############################################################
# indexPrint - generate indexPrints/montages of the selected
# pictures
##############################################################
my $indexW; # index dialog window
my $indexPicsT;
my $indexNrT;
my $sizeT;
sub indexPrint {
return if (!checkExternProgs("indexPrint", "montage"));
if (Exists($indexW)) {
$indexW->deiconify;
$indexW->raise;
return;
}
my $pic_list_ref = shift;
#foreach (@$pic_list_ref) { print "list::: $_\n"; }
my @sellist = @$pic_list_ref;
return unless checkSelection($top, 1, 0, \@sellist);
my $index = $sellist[0];
$index = dirname($sellist[0]).'/'.findNewName($index);
if (-f $index) { # just for safety, we don't want to overwrite something
warn "$index exists: aborting - this should never happen!!!\n";
return;
}
# get size of first pic
my ($pic0x, $pic0y) = getSize($sellist[0]);
# open window
$indexW = $top->Toplevel();
#$indexW->grab();
$indexW->title("montage/index prints of ".scalar @sellist." pictures");
$indexW->iconimage($mapiviicon) if $mapiviicon;
my $w = 26;
labeledEntry($indexW, 'top', $w, "file name of index print", \$index);
labeledEntry2($indexW, 'top', 20, 4, "Columns (x)",\$config{indexCols}, "Rows (y)",\$config{indexRows});
labeledEntry2($indexW, 'top', 20, 4, "x distance", \$config{indexDisX}, "y distance", \$config{indexDisY});
my $sizeF = $indexW->Frame(-relief => "raised")->pack(-expand => 1, -fill => 'x', -padx => 3);
labeledEntry2($sizeF, 'top', 20, 4, "Picture width", \$config{indexPicX}, "Picture height", \$config{indexPicY});
$sizeF->Button(-text => "insert picture size (${pic0x}x$pic0y)", -command => sub { $config{indexPicX} = $pic0x; $config{indexPicY} = $pic0y; })->pack(-anchor => 'e', -padx => 3, -pady => 3);
labeledEntryColor($indexW,'top',$w,"Background color",'Set',\$config{indexBG});
my $lF = $indexW->Frame(-relief => "raised")->pack(-expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$lF->Checkbutton(-variable => \$config{indexLabel}, -text => "add a label to each picture")->pack(-anchor=>'w');
my $labstr =
labeledEntry($lF, 'top', $w, "label string", \$config{indexLabelStr});
$balloon->attach($labstr, -msg => "%b file size\n%c comment\n%d directory\n%e filename extention\n%f filename\n%h height\n%i input filename\n%l label\n%m magick\n%n number of scenes\n%o output filename\n%p page number\n%q quantum depth\n%s scene number\n%t top of filename\n%u unique temporary filename\n%w width\n%x x resolution\n%y y resolution");
my $fss = labeledScale($lF, 'top', $w, "label font size", \$config{indexFontSize}, 0, 50, 1);
$balloon->attach($fss, -msg => "The font size of the labels.\nIf you set this to 0, montage will\ntry to choose a appropriate size.");
my $ibF = $indexW->Frame(-relief => "raised")->pack(-expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$ibF->Checkbutton(-variable => \$config{indexInnerBorder}, -text => "add a border around each picture")->pack(-anchor=>'w');
labeledScale($ibF, 'top', $w, "Border width", \$config{indexInnerBorderWidth}, 1, 1000, 1);
labeledEntryColor($ibF, 'top', $w, "Border color",'Set',\$config{indexInnerBorderColor});
my $obF = $indexW->Frame(-relief => "raised")->pack(-expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$obF->Checkbutton(-variable => \$config{indexBorder}, -text => "add a border around the index print")->pack(-anchor=>'w');
labeledScale($obF, 'top', $w, "Border width", \$config{indexBorderWidth}, 1, 1000, 1);
labeledEntryColor($obF, 'top', $w, "Border color",'Set',\$config{indexBorderColor});
my $qS = labeledScale($indexW, 'top', $w, "Quality of index picture", \$config{PicQuality}, 10, 100, 1);
qualityBalloon($qS);
buttonComment($indexW, 'top');
calcIndexInfo( scalar @sellist );
my $f = $indexW->Frame(-bd => $config{Borderwidth}, -relief => 'groove',)->pack(-expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$f->Label(-textvar => \$indexPicsT, -bg => $config{ColorBG})->pack(-anchor => 'w');
$f->Label(-textvar => \$indexNrT, -bg => $config{ColorBG})->pack(-anchor => 'w');
$f->Label(-textvar => \$sizeT, -bg => $config{ColorBG})->pack(-anchor => 'w');
$f->Button(-text => "update info", -command => sub { calcIndexInfo(scalar @sellist); } )->pack();
my $ButF = $indexW->Frame()->pack(-fill =>'x', -padx => 3, -pady => 3);
my $OKB;
$OKB =
$ButF->Button(-text => 'OK',
-command => sub {
my $nr = calcIndexInfo( scalar @sellist ); # we need the nr of index prints here
if ($nr == 1) {
# just one index print, we leave the name
if (-f $index) {
my $rc =
$indexW->messageBox(-icon => 'warning', -message => "file $index exist. Please press Ok to overwrite.",
-title => "File exists!", -type => 'OKCancel');
return if ($rc !~ m/Ok/i);
}
}
else {
# there is more than one index print, montage will name them xxx01.jpg ...
$index =~ /(.*)(\.jp(g|eg))/i; # split (we need base name and suffix)
$index = "$1-%02d$2";
for (1 .. $nr) {
my $name = sprintf "%s-%02d%s", $1, $_, $2;
if (-f $name) {
my $rc =
$indexW->messageBox(-icon => 'warning', -message => "file $name exist. Please press Ok to overwrite.",
-title => "File exists!", -type => 'OKCancel');
return if ($rc !~ m/Ok/i);
}
}
}
$indexW->destroy(); # close index window
$userinfo = "building index prints of ".scalar @sellist." pictures ..."; $userInfoL->update;
my $command = "montage ";
if ($config{indexInnerBorder}) {
$command .= "-bordercolor \"".$config{indexInnerBorderColor}."\" ";
$command .= "-border ".$config{indexInnerBorderWidth}.'x'.$config{indexInnerBorderWidth}." ";
}
$command .= "-label \"$config{'indexLabelStr'}\" " if $config{indexLabel};
$command .= "-font \"-*-courier-medium-r-*-*-".$config{indexFontSize}."-*-*-*-*-*-iso8859-*\" " if ($config{indexLabel} and ($config{indexFontSize} > 0));
#$command .= "-pointsize ".$config{indexFontSize}." " if $config{indexLabel};
$command .= "-background \"$config{'indexBG'}\" -tile $config{'indexCols'}x$config{'indexRows'} -filter Lanczos -geometry $config{'indexPicX'}x$config{'indexPicY'}+$config{'indexDisX'}+$config{'indexDisY'} ";
my $pic;
# add the selected pictures to $command
foreach my $dpic (@sellist) {
$command .= "\"$dpic\" ";
}
# if there is a second process step (border) we use the lossless MIFF format
my $tmpfile = "$trashdir/indexTmpFile.miff";
if (-f $tmpfile) { warn "tmp file $tmpfile exists! Mapivi tries to remove it"; return unless removeFile($tmpfile); }
if ($config{indexBorder}) {
$command .= "\"$tmpfile\"";
}
else {
$command .= "-quality ".$config{PicQuality}." ";
$command .= "\"$index\"";
}
print "$command\n" if $verbose;
$top->Busy;
if ($EvilOS) {
(system $command) == 0 or warn "execute: $command failed: $!";
}
else {
execute($command);
}
# for win32 we need to wait for this process to finish
if ($config{indexBorder}) {
$command = "convert -bordercolor \"".$config{indexBorderColor}."\" ";
$command .= "-border ".$config{indexBorderWidth}.'x'.$config{indexBorderWidth}." ";
$command .= "-quality ".$config{PicQuality}." ";
$command .= "\"$tmpfile\" ";
$command .= "\"$index\"";
print "$command\n" if $verbose;
if ($EvilOS) { # do not use bgrun for windows
(system $command) == 0 or warn "execute: $command failed: $!";
}
else {
execute($command);
}
}
$top->Unbusy;
removeFile($tmpfile) if (-f $tmpfile);
if ($config{AddMapiviComment}) {
addCommentToPic("Picture made with Mapivi ($mapiviURL)", $index, NO_TOUCH);
}
$userinfo = "ready!"; $userInfoL->update;
if ($nr == 1) {
# for one index we insert it in the listbox
generateOneThumb($index);
# insert index in listbox
addOneRow($picLB, $index, 1, $sellist[0]);
}
else {
# for several index we need a (slower) update
updateThumbs();
}
showPic($index);
})->pack(-side => 'left',-expand => 1,-fill => 'x',-padx => 3,-pady => 3);
$ButF->Button(-text => 'Cancel',
-command => sub {
$indexW->destroy();
}
)->pack(-side => 'left',-expand => 1,-fill => 'x',-padx => 3,-pady => 3);
$indexW->bind('<Key-Escape>', sub {$indexW->destroy;});
$indexW->Popup;
$indexW->waitWindow;
}
##############################################################
# calcIndexInfo
##############################################################
sub calcIndexInfo {
my $nrOfSel = shift;
my $indexPics = $config{indexRows} * $config{indexCols};
$indexPicsT = "One index print holds $indexPics pictures.";
my $indexNr = int($nrOfSel/$indexPics);
$indexNr++ if (($nrOfSel % $indexPics) != 0);
$indexNrT = "With $nrOfSel pictures this results in $indexNr index pictures.";
my $sizex = $config{indexCols} * ($config{indexPicX} + (2*$config{indexDisX}));
my $sizey = $config{indexRows} * ($config{indexPicY} + (2*$config{indexDisY}));
if ($config{indexBorder}) {
$sizex = $sizex + 2 * $config{indexBorderWidth};
$sizey = $sizey + 2 * $config{indexBorderWidth};
}
if ($config{indexInnerBorder}) {
$sizex = $sizex + $config{indexCols} * 2 * $config{indexInnerBorderWidth};
$sizey = $sizey + $config{indexRows} * 2 * $config{indexInnerBorderWidth};
}
$sizeT = "One index will be ca. ${sizex}x${sizey} pixels.";
return ($indexNr);
}
##############################################################
# fisher_yates_shuffle - shuffle an array randomly
##############################################################
sub fisher_yates_shuffle {
my $deck = shift; # $deck is a reference to an array
my $i = @$deck;
while ($i--) {
my $j = int rand ($i+1);
@$deck[$i,$j] = @$deck[$j,$i];
}
}
##############################################################
# reloadPic
##############################################################
sub reloadPic {
deleteCachedPics($actpic); # we need to reread the picture, so we should remove it from the cachedPics list first
showPic($actpic); # display the picture
}
##############################################################
# zoom100 - zoom the actual pic to 100%
##############################################################
sub zoom100 {
return if (!$actpic);
$userinfo = "loading ".basename($actpic)." ..."; $userInfoL->update;
deleteCachedPics($actpic); # we need to reread the picture, so we should clear the cachedPics list first
my $t = $config{AutoZoom}; # save auto zoom value
$config{AutoZoom} = 0; # stop auto zoom
showPic($actpic); # display the picture without auto zoom
$config{AutoZoom} = $t; # reset autozoom to the saved value
}
##############################################################
# fitPicture - (re)zoom the actual picture to fit into the canvas
##############################################################
sub fitPicture {
return unless (-f $actpic);
deleteCachedPics($actpic);
my $autoZoomSave = $config{AutoZoom}; # save actual autoZoom value
$config{AutoZoom} = 1; # enable auto zoom
showPic($actpic);
$config{AutoZoom} = $autoZoomSave; # restore old autoZoom value
}
##############################################################
# slideshow - start/stop slideshow
##############################################################
sub slideshow {
my $last_time;
if ($slideshow) {
$userinfo = "slideshow started"; $userInfoL->update;
$top->after(500); # just a litte delay to show the message above
until ($slideshow == 0) {
if (!defined $last_time || Tk::timeofday()-$last_time > $config{SlideShowTime}) {
my @savedselection = $picLB->info('selection');
showPic(nextSelectedPic($actpic));
$userinfo = basename($actpic)." (slideshow: ".$config{SlideShowTime}."sec)"; $userInfoL->update;
$last_time = Tk::timeofday();
$picLB->selectionClear();
reselect($picLB, @savedselection);
}
DoOneEvent(); # stay responsive
last if (!$slideshow);
}
}
$userinfo = "slideshow stopped"; $userInfoL->update;
}
##############################################################
# getWindows - get a list of toplevel children of the given widget
##############################################################
sub getWindows {
my $w = shift;
my @winlist;
# get all childs of $w
my @childs = $w->children;
# search for toplevels and build list
foreach my $widget (@childs) {
if (ref($widget) eq "Tk::Toplevel") {
push @winlist, $widget;
}
}
return @winlist;
}
##############################################################
# clearAndInsert - clear the given listbox and insert the list
##############################################################
sub clearAndInsert {
my $listBox = shift;
return if (!Exists($listBox));
my @list = @_;
# clear listbox
$listBox->delete(0, 'end');
foreach (@list) {
$listBox->insert('end', $_->cget(-title));
}
}
my $winW;
##############################################################
# showWindowList
##############################################################
sub showWindowList {
if (Exists($winW)) {
$winW->deiconify;
$winW->raise;
return;
}
my @winlist = getWindows($top);
if (@winlist <= 0) {
$top->messageBox(-icon => 'info', -message => "There are no open windows in the moment!",
-title => "No windows", -type => 'OK');
return;
}
# open window
$winW = $top->Toplevel();
$winW->title("MaPiVi window list");
$winW->iconimage($mapiviicon) if $mapiviicon;
$winW->Label(-text => "Sub windows of MaPiVi", -relief => "sunken" )->pack(-fill => 'x', -padx => 3, -pady => 3);
my $listBoxY = @winlist + 1;
$listBoxY = 30 if ($listBoxY > 30); # not higher than 30 entries
my $listBox =
$winW->Scrolled('Listbox',
-scrollbars => 'osoe',
-selectmode => 'extended',
-exportselection => 0,
-width => 80,
-height => $listBoxY,
)->pack(-expand => 1, -fill =>'both');
bindMouseWheel($listBox);
$listBox->bind('<Double-Button-1>', sub {
my @sellist = $listBox->curselection();
foreach (@sellist) {
$winlist[$_]->deiconify;
$winlist[$_]->raise;
$winlist[$_]->update;
}
@winlist = getWindows($top);
clearAndInsert($listBox, @winlist);
} );
clearAndInsert($listBox, @winlist);
my $ButF =
$winW->Frame()->pack(-fill =>'x', -padx => 3, -pady => 3);
$ButF->Button(-text => "Update",
-command => sub {
@winlist = getWindows($top);
clearAndInsert($listBox, @winlist);
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$ButF->Button(-text => "Iconify",
-command => sub {
my @sellist = $listBox->curselection();
foreach (@sellist) {
$winlist[$_]->iconify;
}
@winlist = getWindows($top);
clearAndInsert($listBox, @winlist);
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$ButF->Button(-text => "Close",
-command => sub {
my @sellist = $listBox->curselection();
foreach (@sellist) {
$winlist[$_]->destroy() if (Exists($winlist[$_]));
}
return if (!Exists($winW)); # own win closed - finished
@winlist = getWindows($top);
clearAndInsert($listBox, @winlist);
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$ButF->Button(-text => "Show",
-command => sub {
my @sellist = $listBox->curselection();
foreach (@sellist) {
$winlist[$_]->deiconify;
$winlist[$_]->raise;
$winlist[$_]->update;
}
@winlist = getWindows($top);
clearAndInsert($listBox, @winlist);
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$ButF->Button(-text => 'Cancel',
-command => sub {
$winW->destroy();
}
)->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$winW->bind('<Key-Escape>', sub {$winW->destroy;});
$winW->bind('<Key-q>' , sub {$winW->destroy;});
$winW->Popup;
$winW->waitWindow;
}
##############################################################
# toggle - toggle the value of a boolean variable reference
##############################################################
sub toggle {
my $varRef = shift;
if ($$varRef == 1) {
$$varRef = 0;
}
elsif ($$varRef == 0) {
$$varRef = 1;
}
else {
warn "toggle: Reference has unexpected value: $$varRef\n";
}
}
##############################################################
# execute
##############################################################
sub execute {
my $string = shift; # command to execute
my $actexe; # file handle to Tk::IO object (background process)
print "execute: $string\n" if $verbose;
if (!$EvilOS) { # running on a "good" OS like Linux we can use background processes :)
# init a background process
$actexe = Tk::IO->new(-linecommand => sub { nop(); },
-childcommand => sub { print "execute: child com\n" if $verbose; } );
# start the background process
$actexe->exec($string);
# the busy call made some problems with jhead and the autorot option
# while it was enabled the $actexe->wait call sometimes never returned
#$top->Busy;
# waiting for current process to finish
$actexe->wait();
#$top->Unbusy;
}
# we run on a evil OS like windows - no threading :(
# Tk::IO is supposed to run under windows, but it does not with mine
else {
#$top->Busy;
#(system "$string") == 0 or warn "execute: $string failed: $!";
#$top->Unbusy;
bgRun($string);
}
}
##############################################################
# findApp - find Windows-App-Name for Win32::Process
# from Uwe Steffen
##############################################################
sub findApp
{
my ($cmd)=@_;
$cmd =~ /^\s*(\w+)/;
my $cmdName=$1.".exe";
#print "cmdName:",$cmdName,"\n";
if (defined($winapps{$cmdName}))
{
return $winapps{$cmdName};
}
my @path=split (/;/,$ENV{PATH});
foreach my $dir (@path)
{
my $test=$dir."/$cmdName";
#print "Test: $test \n";
if ( -x $test )
{
$winapps{$cmdName}=$test;
return $test;
}
}
}
##############################################################
# bgRun - run a process in background
# from Uwe Steffen
##############################################################
sub bgRun {
my ($cmd) = @_;
if (!$EvilOS) {
warn "bgRun should not be called for non Windows systems!";
return 0;
}
if (Win32ProcAvail) {
my ($dir,$pid,$proc);
my ($bInherit) = 0;
my ($flags) = Win32::Process::CREATE_NO_WINDOW() |
Win32::Process::IDLE_PRIORITY_CLASS() |
Win32::Process::DETACHED_PROCESS();
if ( $cmd =~ /^(\w+:[\w\\.]+)/) {
print "Process with full path: ",$cmd," APP:", $1,"\n" if $verbose;
$pid = Win32::Process::Create($proc, $1, $cmd, $bInherit, $flags, "." );
} else {
print "Process without full path: ",$cmd," APP:", findApp($cmd),"\n" if $verbose;
$pid = Win32::Process::Create($proc, findApp($cmd), $cmd, $bInherit, $flags, "." );
}
if ($pid) {
$proc->Wait(15000);
print "bgRun: timeout\n";
return 1;
} else {
warn "Could not start $cmd.\n";
warn "Error: " . Win32::FormatMessage(Win32::GetLastError());
return 0;
}
} else { # Win32::Process module not available
$top->Busy;
(system "$cmd") == 0 or warn "bgRun: $cmd failed: $!";
$top->Unbusy;
}
}
##############################################################
# cleanThumbDB - remove all old thumbnails in the thumbDB
##############################################################
sub cleanThumbDB {
my $days = 30;
my $thumbDB = "$configdir/thumbDB";
my @thumbs;
my $rc = $top->messageBox(-icon => "question",
-message => "This function will delete all stored thumbnails in the thumbnail data base which have no corresponding picture and are older than $days days. Please press Ok to proceed.",
-title => "Clean thumbnail database", -type => 'OKCancel');
return if ($rc !~ m/Ok/i);
$userinfo = "searching outdated thumbnails ..."; $userInfoL->update;
find(sub {
#print "dir: $File::Find::name\n";
if (-f and (-M >= $days)) {
my $orig = $File::Find::name;
$orig =~ s/^$thumbDB//;
unless (-f $orig) {
print "file: $File::Find::name -> $orig\n";
push @thumbs, $File::Find::name;
}
}
}, $thumbDB);
# todo: ignore /mnt/cdrom (%ignorePaths) ...
$userinfo = "found ".@thumbs." outdated thumbnails ..."; $userInfoL->update;
if (@thumbs > 0) {
my @dummylist;
# todo: use mySelListBoxDialog user may select which to delete
if (mySelListBoxDialog("Really delete?",
"Please press Ok to delete these ".scalar @thumbs." thumbnails.",
'OK', \@dummylist, @thumbs)) {
foreach (@thumbs) { print "removing $_\n"; removeFile($_); }
}
}
$userinfo = "ready!"; $userInfoL->update;
return;
# todo: remove empty dirs in $thumbDB ...
}
##############################################################
# cleanDir - remove all dirs and files added by mapivi from
# the given dir
##############################################################
sub cleanDir {
my $dir = shift;
print "dir = $dir actdir = $actdir\n" if $verbose;
return unless ((defined $dir) or (-d $dir));
my $rc;
if (($cleanDirLevel == 0) or (!$cleanDirNoAsk)) {
my $dia = $top->DialogBox(-title => "Clean directory ".basename($dir)."?",
-buttons => ['OK', 'Cancel']);
$dia->add("Label", -text => "Remove all sub directories and files from\n$dir\nwhich were created from MaPiVi\nContinue?", -bg => $config{ColorBG}, -justify => "left")->pack;
$dia->add("Checkbutton", -text => "Continue without asking again", -variable => \$cleanDirNoAsk)->pack;
$rc = $dia->Show();
return if ($rc ne 'OK');
}
my ($subdir, @fileDirList);
my @subdirs = ("$dir/$thumbdirname", "$dir/$exifdirname");
foreach $subdir (@subdirs) {
if (-d $subdir) {
@fileDirList = readDir($subdir);
unless ($cleanDirNoAsk) {
$rc = $top->messageBox(-icon => 'question',
-message => "There are ".scalar @fileDirList." files in the sub directory\n".basename($subdir)."\nRemove?",
-title => "Remove sub directory?",
-type => 'OKCancel');
next if ($rc !~ m/Ok/i);
}
$userinfo = "cleaning $subdir ..."; $userInfoL->update;
foreach (@fileDirList) {
if (-f "$subdir/$_") {
removeFile("$subdir/$_")
}
else {
$top->messageBox(-icon => 'warning', -message => "There is a non file in $subdir: $_!",
-title => 'Warning', -type => 'OK') if ($_ ne "..");
}
}
if (! rmdir($subdir)) {
$top->messageBox(-icon => 'warning', -message => "Could not remove $subdir: $_!",
-title => 'Error', -type => 'OK');
}
}
}
my @dirs = getDirs($dir);
return if (@dirs == 0);
my %dirh;
# copy the list into a hash
foreach (@dirs) { $dirh{$_} = 1; }
# sort some special dirs out
foreach ($thumbdirname, $exifdirname, ".xvpics") {
if (defined $dirh{$_}) {
delete $dirh{$_};
}
}
# are there some other dirs?
my $nr = keys %dirh;
if (($nr > 0) and (!$cleanDirNoAsk)) {
$rc = $top->messageBox(-icon => 'question',
-message => "There are $nr sub directories in\n$dir\n, should I clean them too?",
-title => "Clean sub directories?",
-type => 'OKCancel');
return if ($rc !~ m/Ok/i);
}
# recursive call of cleanDir()
foreach (sort keys %dirh) {
$cleanDirLevel++;
cleanDir ("$dir/$_");
$cleanDirLevel--;
}
if ($cleanDirLevel == 0) {
$userinfo = "ready"; $userInfoL->update;
}
}
##############################################################
# isInList - check if a string is element of a list reference
##############################################################
sub isInList {
my $e = shift;
my $listRef = shift;
my $found = 0;
foreach (@$listRef) {
if ($e eq $_) {
$found = 1;
last;
}
}
return $found;
}
##############################################################
# screenshot
##############################################################
sub screenshot {
if (Exists($scsw)) {
$scsw->deiconify;
$scsw->raise;
return;
}
return if (!checkExternProgs("screenshot", "xwd"));
return if (!checkExternProgs("screenshot", "convert"));
# open window
$scsw = $top->Toplevel();
$scsw->title("Make screenshot");
$scsw->iconimage($mapiviicon) if $mapiviicon;
my $root = "";
my $frame = "-frame";
my $tmpfile = "$trashdir/screenshot.jpg";
$tmpfile = "$trashdir/".findNewName($tmpfile);
my $file = "$actdir/screenshot.jpg";
$file = "$actdir/".findNewName($file);
my $hideMapivi = 0;
my $showPic = 1;
my $ifB;
my $f1 = $scsw->Frame(-bd => $config{Borderwidth}, -relief => 'groove')->pack(-fill => 'x',-padx => 3,-pady => 3);
$f1->Radiobutton(-text => "single window (select window with mouse click after pressing OK)", -variable => \$root, -value => "",
-command => sub { $ifB->configure(-state => 'normal');}
)->pack(-anchor => 'w');
$f1->Radiobutton(-text => "complete desktop", -variable => \$root, -value => "-root",
-command => sub { $frame = ""; $ifB->configure(-state => "disabled");}
)->pack(-anchor => 'w');
my $f2 = $scsw->Frame(-bd => $config{Borderwidth}, -relief => 'groove')->pack(-fill => 'x',-padx => 3,-pady => 3);
$ifB =
$f2->Checkbutton(-variable => \$frame, -onvalue => "-frame", -offvalue => "",
-anchor => 'w',
-text => "include window border"
)->pack(-anchor => 'w');
$f2->Checkbutton(-variable => \$hideMapivi,
-anchor => 'w',
-text => "hide Mapivi window"
)->pack(-anchor => 'w');
$f2->Checkbutton(-variable => \$showPic,
-anchor => 'w',
-text => "show screenshot in Mapivi when finished"
)->pack(-anchor => 'w');
buttonComment($f2, 'top');
labeledEntryButton($scsw,'top',23,"file name",'Set',\$file);
my $qS = labeledScale($scsw, 'top', 23, "Quality of picture (%)", \$config{PicQuality}, 10, 100, 1);
qualityBalloon($qS);
my $ButF =
$scsw->Frame()->pack(-fill =>'x', -padx => 3, -pady => 3);
my $OKB =
$ButF->Button(-text => 'OK',
-command => sub {
if (-f $file) {
my $rc = $scsw->messageBox(-icon => 'warning',
-message => "file\n\"$file\"\nexist.\nOk to overwrite?",
-title => "Screenshot", -type => 'OKCancel');
return if ($rc !~ m/Ok/i);
}
if (-f $tmpfile) {
my $rc = $scsw->messageBox(-icon => 'warning',
-message => "file $tmpfile exist. Ok to overwrite?",
-title => "Screenshot", -type => 'OKCancel');
return if ($rc !~ m/Ok/i);
}
$top->iconify() if $hideMapivi;
$scsw->withdraw();
$scsw->destroy();
$top->update if (!$hideMapivi);
# call external command jpegtran and rotate to the temp file
my $command = "xwd $frame $root -out \"$tmpfile\" ";
#(system "$command") == 0 or warn "screenshot: $! ($command)";
execute($command);
$top->deiconify if $hideMapivi;
if (!-f $tmpfile) { warn "nothing to convert!"; return; }
$command = "convert -quality ".$config{PicQuality}." \"$tmpfile\" \"$file\"";
$userinfo = "converting to JPEG format ..."; $userInfoL->update;
$top->Busy;
#(system "$command") == 0 or warn "convert: $! ($command)";
execute($command);
$top->Unbusy;
removeFile($tmpfile);
if ($config{AddMapiviComment}) {
addCommentToPic("Screenshot made with Mapivi ($mapiviURL)", $file, NO_TOUCH);
}
$userinfo = "ready!"; $userInfoL->update;
if ($showPic) {
my $dir = dirname($file);
if ($actdir ne $dir) {
openDirPost($dir);
}
else {
updateThumbs();
}
showPic($file);
}
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$balloon->attach($OKB, -msg =>
'In "single window" mode the mouse cursor will turn into a cross after pressing OK.
Just make a left mouse click on the desired window.
In "desktop" mode the screenshot will be taken immediatelly after pressing the OK button.
There may be two beeps in both modes if sound is enabled.');
$ButF->Button(-text => 'Cancel',
-command => sub {
$scsw->withdraw();
$scsw->destroy();
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$scsw->Popup;
$scsw->waitWindow;
}
##############################################################
# dragFromPicLB - drag pictures from the thumb table
##############################################################
sub dragFromPicLB {
my($token) = @_;
my $w = $token->parent; # $w is the $picLB hlist
my $e = $w->XEvent;
$w->update;
my @sellist = $w->info('selection');
return if (@sellist < 1);
if ($EvilOS) {
$userinfo = "copy or move ";
} else {
$userinfo = "copy, link, or move ";
}
# only one picture selected
if (@sellist == 1) {
#my $tokentext = $w->itemCget($sellist[0], 1, -text);
my $tokentext = $sellist[0];
# Configure the dnd token to show the listbox entry
if (!$w->info("exists", $sellist[0])) {
print "dragFromPicLB: item not available\n";
return;
}
if ($dragAndDropIcon1) {
$token->configure(-image => $dragAndDropIcon1);
}
else {
$token->configure(-text => " $tokentext");
}
$userinfo .= $tokentext; $userInfoL->update;
}
# more than one pictures selected
else {
if ($dragAndDropIcon2) {
$token->configure(-image => $dragAndDropIcon2);
}
else {
$token->configure(-text => " ".scalar @sellist." pictures");
}
$userinfo .= scalar @sellist." pictures"; $userInfoL->update;
}
# Show the token
my($X, $Y) = ($e->X, $e->Y);
$token->MoveToplevelWindow($X, $Y);
$token->raise;
$token->deiconify;
$token->FindSite($X, $Y, $e);
Tk->break; # stop default binding of this event
}
##############################################################
# dropToDirTree - drop pictures on the dirtree (copy or move)
##############################################################
sub dropToDirTree {
$token->withdraw;
$userinfo = ""; $userInfoL->update;
my @sellist = $picLB->info('selection');
my $targetdir = getNearestItem($dirtree);
my $details;
return if (@sellist < 1);
my $dirtreeNoScroll = $dirtree->Subwidget("scrolled");
return unless ($top->containing($top->pointerxy) eq $dirtreeNoScroll);
$targetdir =~ s/\/\//\//g; # replace all // with /
foreach my $dpic (@sellist) {
warn "$dpic n.a." unless ($picLB->info("exists", $dpic));
my $pic = basename($dpic);
my $size = getFileSize($dpic, FORMAT);
$details .= sprintf "%-30s %20s\n", $pic, $size;
}
my $text = "Should I ";
if ($EvilOS) {
$text .= "copy or move ";
} else {
$text .= "copy, link, or move ";
}
if (@sellist == 1) {
$text .= "this picture";
} else {
$text .= "these ".scalar @sellist." pictures";
}
$text .= " to $targetdir?\n\n$details";
my $rc = 'Cancel';
if ($EvilOS) {
$rc = myButtonDialog("Copy/Move", $text, undef, "Copy", "Move", 'Cancel');
} else {
$rc = myButtonDialog("Copy/Link/Move", $text, undef,
"Copy", "Link", "Move", 'Cancel');
}
if ($rc eq 'Cancel') {
return;
} elsif ($rc eq "Copy") {
dirSave($targetdir);
copyPics($targetdir, COPY, $picLB, @sellist);
} elsif ($rc eq "Link") {
dirSave($targetdir);
linkPics($targetdir, @sellist);
} elsif ($rc eq "Move") {
dirSave($targetdir);
movePics($targetdir, $picLB, @sellist);
} else {
warn "unexpected rc: $rc";
return;
}
}
##############################################################
#dragAndDropExtern - todo
##############################################################
sub dragAndDropExtern {
my($widget, $selection) = @_;
my $filename;
eval {
if ($^O eq 'MSWin32') {
$filename = $widget->SelectionGet(-selection => $selection, 'STRING');
} else {
$filename = $widget->SelectionGet(-selection => $selection, 'FILE_NAME');
}
};
return if (!defined $filename);
#print "drop extern received: $filename\n";
$top->messageBox(-icon => 'warning',
-message => "drop extern received: $filename",
-title => "Drag and drop", -type => 'OK');
unless (-f $filename or -d $filename) { print "$filename is no dir and no file\n"; return; }
my $dir = $filename;
if (-f $filename) {
return if ($filename !~ /(.*)(\.jp(g|eg))/i);
$dir = dirname($filename);
}
print "drag: dir = $dir\n";
return unless (-d $dir);
openDirPost($dir);
if (-f $filename) {
showPic($filename);
}
}
##############################################################
# checkWriteable
##############################################################
sub checkWriteable($) {
my $dpic = shift;
my $pic = basename($dpic);
my $dir = dirname($dpic);
my $thumb = getThumbFileName($dpic);
return 0 if (! -f $dpic); # no file
return 1 if (-w $dpic); # OK, file is writable
if (!-w $dpic) {
my $message = "The picture $pic is write proteced!\nShould I try to overwrite the write protection?";
my $rc = myButtonDialog("$pic is write protected", $message, $thumb, 'OK', 'Cancel');
if ($rc eq 'OK') {
my $mode = (lstat $dpic)[2]; # get the actual access mode
$mode = $mode | 0200; # set user write (+uw)
return (chmod($mode, $dpic)); # try to change the mode
}
else {
return 0; # file is left write protected
}
}
}
##############################################################
# checkWriteableMulti
##############################################################
sub checkWriteableMulti {
my @dpics = @_;
my @protected = ();
foreach (@dpics) {
if ((-f $_) and (!-w $_)) {
push @protected, $_;
}
}
return "" unless (@protected); # nothing to do
my $text = "The following pictures are write protected:\n\n";
foreach (@protected) {
$text .= "$_\n";
}
$text .= "\nShould I try to overwrite the write protection?";
my $rc = myButtonDialog(scalar @protected." pictures are write protected", $text, undef, 'OK', 'Cancel', 'Cancel All');
if ($rc eq 'OK') {
foreach (@protected) {
my $mode = (lstat $_)[2]; # get the actual access mode
$mode = $mode | 0200; # set user write (+uw)
chmod($mode, $_); # try to change the mode
}
}
return $rc;
}
##############################################################
# bindMouseWheel - this won't be needed with Tk >= 804.025
##############################################################
sub bindMouseWheel {
return if ($Tk::VERSION >= 804);
print "activating mouse wheel\n" if $verbose;
my($w) = @_;
if ($^O eq 'MSWin32')
{
$w->bind('<MouseWheel>' =>
[ sub { $_[0]->yview('scroll', -($_[1] / 120) * 3, 'units') },
Ev('D') ]);
}
else
{
# Support for mousewheels on Linux commonly comes through
# mapping the wheel to buttons 4 and 5. If you have a
# mousewheel ensure that the mouse protocol is set to
# "IMPS/2" in your /etc/X11/XF86Config (or XF86Config-4)
# file:
#
# Section "InputDevice"
# Identifier "Mouse0"
# Driver "mouse"
# Option "Device" "/dev/mouse"
# Option "Protocol" "IMPS/2"
# Option "Emulate3Buttons" "off"
# Option "ZAxisMapping" "4 5"
# EndSection
$w->bind('<4>' => sub {
$_[0]->yview('scroll', -3, 'units') unless $Tk::strictMotif;
});
$w->bind('<5>' => sub {
$_[0]->yview('scroll', +3, 'units') unless $Tk::strictMotif;
});
}
} # end BindMouseWheel
##############################################################
# diffPics - create a new picture containing the difference
# between two pictures
##############################################################
sub diffPics {
return if (!checkExternProgs("diffPics", "composite"));
my @sellist = $picLB->info('selection');
return unless checkSelection($top, 2, 2, \@sellist);
my $dpicA = $sellist[0];
my $dpicB = $sellist[1];
my $dpicDiff = $dpicA;
$dpicDiff =~ s/(.*)(\.jp(g|eg))/$1-diff$2/i; # pic.jpg -> pic-diff.jpg
$dpicDiff = dirname($dpicA).'/'.findNewName($dpicDiff); # pic-diff.jpg -> pic-diff-03.jpg
$userinfo = "creating difference picture ..."; $userInfoL->update;
#my $command = "composite -compose difference \"$dpicA\" \"$dpicB\" \"$dpicDiff\"";
my $command = "convert \"$dpicA\" \"$dpicB\" -compose difference -composite -normalize \"$dpicDiff\"";
print "diffPics: $command\n" if $verbose;
$top->Busy;
execute($command);
$top->Unbusy;
$userinfo = "ready! (difference picture created)"; $userInfoL->update;
generateOneThumb($dpicDiff);
# insert diff pic in listbox
addOneRow($picLB, $dpicDiff, 1, $dpicA);
#updateThumbs();
showPic($dpicDiff);
}
##############################################################
# interpolatePics
##############################################################
sub interpolatePics {
my @sellist = $picLB->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
my $selected = @sellist;
my ($pic, $dpic, $dirtpic, $i);
return if (!interpolateDialog(scalar @sellist));
return if (!checkExternProgs("interpolatePics", "jpegpixi"));
$userinfo = "interpolating $selected pictures"; $userInfoL->update;
# check if some files are links
return if (!checkLinks($picLB, @sellist));
my $pw = progressWinInit($top, "Interpolate pictures");
$i = 0;
foreach $dpic (@sellist) {
last if progressWinCheck($pw);
$i++;
progressWinUpdate($pw, "interpolating ($i/$selected) ...", $i, $selected);
$pic = basename($dpic);
$dirtpic = "$dpic"."-cjpg"; # temporary file
next if (!checkWriteable($dpic));
next if (!makeBackup($dpic));
# check if temp file exists
next if (!checkTempFile($dirtpic));
# call external command jpegpixi
my $command = "jpegpixi -m ".$config{DeadPixelMethod}." \"$dpic\" \"$dirtpic\" ".$config{DeadPixelStr};
execute($command);
# now overwrite the original pic with the temp file and delete the temp file
next if (!overwrite("$dpic", "$dirtpic"));
if ($config{AddMapiviComment}) {
$command =~ s/\"//g;
$command = "Picture processed by Mapivi ($mapiviURL):\n".$command;
addCommentToPic($command, $dpic, NO_TOUCH);
}
updateOneRow($dpic, $picLB);
deleteCachedPics($dpic);
showPic($dpic) if ($dpic eq $actpic); # redisplay the picture if it is the actual one
}
progressWinEnd($pw);
reselect($picLB, @sellist);
$userinfo = "ready! ($i of $selected interpolated)"; $userInfoL->update;
generateThumbs(ASK, SHOW);
}
##############################################################
# interpolateDialog
##############################################################
sub interpolateDialog {
if (Exists($interpW)) {
$interpW->deiconify;
$interpW->raise;
return;
}
my $pics = shift;
if (!defined($pics)) {
$pics = "";
}
else {
$pics = "$pics ";
}
my $rc = 0;
my $deadpixels = $config{DeadPixelStr};
my $method = $config{DeadPixelMethod};
# open window
$interpW = $top->Toplevel();
$interpW->title("Interploate pictures");
$interpW->iconimage($mapiviicon) if $mapiviicon;
$interpW->Label(-text => "Remove dead pixels from ${pics}pictures with Jpegpixi", -bg => $config{ColorBG})->pack(-anchor => 'w', -padx => 3, -pady => 3);
$interpW->Label(-text => "This function should be called as first step when processing pictures\n(e.g. it must be called before rotating the pictures).", -bg => $config{ColorBG}, -justify => "left")->pack(-anchor => 'w', -padx => 3, -pady => 3);
my $infotext = "Some Infos about Jpegpixi from the author (see: http://www.zero-based.org/software/jpegpixi/):
\"Jpegpixi is short for JPEG Pixel Interpolator. The intent of the program is to interpolate pixels (single pixels, dots, stripes) in JPEG images. This is useful to correct images from a digital camera with CCD defects. For example, if one pixel is always bright green, this pixel can be interpolated with jpegpixi.
Jpegpixi is unique in that it tries to preserve the quality of the JPEG image as much as possible. Usual graphics programs decode JPEG images when they are loaded, and re-encode them when they are saved, which results in an overall loss of quality. Jpegpixi, on the other hand, only decodes the DCT blocks (typically 88, 168, or 1616 pixel areas) which contain pixels to be interpolated, and when it re-encodes them, it uses exactly the same parameters with which the image has originally been encoded. These blocks are therefore only minimally disturbed, and other blocks remain pixel-by-pixel identical to the original image.
Usage: jpegpixi [OPTION]... SOURCE DEST [[D:]X,Y[,S]|[,SX,SY]]...
Pixel block specification:
D can be `V' or `v' (vertical 1D interpolation),
`H' or `h' (horizontal 1D interpolation),
`2' (2D interpolation) [default];
X,Y specifies the top left corner of the pixel block to be interpolated;
S specifies the size of the block [default: 1];
SX,SY specifies separate sizes for the X and Y direction.\"
The part: [OPTION] and [[D:]X,Y[,S]|[,SX,SY]]...
may be changed in this dialog, the rest (jpegpixi ... SOURCE DEST) will be done by MaPiVi.
Example:
If there are two dead pixels at the coordinates x=832 y=344 and x=1024 y=872 in your pictures, each of them 2 pixels wide and high, you should enter this string: \"832,344,2 1024,872,2\".
";
my $metF = $interpW->Frame()->pack(-fill =>'x', -padx => 0, -pady => 0);
$metF->Label(-text => "Interpolation method", -bg => $config{ColorBG})->pack(-side => "left", -anchor => 'w', -padx => 3, -pady => 3);
my $methB = $metF->Optionmenu(-textvariable => \$method, -options => [qw(average linear quadratic cubic)] )->pack(-side => "left", -anchor => 'w', -padx => 3, -pady => 0);
$interpW->Label(-text => "Pixel block specification", -bg => $config{ColorBG})->pack(-anchor => 'w', -padx => 3, -pady => 3);
my $entry = $interpW->Entry(-textvariable => \$deadpixels,
-width => 70,
)->pack(-fill => 'x', -expand => "1", -padx => 3, -pady => 3);
$entry->xview('end');
$entry->icursor('end');
buttonBackup($interpW, 'top');
buttonComment($interpW, 'top');
my $ButF = $interpW->Frame()->pack(-fill =>'x', -padx => 3, -pady => 3);
my $OKB = $ButF->Button(-text => 'OK',
-command => sub {
$interpW->withdraw();
$interpW->destroy();
$config{DeadPixelMethod} = $method;
$config{DeadPixelStr} = $deadpixels;
$rc = 1;
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$ButF->Button(-text => "Help",
-command => sub {
showText("Infos about Jpegpixi", $infotext, NO_WAIT);
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
my $Xbut = $ButF->Button(-text => 'Cancel',
-command => sub { $rc = 0;
$interpW->withdraw();
$interpW->destroy();
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$interpW->bind('<Key-q>', sub { $Xbut->invoke; });
$interpW->bind('<Key-Escape>', sub { $Xbut->invoke; });
$interpW->Popup;
$interpW->waitWindow;
return $rc;
}
##############################################################
# fuzzyBorder - add a fuzzy border to the selected pics
##############################################################
sub fuzzyBorder {
my @sellist = $picLB->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
my $selected = @sellist;
my ($dpic, $i);
return if (!fuzzyBorderDialog());
my $bw = $config{FuzzyBorderWidth};
my $frame = "$trashdir/framePic.miff"; # we need MIFF or PNG because of the alpha channel
removeFile($frame);
return if (!checkExternProgs("fuzzyBorder", "convert", "composite"));
$userinfo = "adding fuzzy border to $selected pictures"; $userInfoL->update;
# check if some files are links
return if (!checkLinks($picLB, @sellist));
my $pw = progressWinInit($top, "Adding fuzzy border");
$i = 0;
foreach $dpic (@sellist) {
last if progressWinCheck($pw);
progressWinUpdate($pw, "creating border ($i/$selected) ...", $i, $selected);
next if (!checkWriteable($dpic));
next if (!makeBackup($dpic));
# get size of pic
my ($x, $y) = getSize($dpic);
# create an empty picture with a fuzzy frame
my $command = "convert -size ${x}x${y} xc:none -fill ".$config{FuzzyBorderColor}." ";
#$command .= "-draw \'rectangle 0,0 $x,$bw\' "; # upper
#$command .= "-draw \'rectangle 0,".($y-$bw)." $x,$y\' "; # lower
#$command .= "-draw \'rectangle 0,0 $bw,$y\' "; # left
#$command .= "-draw \'rectangle ".($x-$bw).",0 $x,$y\' "; # right border
# windows needs " instead of '
$command .= "-draw \"rectangle 0,0 $x,$bw\" "; # upper
$command .= "-draw \"rectangle 0,".($y-$bw)." $x,$y\" "; # lower
$command .= "-draw \"rectangle 0,0 $bw,$y\" "; # left
$command .= "-draw \"rectangle ".($x-$bw).",0 $x,$y\" "; # right border
$command .= "-blur 0x".$config{FuzzyBorderBlur}." \"$frame\" ";
if (!$EvilOS) {
execute($command);
}
else { # else we run in a timeout
(system "$command") == 0 or warn "fuzzy frame: $command failed: $!";
}
unless (-f $frame) {
warn "fuzzyBorder: could not create fuzzy border, skipping $dpic!\n";
next;
}
progressWinUpdate($pw, "adding border ($i/$selected) ...", $i, $selected);
# compose the frame on top of the picture
$command = "composite -quality ".$config{PicQuality}." -compose Atop \"$frame\" \"$dpic\" \"$dpic\" ";
if (!$EvilOS) {
execute($command);
}
else { # else we run in a timeout
(system "$command") == 0 or warn "fuzzy frame: $command failed: $!";
}
$i++;
progressWinUpdate($pw, "adding border ($i/$selected) ...", $i, $selected);
if ($config{AddMapiviComment}) {
$command =~ s/\"//g;
$command = "Picture processed by Mapivi ($mapiviURL):\n".$command;
addCommentToPic($command, $dpic, NO_TOUCH);
}
updateOneRow($dpic, $picLB);
deleteCachedPics($dpic);
showPic($dpic) if ($dpic eq $actpic); # redisplay the picture if it is the actual one
}
progressWinEnd($pw);
removeFile($frame);
reselect($picLB, @sellist);
$userinfo = "ready! (added fuzzy border to $i of $selected)"; $userInfoL->update;
generateThumbs(ASK, SHOW);
}
##############################################################
# fuzzyBorderDialog
##############################################################
sub fuzzyBorderDialog {
if (Exists($fuzzybw)) {
$fuzzybw->deiconify;
$fuzzybw->raise;
return;
}
my $rc = 0;
# open window
$fuzzybw = $top->Toplevel();
$fuzzybw->title("Fuzzy border");
$fuzzybw->iconimage($mapiviicon) if $mapiviicon;
my $bS = labeledScale($fuzzybw, 'top', 23, "Border width (pixel)", \$config{FuzzyBorderWidth}, 1, 200, 1);
my $fS = labeledScale($fuzzybw, 'top', 23, "Blur radius (pixel)", \$config{FuzzyBorderBlur}, 1, 200, 1);
my $cB = labeledEntryColor($fuzzybw,'top',23,"Border color",'Set',\$config{FuzzyBorderColor});
my $qS = labeledScale($fuzzybw, 'top', 23, "Quality of picture (%)", \$config{PicQuality}, 10, 100, 1);
qualityBalloon($qS);
buttonBackup($fuzzybw, 'top');
buttonComment($fuzzybw, 'top');
my $ButF = $fuzzybw->Frame()->pack(-fill =>'x', -padx => 3, -pady => 3);
my $OKB = $ButF->Button(-text => 'OK',
-command => sub {
$fuzzybw->withdraw();
$fuzzybw->destroy();
$rc = 1;
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
my $Xbut = $ButF->Button(-text => 'Cancel',
-command => sub { $rc = 0;
$fuzzybw->withdraw();
$fuzzybw->destroy();
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$fuzzybw->bind('<Key-q>', sub { $Xbut->invoke; });
$fuzzybw->bind('<Key-Escape>', sub { $Xbut->invoke; });
$fuzzybw->Popup;
$fuzzybw->waitWindow;
return $rc;
}
##############################################################
# losslessBorder - add a frame to the selected pics without
# recompressing the picture
##############################################################
sub losslessBorder {
# check if jpegtran supports lossless dropping
my $usage = `jpegtran -? 2>&1`;
if ($usage !~ m/.*-drop.*/) {
$top->messageBox(-icon => 'warning', -message => "Sorry, but your version of jpegtran does not support lossless dropping!\nTry to get the lossless drop patch from http://jpegclub.org.",
-title => "Wrong jpegtran version", -type => 'OK');
return;
}
return if (!checkExternProgs("losslessBorder", "convert"));
my @sellist = $picLB->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
my $selected = @sellist;
my ($dpic, $i);
return if (!losslessBorderDialog());
my $bi = $config{llBorderWidthI}; # inner width
my $bw = $config{llBorderWidth}; # complete width
my $frame = "$trashdir/framePic.jpg";
if (-f $frame) {
warn "file $frame exists! Please delete it first!";
return;
}
$userinfo = "adding lossless border to $selected pictures"; $userInfoL->update;
# check if some files are links
return if (!checkLinks($picLB, @sellist));
my $pw = progressWinInit($top, "Adding lossless border");
$i = 0;
foreach $dpic (@sellist) {
last if progressWinCheck($pw);
progressWinUpdate($pw, "creating border ($i/$selected) ...", $i, $selected);
next if (!checkWriteable($dpic));
next if (!makeBackup($dpic));
# get size of pic
my ($x, $y) = getSize($dpic);
my $cx = $x + 2 * $bw;
my $cy = $y + 2 * $bw;
my $r1 = $bw - $bi;
my $rx2 = $cx - $bw + $bi - 1;
my $ry2 = $cy - $bw + $bi - 1;
print "losslessBorder: pic $x,$y canvas $cx,$cy rect $r1,$r1 $rx2,$ry2\n" if $verbose;
# create an empty picture with a frame
my $command = "convert -size ${cx}x${cy} xc:\"".$config{llBorderColor}."\" -fill \"".$config{llBorderColorI}."\" ";
$command .= "-draw \'rectangle $r1,$r1 $rx2,$ry2\' -quality 95 \"$frame\" ";
execute($command);
unless (-f $frame) {
warn "losslessBorder: could not create lossless border, skipping $dpic!\n";
next;
}
progressWinUpdate($pw, "adding border ($i/$selected) ...", $i, $selected);
# drop the picture on top of the frame
$command = "jpegtran -drop +${bw}+${bw} \"$dpic\" -outfile \"$dpic\" \"$frame\" ";
execute($command);
$i++;
progressWinUpdate($pw, "adding border ($i/$selected) ...", $i, $selected);
if ($config{AddMapiviComment}) {
$command =~ s/\"//g;
$command = "Picture processed by Mapivi ($mapiviURL):\n".$command;
addCommentToPic($command, $dpic, NO_TOUCH);
}
updateOneRow($dpic, $picLB);
deleteCachedPics($dpic);
showPic($dpic) if ($dpic eq $actpic); # redisplay the picture if it is the actual one
}
progressWinEnd($pw);
removeFile($frame);
reselect($picLB, @sellist);
$userinfo = "ready! (added lossless border to $i of $selected)"; $userInfoL->update;
generateThumbs(ASK, SHOW);
}
##############################################################
# losslessBorderDialog
##############################################################
sub losslessBorderDialog {
if (Exists($ll_b_w)) {
$ll_b_w->deiconify;
$ll_b_w->raise;
return;
}
my $rc = 0;
# open window
$ll_b_w = $top->Toplevel();
$ll_b_w->title("Add lossless border");
$ll_b_w->iconimage($mapiviicon) if $mapiviicon;
labeledScale($ll_b_w, 'top', 30, "Border width (pixel)", \$config{llBorderWidth}, 8, 200, 8);
labeledEntryColor($ll_b_w,'top',30,"Border color",'Set',\$config{llBorderColor});
labeledScale($ll_b_w, 'top', 30, "Inner border width (pixel)", \$config{llBorderWidthI}, 1, 50, 1);
labeledEntryColor($ll_b_w,'top',30,"Inner border color",'Set',\$config{llBorderColorI});
buttonBackup($ll_b_w, 'top');
buttonComment($ll_b_w, 'top');
my $ButF = $ll_b_w->Frame()->pack(-fill =>'x', -padx => 3, -pady => 3);
my $OKB = $ButF->Button(-text => 'OK',
-command => sub {
$ll_b_w->withdraw();
$ll_b_w->destroy();
$rc = 1;
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
my $Xbut = $ButF->Button(-text => 'Cancel',
-command => sub { $rc = 0;
$ll_b_w->withdraw();
$ll_b_w->destroy();
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$ll_b_w->bind('<Key-q>', sub { $Xbut->invoke; });
$ll_b_w->bind('<Key-Escape>', sub { $Xbut->invoke; });
$ll_b_w->Popup;
$ll_b_w->waitWindow;
return $rc;
}
##############################################################
# importWizard
##############################################################
sub importWizard {
if (Exists($wizW)) {
$wizW->deiconify;
$wizW->raise;
return;
}
my $pics = shift;
my $rc = 0;
# open window
$wizW = $top->Toplevel();
$wizW->title("Import pictures wizard");
$wizW->iconimage($mapiviicon) if $mapiviicon;
$wizW->Label(-text => "Import pictures from a removable device like e.g. a camera\nor a card reader connected via e.g. USB.\nThe selected actions will take place in the displayed order.", -bg => $config{ColorBG}, -justify => "left")->pack(-anchor => 'w', -padx => 3, -pady => 3);
my ($s,$m,$ho,$d,$mo,$y) = localtime(time());
# do some adjustments
$y += 1900; $mo++;
# build up the date string for the dir structure (e.g. "2006/10/29")
my $date = sprintf "%04d/%02d/%02d", $y, $mo, $d;
my $w = 32;
my $w2 = $w - 3;
if (!$EvilOS && !$MacOSX) {
my $moF = $wizW->Frame()->pack(-anchor => 'w', -fill => 'x');
$moF->Checkbutton(-variable => \$config{ImportMount},
-anchor => 'w',
#-width => $w2*2,
-text => "Mount device"
)->pack(-side => "left", -anchor => 'w', -padx => 3, -pady => 3);
$moF->Label(-textvariable => \$config{ImportDevice},
-anchor => 'w',
-bg => $config{ColorBG})->pack(-side => "left", -anchor => 'w', -padx => 3, -pady => 3);
$moF->Button(-text => 'Set',
-command => sub {
mountDialog();
$wizW->raise;
})->pack(-side => "right", -anchor => 'w', -padx => 3, -pady => 3);
$moF->Button(-text => "Mount now",
-command => sub {
my $command = "mount ".$config{ImportDevice};
execute($command);
})->pack(-side => "right", -anchor => 'w', -padx => 3, -pady => 3);
}
else {
$config{ImportMount} = 0; # no mount for windows
# Mac OS X automounts when the device is plugged in.
}
labeledEntryButton($wizW,'top',$w,"Source directory",'Set',\$config{ImportSource}, 1);
$wizW->Checkbutton(-variable => \$config{ImportSubdirs},
-anchor => 'w',
-text => "Import from all sub directories, too"
)->pack(-side => 'top', -anchor => 'w', -padx => 3, -pady => 3);
labeledEntryButton($wizW,'top',$w,"Target directory (fix part)",'Set',\$config{ImportTargetFix}, 1);
my $varF = $wizW->Frame()->pack(-anchor => 'w', -fill => 'x');
labeledEntry($varF,"left",$w,"Target directory (variable part)",\$config{ImportTargetVar});
$varF->Button(-text => 'Set' , -command => sub {$config{ImportTargetVar} = $date;})->pack(-side => "right", -padx => 3, -pady => 3);
$varF->Label(-text => "actual date:",
-anchor => "e",
-bg => $config{ColorBG})->pack(-side => "right", -anchor => 'w', -padx => 3, -pady => 3);
my $dpF = $wizW->Frame()->pack(-anchor => 'w', -fill => 'x');
my $dpC = $dpF->Checkbutton(-variable => \$config{ImportDeadPixel},
-anchor => 'w',
-text => "Interpolate dead pixels"
)->pack(-side => "left", -anchor => 'w', -padx => 3, -pady => 3);
my $dpB = $dpF->Button(-text => 'Set',
-command => sub {
interpolateDialog();
$wizW->raise;
})->pack(-side => "right", -anchor => 'w', -padx => 3, -pady => 3);
if (missingProgs("Interpolate dead pixels", "jpegpixi")) {
$config{ImportDeadPixel} = 0; # disabled if jpegpixi is not available
$dpC->configure(-state => "disabled");
$dpB->configure(-state => "disabled");
$dpC->configure(-disabledforeground => 'gray30');
$dpB->configure(-disabledforeground => 'gray30');
$balloon->attach($dpF, -msg => explainMissingProg("Interpolate dead pixels", "jpegpixi"));
}
my $rot = $wizW->Checkbutton(-variable => \$config{ImportRotate},
-anchor => 'w',
-text => "Automatic rotation (lossless)"
)->pack(-anchor => 'w', -padx => 3, -pady => 3);
if (missingProgs("Automatic rotation", "jhead") > 0) {
$config{ImportRotate} = 0; # disabled if jhead is not available
$rot->configure(-state => "disabled");
$rot->configure(-disabledforeground => 'gray30');
$balloon->attach($rot, -msg => explainMissingProg("Automatic rotation", "jhead"));
}
my $comF = $wizW->Frame()->pack(-anchor => 'w', -fill => 'x');
$comF->Checkbutton(-variable => \$config{NameComment},
-anchor => 'w',
-text => "Add original file name to comment ("
)->pack(-side => "left", -anchor => 'w', -padx => 3, -pady => 3);
$comF->Checkbutton(-variable => \$config{NameComRmSuffix},
-anchor => 'w',
-text => "remove file suffix )"
)->pack(-side => "left", -anchor => 'w', -padx => 0, -pady => 3);
my $acomF = $wizW->Frame()->pack(-anchor => 'w', -fill => 'x');
$acomF->Checkbutton(-variable => \$config{ImportAddCom},
-anchor => 'w',
-text => '',
)->pack(-side => 'left', -anchor => 'w', -padx => 3, -pady => 3);
labeledEntry($acomF,"left",$w,"Add this comment to each picture",\$config{ImportAddComment});
my $iptcF = $wizW->Frame()->pack(-anchor => 'w', -fill => 'x');
$iptcF->Checkbutton(-variable => \$config{ImportAddIPTC},
-anchor => 'w',
-text => '',
)->pack(-side => 'left', -anchor => 'w', -padx => 3, -pady => 3);
labeledEntryButton($iptcF,'top',$w,"Add IPTC info to each picture",'Set',\$config{ImportIPTCTempl});
my $renF = $wizW->Frame()->pack(-anchor => 'w', -fill => 'x');
$renF->Checkbutton(-variable => \$config{ImportRename},
-anchor => 'w',
-text => "Smart Rename with this pattern:"
)->pack(-side => "left", -anchor => 'w', -padx => 3, -pady => 3);
$renF->Label(-textvariable => \$config{FileNameFormat},
-bg => $config{ColorBG},
-anchor => 'w',
#-width => ($w2-2),
)->pack(-side => "left", -anchor => 'w', -padx => 3, -pady => 3);
$renF->Button(-text => 'Set',
-command => sub {
getRenameFormat();
})->pack(-side => "right", -anchor => 'w', -padx => 3, -pady => 3);
$wizW->Checkbutton(-variable => \$config{ImportDeleteCameraJunk},
-anchor => 'w',
-text => "Delete camera junk files in target directory after copy (e.g. *.CTG)"
)->pack(-anchor => 'w', -padx => 3, -pady => 3);
$wizW->Checkbutton(-variable => \$config{ImportDelete},
-anchor => 'w',
-text => "Delete files in source directory after copy"
)->pack(-anchor => 'w', -padx => 3, -pady => 3);
if (!$EvilOS) {
my $ejF = $wizW->Frame()->pack(-anchor => 'w', -fill => 'x');
$ejF->Checkbutton(-variable => \$config{ImportUnmount},
-anchor => 'w',
#-width => $w2*2,
-text => "Unmount device when finished"
)->pack(-side => "left", -anchor => 'w', -padx => 3, -pady => 3);
# It is not necessary to set the mount device in Mac OS X, because
# the diskutil command can unmount by the name of the source dir.
if (!$MacOSX) {
$ejF->Button(-text => 'Set',
-command => sub {
mountDialog();
$wizW->raise;
})->pack(-side => "right", -anchor => 'w', -padx => 3, -pady => 3);
}
}
else {
$config{ImportUnmount} = 0; # no umount for windows
}
$wizW->Checkbutton(-variable => \$config{ImportShowPics},
-anchor => 'w',
-text => "Show pictures when import finished"
)->pack(-anchor => 'w', -padx => 3, -pady => 3);
my $ButF = $wizW->Frame()->pack(-fill =>'x', -padx => 3, -pady => 3);
my $OKB = $ButF->Button(-text => 'OK',
-command => sub {
$wizW->withdraw();
$wizW->destroy();
$rc = 1;
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
my $Xbut = $ButF->Button(-text => 'Cancel',
-command => sub { $rc = 0;
$wizW->withdraw();
$wizW->destroy();
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$wizW->bind('<Key-Escape>', sub { $Xbut->invoke; });
$wizW->Popup;
$wizW->waitWindow;
return if ($rc != 1);
$rc = importPictures();
openDirPost($config{ImportTargetFix}."/".$config{ImportTargetVar}) if $config{ImportShowPics};
if ($rc) {
$userinfo = "import finished successfully!";
}
else {
$userinfo = "import finished with errors!";
}
$userInfoL->update;
}
my $printW;
##############################################################
# copyToPrint - copy pics to print directories
# (e.g. 2_times_5x7/ or 1_times_13x18/)
##############################################################
sub copyToPrint {
my $lb =shift;
my @sellist = $lb->info('selection');
return unless checkSelection($top, 1, 0, \@sellist);
if (Exists($printW)) {
$printW->deiconify;
$printW->raise;
return;
}
my $pics = shift;
my $rc = 0;
# open window
$printW = $lb->Toplevel();
$printW->title("copy pictures to print directory");
$printW->iconimage($mapiviicon) if $mapiviicon;
$printW->Label(-text => "Copy ".scalar @sellist." pictures to a according print directory.", -bg => $config{ColorBG}, -justify => "left")->pack(-anchor => 'w', -padx => 3, -pady => 3);
my $w = 32;
my $w2 = $w - 3;
my $times = 1;
my $timesStr = "times";
my $size = "10x15";
labeledEntryButton($printW,'top',$w,"Print base directory",'Set',\$config{PrintBaseDir}, 1);
my $sf = $printW->Frame()->pack();
$sf->Label(-text => "numer, string and size", -width => $w, -bg => $config{ColorBG}, -justify => "left")->pack(-side => "left");
$sf->Optionmenu(-textvariable => \$config{PrintTimes},
-options => [qw(1 2 3 4 5 6 7 8 9 10)],
-command => sub { $config{PrintVarDir} = $config{PrintTimes}.$config{PrintTimesStr}.$config{PrintSize}; },
)->pack(-side => "left", -anchor => 'w');
$sf->Optionmenu(-textvariable => \$config{PrintTimesStr},
-options => [qw(times mal - x _x_ _times_ _mal_ _prints_in_ _Abzuege_in_)],
-command => sub { $config{PrintVarDir} = $config{PrintTimes}.$config{PrintTimesStr}.$config{PrintSize}; },
)->pack(-side => "left", -anchor => 'w');
$sf->Optionmenu(-textvariable => \$config{PrintSize},
-options => [qw(4x6 5x7 8x10 11x14 9x13 10x15 13x18 18x27 30x40 50x70)],
-command => sub { $config{PrintVarDir} = $config{PrintTimes}.$config{PrintTimesStr}.$config{PrintSize}; },
)->pack(-side => "left", -anchor => 'w');
labeledEntry($printW,'top',$w,"directory",\$config{PrintVarDir});
my $ButF = $printW->Frame()->pack(-fill =>'x', -padx => 3, -pady => 3);
my $OKB = $ButF->Button(-text => 'OK',
-command => sub {
$printW->withdraw();
$printW->destroy();
$rc = 1;
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
my $Xbut = $ButF->Button(-text => 'Cancel',
-command => sub { $rc = 0;
$printW->withdraw();
$printW->destroy();
})->pack(-side => 'left', -expand => 1, -fill => 'x', -padx => 3, -pady => 3);
$printW->bind('<Key-Escape>', sub { $Xbut->invoke; });
$printW->Popup;
$printW->waitWindow;
return if ($rc != 1);
if (!-d $config{PrintBaseDir}) {
my $rc = $top->messageBox(-icon => 'question',
-message => $config{PrintBaseDir}." does not exist. Should I create it?",
-title => "Create print base directory?", -type => 'OKCancel');
return if ($rc !~ m/Ok/i);
eval { mkpath($config{PrintBaseDir}, 0, 0755) }; # 0 = no output, 0755 = access rights
if ($@) {
warn "Couldn't create ",$config{PrintBaseDir},": $@";
return;
}
}
my $printdir = $config{PrintBaseDir}."/".$config{PrintVarDir};
print "copy pics to $printdir\n" if $verbose;
makeDir($printdir, NO_ASK); # do not ask
my $pw = progressWinInit($top, "Copy to print");
my $i = 0;
foreach my $spic (@sellist) {
last if progressWinCheck($pw);
$i++;
my $pic = basename($spic);
my $tpic = "$printdir/$pic";
progressWinUpdate($pw, "copy ($i/".scalar @sellist.") ...", $i, scalar @sellist);
if (!mycopy($spic, $tpic, ASK_OVERWRITE)) { # ask before overwrite
warn "error in copy $pic!\n";
}
}
progressWinEnd($pw);
$userinfo = "copy finished! ($i/".scalar @sellist.")"; $userInfoL->update;
}
##############################################################
# importPictures
##############################################################
sub importPictures {
##############################################################
##### mount device
if ($config{ImportMount}) {
$userinfo = "mounting ".$config{ImportDevice}." ..."; $userInfoL->update;
my $command = "mount ".$config{ImportDevice};
execute($command);
}
my $source = $config{ImportSource};
##### check source dir
$userinfo = "checking directories ..."; $userInfoL->update;
if (!-d $source) {
$top->messageBox(-icon => 'warning',
-message => "Sorry, but the source directory\n$source\ndoes not exists!\nPlease check, if the device is mounted.",
-title => "Import pictures - Error", -type => 'OK');
return 0;
}
my @sdirs; # all dirs to process
# add the sub dirs
if ($config{ImportSubdirs}) {
push @sdirs, getDirsRecursive($source);
}
push @sdirs, $source unless isInList($source, \@sdirs); # the source dir is the minimum
# the target dir
my $tdir = $config{ImportTargetFix}."/".$config{ImportTargetVar};
##### check if target is available, create it if not
makeDir($tdir, ASK) if (!-d $tdir);
##### check if target is now available
if (!-d $tdir) {
warn "$tdir not created!!!";
return 0;
}
#### get the IPTC template only once, before starting loop
my $iptc;
if ($config{ImportAddIPTC}) {
if (defined $config{ImportIPTCTempl} and -f $config{ImportIPTCTempl}) {
$iptc = retrieve($config{ImportIPTCTempl});
unless (defined $iptc) {
$top->messageBox(-icon => 'warning',
-message => "Sorry, but Mapivi could not retrieve IPTC template $config{ImportIPTCTempl}!\nPlease check, if the file is available.",
-title => "Import pictures - Error", -type => 'OK');
return 0;
}
}
else {
$top->messageBox(-icon => 'warning',
-message => "Sorry, but Mapivi could not find the IPTC template $config{ImportIPTCTempl}!\nPlease check, if the file is available.",
-title => "Import pictures - Error", -type => 'OK');
return 0;
}
}
# open log window
if (Exists($impW)) {
$impW->deiconify;
$impW->raise;
return 0;
}
# open window
$impW = $top->Toplevel();
$impW->title("Import pictures log");
$impW->iconimage($mapiviicon) if $mapiviicon;
my ($s,$m,$ho,$d,$mo,$y) = localtime(time());
my $time = sprintf "%02d:%02d:%02d", $ho, $m, $s;
my $butF = $impW->Frame()->pack(-expand => 1, -fill =>'x');
$butF->Button(-text => "Close",
-command => sub {
$impW->withdraw();
$impW->destroy();
},
)->pack(-expand => 1, -side => "left", -fill => 'x');
my $stop = 0;
my $stopB = $butF->Button(-text => "Stop",
-command => sub { $stop = 1; }
)->pack(-side => 'left', -anchor => 'w', -expand => 0,-padx => 1,-pady => 1);
my $stopImg = $top->Photo(-file => "$configdir/StopPic.gif") if (-f "$configdir/StopPic.gif");
$stopB->configure(-image => $stopImg, -borderwidth => 0) if $stopImg;
$stopB->configure(-state => "disabled");
my $dcount = 0; # progress of dirs
my $pcount = 0; # progress of pics
my $progF = $impW->Frame()->pack(-expand => 1, -fill =>'x');
$progF->Label(-text => "progress directories ", -bg => $config{ColorBG})->pack(-side => "left");
$progF->ProgressBar(-takefocus => 0,
-borderwidth => 1,
-relief => 'sunken',
-length => 100,
-padx => 0,
-pady => 0,
-variable => \$dcount,
-colors => [0 => $config{ColorProgress}],
-resolution => 1,
-blocks => scalar @sdirs,
-anchor => 'w',
-from => 0,
-to => scalar @sdirs,
)->pack(-side => "left", -fill => 'x', -expand => 1, -padx => 2, -pady => 3);
$progF->Label(-text => " pictures ", -bg => $config{ColorBG})->pack(-side => "left");
my $picProg =
$progF->ProgressBar(-takefocus => 0,
-borderwidth => 1,
-relief => 'sunken',
-length => 100,
-padx => 0,
-pady => 0,
-variable => \$pcount,
-colors => [0 => $config{ColorProgress}],
-resolution => 1,
-anchor => 'w',
-from => 0,
-to => 100,
)->pack(-side => "left", -fill => 'x', -expand => 1, -padx => 2, -pady => 3);
my $rotext = $impW->Scrolled("ROText",
-scrollbars => 'oe',
-wrap => 'word',
-tabs => '4',
-width => 90,
-height => 30,
)->pack(-fill => "both", -expand => 1, -padx => 1, -pady => 1);
$rotext->tagConfigure("R",-foreground => "brown4");
$rotext->tagConfigure("G",-foreground => "DeepSkyBlue4");
$rotext->tagConfigure("B",-foreground => "blue4");
$impW->Popup;
$rotext->insert('end', "$time starting import ...\n", "B"); $impW->update;
$stopB->configure(-state => 'normal');
foreach $source (@sdirs) {
last if $stop;
$dcount++;
$rotext->insert('end', "in directory ($dcount/".scalar @sdirs.") $source ...\n", "G"); $impW->update;
##### get and check files to import
my @importfiles = getFiles($source);
print "In dir $source are ".@importfiles." files\n" if $verbose;
if (@importfiles <= 0) {
$rotext->insert('end', " no pictures in this directory - skipping\n", "R"); $rotext->see('end');
next;
}
$picProg->configure(-to => scalar @importfiles, -blocks => scalar @importfiles);
##### copy all files from source to target
$pcount = 0;
my $sum = 0; # the sum of all files copied in MegaBytes
my $startTime = Tk::timeofday();
foreach my $file (@importfiles) {
last if $stop;
$pcount++;
my $size = getFileSize("$source/$file", NO_FORMAT)/(1024*1024); # get size in MegaBytes
my $sizeF = sprintf "%.2f", $size;
$rotext->insert('end', " ($pcount/".scalar @importfiles.") copy $file ($sizeF MB)\n");
$rotext->see('end');
$impW->update;
mycopy("$source/$file", "$tdir/$file", ASK_OVERWRITE);
$sum += $size if (-f "$tdir/$file");
}
my $duration = Tk::timeofday() - $startTime; # in seconds
my $rate = $sum/$duration if ($duration > 0); # MegaBytes/second
my $string = sprintf "The transfer of %.2f MB took %.2f seconds; transferrate %.2f MB/s\n", $sum, $duration, $rate;
$rotext->insert('end', $string); $rotext->see('end');
##### check if the copy was successfull
my $filediff = 0;
my $sizediff = 0;
# check if every source file is in the target dir and if the file size is the same
foreach (@importfiles) {
$filediff++ if (!-f "$tdir/$_");
$sizediff++ if (getFileSize("$tdir/$_", NO_FORMAT) != getFileSize("$source/$_", NO_FORMAT));
}
if (($filediff > 0) or ($sizediff > 0)) {
my $rc = $top->messageBox(-icon => 'question',
-message => "Not all files in the source and target directory are eqal.\n$filediff files are missing and $sizediff files have another size.\nShould I continue?",
-title => "Continue?", -type => 'OKCancel');
return 0 if ($rc !~ m/Ok/i);
}
##### get the imported JPEG pictures (from the source dir!!!)
# no questions about NON-JPEGS while importing please!
my $tmp = $config{CheckForNonJPEGs};
$config{CheckForNonJPEGs} = 0;
my @piclist = getPics($source, JUST_FILE); # no sort needed
$config{CheckForNonJPEGs} = $tmp;
##### process JPEGS
if ($config{ImportDeadPixel} or $config{ImportRotate} or $config{ImportRename} or $config{NameComment} or $config{ImportAddCom} or $config{ImportAddIPTC}) {
my $command = "";
my @renamed;
$pcount = 0;
foreach (@piclist) {
last if $stop;
$pcount++;
my $pic = $_;
my $dpic = "$tdir/$pic";
$rotext->insert('end', " ($pcount/".scalar @piclist.") $pic ", "G"); $rotext->see('end');
if (!-f $dpic) {
$rotext->insert('end', " *** $dpic is missing - skipping! ***", "R"); $rotext->see('end');
warn "importPictures: $dpic is missing - skipping!\n";
next;
}
my $tmppic = "$dpic"."-cjpg"; # temporary file
##############################################################
##### interpolate dead pixels
if ($config{ImportDeadPixel}) {
if (checkWriteable($dpic)) {
# check if temp file exists
if (checkTempFile($tmppic)) {
$rotext->insert('end', "interpolating, "); $rotext->see('end');
# call external command jpegpixi
$command = "jpegpixi -m ".$config{DeadPixelMethod}." \"$dpic\" \"$tmppic\" ".$config{DeadPixelStr};
print "command = $command\n" if $verbose;
execute($command);
# now overwrite the original pic with the temp file and delete the temp file
overwrite("$dpic", "$tmppic");
} else {
warn "importPictures: problem with temppic ($tmppic)";
}
} else {
warn "importPictures: picture $pic is not writeable";
}
}
##############################################################
##### auto rotate pics
if ($config{ImportRotate}) {
$rotext->insert('end', "rotating, "); $rotext->see('end');
$command = "jhead -autorot \"$dpic\" ";
print "command = $command\n" if $verbose;
execute($command);
}
##############################################################
##### add file name to comment
if ($config{NameComment}) {
$rotext->insert('end', "adding name to comment, "); $rotext->see('end');
my $com = $pic;
if (($config{NameComRmSuffix}) and ($pic =~ /(.*)(\.jp(g|eg))/i)) {
$com = $1; # just the file name without .jp(e)g suffix
}
# add the filename as comment
addCommentToPic($com, $dpic, NO_TOUCH) if ($com ne "");
}
##############################################################
##### add IPTC template to picture
if ($config{ImportAddIPTC} and defined $config{ImportIPTCTempl} and -f $config{ImportIPTCTempl}) {
$rotext->insert('end', "adding IPTC, "); $rotext->see('end');
# add IPTC to pic
my $meta = getMetaData($dpic, 'APP13');
if (defined $meta) {
# todo, we could also use UPDATE or REPLACE here
$meta->set_app13_data($iptc, 'ADD', 'IPTC');
# make the SupplementalCategories and Keywords unique and sorted
uniqueIPTC($meta);
$meta->save();
}
}
##############################################################
##### add comment to picture
if ($config{ImportAddCom} and defined $config{ImportAddComment} and $config{ImportAddComment} ne '') {
$rotext->insert('end', "adding comment, "); $rotext->see('end');
# add comment to pic
addCommentToPic($config{ImportAddComment}, $dpic, NO_TOUCH);
}
##############################################################
##### smart rename pics
if ($config{ImportRename}) {
$rotext->insert('end', "renaming "); $rotext->see('end');
my $newname = "";
my $doForAll = 1; # use the file date, if there is no EXIF date without asking
my $rc = applyRenameFormat($dpic, $config{FileNameFormat}, \$newname, \$doForAll);
$newname = findNewName("$tdir/$newname");
if (($rc ne "Skip this picture") and ($rc ne "Cancel all")) {
if (-f "$tdir/$newname") { # just a safety check
warn "$newname already exists - skipping\n";
next;
}
print "renaming from $pic to $newname\n" if $verbose;
# rename the picture
if (!rename ($dpic, "$tdir/$newname")) {
# rename failed
$top->messageBox(-icon => 'warning', -message => "Could not rename $pic to $newname: $!",
-title => 'Error', -type => 'OK');
}
else {
# todo: rename raw pics as option (but how to handle renameSmartFix?
push @renamed, "$tdir/$newname";
}
}
}
$rotext->insert('end', "\n"); $rotext->see('end');
$rotext->update;
} # foreach pics end
my $errors = "";
renameSmartFix(\$errors, @renamed) if $config{ImportRename};
}
$stopB->configure(-state => "disabled");
##############################################################
##### delete worthless camera state files
if ($config{ImportDeleteCameraJunk}) {
my @junkfiles = grep {m/.*\.($cameraJunkSuffixes)$/i} @importfiles;
$pcount = 0;
$stopB->configure(-state => 'normal');
foreach (@junkfiles) {
last if $stop;
$pcount++;
$rotext->insert('end', " ($pcount/".scalar @junkfiles.") deleting $_\n"); $rotext->see('end'); $rotext->update;
removeFile("$tdir/$_");
}
$stopB->configure(-state => "disabled");
}
##############################################################
##### delete imported pics
if ($config{ImportDelete}) {
# check if everything is alright
if (($filediff > 0) or ($sizediff > 0)) {
my $rc = $top->messageBox(-icon => 'question',
-message => "There have been some warnings while importing.\nShould I continue and delete the ".scalar @importfiles." files in the source directory?",
-title => "Continue?", -type => 'OKCancel');
return 0 if ($rc !~ m/Ok/i);
}
$pcount = 0;
$stopB->configure(-state => 'normal');
# remove the pics on the source dir
foreach (@importfiles) {
last if $stop;
$pcount++;
$rotext->insert('end', " ($pcount/".scalar @importfiles.") deleting $_\n"); $rotext->see('end'); $rotext->update;
removeFile("$source/$_");
}
}
} # foreach dirs end
$stopB->configure(-state => "disabled");
##############################################################
##### unmount device
if ($config{ImportUnmount}) {
my $command;
my $mountpoint;
if ($MacOSX) {
$command = "diskutil unmount";
$mountpoint = $config{ImportSource};
} else {
# todo: don't know what fits better
#$command = "umount";
$command = "eject";
$mountpoint = $config{ImportDevice};
}
$rotext->insert('end', "unmounting $mountpoint\n"); $rotext->see('end'); $rotext->update;
execute("$command \"$mountpoint\"");
}
($s,$m,$ho,$d,$mo,$y) = localtime(time());
$time = sprintf "%02d:%02d:%02d", $ho, $m, $s;
$rotext->insert('end', "$time import finished!\n", "B"); $rotext->see('end'); $rotext->update;
return 1;
}
##############################################################
# mountDialog
##############################################################
sub mountDialog {
my $device = $config{ImportDevice};
my $rc = myEntryDialog('Set mount device',
'Please enter the device to mount/unmount, when importing pictures.
(Mapivi will execute the commands "mount" and "umount" with this device.)',
\$device);
if ($rc eq 'OK') {
$config{ImportDevice} = $device;
}
}
##############################################################
# setChildState - changes the state of a widget and
# all his descendants (if possible)
##############################################################
sub setChildState {
my $widget = shift;
my $state = shift;
$widget->Walk( sub {
print "changing widget ",ref($_[0])," to state $state\n" if $verbose;
eval { $_[0]->configure(-state => $state); }
});
}
##############################################################
# progressWinInit
##############################################################
sub progressWinInit($$) {
my $widget = shift;
my $title = shift;
# open window
my $pw = $widget->Toplevel();
$pw->withdraw;
$pw->title("Mapivi: $title");
$pw->iconimage($mapiviicon) if $mapiviicon;
$pw->iconname("Mapivi progress");
# init the values
$pw->{stop} = 0;
$pw->{percent} = 0;
$pw->{label} = "";
$pw->{label2} = "0% done";
$pw->{start_time} = Tk::timeofday();
$pw->Label(-textvariable => \$pw->{label}, -width => 80, -anchor => 'w', -bg => $config{ColorBG})->pack(-padx => 3, -pady => 10);
$pw->Label(-textvariable => \$pw->{label2}, -anchor => 'w', -bg => $config{ColorBG})->pack(-padx => 3, -pady => 10);
$pw->{progbar} =
$pw->ProgressBar(-takefocus => 0,
-borderwidth => 1,
-relief => 'sunken',
#-width => (2*$config{FontSize}), # try to guess the height of the labels
#-length => 30,
-padx => 0,
-pady => 0,
-variable => \$pw->{percent},
-colors => [0 => $config{ColorProgress}],
-resolution => 1,
-blocks => 10,
-anchor => 'w',
-from => 0,
-to => 100,
)->pack(-fill => 'both', -expand => 0, -padx => 3, -pady => 10);
$pw->Button(-text => 'Cancel',
-command => sub {
$pw->{stop} = 1;
$pw->{label} = "stopping ...";
$pw->update();
})->pack(-fill => 'x', -expand => 1, -padx => 3, -pady => 10);
centerWindow($pw);
$pw->deiconify;
$pw->raise;
return $pw;
}
##############################################################
# progressWinCheck
##############################################################
sub progressWinCheck($) {
my $pw = shift;
warn "pw->stop undefined!" unless defined($pw->{stop});
return ($pw->{stop});
}
##############################################################
# progressWinUpdate
##############################################################
sub progressWinUpdate($$$$) {
my $pw = shift;
# show progress and found pics every 0.3 seconds - idea from Slaven
return unless (!defined $pw->{last_time} || Tk::timeofday()-$pw->{last_time} > 0.3);
my $string = shift;
my $index = shift;
my $total = shift;
if ($total == 0) {
warn "total ($total) is zero!";
return;
}
my $add_str = "";
my $percent = int(($index/$total)*100);
my $min = 0;
my $sec = int(Tk::timeofday() - $pw->{start_time});
# try to estimate the time to go, after 3% are finished
if (($percent > 3) and ($sec > 10)) {
my $to_go = int($sec * $total / $index) - $sec; # time to go in seconds
my $min = 0;
if ($to_go > 59) { $min = int($to_go / 60); $to_go = $to_go % 60; } # modulo
$add_str = sprintf ", estimated time to go %d:%02d",$min, $to_go;
}
if ($sec > 59) { $min = int($sec / 60); $sec = $sec % 60; } # modulo
$pw->{label2} = sprintf "%d%% done, time elapsed %d:%02d%s",$percent,$min,$sec, $add_str;
$pw->{percent} = $percent;
$pw->{label} = $string;
$pw->iconname("$percent% done");
$pw->update();
$pw->{last_time} = Tk::timeofday();
}
##############################################################
# progressWinEnd
##############################################################
sub progressWinEnd($) {
my $pw = shift;
if (Exists($pw)) {
$pw->withdraw;
$pw->destroy;
}
}
##############################################################
# topFullScreen - toggle the main window to fullscreen and back
##############################################################
sub topFullScreen {
if ($topFullScreen == 0) {
# save layout and geometry
%topFullSceenConf = %config;
$topFullSceenConf{Geometry} = $top->geometry; # save the actual geometry
}
toggle(\$topFullScreen);
# remove/add the window border
topToggleBorder() if $config{ToggleBorder};
if ($topFullScreen) { # switch to fullscreen
#unset geometry
#$top->geometry("");
#$top->geometry("+0+0");
$config{ShowMenu} = 0;
$config{ShowInfoFrame} = 0;
$config{ShowCommentField} = 0;
$config{ShowEXIFField} = 0;
$config{Layout} = 4 ;
layout(1);
#$mainF->configure(-bg => $config{ColorBGCanvas});
#$mainF->configure(-fg => $config{ColorBGCanvas});
#$mainF->configure(-highlightcolor => $config{ColorBGCanvas});
#$mainF->configure(-highlightbackground => $config{ColorBGCanvas});
$top->withdraw;
my $w = $top->screenwidth; # - 20;
my $h = $top->screenheight; # - 80;
$top->geometry("${w}x${h}+0+0");
$top->deiconify;
if ($config{ToggleBorder}) {
$top->grabGlobal;
$top->focusForce;
}
} else { # reset from fullscreen mode
$top->withdraw;
$mainF->configure(-bg => $config{ColorBGCanvas});
$top->geometry($topFullSceenConf{Geometry});
$config{ShowMenu} = $topFullSceenConf{ShowMenu};
$config{ShowInfoFrame} = $topFullSceenConf{ShowInfoFrame};
$config{ShowCommentField} = $topFullSceenConf{ShowCommentField};
$config{ShowEXIFField} = $topFullSceenConf{ShowEXIFField};
$config{Layout} = $topFullSceenConf{Layout};
$top->deiconify;
layout(1);
}
# the canvas size has changed, so we need to rezoom all cached pics
deleteCachedPics();
fitPicture();
#$top->deiconify;
#$top->focus;
}
##############################################################
# topToggleBorder
##############################################################
sub topToggleBorder {
return unless $config{ToggleBorder};
print "fullscreen: $topFullScreen\n" if $verbose;
$top->overrideredirect($topFullScreen); # toggle window decoration on/off
if ($topFullScreen) { # switch to fullscreen
# rebind the Esc-key to escape from fullscreen
$top->bind('<Key-Escape>', sub { topFullScreen(); Tk->break; } );
# grab the focus to receive all keys - this is a bit dangerous
$top->bind('<Enter>', sub { $top->focusForce; $top->grabGlobal; });
$top->bind('<Leave>', sub { $top->grabRelease; });
}
else {
# rebind Esc-key to the old binding
#$top->bind('<Key-Alt_L>', sub { Tk->break; } );
$top->bind('<Key-Escape>', sub { $top->iconify; Tk->break; } );
$top->bind('<Enter>', sub { Tk->break; });
$top->bind('<Leave>', sub { Tk->break; });
$top->grabRelease;
}
}
##############################################################
# mapiviUpdate - called if the mapivi version number changed
# between two starts of mapivi (introduced with
# version 0.7.3)
##############################################################
sub mapiviUpdate {
my $ver = 'unknown';
$ver = $config{Version} if ((defined $config{Version}) and ($config{Version} ne '000'));
print "Mapivi up/downgrade from version $ver to version $version detected\n"
}
##############################################################
# beep - play a beep sound (bell)
##############################################################
sub beep {
print "\a"; # this is a beep
# if this won't work, try this:
#print "\007";
}
##############################################################
# gratulation
##############################################################
sub gratulation {
my $nr = $config{NrOfRuns};
my $text = <<"EOT";
Gratulation!!!
You\'ve started MaPiVi $nr times!
You are a real MaPiVi Power User!
I would be really glad to receive an email about this event.
Mapivi is free software, but if you wish you may make a donation,
please go to http://herrmanns-stern.de/software/donations.shtml
Your donation of any amount will encourage me to continue the
development of Mapivi.
Maybe you could also tell me on which hardware and operating system you are using MaPiVi?
I would like to add this information on the supported systems section of the README file.
Martin Herrmann (author of Mapivi)
email: Martin-Herrmann\@gmx.de
EOT
showText("MaPiVi start nr. $nr", $text, NO_WAIT);
}
##############################################################
# showCopyright
##############################################################
sub showCopyright {
print <<EOCopyright;
Mapivi $version - Martin's Picture Viewer and Organizer
Copyright (C) 2002, 2003, 2004, 2005, 2006 Martin Herrmann
Mapivi comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute
it under certain conditions.
EOCopyright
# in front of EOCopyright are no blanks allowed!
}
# Tell Emacs that this is really a perl script
# Local Variables:
# mode:perl
# End:
|