/usr/share/perl5/Gscan2pdf/Document.pm is in gscan2pdf 1.2.3-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 | package Gscan2pdf::Document;
use strict;
use warnings;
use feature "switch";
use threads;
use threads::shared;
use Thread::Queue;
use Gscan2pdf::Scanner::Options;
use Gscan2pdf::Page;
use Glib 1.210 qw(TRUE FALSE)
; # To get TRUE and FALSE. 1.210 necessary for Glib::SOURCE_REMOVE and Glib::SOURCE_CONTINUE
use Socket;
use FileHandle;
use Image::Magick;
use File::Temp; # To create temporary files
use File::Basename; # Split filename into dir, file, ext
use File::Copy;
use Storable qw(store retrieve);
use Archive::Tar; # For session files
use Proc::Killfam;
use Locale::gettext 1.05; # For translations
use IPC::Open3 'open3';
use Symbol; # for gensym
use Try::Tiny;
use Set::IntSpan 1.10; # For size method for page numbering issues
use PDF::API2;
use English qw( -no_match_vars ); # for $PROCESS_ID, $INPUT_RECORD_SEPARATOR
use Readonly;
Readonly our $POINTS_PER_INCH => 72;
Readonly my $_POLL_INTERVAL => 100; # ms
Readonly my $THUMBNAIL => 100; # pixels
Readonly my $YEAR => 5;
Readonly my $BOX_TOLERANCE => 5;
BEGIN {
use Exporter ();
our ( $VERSION, @EXPORT_OK, %EXPORT_TAGS );
$VERSION = '1.2.3';
use base qw(Exporter Gtk2::Ex::Simple::List);
%EXPORT_TAGS = (); # eg: TAG => [ qw!name1 name2! ],
# your exported package globals go here,
# as well as any optionally exported functions
@EXPORT_OK = qw();
# define hidden string column for page data
Gtk2::Ex::Simple::List->add_column_type(
'hstring',
type => 'Glib::Scalar',
attr => 'hidden'
);
}
our @EXPORT_OK;
my $_PID = 0; # flag to identify which process to cancel
my $jobs_completed = 0;
my $jobs_total = 0;
my $EMPTY = q{};
my $SPACE = q{ };
my ( $_self, $d, $logger, $paper_sizes );
my %format = (
'pnm' => 'Portable anymap',
'ppm' => 'Portable pixmap format (color)',
'pgm' => 'Portable graymap format (gray scale)',
'pbm' => 'Portable bitmap format (black and white)',
);
sub setup {
( my $class, $logger ) = @_;
$_self = {};
$d = Locale::gettext->domain(Glib::get_application_name);
Gscan2pdf::Page->set_logger($logger);
$_self->{requests} = Thread::Queue->new;
$_self->{info_queue} = Thread::Queue->new;
$_self->{page_queue} = Thread::Queue->new;
share $_self->{status};
share $_self->{message};
share $_self->{progress};
share $_self->{process_name};
share $_self->{cancel};
$_self->{thread} = threads->new( \&_thread_main, $_self );
return;
}
sub new {
my ( $class, %options ) = @_;
my $self = Gtk2::Ex::Simple::List->new(
q{#} => 'int',
$d->get('Thumbnails') => 'pixbuf',
'Page Data' => 'hstring',
);
$self->get_selection->set_mode('multiple');
$self->set_headers_visible(FALSE);
$self->set_reorderable(TRUE);
for ( keys %options ) {
$self->{$_} = $options{$_};
}
# Default thumbnail sizes
if ( not defined( $self->{heightt} ) ) { $self->{heightt} = $THUMBNAIL }
if ( not defined( $self->{widtht} ) ) { $self->{widtht} = $THUMBNAIL }
bless( $self, $class );
return $self;
}
# Set the paper sizes in the manager and worker threads
sub set_paper_sizes {
( my $class, $paper_sizes ) = @_;
_enqueue_request( 'paper_sizes', { paper_sizes => $paper_sizes } );
return;
}
sub quit {
_enqueue_request('quit');
$_self->{thread}->join();
$_self->{thread} = undef;
return;
}
# Flag the given process to cancel itself
sub cancel {
my ( $self, $pid, $callback ) = @_;
if ( defined $self->{running_pids}{$pid} ) {
$self->{cancel_cb}{$pid} = $callback;
}
return;
}
sub get_file_info {
my ( $self, %options ) = @_;
# File in which to store the subprocess ID so that it can be killed if necessary
my $pidfile = File::Temp->new( DIR => $self->{dir}, SUFFIX => '.pid' );
my $sentinel =
_enqueue_request( 'get-file-info',
{ path => $options{path}, pidfile => "$pidfile" } );
return $self->_monitor_process(
sentinel => $sentinel,
pidfile => $pidfile,
info => TRUE,
queued_callback => $options{queued_callback},
started_callback => $options{started_callback},
running_callback => $options{running_callback},
error_callback => $options{error_callback},
cancelled_callback => $options{cancelled_callback},
finished_callback => $options{finished_callback},
);
}
sub import_file {
my ( $self, %options ) = @_;
# File in which to store the process ID so that it can be killed if necessary
my $pidfile = File::Temp->new( DIR => $self->{dir}, SUFFIX => '.pid' );
my $sentinel = _enqueue_request(
'import-file',
{
info => $options{info},
first => $options{first},
last => $options{last},
dir => "$self->{dir}",
pidfile => "$pidfile"
}
);
return $self->_monitor_process(
sentinel => $sentinel,
pidfile => $pidfile,
add => $options{last} - $options{first} + 1,
queued_callback => $options{queued_callback},
started_callback => $options{started_callback},
running_callback => $options{running_callback},
error_callback => $options{error_callback},
cancelled_callback => $options{cancelled_callback},
finished_callback => $options{finished_callback},
);
}
sub fetch_file {
my ( $self, $n ) = @_;
my $i = 0;
if ($n) {
while ( $i < $n ) {
my $page = $_self->{page_queue}->dequeue;
if ( ref($page) eq $EMPTY ) {
$n = $page;
return $self->fetch_file($n);
}
else {
$self->add_page( $page->thaw );
++$i;
}
}
}
else {
while ( defined( my $page = $_self->{page_queue}->dequeue_nb() ) ) {
if ( ref($page) eq $EMPTY ) {
$n = $page;
return $self->fetch_file($n);
}
else {
$self->add_page( $page->thaw );
++$i;
}
}
}
return $i;
}
# Check how many pages could be scanned
sub pages_possible {
my ( $self, $start, $step ) = @_;
my $n = 0;
my $i = $#{ $self->{data} };
while (TRUE) {
# Settings take us into negative page range
if ( $start + $n * $step < 1 ) { ## no critic (ProhibitCascadingIfElse)
return $n;
}
# Empty document and negative step
elsif ( $i < 0 and $step < 0 ) {
return -$start / $step;
}
# Empty document, or checked beyond end of document, allow infinite pages
elsif (
(
@{ $self->{data} } == 0
or $self->{data}[ $#{ $self->{data} } ][0] < $start
)
and $step > 0
)
{
return -1; ## no critic (ProhibitMagicNumbers)
}
# Found existing page
elsif ( $self->{data}[$i][0] == $start + $n * $step ) {
return $n;
}
# Current page doesn't exist, check for at least one more
elsif ( $n == 0 ) {
++$n;
}
# In the middle of the document, scan back to find page nearer start
elsif ( $self->{data}[$i][0] > $start + $n * $step and $i > 0 ) {
--$i;
}
# Try one more page
else {
++$n;
}
}
return;
}
# Add a new page to the document
sub add_page {
my ( $self, $page, $pagenum, $success_cb ) = @_;
# Add to the page list
if ( not defined($pagenum) ) { $pagenum = $#{ $self->{data} } + 2 }
# Block the row-changed signal whilst adding the scan (row) and sorting it.
if ( defined $self->{row_changed_signal} ) {
$self->get_model->signal_handler_block( $self->{row_changed_signal} );
}
my $thumb = get_pixbuf( $page->{filename}, $self->{heightt}, $self->{widtht} );
my $resolution = $page->resolution($paper_sizes);
push @{ $self->{data} }, [ $pagenum, $thumb, $page ];
$logger->info(
"Added $page->{filename} at page $pagenum with resolution $resolution");
# Block selection_changed_signal to prevent its firing changing pagerange to all
if ( defined $self->{selection_changed_signal} ) {
$self->get_selection->signal_handler_block(
$self->{selection_changed_signal} );
}
$self->get_selection->unselect_all;
$self->manual_sort_by_column(0);
if ( defined $self->{selection_changed_signal} ) {
$self->get_selection->signal_handler_unblock(
$self->{selection_changed_signal} );
}
if ( defined $self->{row_changed_signal} ) {
$self->get_model->signal_handler_unblock( $self->{row_changed_signal} );
}
my @page;
# Due to the sort, must search for new page
$page[0] = 0;
# $page[0] < $#{$self -> {data}} needed to prevent infinite loop in case of
# error importing.
while ( $page[0] < $#{ $self->{data} }
and $self->{data}[ $page[0] ][0] != $pagenum )
{
++$page[0];
}
$self->select(@page);
if ($success_cb) { $success_cb->() }
return $page[0];
}
# Helpers:
sub compare_numeric_col { ## no critic (RequireArgUnpacking, RequireFinalReturn)
$_[0] <=> $_[1];
}
sub compare_text_col { ## no critic (RequireArgUnpacking, RequireFinalReturn)
$_[0] cmp $_[1];
}
# Manual one-time sorting of the simplelist's data
sub manual_sort_by_column {
my ( $self, $sortcol ) = @_;
# The sort function depends on the column type
my %sortfuncs = (
'Glib::Scalar' => \&compare_text_col,
'Glib::String' => \&compare_text_col,
'Glib::Int' => \&compare_numeric_col,
'Glib::Double' => \&compare_numeric_col,
);
# Remember, this relies on the fact that simplelist keeps model
# and view column indices aligned.
my $sortfunc = $sortfuncs{ $self->get_model->get_column_type($sortcol) };
# Deep copy the tied data so we can sort it. Otherwise, very bad things happen.
my @data = map { [ @{$_} ] } @{ $self->{data} };
@data = sort { $sortfunc->( $a->[$sortcol], $b->[$sortcol] ) } @data;
@{ $self->{data} } = @data;
return;
}
# Returns the pixbuf scaled to fit in the given box
sub get_pixbuf {
my ( $filename, $height, $width ) = @_;
my $pixbuf;
try {
$pixbuf =
Gtk2::Gdk::Pixbuf->new_from_file_at_scale( $filename, $width, $height,
TRUE );
}
catch {
$logger->warn("Caught error getting pixbuf: $_");
};
return $pixbuf;
}
sub save_pdf {
my ( $self, %options ) = @_;
for my $i ( 0 .. $#{ $options{list_of_pages} } ) {
$options{list_of_pages}->[$i] =
$options{list_of_pages}->[$i]
->freeze; # sharing File::Temp objects causes problems
}
# File in which to store the process ID so that it can be killed if necessary
my $pidfile = File::Temp->new( DIR => $self->{dir}, SUFFIX => '.pid' );
my $sentinel = _enqueue_request(
'save-pdf',
{
path => $options{path},
list_of_pages => $options{list_of_pages},
metadata => $options{metadata},
options => $options{options},
dir => "$self->{dir}",
pidfile => "$pidfile"
}
);
return $self->_monitor_process(
sentinel => $sentinel,
pidfile => $pidfile,
queued_callback => $options{queued_callback},
started_callback => $options{started_callback},
running_callback => $options{running_callback},
error_callback => $options{error_callback},
cancelled_callback => $options{cancelled_callback},
finished_callback => $options{finished_callback},
);
}
sub save_djvu {
my ( $self, %options ) = @_;
for my $i ( 0 .. $#{ $options{list_of_pages} } ) {
$options{list_of_pages}->[$i] =
$options{list_of_pages}->[$i]
->freeze; # sharing File::Temp objects causes problems
}
# File in which to store the process ID so that it can be killed if necessary
my $pidfile = File::Temp->new( DIR => $self->{dir}, SUFFIX => '.pid' );
my $sentinel = _enqueue_request(
'save-djvu',
{
path => $options{path},
list_of_pages => $options{list_of_pages},
dir => "$self->{dir}",
pidfile => "$pidfile"
}
);
return $self->_monitor_process(
sentinel => $sentinel,
pidfile => $pidfile,
queued_callback => $options{queued_callback},
started_callback => $options{started_callback},
running_callback => $options{running_callback},
error_callback => $options{error_callback},
cancelled_callback => $options{cancelled_callback},
finished_callback => $options{finished_callback},
);
}
sub save_tiff {
my ( $self, %options ) = @_;
for my $i ( 0 .. $#{ $options{list_of_pages} } ) {
$options{list_of_pages}->[$i] =
$options{list_of_pages}->[$i]
->freeze; # sharing File::Temp objects causes problems
}
# File in which to store the process ID so that it can be killed if necessary
my $pidfile = File::Temp->new( DIR => $self->{dir}, SUFFIX => '.pid' );
my $sentinel = _enqueue_request(
'save-tiff',
{
path => $options{path},
list_of_pages => $options{list_of_pages},
options => $options{options},
ps => $options{ps},
dir => "$self->{dir}",
pidfile => "$pidfile"
}
);
return $self->_monitor_process(
sentinel => $sentinel,
pidfile => $pidfile,
queued_callback => $options{queued_callback},
started_callback => $options{started_callback},
running_callback => $options{running_callback},
error_callback => $options{error_callback},
cancelled_callback => $options{cancelled_callback},
finished_callback => $options{finished_callback},
);
}
sub rotate {
my ( $self, %options ) = @_;
my $sentinel = _enqueue_request(
'rotate',
{
angle => $options{angle},
page => $options{page}->freeze,
dir => "$self->{dir}"
}
);
return $self->_monitor_process(
sentinel => $sentinel,
update_slist => TRUE,
queued_callback => $options{queued_callback},
started_callback => $options{started_callback},
running_callback => $options{running_callback},
error_callback => $options{error_callback},
cancelled_callback => $options{cancelled_callback},
display_callback => $options{display_callback},
finished_callback => $options{finished_callback},
);
}
sub update_page {
my ( $self, $display_callback ) = @_;
my (@out);
my $data = $_self->{page_queue}->dequeue;
# find old page
my $i = 0;
while ( $i <= $#{ $self->{data} }
and $self->{data}[$i][2]{filename} ne $data->{old}{filename} )
{
$i++;
}
# if found, replace with new one
if ( $i <= $#{ $self->{data} } ) {
# Move the temp file from the thread to a temp object that will be automatically cleared up
my $new = $data->{new}->thaw;
if ( defined $self->{row_changed_signal} ) {
$self->get_model->signal_handler_block( $self->{row_changed_signal} );
}
my $resolution = $new->resolution($paper_sizes);
$logger->info(
"Replaced $self->{data}[$i][2]->{filename} at page $self->{data}[$i][0] with $new->{filename}, resolution $resolution"
);
$self->{data}[$i][1] =
get_pixbuf( $new->{filename}, $self->{heightt}, $self->{widtht} );
$self->{data}[$i][2] = $new;
push @out, $new;
if ( defined $data->{new2} ) {
$new = $data->{new2}->thaw;
splice @{ $self->{data} }, $i + 1, 0,
[
$self->{data}[$i][0] + 1,
get_pixbuf( $new->{filename}, $self->{heightt}, $self->{widtht} ), $new
];
$logger->info(
"Inserted $new->{filename} at page ",
$self->{data}[ $i + 1 ][0],
" with resolution $resolution"
);
push @out, $new;
}
if ( defined $self->{row_changed_signal} ) {
$self->get_model->signal_handler_unblock( $self->{row_changed_signal} );
}
my @selected = $self->get_selected_indices;
if ( @selected and $i == $selected[0] ) { $self->select(@selected) }
if ($display_callback) { $display_callback->( $self->{data}[$i][2] ) }
}
return \@out;
}
sub save_image {
my ( $self, %options ) = @_;
for my $i ( 0 .. $#{ $options{list_of_pages} } ) {
$options{list_of_pages}->[$i] =
$options{list_of_pages}->[$i]
->freeze; # sharing File::Temp objects causes problems
}
# File in which to store the process ID so that it can be killed if necessary
my $pidfile = File::Temp->new( DIR => $self->{dir}, SUFFIX => '.pid' );
my $sentinel = _enqueue_request(
'save-image',
{
path => $options{path},
list_of_pages => $options{list_of_pages},
pidfile => "$pidfile"
}
);
return $self->_monitor_process(
sentinel => $sentinel,
pidfile => $pidfile,
queued_callback => $options{queued_callback},
started_callback => $options{started_callback},
running_callback => $options{running_callback},
error_callback => $options{error_callback},
cancelled_callback => $options{cancelled_callback},
finished_callback => $options{finished_callback},
);
}
sub save_text {
my ( $self, %options ) = @_;
for my $i ( 0 .. $#{ $options{list_of_pages} } ) {
$options{list_of_pages}->[$i] =
$options{list_of_pages}->[$i]
->freeze; # sharing File::Temp objects causes problems
}
my $sentinel = _enqueue_request(
'save-text',
{
path => $options{path},
list_of_pages => $options{list_of_pages},
}
);
return $self->_monitor_process(
sentinel => $sentinel,
queued_callback => $options{queued_callback},
started_callback => $options{started_callback},
running_callback => $options{running_callback},
error_callback => $options{error_callback},
cancelled_callback => $options{cancelled_callback},
finished_callback => $options{finished_callback},
);
}
sub analyse {
my ( $self, %options ) = @_;
my $sentinel =
_enqueue_request( 'analyse', { page => $options{page}->freeze } );
return $self->_monitor_process(
sentinel => $sentinel,
update_slist => TRUE,
queued_callback => $options{queued_callback},
started_callback => $options{started_callback},
running_callback => $options{running_callback},
error_callback => $options{error_callback},
cancelled_callback => $options{cancelled_callback},
finished_callback => $options{finished_callback},
);
}
sub threshold {
my ( $self, %options ) = @_;
my $sentinel = _enqueue_request(
'threshold',
{
threshold => $options{threshold},
page => $options{page}->freeze,
dir => "$self->{dir}"
}
);
return $self->_monitor_process(
sentinel => $sentinel,
update_slist => TRUE,
queued_callback => $options{queued_callback},
started_callback => $options{started_callback},
running_callback => $options{running_callback},
error_callback => $options{error_callback},
cancelled_callback => $options{cancelled_callback},
display_callback => $options{display_callback},
finished_callback => $options{finished_callback},
);
}
sub negate {
my ( $self, %options ) = @_;
my $sentinel =
_enqueue_request( 'negate',
{ page => $options{page}->freeze, dir => "$self->{dir}" } );
return $self->_monitor_process(
sentinel => $sentinel,
update_slist => TRUE,
queued_callback => $options{queued_callback},
started_callback => $options{started_callback},
running_callback => $options{running_callback},
error_callback => $options{error_callback},
cancelled_callback => $options{cancelled_callback},
display_callback => $options{display_callback},
finished_callback => $options{finished_callback},
);
}
sub unsharp {
my ( $self, %options ) = @_;
my $sentinel = _enqueue_request(
'unsharp',
{
page => $options{page}->freeze,
radius => $options{radius},
sigma => $options{sigma},
amount => $options{amount},
threshold => $options{threshold},
dir => "$self->{dir}",
}
);
return $self->_monitor_process(
sentinel => $sentinel,
update_slist => TRUE,
queued_callback => $options{queued_callback},
started_callback => $options{started_callback},
running_callback => $options{running_callback},
error_callback => $options{error_callback},
cancelled_callback => $options{cancelled_callback},
display_callback => $options{display_callback},
finished_callback => $options{finished_callback},
);
}
sub crop {
my ( $self, %options ) = @_;
my $sentinel = _enqueue_request(
'crop',
{
page => $options{page}->freeze,
x => $options{x},
y => $options{y},
w => $options{w},
h => $options{h},
dir => "$self->{dir}",
}
);
return $self->_monitor_process(
sentinel => $sentinel,
update_slist => TRUE,
queued_callback => $options{queued_callback},
started_callback => $options{started_callback},
running_callback => $options{running_callback},
error_callback => $options{error_callback},
cancelled_callback => $options{cancelled_callback},
display_callback => $options{display_callback},
finished_callback => $options{finished_callback},
);
}
sub to_png {
my ( $self, %options ) = @_;
my $sentinel =
_enqueue_request( 'to-png',
{ page => $options{page}->freeze, dir => "$self->{dir}" } );
return $self->_monitor_process(
sentinel => $sentinel,
update_slist => TRUE,
queued_callback => $options{queued_callback},
started_callback => $options{started_callback},
running_callback => $options{running_callback},
error_callback => $options{error_callback},
cancelled_callback => $options{cancelled_callback},
finished_callback => $options{finished_callback},
);
}
sub tesseract {
my ( $self, %options ) = @_;
# File in which to store the process ID so that it can be killed if necessary
my $pidfile = File::Temp->new( DIR => $self->{dir}, SUFFIX => '.pid' );
my $sentinel = _enqueue_request(
'tesseract',
{
page => $options{page}->freeze,
language => $options{language},
pidfile => "$pidfile"
}
);
return $self->_monitor_process(
sentinel => $sentinel,
update_slist => TRUE,
pidfile => $pidfile,
queued_callback => $options{queued_callback},
started_callback => $options{started_callback},
running_callback => $options{running_callback},
error_callback => $options{error_callback},
cancelled_callback => $options{cancelled_callback},
display_callback => $options{display_callback},
finished_callback => $options{finished_callback},
);
}
sub ocropus {
my ( $self, %options ) = @_;
# File in which to store the process ID so that it can be killed if necessary
my $pidfile = File::Temp->new( DIR => $self->{dir}, SUFFIX => '.pid' );
my $sentinel = _enqueue_request(
'ocropus',
{
page => $options{page}->freeze,
language => $options{language},
pidfile => "$pidfile"
}
);
return $self->_monitor_process(
sentinel => $sentinel,
update_slist => TRUE,
pidfile => $pidfile,
queued_callback => $options{queued_callback},
started_callback => $options{started_callback},
running_callback => $options{running_callback},
error_callback => $options{error_callback},
cancelled_callback => $options{cancelled_callback},
display_callback => $options{display_callback},
finished_callback => $options{finished_callback},
);
}
sub cuneiform {
my ( $self, %options ) = @_;
# File in which to store the process ID so that it can be killed if necessary
my $pidfile = File::Temp->new( DIR => $self->{dir}, SUFFIX => '.pid' );
my $sentinel = _enqueue_request(
'cuneiform',
{
page => $options{page}->freeze,
language => $options{language},
pidfile => "$pidfile"
}
);
return $self->_monitor_process(
sentinel => $sentinel,
update_slist => TRUE,
pidfile => $pidfile,
queued_callback => $options{queued_callback},
started_callback => $options{started_callback},
running_callback => $options{running_callback},
error_callback => $options{error_callback},
cancelled_callback => $options{cancelled_callback},
display_callback => $options{display_callback},
finished_callback => $options{finished_callback},
);
}
sub gocr {
my ( $self, %options ) = @_;
# File in which to store the process ID so that it can be killed if necessary
my $pidfile = File::Temp->new( DIR => $self->{dir}, SUFFIX => '.pid' );
my $sentinel =
_enqueue_request( 'gocr',
{ page => $options{page}->freeze, pidfile => "$pidfile" } );
return $self->_monitor_process(
sentinel => $sentinel,
update_slist => TRUE,
pidfile => $pidfile,
queued_callback => $options{queued_callback},
started_callback => $options{started_callback},
running_callback => $options{running_callback},
error_callback => $options{error_callback},
cancelled_callback => $options{cancelled_callback},
display_callback => $options{display_callback},
finished_callback => $options{finished_callback},
);
}
sub unpaper {
my ( $self, %options ) = @_;
# File in which to store the process ID so that it can be killed if necessary
my $pidfile = File::Temp->new( DIR => $self->{dir}, SUFFIX => '.pid' );
my $sentinel = _enqueue_request(
'unpaper',
{
page => $options{page}->freeze,
options => $options{options},
pidfile => "$pidfile",
dir => "$self->{dir}",
}
);
return $self->_monitor_process(
sentinel => $sentinel,
update_slist => TRUE,
pidfile => $pidfile,
queued_callback => $options{queued_callback},
started_callback => $options{started_callback},
running_callback => $options{running_callback},
error_callback => $options{error_callback},
cancelled_callback => $options{cancelled_callback},
display_callback => $options{display_callback},
finished_callback => $options{finished_callback},
);
}
sub user_defined {
my ( $self, %options ) = @_;
# File in which to store the process ID so that it can be killed if necessary
my $pidfile = File::Temp->new( DIR => $self->{dir}, SUFFIX => '.pid' );
my $sentinel = _enqueue_request(
'user-defined',
{
page => $options{page}->freeze,
command => $options{command},
dir => "$self->{dir}",
pidfile => "$pidfile"
}
);
return $self->_monitor_process(
sentinel => $sentinel,
update_slist => TRUE,
pidfile => $pidfile,
queued_callback => $options{queued_callback},
started_callback => $options{started_callback},
running_callback => $options{running_callback},
error_callback => $options{error_callback},
cancelled_callback => $options{cancelled_callback},
display_callback => $options{display_callback},
finished_callback => $options{finished_callback},
);
}
# Dump $self to a file.
# If a filename is given, zip it up as a session file
sub save_session {
my ( $self, $filename ) = @_;
my ( %session, @filenamelist );
for my $i ( 0 .. $#{ $self->{data} } ) {
$session{ $self->{data}[$i][0] }{filename} =
$self->{data}[$i][2]{filename}->filename;
push @filenamelist, $self->{data}[$i][2]{filename}->filename;
for my $key ( keys( %{ $self->{data}[$i][2] } ) ) {
if ( $key ne 'filename' ) {
$session{ $self->{data}[$i][0] }{$key} = $self->{data}[$i][2]{$key};
}
}
}
push @filenamelist, File::Spec->catfile( $self->{dir}, 'session' );
my @selection = $self->get_selected_indices;
@{ $session{selection} } = @selection;
store( \%session, File::Spec->catfile( $self->{dir}, 'session' ) );
if ( defined $filename ) {
my $tar = Archive::Tar->new;
$tar->add_files(@filenamelist);
$tar->write( $filename, TRUE, $EMPTY );
}
return;
}
sub open_session_file {
my ( $self, $filename, $error_callback ) = @_;
if ( not defined($filename) ) {
if ($error_callback) {
$error_callback->("Error: session file not supplied.");
}
return;
}
my $tar = Archive::Tar->new( $filename, TRUE );
my @filenamelist = $tar->list_files;
my @sessionfile = grep { /\/session$/xsm } @filenamelist;
my $sesdir = File::Spec->catfile( $self->{dir}, dirname( $sessionfile[0] ) );
for (@filenamelist) {
$tar->extract_file( $_, File::Spec->catfile( $sesdir, basename($_) ) );
}
$self->open_session( $sesdir, TRUE, $error_callback );
return;
}
sub open_session {
my ( $self, $sesdir, $delete, $error_callback ) = @_;
my $sessionfile = File::Spec->catfile( $sesdir, 'session' );
if ( not -r $sessionfile ) {
if ($error_callback) {
$error_callback->("Error: Unable to read $sessionfile");
}
return;
}
my $sessionref = retrieve($sessionfile);
my %session = %{$sessionref};
# Block the row-changed signal whilst adding the scan (row) and sorting it.
if ( defined $self->{row_changed_signal} ) {
$self->get_model->signal_handler_block( $self->{row_changed_signal} );
}
my @selection = @{ $session{selection} };
delete $session{selection};
for my $pagenum ( sort { $a <=> $b } ( keys(%session) ) ) {
# don't reuse session directory
$session{$pagenum}{dir} = $self->{dir};
$session{$pagenum}{delete} = $delete;
# correct the path now that it is relative to the current session dir
if ( $sesdir ne $self->{dir} ) {
$session{$pagenum}{filename} =
File::Spec->catfile( $sesdir, basename( $session{$pagenum}{filename} ) );
}
# Populate the SimpleList
try {
my $page = Gscan2pdf::Page->new( %{ $session{$pagenum} } );
my $thumb =
get_pixbuf( $page->{filename}, $self->{heightt}, $self->{widtht} );
push @{ $self->{data} }, [ $pagenum, $thumb, $page ];
}
catch {
if ($error_callback) {
$error_callback->(
sprintf( $d->get("Error importing page %d. Ignoring."), $pagenum ) );
}
};
}
if ( defined $self->{row_changed_signal} ) {
$self->get_model->signal_handler_unblock( $self->{row_changed_signal} );
}
$self->select(@selection);
return;
}
# Renumber pages
sub renumber {
my ( $self, $start, $step, $selection ) = @_;
if ( defined($start) ) {
if ( not defined($step) ) { $step = 1 }
if ( not defined($selection) ) { $selection = 'all' }
my @selection;
if ( $selection eq 'selected' ) {
@selection = $self->get_selected_indices;
}
else {
@selection = 0 .. $#{ $self->{data} };
}
for (@selection) {
$self->{data}[$_][0] = $start;
$start += $step;
}
}
# If $start and $step are undefined, just make sure that the numbering is
# ascending.
else {
for ( 1 .. $#{ $self->{data} } ) {
if ( $self->{data}[$_][0] <= $self->{data}[ $_ - 1 ][0] ) {
$self->{data}[$_][0] = $self->{data}[ $_ - 1 ][0] + 1;
}
}
}
return;
}
# Check if $start and $step give duplicate page numbers
sub valid_renumber {
my ( $self, $start, $step, $selection ) = @_;
return FALSE if ( $step == 0 );
# if we are renumbering all pages, just make sure the numbers stay positive
if ( $selection eq 'all' ) {
return ( $start + $#{ $self->{data} } * $step > 0 ) ? TRUE : FALSE
if ( $step < 0 );
return TRUE;
}
# Get list of pages not in selection
my @selected = $self->get_selected_indices;
my @all = ( 0 .. $#{ $self->{data} } );
# Convert the indices to sets of page numbers
@selected = $self->index2page_number(@selected);
@all = $self->index2page_number(@all);
my $selected = Set::IntSpan->new( \@selected );
my $all = Set::IntSpan->new( \@all );
my $not_selected = $all->diff($selected);
# Create a set from the current settings
my $current = Set::IntSpan->new;
for ( 0 .. $#selected ) { $current->insert( $start + $step * $_ ) }
# Are any of the new page numbers the same as those not selected?
return FALSE if ( $current->intersect($not_selected)->size );
return TRUE;
}
# helper function to return an array of page numbers given an array of page indices
sub index2page_number {
my ( $self, @index ) = @_;
for (@index) {
$_ = ${ $self->{data} }[$_][0];
}
return @index;
}
# return array index of pages depending on which radiobutton is active
sub get_page_index {
my ( $self, $page_range, $error_callback ) = @_;
my @index;
if ( $page_range eq 'all' ) {
if ( $#{ $self->{data} } > -1 ) {
return 0 .. $#{ $self->{data} };
}
else {
$error_callback->( $d->get('No pages to process') );
return;
}
}
elsif ( $page_range eq 'selected' ) {
@index = $self->get_selected_indices;
if ( @index == 0 ) {
$error_callback->( $d->get('No pages selected') );
return;
}
}
return @index;
}
# Have to roll my own slurp sub to support utf8
sub slurp {
my ($file) = @_;
local $INPUT_RECORD_SEPARATOR = undef;
my ($text);
if ( ref($file) eq 'GLOB' ) {
$text = <$file>;
}
else {
open my $fh, '<:encoding(UTF8)', $file or die "Error: cannot open $file\n";
$text = <$fh>;
close $fh or die "Error: cannot close $file\n";
}
return $text;
}
# Wrapper for open3
sub open_three {
my ($cmd) = @_;
# we create a symbol for the err because open3 will not do that for us
my $err = gensym();
open3( undef, my $reader, $err, $cmd );
return ( slurp($reader), slurp($err) );
}
# Check that a command exists
sub check_command {
my ($cmd) = @_;
return system("which $cmd >/dev/null 2>/dev/null") == 0 ? TRUE : FALSE;
}
# Compute a timestamp
sub timestamp {
my @time = localtime();
# return a time which can be string-wise compared
return sprintf( "%04d%02d%02d%02d%02d%02d", reverse @time[ 0 .. $YEAR ] );
}
# Set session dir
sub set_dir {
my ( $self, $dir ) = @_;
$self->{dir} = $dir;
return;
}
sub _enqueue_request {
my ( $action, $data ) = @_;
my $sentinel : shared = 0;
$_self->{requests}->enqueue(
{
action => $action,
sentinel => \$sentinel,
( $data ? %{$data} : () )
}
);
if ( $_self->{requests}->pending == 0 ) {
$jobs_completed = 0;
$jobs_total = 0;
}
$jobs_total++;
return \$sentinel;
}
sub _monitor_process {
my ( $self, %options ) = @_;
# Get new process ID
my $pid = ++$_PID;
$self->{running_pids}{$pid} = 1;
if ( $options{queued_callback} ) {
$options{queued_callback}->(
process_name => $_self->{process_name},
jobs_completed => $jobs_completed,
jobs_total => $jobs_total
);
}
Glib::Timeout->add(
$_POLL_INTERVAL,
sub {
if ( ${ $options{sentinel} } == 2 ) {
$jobs_completed++;
$self->_monitor_process_finished_callback( $pid, \%options );
return Glib::SOURCE_REMOVE;
}
elsif ( ${ $options{sentinel} } == 1 ) {
$self->_monitor_process_running_callback( $pid, \%options );
return Glib::SOURCE_CONTINUE;
}
return Glib::SOURCE_CONTINUE;
}
);
return $pid;
}
sub _monitor_process_running_callback {
my ( $self, $pid, $options ) = @_;
if ( exists $self->{cancel_cb}{$pid} ) {
if ( not defined( $self->{cancel_cb}{$pid} )
or ref( $self->{cancel_cb}{$pid} ) eq 'CODE' )
{
if ( defined $options->{pidfile} ) {
_cancel_process( slurp( $options->{pidfile} ) );
}
else {
_cancel_process();
}
if ( $options->{cancelled_callback} ) { $options->{cancelled_callback}->() }
if ( $self->{cancel_cb}{$pid} ) { $self->{cancel_cb}{$pid}->() }
# Flag that the callbacks have been done here
# so they are not repeated here or in finished
$self->{cancel_cb}{$pid} = 1;
delete $self->{running_pids}{$pid};
}
return;
}
if ( $options->{add} ) { $self->fetch_file( $options->{add} ) }
if ( $options->{started_callback} and not $options->{started_flag} ) {
$options->{started_flag} = $options->{started_callback}->(
1, $_self->{process_name},
$jobs_completed, $jobs_total, $_self->{message}, $_self->{progress}
);
}
if ( $options->{running_callback} ) {
$options->{running_callback}->(
process => $_self->{process_name},
jobs_completed => $jobs_completed,
jobs_total => $jobs_total,
message => $_self->{message},
progress => $_self->{progress}
);
}
return;
}
sub _monitor_process_finished_callback {
my ( $self, $pid, $options ) = @_;
if ( exists $self->{cancel_cb}{$pid} ) {
if ( not defined( $self->{cancel_cb}{$pid} )
or ref( $self->{cancel_cb}{$pid} ) eq 'CODE' )
{
if ( defined $options->{pidfile} ) {
_cancel_process( slurp( $options->{pidfile} ) );
}
else {
_cancel_process();
}
if ( $options->{cancelled_callback} ) { $options->{cancelled_callback}->() }
if ( $self->{cancel_cb}{$pid} ) { $self->{cancel_cb}{$pid}->() }
}
delete $self->{cancel_cb}{$pid};
delete $self->{running_pids}{$pid};
return;
}
if ( $options->{started_callback} and not $options->{started_flag} ) {
$options->{started_callback}->();
}
if ( $_self->{status} ) {
if ( $options->{error_callback} ) {
$options->{error_callback}->( $_self->{message} );
}
return;
}
if ( $options->{add} ) { $options->{add} -= $self->fetch_file }
my $data;
if ( $options->{info} ) {
$data = $_self->{info_queue}->dequeue;
}
elsif ( $options->{update_slist} ) {
$data = $self->update_page( $options->{display_callback} );
}
if ( $options->{finished_callback} ) {
$options->{finished_callback}->( $data, $_self->{requests}->pending );
}
delete $self->{cancel_cb}{$pid};
delete $self->{running_pids}{$pid};
return;
}
sub _cancel_process {
my ($pid) = @_;
# Empty process queue first to stop any new process from starting
$logger->info("Emptying process queue");
while ( $_self->{requests}->dequeue_nb ) { }
# Then send the thread a cancel signal to stop it going beyond the next break point
$_self->{cancel} = TRUE;
# Before killing any process running in the thread
if ($pid) {
$logger->info("Killing pid $pid");
local $SIG{HUP} = 'IGNORE';
killfam 'HUP', ($pid);
}
return;
}
sub _thread_main {
my ($self) = @_;
while ( my $request = $self->{requests}->dequeue ) {
$self->{process_name} = $request->{action};
undef $_self->{cancel};
# Signal the sentinel that the request was started.
${ $request->{sentinel} }++;
given ( $request->{action} ) {
when ('analyse') {
_thread_analyse( $self, $request->{page} );
}
when ('cancel') {
_thread_cancel($self);
}
when ('crop') {
_thread_crop(
$self,
page => $request->{page},
x => $request->{x},
y => $request->{y},
w => $request->{w},
h => $request->{h},
dir => $request->{dir},
);
}
when ('cuneiform') {
_thread_cuneiform( $self, $request->{page}, $request->{language},
$request->{pidfile} );
}
when ('get-file-info') {
_thread_get_file_info( $self, $request->{path}, $request->{pidfile} );
}
when ('gocr') {
_thread_gocr( $self, $request->{page}, $request->{pidfile} );
}
when ('import-file') {
_thread_import_file(
$self,
info => $request->{info},
first => $request->{first},
last => $request->{last},
dir => $request->{dir},
pidfile => $request->{pidfile}
);
}
when ('negate') {
_thread_negate( $self, $request->{page}, $request->{dir} );
}
when ('ocropus') {
_thread_ocropus( $self, $request->{page}, $request->{language},
$request->{pidfile} );
}
when ('paper_sizes') {
_thread_paper_sizes( $self, $request->{paper_sizes} );
}
when ('quit') {
last;
}
when ('rotate') {
_thread_rotate( $self, $request->{angle}, $request->{page},
$request->{dir} );
}
when ('save-djvu') {
_thread_save_djvu( $self, $request->{path}, $request->{list_of_pages},
$request->{dir}, $request->{pidfile} );
}
when ('save-image') {
_thread_save_image( $self, $request->{path}, $request->{list_of_pages},
$request->{pidfile} );
}
when ('save-pdf') {
_thread_save_pdf(
$self,
path => $request->{path},
list_of_pages => $request->{list_of_pages},
metadata => $request->{metadata},
options => $request->{options},
dir => $request->{dir},
pidfile => $request->{pidfile}
);
}
when ('save-text') {
_thread_save_text( $self, $request->{path}, $request->{list_of_pages} );
}
when ('save-tiff') {
_thread_save_tiff(
$self,
path => $request->{path},
list_of_pages => $request->{list_of_pages},
options => $request->{options},
ps => $request->{ps},
dir => $request->{dir},
pidfile => $request->{pidfile}
);
}
when ('tesseract') {
_thread_tesseract( $self, $request->{page}, $request->{language},
$request->{pidfile} );
}
when ('threshold') {
_thread_threshold( $self, $request->{threshold}, $request->{page},
$request->{dir} );
}
when ('to-png') {
_thread_to_png( $self, $request->{page}, $request->{dir} );
}
when ('unpaper') {
_thread_unpaper( $self, $request->{page}, $request->{options},
$request->{pidfile}, $request->{dir} );
}
when ('unsharp') {
_thread_unsharp(
$self,
page => $request->{page},
radius => $request->{radius},
sigma => $request->{sigma},
amount => $request->{amount},
threshold => $request->{threshold},
dir => $request->{dir},
);
}
when ('user-defined') {
_thread_user_defined(
$self, $request->{page}, $request->{command},
$request->{dir}, $request->{pidfile}
);
}
default {
$logger->info( "Ignoring unknown request " . $request->{action} );
next;
}
}
# Signal the sentinel that the request was completed.
${ $request->{sentinel} }++;
undef $self->{process_name};
}
return;
}
sub _thread_get_file_info {
my ( $self, $filename, $pidfile, %info ) = @_;
$self->{status} = 0;
if ( not -e $filename ) {
$self->{status} = 1;
$self->{message} = sprintf( $d->get("File %s not found"), $filename );
return;
}
$logger->info("Getting info for $filename");
( my $format, undef ) = open_three("file -b \"$filename\"");
$logger->info($format);
given ($format) {
when (/gzip\ compressed\ data/xsm) {
$info{path} = $filename;
$info{format} = 'session file';
$self->{info_queue}->enqueue( \%info );
return;
}
when (/DjVu/xsm) {
# Dig out the number of pages
my $cmd = "djvudump \"$filename\"";
$logger->info($cmd);
( my $info, undef ) = open_three("echo $PROCESS_ID > $pidfile;$cmd");
return if $_self->{cancel};
$logger->info($info);
my $pages = 1;
if ( $info =~ /\s(\d+)\s+page/xsm ) {
$pages = $1;
}
# Dig out and the resolution of each page
my (@ppi);
$info{format} = 'DJVU';
while ( $info =~ /\s(\d+)\s+dpi(.*)/xsm ) {
push @ppi, $1;
$info = $2;
$logger->info("Page $#ppi is $ppi[$#ppi] ppi");
}
if ( $pages != @ppi ) {
$self->{status} = 1;
$self->{message} =
$d->get('Unknown DjVu file structure. Please contact the author.');
return;
}
$info{ppi} = \@ppi;
$info{pages} = $pages;
$info{path} = $filename;
$self->{info_queue}->enqueue( \%info );
return;
}
when (/PDF\ document/xsm) {
$format = 'Portable Document Format';
my $cmd = "pdfinfo \"$filename\"";
$logger->info($cmd);
( my $info, undef ) = open_three("echo $PROCESS_ID > $pidfile;$cmd");
return if $_self->{cancel};
$logger->info($info);
my $pages = 1;
if ( $info =~ /Pages:\s+(\d+)/xsm ) {
$pages = $1;
}
$logger->info("$pages pages");
$info{pages} = $pages;
}
when (/TIFF\ image\ data/xsm) {
$format = 'Tagged Image File Format';
my $cmd = "tiffinfo \"$filename\"";
$logger->info($cmd);
( my $info, undef ) = open_three("echo $PROCESS_ID > $pidfile;$cmd");
return if $_self->{cancel};
$logger->info($info);
# Count number of pages
my $pages = () = $info =~ /TIFF\ Directory\ at\ offset/xsmg;
$logger->info("$pages pages");
$info{pages} = $pages;
}
default {
# Get file type
my $image = Image::Magick->new;
my $x = $image->Read($filename);
return if $_self->{cancel};
if ("$x") { $logger->warn($x) }
$format = $image->Get('format');
if ( defined $format ) { $logger->info("Format $format") }
undef $image;
if ( not defined($format) ) {
$self->{status} = 1;
$self->{message} =
sprintf( $d->get("%s is not a recognised image type"), $filename );
return;
}
$info{pages} = 1;
}
}
$info{format} = $format;
$info{path} = $filename;
$self->{info_queue}->enqueue( \%info );
return;
}
sub _thread_import_file {
my ( $self, %options ) = @_;
my $PNG = qr/Portable\ Network\ Graphics/xsm;
my $JPG = qr/Joint\ Photographic\ Experts\ Group\ JFIF\ format/xsm;
my $GIF = qr/CompuServe\ graphics\ interchange\ format/xsm;
given ( $options{info}->{format} ) {
when ('DJVU') {
# Extract images from DjVu
if ( $options{last} >= $options{first} and $options{first} > 0 ) {
for my $i ( $options{first} .. $options{last} ) {
$self->{progress} = ( $i - 1 ) / ( $options{last} - $options{first} + 1 );
$self->{message} = sprintf( $d->get("Importing page %i of %i"),
$i, $options{last} - $options{first} + 1 );
my $tif = File::Temp->new(
DIR => $options{dir},
SUFFIX => '.tif',
UNLINK => FALSE
);
my $cmd = "ddjvu -format=tiff -page=$i \"$options{info}->{path}\" $tif";
$logger->info($cmd);
system("echo $PROCESS_ID > $options{pidfile};$cmd");
return if $_self->{cancel};
my $page = Gscan2pdf::Page->new(
filename => $tif,
dir => $options{dir},
delete => TRUE,
format => 'Tagged Image File Format',
resolution => $options{info}->{ppi}[ $i - 1 ],
);
$self->{page_queue}->enqueue( $page->freeze );
}
}
}
when ('Portable Document Format') {
# Extract images from PDF
if ( $options{last} >= $options{first} and $options{first} > 0 ) {
my $cmd =
"pdfimages -f $options{first} -l $options{last} \"$options{info}->{path}\" x";
$logger->info($cmd);
my $status = system("echo $PROCESS_ID > $options{pidfile};$cmd");
return if $_self->{cancel};
if ($status) {
$self->{status} = 1;
$self->{message} = $d->get('Error extracting images from PDF');
}
# Import each image
my @images = glob('x-???.???');
$self->{page_queue}->enqueue( $#images + 1 );
foreach (@images) {
my ($ext) = /([^.]+)$/xsm;
my $page = Gscan2pdf::Page->new(
filename => $_,
dir => $options{dir},
delete => TRUE,
format => $format{$ext},
);
$self->{page_queue}->enqueue( $page->to_png($paper_sizes)->freeze );
}
}
}
when ('Tagged Image File Format') {
# Split the tiff into its pages and import them individually
if ( $options{last} >= $options{first} and $options{first} > 0 ) {
for my $i ( $options{first} - 1 .. $options{last} - 1 ) {
$self->{progress} = $i / ( $options{last} - $options{first} + 1 );
$self->{message} = sprintf( $d->get("Importing page %i of %i"),
$i, $options{last} - $options{first} + 1 );
my $tif = File::Temp->new(
DIR => $options{dir},
SUFFIX => '.tif',
UNLINK => FALSE
);
my $cmd = "tiffcp \"$options{info}->{path}\",$i $tif";
$logger->info($cmd);
system("echo $PROCESS_ID > $options{pidfile};$cmd");
return if $_self->{cancel};
my $page = Gscan2pdf::Page->new(
filename => $tif,
dir => $options{dir},
delete => TRUE,
format => $options{info}->{format},
);
$self->{page_queue}->enqueue( $page->freeze );
}
}
}
when (/(?:$PNG|$JPG|$GIF)/xsm) {
my $page = Gscan2pdf::Page->new(
filename => $options{info}->{path},
dir => $options{dir},
format => $options{info}->{format},
);
$self->{page_queue}->enqueue( $page->freeze );
}
# only 1-bit Portable anymap is properly supported, so convert ANY pnm to png
default {
my $page = Gscan2pdf::Page->new(
filename => $options{info}->{path},
dir => $options{dir},
format => $options{info}->{format},
);
$self->{page_queue}->enqueue( $page->to_png($paper_sizes)->freeze );
}
}
return;
}
# Perl-Critic is confused by @_ in finally{} See P::C bug #79138
sub _thread_save_pdf { ## no critic (RequireArgUnpacking)
my ( $self, %options ) = @_;
my $pagenr = 0;
my $ttfcache;
# Create PDF with PDF::API2
$self->{message} = $d->get('Setting up PDF');
my $pdf = PDF::API2->new( -file => $options{path} );
if ( defined $options{metadata} ) { $pdf->info( %{ $options{metadata} } ) }
my $corecache = $pdf->corefont('Times-Roman');
if ( defined $options{options}->{font} ) {
$ttfcache = $pdf->ttfont( $options{options}->{font}, -unicodemap => 1 );
$logger->info("Using $options{options}->{font} for non-ASCII text");
}
foreach my $pagedata ( @{ $options{list_of_pages} } ) {
++$pagenr;
$self->{progress} = $pagenr / ( $#{ $options{list_of_pages} } + 2 );
$self->{message} = sprintf( $d->get("Saving page %i of %i"),
$pagenr, $#{ $options{list_of_pages} } + 1 );
my $filename = $pagedata->{filename};
my $image = Image::Magick->new;
my $status = $image->Read($filename);
return if $_self->{cancel};
if ("$status") { $logger->warn($status) }
# Get the size and resolution. Resolution is dots per inch, width
# and height are in inches.
my $w = $image->Get('width') / $pagedata->{resolution};
my $h = $image->Get('height') / $pagedata->{resolution};
$pagedata->{w} = $w;
$pagedata->{h} = $h;
# Automatic mode
my $type;
if ( not defined( $options{options}->{compression} )
or $options{options}->{compression} eq 'auto' )
{
$pagedata->{depth} = $image->Get('depth');
$logger->info("Depth of $filename is $pagedata->{depth}");
if ( $pagedata->{depth} == 1 ) {
$pagedata->{compression} = 'lzw';
}
else {
$type = $image->Get('type');
$logger->info("Type of $filename is $type");
if ( $type =~ /TrueColor/xsm ) {
$pagedata->{compression} = 'jpg';
}
else {
$pagedata->{compression} = 'png';
}
}
$logger->info("Selecting $pagedata->{compression} compression");
}
else {
$pagedata->{compression} = $options{options}->{compression};
}
( $filename, my $format, my $output_resolution ) =
_convert_image_for_pdf( $self, $pagedata, $image, %options );
$logger->info(
"Defining page at ",
$w * $POINTS_PER_INCH,
"pt x ", $h * $POINTS_PER_INCH, "pt"
);
my $page = $pdf->page;
$page->mediabox( $w * $POINTS_PER_INCH, $h * $POINTS_PER_INCH );
_add_text_to_PDF( $page, $pagedata, $ttfcache, $corecache );
# Add scan
my $gfx = $page->gfx;
my $imgobj;
my $msg;
given ($format) {
when ('png') {
try { $imgobj = $pdf->image_png($filename) } catch { $msg = $_ };
}
when ('jpg') {
try { $imgobj = $pdf->image_jpeg($filename) } catch { $msg = $_ };
}
when ('pnm') {
try { $imgobj = $pdf->image_pnm($filename) } catch { $msg = $_ };
}
when ('gif') {
try { $imgobj = $pdf->image_gif($filename) } catch { $msg = $_ };
}
when ('tif') {
try { $imgobj = $pdf->image_tiff($filename) } catch { $msg = $_ };
}
default {
$msg = "Unknown format $format file $filename";
}
}
return if $_self->{cancel};
if ($msg) {
$logger->warn($msg);
$self->{status} = 1;
$self->{message} =
sprintf( $d->get("Error creating PDF image object: %s"), $msg );
return;
}
else {
try {
$gfx->image( $imgobj, 0, 0, $w * $POINTS_PER_INCH, $h * $POINTS_PER_INCH );
}
catch {
$logger->warn($_);
$self->{status} = 1;
$self->{message} =
sprintf( $d->get("Error embedding file image in %s format to PDF: %s"),
$format, $_ );
}
finally {
if ( not @_ ) {
$logger->info("Adding $filename at $output_resolution PPI");
}
};
}
return if $_self->{cancel};
}
$self->{message} = $d->get('Closing PDF');
$pdf->save;
$pdf->end;
return;
}
# Convert file if necessary
sub _convert_image_for_pdf {
my ( $self, $pagedata, $image, %options ) = @_;
my $filename = $pagedata->{filename};
my $compression = $pagedata->{compression};
my $format;
if ( $filename =~ /\.(\w*)$/xsm ) {
$format = $1;
}
# The output resolution is normally the same as the input
# resolution.
my $output_resolution = $pagedata->{resolution};
if (( $compression ne 'none' and $compression ne $format )
or $options{options}->{downsample}
or $compression eq 'jpg' )
{
if ( $compression !~ /(?:jpg|png)/xsm and $format ne 'tif' ) {
my $ofn = $filename;
$filename = File::Temp->new( DIR => $options{dir}, SUFFIX => '.tif' );
$logger->info("Converting $ofn to $filename");
}
elsif ( $compression =~ /(?:jpg|png)/xsm ) {
my $ofn = $filename;
$filename = File::Temp->new(
DIR => $options{dir},
SUFFIX => ".$compression"
);
$logger->info("Converting $ofn to $filename");
}
if ( $options{options}->{downsample} ) {
$output_resolution = $options{options}->{'downsample dpi'};
my $w_pixels = $pagedata->{w} * $output_resolution;
my $h_pixels = $pagedata->{h} * $output_resolution;
$logger->info("Resizing $filename to $w_pixels x $h_pixels");
my $status = $image->Resize( width => $w_pixels, height => $h_pixels );
if ("$status") { $logger->warn($status) }
}
if ( defined( $options{options}->{quality} ) and $compression eq 'jpg' ) {
my $status = $image->Set( quality => $options{options}->{quality} );
if ("$status") { $logger->warn($status) }
}
$format =
_write_image_object( $image, $filename, $format, $pagedata,
$options{options}->{downsample} );
if ( $compression !~ /(?:jpg|png)/xsm ) {
my $filename2 = File::Temp->new( DIR => $options{dir}, SUFFIX => '.tif' );
my $error = File::Temp->new( DIR => $options{dir}, SUFFIX => '.txt' );
my $cmd = "tiffcp -c $compression $filename $filename2";
$logger->info($cmd);
my $status = system("echo $PROCESS_ID > $options{pidfile};$cmd 2>$error");
return if $_self->{cancel};
if ($status) {
my $output = slurp($error);
$logger->info($output);
$self->{status} = 1;
$self->{message} =
sprintf( $d->get("Error compressing image: %s"), $output );
return;
}
$filename = $filename2;
}
}
return $filename, $format, $output_resolution;
}
sub _write_image_object {
my ( $image, $filename, $format, $pagedata, $downsample ) = @_;
my $compression = $pagedata->{compression};
if (( $compression !~ /(?:jpg|png)/xsm and $format ne 'tif' )
or ( $compression =~ /(?:jpg|png)/xsm )
or $downsample )
{
# depth required because resize otherwise increases depth
# to maintain information
if ( not defined( $pagedata->{depth} ) ) {
$pagedata->{depth} = $image->Get('depth');
}
$logger->info(
"Writing temporary image $filename with depth $pagedata->{depth}");
my $status =
$image->Write( filename => $filename, depth => $pagedata->{depth} );
return if $_self->{cancel};
if ("$status") { $logger->warn($status) }
if ( $filename =~ /\.(\w*)$/xsm ) {
$format = $1;
}
}
return $format;
}
# Add OCR as text behind the scan
sub _add_text_to_PDF {
my ( $page, $data, $ttfcache, $corecache ) = @_;
if ( defined( $data->{hocr} ) ) {
my $h = $data->{h};
my $w = $data->{w};
my $resolution = $data->{resolution};
$logger->info('Embedding OCR output behind image');
my $font;
my $text = $page->text;
for my $box ( $data->boxes ) {
my ( $x1, $y1, $x2, $y2, $txt ) = @{$box};
if ( $txt =~ /([[:^ascii:]])/xsm and defined($ttfcache) ) {
if ( defined $1 ) { $logger->debug("non-ascii text is '$1' in '$txt'") }
$font = $ttfcache;
}
else {
$font = $corecache;
}
if ( $x1 == 0 and $y1 == 0 and not defined($x2) ) {
( $x2, $y2 ) = ( $w * $resolution, $h * $resolution );
}
if ( abs( $h * $resolution - $y2 + $y1 ) > $BOX_TOLERANCE
and abs( $w * $resolution - $x2 + $x1 ) > $BOX_TOLERANCE )
{
# Box is smaller than the page. We know the text position.
# Set the text position.
# Translate x1 and y1 to inches and then to points. Invert the
# y coordinate (since the PDF coordinates are bottom to top
# instead of top to bottom) and subtract $size, since the text
# will end up above the given point instead of below.
my $size = ( $y2 - $y1 ) / $resolution * $POINTS_PER_INCH;
$text->font( $font, $size );
$text->translate( $x1 / $resolution * $POINTS_PER_INCH,
( $h - ( $y1 / $resolution ) ) * $POINTS_PER_INCH - $size );
$text->text( $txt, utf8 => 1 );
}
else {
my $size = 1;
$text->font( $font, $size );
_wrap_text_to_page( $txt, $size, $text, $h, $w );
}
}
}
return;
}
# Box is the same size as the page. We don't know the text position.
# Start at the top of the page (PDF coordinate system starts
# at the bottom left of the page)
sub _wrap_text_to_page {
my ( $txt, $size, $text_box, $h, $w ) = @_;
my $y = $h * $POINTS_PER_INCH - $size;
foreach my $line ( split( /\n/xsm, $txt ) ) {
my $x = 0;
# Add a word at a time in order to linewrap
foreach my $word ( split( $SPACE, $line ) ) {
if ( length($word) * $size + $x > $w * $POINTS_PER_INCH ) {
$x = 0;
$y -= $size;
}
$text_box->translate( $x, $y );
if ( $x > 0 ) { $word = $SPACE . $word }
$x += $text_box->text( $word, utf8 => 1 );
}
$y -= $size;
}
return;
}
sub _thread_save_djvu {
my ( $self, $path, $list_of_pages, $dir, $pidfile ) = @_;
my $page = 0;
my @filelist;
foreach my $pagedata ( @{$list_of_pages} ) {
++$page;
$self->{progress} = $page / ( $#{$list_of_pages} + 2 );
$self->{message} =
sprintf( $d->get("Writing page %i of %i"), $page, $#{$list_of_pages} + 1 );
my $filename = $pagedata->{filename};
my $djvu = File::Temp->new( DIR => $dir, SUFFIX => '.djvu' );
# Check the image depth to decide what sort of compression to use
my $image = Image::Magick->new;
my $x = $image->Read($filename);
if ("$x") { $logger->warn($x) }
my $depth = $image->Get('depth');
my $class = $image->Get('class');
my $compression;
# Get the size
$pagedata->{w} = $image->Get('width');
$pagedata->{h} = $image->Get('height');
$pagedata->{pidfile} = $pidfile;
$pagedata->{page_number} = $page;
# c44 can only use pnm and jpg
my $format;
if ( $filename =~ /\.(\w*)$/xsm ) {
$format = $1;
}
if ( $depth > 1 ) {
$compression = 'c44';
if ( $format !~ /(?:pnm|jpg)/xsm ) {
my $pnm = File::Temp->new( DIR => $dir, SUFFIX => '.pnm' );
$x = $image->Write( filename => $pnm );
if ("$x") { $logger->warn($x) }
$filename = $pnm;
}
}
# cjb2 can only use pnm and tif
else {
$compression = 'cjb2';
if ( $format !~ /(?:pnm|tif)/xsm
or ( $format eq 'pnm' and $class ne 'PseudoClass' ) )
{
my $pbm = File::Temp->new( DIR => $dir, SUFFIX => '.pbm' );
$x = $image->Write( filename => $pbm );
if ("$x") { $logger->warn($x) }
$filename = $pbm;
}
}
# Create the djvu
my $cmd = sprintf "$compression -dpi %d $filename $djvu",
$pagedata->{resolution};
$logger->info($cmd);
my ( $status, $size ) =
( system("echo $PROCESS_ID > $pidfile;$cmd"), -s "$djvu" )
; # quotes needed to prevent -s clobbering File::Temp object
return if $_self->{cancel};
if ( $status != 0 or not $size ) {
$self->{status} = 1;
$self->{message} = $d->get('Error writing DjVu');
$logger->error(
"Error writing image for page $page of DjVu (process returned $status, image size $size)"
);
return;
}
push @filelist, $djvu;
_add_text_to_DJVU( $self, $djvu, $dir, $pagedata );
}
$self->{progress} = 1;
$self->{message} = $d->get('Closing DjVu');
my $cmd = "djvm -c '$path' @filelist";
$logger->info($cmd);
my $status = system("echo $PROCESS_ID > $pidfile;$cmd");
return if $_self->{cancel};
if ($status) {
$self->{status} = 1;
$self->{message} = $d->get('Error closing DjVu');
$logger->error("Error closing DjVu");
}
return;
}
# Add OCR to text layer
sub _add_text_to_DJVU {
my ( $self, $djvu, $dir, $pagedata ) = @_;
if ( defined( $pagedata->{hocr} ) ) {
# Get the size
my $w = $pagedata->{w};
my $h = $pagedata->{h};
my $resolution = $pagedata->{resolution};
# Open djvusedtxtfile
my $djvusedtxtfile = File::Temp->new( DIR => $dir, SUFFIX => '.txt' );
open my $fh, '>:encoding(UTF8)', ## no critic (RequireBriefOpen)
$djvusedtxtfile
or croak( sprintf( $d->get("Can't open file: %s"), $djvusedtxtfile ) );
print $fh "(page 0 0 $w $h\n";
# Write the text boxes
for my $box ( $pagedata->boxes ) {
my ( $x1, $y1, $x2, $y2, $txt ) = @{$box};
if ( $x1 == 0 and $y1 == 0 and not defined($x2) ) {
( $x2, $y2 ) = ( $w * $resolution, $h * $resolution );
}
# Escape any inverted commas
$txt =~ s/\\/\\\\/gxsm;
$txt =~ s/"/\\\"/gxsm;
printf $fh "\n(line %d %d %d %d \"%s\")", $x1, $h - $y2, $x2, $h - $y1, $txt;
}
print $fh ")";
close $fh
or croak( sprintf( $d->get("Can't close file: %s"), $djvusedtxtfile ) );
# Write djvusedtxtfile
my $cmd = "djvused '$djvu' -e 'select 1; set-txt $djvusedtxtfile' -s";
$logger->info($cmd);
my $status = system("echo $PROCESS_ID > $pagedata->{pidfile};$cmd");
return if $_self->{cancel};
if ($status) {
$self->{status} = 1;
$self->{message} = $d->get('Error adding text layer to DjVu');
$logger->error(
"Error adding text layer to DjVu page $pagedata->{page_number}");
}
}
return;
}
sub _thread_save_tiff {
my ( $self, %options ) = @_;
my $page = 0;
my @filelist;
foreach my $pagedata ( @{ $options{list_of_pages} } ) {
++$page;
$self->{progress} = ( $page - 1 ) / ( $#{ $options{list_of_pages} } + 2 );
$self->{message} = sprintf( $d->get("Converting image %i of %i to TIFF"),
$page, $#{ $options{list_of_pages} } + 1 );
my $filename = $pagedata->{filename};
if (
$filename !~ /\.tif/xsm
or ( defined( $options{options}->{compression} )
and $options{options}->{compression} eq 'jpeg' )
)
{
my $tif = File::Temp->new( DIR => $options{dir}, SUFFIX => '.tif' );
my $resolution = $pagedata->{resolution};
# Convert to tiff
my $depth = $EMPTY;
if ( defined( $options{options}->{compression} )
and $options{options}->{compression} eq 'jpeg' )
{
$depth = '-depth 8';
}
my $cmd =
"convert -units PixelsPerInch -density $resolution $depth $filename $tif";
$logger->info($cmd);
my $status = system("echo $PROCESS_ID > $options{pidfile};$cmd");
return if $_self->{cancel};
if ($status) {
$self->{status} = 1;
$self->{message} = $d->get('Error writing TIFF');
return;
}
$filename = $tif;
}
push @filelist, $filename;
}
my $compression = $EMPTY;
if ( defined $options{options}->{compression} ) {
$compression = "-c $options{options}->{compression}";
if ( $compression eq 'jpeg' ) {
$compression .= ":$options{options}->{quality}";
}
}
# Create the tiff
$self->{progress} = 1;
$self->{message} = $d->get('Concatenating TIFFs');
my $rows = $EMPTY;
if ( defined( $options{options}->{compression} )
and $options{options}->{compression} eq 'jpeg' )
{
$rows = '-r 16';
}
my $cmd = "tiffcp $rows $compression @filelist '$options{path}'";
$logger->info($cmd);
my $out = File::Temp->new( DIR => $options{dir}, SUFFIX => '.stdout' );
my $status = system("echo $PROCESS_ID > $options{pidfile};$cmd 2>$out");
return if $_self->{cancel};
if ($status) {
my $output = slurp($out);
$logger->info($output);
$self->{status} = 1;
$self->{message} = sprintf( $d->get("Error compressing image: %s"), $output );
return;
}
if ( defined $options{ps} ) {
$self->{message} = $d->get('Converting to PS');
# Note: -a option causes tiff2ps to generate multiple output
# pages, one for each page in the input TIFF file. Without it, it
# only generates output for the first page.
$cmd = "tiff2ps -a $options{path} > '$options{ps}'";
$logger->info($cmd);
( my $output, undef ) = open_three($cmd);
}
return;
}
sub _thread_rotate {
my ( $self, $angle, $page, $dir ) = @_;
my $filename = $page->{filename};
$logger->info("Rotating $filename by $angle degrees");
# Rotate with imagemagick
my $image = Image::Magick->new;
my $x = $image->Read($filename);
return if $_self->{cancel};
if ("$x") { $logger->warn($x) }
# workaround for those versions of imagemagick that produce 16bit output
# with rotate
my $depth = $image->Get('depth');
$x = $image->Rotate($angle);
return if $_self->{cancel};
if ("$x") { $logger->warn($x) }
my $suffix;
if ( $filename =~ /\.(\w*)$/xsm ) {
$suffix = $1;
}
$filename = File::Temp->new(
DIR => $dir,
SUFFIX => ".$suffix",
UNLINK => FALSE
);
$x = $image->Write( filename => $filename, depth => $depth );
return if $_self->{cancel};
if ("$x") { $logger->warn($x) }
my $new = $page->freeze;
$new->{filename} = $filename->filename; # can't queue File::Temp objects
$new->{dirty_time} = timestamp(); #flag as dirty
my %data = ( old => $page, new => $new );
$self->{page_queue}->enqueue( \%data );
return;
}
sub _thread_save_image {
my ( $self, $path, $list_of_pages, $pidfile ) = @_;
if ( @{$list_of_pages} == 1 ) {
my $cmd =
"convert $list_of_pages->[0]{filename} -density $list_of_pages->[0]{resolution} '$path'";
$logger->info($cmd);
my $status = system("echo $PROCESS_ID > $pidfile;$cmd");
return if $_self->{cancel};
if ($status) {
$self->{status} = 1;
$self->{message} = $d->get('Error saving image');
}
}
else {
my $current_filename;
my $i = 1;
foreach ( @{$list_of_pages} ) {
$current_filename = sprintf $path, $i++;
my $cmd = sprintf "convert %s -density %d \"%s\"",
$_->{filename}, $_->{resolution},
$current_filename;
my $status = system("echo $PROCESS_ID > $pidfile;$cmd");
return if $_self->{cancel};
if ($status) {
$self->{status} = 1;
$self->{message} = $d->get('Error saving image');
}
}
}
return;
}
sub _thread_save_text {
my ( $self, $path, $list_of_pages, $fh ) = @_;
if ( not open( $fh, ">", $path ) ) {
$self->{status} = 1;
$self->{message} = sprintf( $d->get("Can't open file: %s"), $path );
return;
}
foreach ( @{$list_of_pages} ) {
print $fh $_->{hocr};
return if $_self->{cancel};
}
if ( not close($fh) ) {
$self->{status} = 1;
$self->{message} = sprintf( $d->get("Can't close file: %s"), $path );
}
return;
}
sub _thread_analyse {
my ( $self, $page ) = @_;
# Identify with imagemagick
my $image = Image::Magick->new;
my $x = $image->Read( $page->{filename} );
return if $_self->{cancel};
if ("$x") { $logger->warn($x) }
my ( $depth, $min, $max, $mean, $stddev ) = $image->Statistics();
if ( not defined($depth) ) { $logger->warn("image->Statistics() failed") }
$logger->info("std dev: $stddev mean: $mean");
return if $_self->{cancel};
my $maxQ = ( 1 << $depth ) - 1;
$mean = $maxQ ? $mean / $maxQ : 0;
if ( $stddev eq "nan" ) { $stddev = 0 }
# my $quantum_depth = $image->QuantumDepth;
# warn "image->QuantumDepth failed" unless defined $quantum_depth;
# TODO add any other useful image analysis here e.g. is the page mis-oriented?
# detect mis-orientation possible algorithm:
# blur or low-pass filter the image (so words look like ovals)
# look at few vertical narrow slices of the image and get the Standard Deviation
# if most of the Std Dev are high, then it might be portrait
# TODO may need to send quantumdepth
my $new = $page->clone;
$new->{mean} = $mean;
$new->{std_dev} = $stddev;
$new->{analyse_time} = timestamp();
my %data = ( old => $page, new => $new );
$self->{page_queue}->enqueue( \%data );
return;
}
sub _thread_threshold {
my ( $self, $threshold, $page, $dir ) = @_;
my $filename = $page->{filename};
my $image = Image::Magick->new;
my $x = $image->Read($filename);
return if $_self->{cancel};
if ("$x") { $logger->warn($x) }
# Threshold the image
$image->BlackThreshold( threshold => "$threshold%" );
return if $_self->{cancel};
$image->WhiteThreshold( threshold => "$threshold%" );
return if $_self->{cancel};
# Write it
$filename = File::Temp->new( DIR => $dir, SUFFIX => '.pbm', UNLINK => FALSE );
$x = $image->Write( filename => $filename );
return if $_self->{cancel};
if ("$x") { $logger->warn($x) }
my $new = $page->freeze;
$new->{filename} = $filename->filename; # can't queue File::Temp objects
$new->{dirty_time} = timestamp(); #flag as dirty
my %data = ( old => $page, new => $new );
$self->{page_queue}->enqueue( \%data );
return;
}
sub _thread_negate {
my ( $self, $page, $dir ) = @_;
my $filename = $page->{filename};
my $image = Image::Magick->new;
my $x = $image->Read($filename);
return if $_self->{cancel};
if ("$x") { $logger->warn($x) }
my $depth = $image->Get('depth');
# Negate the image
$image->Negate;
return if $_self->{cancel};
# Write it
my $suffix;
if ( $filename =~ /(\.\w*)$/xsm ) {
$suffix = $1;
}
$filename = File::Temp->new( DIR => $dir, SUFFIX => $suffix, UNLINK => FALSE );
$x = $image->Write( depth => $depth, filename => $filename );
return if $_self->{cancel};
if ("$x") { $logger->warn($x) }
$logger->info("Negating to $filename");
my $new = $page->freeze;
$new->{filename} = $filename->filename; # can't queue File::Temp objects
$new->{dirty_time} = timestamp(); #flag as dirty
my %data = ( old => $page, new => $new );
$self->{page_queue}->enqueue( \%data );
return;
}
sub _thread_unsharp {
my ( $self, %options ) = @_;
my $filename = $options{page}->{filename};
my $image = Image::Magick->new;
my $x = $image->Read($filename);
return if $_self->{cancel};
if ("$x") { $logger->warn($x) }
# Unsharp the image
$image->UnsharpMask(
radius => $options{radius},
sigma => $options{sigma},
amount => $options{amount},
threshold => $options{threshold},
);
return if $_self->{cancel};
# Write it
my $suffix;
if ( $filename =~ /\.(\w*)$/xsm ) {
$suffix = $1;
}
$filename = File::Temp->new(
DIR => $options{dir},
SUFFIX => ".$suffix",
UNLINK => FALSE
);
$x = $image->Write( filename => $filename );
return if $_self->{cancel};
if ("$x") { $logger->warn($x) }
$logger->info(
"Wrote $filename with unsharp mask: r=$options{radius}, s=$options{sigma}, a=$options{amount}, t=$options{threshold}"
);
my $new = $options{page}->freeze;
$new->{filename} = $filename->filename; # can't queue File::Temp objects
$new->{dirty_time} = timestamp(); #flag as dirty
my %data = ( old => $options{page}, new => $new );
$self->{page_queue}->enqueue( \%data );
return;
}
sub _thread_crop {
my ( $self, %options ) = @_;
my $filename = $options{page}->{filename};
my $image = Image::Magick->new;
my $e = $image->Read($filename);
return if $_self->{cancel};
if ("$e") { $logger->warn($e) }
# Crop the image
$e = $image->Crop(
width => $options{w},
height => $options{h},
x => $options{x},
y => $options{y}
);
$image->Set( page => '0x0+0+0' );
return if $_self->{cancel};
if ("$e") { $logger->warn($e) }
# Write it
my $suffix;
if ( $filename =~ /\.(\w*)$/xsm ) {
$suffix = $1;
}
$filename = File::Temp->new(
DIR => $options{dir},
SUFFIX => ".$suffix",
UNLINK => FALSE
);
$logger->info(
"Cropping $options{w} x $options{h} + $options{x} + $options{y} to $filename"
);
$e = $image->Write( filename => $filename );
return if $_self->{cancel};
if ("$e") { $logger->warn($e) }
my $new = $options{page}->freeze;
$new->{filename} = $filename->filename; # can't queue File::Temp objects
$new->{dirty_time} = timestamp(); #flag as dirty
my %data = ( old => $options{page}, new => $new );
$self->{page_queue}->enqueue( \%data );
return;
}
sub _thread_to_png {
my ( $self, $page, $dir ) = @_;
my $new = $page->to_png($paper_sizes);
return if $_self->{cancel};
my %data = ( old => $page, new => $new->freeze );
$logger->info("Converted $page->{filename} to $data{new}{filename}");
$self->{page_queue}->enqueue( \%data );
return;
}
sub _thread_tesseract {
my ( $self, $page, $language, $pidfile ) = @_;
my $new = $page->clone;
( $new->{hocr}, $new->{warnings} ) =
Gscan2pdf::Tesseract->hocr( $page->{filename}, $language, $logger,
$pidfile );
return if $_self->{cancel};
$new->{ocr_flag} = 1; #FlagOCR
$new->{ocr_time} = timestamp(); #remember when we ran OCR on this page
my %data = ( old => $page, new => $new );
$self->{page_queue}->enqueue( \%data );
return;
}
sub _thread_ocropus {
my ( $self, $page, $language, $pidfile ) = @_;
my $new = $page->clone;
$new->{hocr} =
Gscan2pdf::Ocropus->hocr( $page->{filename}, $language, $logger, $pidfile );
return if $_self->{cancel};
$new->{ocr_flag} = 1; #FlagOCR
$new->{ocr_time} = timestamp(); #remember when we ran OCR on this page
my %data = ( old => $page, new => $new );
$self->{page_queue}->enqueue( \%data );
return;
}
sub _thread_cuneiform {
my ( $self, $page, $language, $pidfile ) = @_;
my $new = $page->clone;
$new->{hocr} =
Gscan2pdf::Cuneiform->hocr( $page->{filename}, $language, $logger,
$pidfile );
return if $_self->{cancel};
$new->{ocr_flag} = 1; #FlagOCR
$new->{ocr_time} = timestamp(); #remember when we ran OCR on this page
my %data = ( old => $page, new => $new );
$self->{page_queue}->enqueue( \%data );
return;
}
sub _thread_gocr {
my ( $self, $page, $pidfile ) = @_;
my $pnm;
if ( $page->{filename} !~ /\.pnm$/xsm ) {
# Temporary filename for new file
$pnm = File::Temp->new( SUFFIX => '.pnm' );
my $image = Image::Magick->new;
$image->Read( $page->{filename} );
return if $_self->{cancel};
$image->Write( filename => $pnm );
return if $_self->{cancel};
}
else {
$pnm = $page->{filename};
}
my $new = $page->clone;
# Temporary filename for output
my $txt = File::Temp->new( SUFFIX => '.txt' );
# Using temporary txt file, as perl munges charset encoding
# if text is passed by stdin/stdout
my $cmd = "gocr $pnm -o $txt";
$logger->info($cmd);
system("echo $PROCESS_ID > $pidfile;$cmd");
( $new->{hocr}, undef ) = Gscan2pdf::Document::slurp($txt);
return if $_self->{cancel};
$new->{ocr_flag} = 1; #FlagOCR
$new->{ocr_time} = timestamp(); #remember when we ran OCR on this page
my %data = ( old => $page, new => $new );
$self->{page_queue}->enqueue( \%data );
return;
}
sub _thread_unpaper {
my ( $self, $page, $options, $pidfile, $dir ) = @_;
my $filename = $page->{filename};
my $in;
if ( $filename !~ /\.pnm$/xsm ) {
my $image = Image::Magick->new;
my $x = $image->Read($filename);
if ("$x") { $logger->warn($x) }
my $depth = $image->Get('depth');
# Unforunately, -depth doesn't seem to work here, so forcing depth=1 using pbm extension.
my $suffix = ".pbm";
if ( $depth > 1 ) { $suffix = ".pnm" }
# Temporary filename for new file
$in = File::Temp->new(
DIR => $dir,
SUFFIX => $suffix,
);
# FIXME: need to -compress Zip from perlmagick "convert -compress Zip $slist->{data}[$pagenum][2]{filename} $in;";
$image->Write( filename => $in );
}
else {
$in = $filename;
}
my $out = File::Temp->new(
DIR => $dir,
SUFFIX => '.pnm',
UNLINK => FALSE
);
my $out2 = $EMPTY;
if ( $options =~ /--output-pages\ 2\ /xsm ) {
$out2 = File::Temp->new(
DIR => $dir,
SUFFIX => '.pnm',
UNLINK => FALSE
);
}
# --overwrite needed because $out exists with 0 size
my $cmd = sprintf "$options;", $in, $out, $out2;
$logger->info($cmd);
system("echo $PROCESS_ID > $pidfile;$cmd");
return if $_self->{cancel};
my $new = Gscan2pdf::Page->new(
filename => $out,
dir => $dir,
delete => TRUE,
format => 'Portable anymap',
);
$new->{dirty_time} = timestamp(); #flag as dirty
my %data = ( old => $page, new => $new->freeze );
if ( $out2 ne $EMPTY ) {
my $new2 = Gscan2pdf::Page->new(
filename => $out2,
dir => $dir,
delete => TRUE,
format => 'Portable anymap',
);
$new2->{dirty_time} = timestamp(); #flag as dirty
$data{new2} = $new2->freeze;
}
$self->{page_queue}->enqueue( \%data );
return;
}
sub _thread_user_defined {
my ( $self, $page, $cmd, $dir, $pidfile ) = @_;
my $in = $page->{filename};
my $suffix;
if ( $in =~ /(\.\w*)$/xsm ) {
$suffix = $1;
}
my $out = File::Temp->new(
DIR => $dir,
SUFFIX => $suffix,
UNLINK => FALSE
);
if ( $cmd =~ s/%o/$out/gxsm ) {
$cmd =~ s/%i/$in/gxsm;
}
else {
if ( not copy( $in, $out ) ) {
$self->{status} = 1;
$self->{message} = $d->get('Error copying page');
$d->get('Error copying page');
return;
}
$cmd =~ s/%i/$out/gxsm;
}
$cmd =~ s/%r/$page->{resolution}/gxsm;
$logger->info($cmd);
system("echo $PROCESS_ID > $pidfile;$cmd");
return if $_self->{cancel};
# Get file type
my $image = Image::Magick->new;
my $x = $image->Read($out);
if ("$x") { $logger->warn($x) }
my $new = Gscan2pdf::Page->new(
filename => $out,
dir => $dir,
delete => TRUE,
format => $image->Get('format'),
);
my %data = ( old => $page, new => $new->freeze );
$self->{page_queue}->enqueue( \%data );
return;
}
sub _thread_paper_sizes {
( my $self, $paper_sizes ) = @_;
return;
}
1;
__END__
|