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
|
/*
SPDX-FileCopyrightText: 2004-2005 Enrico Ros <eros.kde@email.it>
SPDX-FileCopyrightText: 2004-2008 Albert Astals Cid <aacid@kde.org>
Work sponsored by the LiMux project of the city of Munich:
SPDX-FileCopyrightText: 2017, 2018 Klarälvdalens Datakonsult AB a KDAB Group company <info@kdab.com>
SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "document.h"
#include "document_p.h"
#include "documentcommands_p.h"
#include <algorithm>
#include <limits.h>
#include <memory>
#ifdef Q_OS_WIN
#include <qt_windows.h>
#elif defined(Q_OS_FREEBSD)
// clang-format off
// FreeBSD really wants this include order
#include <sys/types.h>
#include <sys/sysctl.h>
// clang-format on
#include <vm/vm_param.h>
#endif
// qt/kde/system includes
#include <QApplication>
#include <QDesktopServices>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QLabel>
#include <QMap>
#include <QMimeDatabase>
#include <QPageSize>
#include <QPrintDialog>
#include <QRegularExpression>
#include <QScreen>
#include <QStack>
#include <QStandardPaths>
#include <QTemporaryFile>
#include <QTextStream>
#include <QTimer>
#include <QUndoCommand>
#include <QWindow>
#include <QtAlgorithms>
#include <KApplicationTrader>
#include <KAuthorized>
#include <KConfigDialog>
#include <KFormat>
#include <KIO/Global>
#include <KIO/JobUiDelegate>
#include <KIO/JobUiDelegateFactory>
#include <KIO/OpenUrlJob>
#include <KLocalizedString>
#include <KMacroExpander>
#include <KPluginMetaData>
#include <KProcess>
#include <KShell>
#include <kio_version.h>
#include <kzip.h>
// local includes
#include "action.h"
#include "annotations.h"
#include "annotations_p.h"
#include "audioplayer.h"
#include "bookmarkmanager.h"
#include "chooseenginedialog_p.h"
#include "debug_p.h"
#include "form.h"
#include "generator_p.h"
#include "interfaces/configinterface.h"
#include "interfaces/guiinterface.h"
#include "interfaces/printinterface.h"
#include "interfaces/saveinterface.h"
#include "misc.h"
#include "observer.h"
#include "page.h"
#include "page_p.h"
#include "pagecontroller_p.h"
#include "script/event_p.h"
#include "scripter.h"
#include "settings_core.h"
#include "sourcereference.h"
#include "sourcereference_p.h"
#include "texteditors_p.h"
#include "tile.h"
#include "tilesmanager_p.h"
#include "utils.h"
#include "utils_p.h"
#include "view.h"
#include "view_p.h"
#include <config-okular.h>
#if HAVE_MALLOC_TRIM
#include "malloc.h"
#endif
using namespace Okular;
struct AllocatedPixmap {
// owner of the page
DocumentObserver *observer;
int page;
qulonglong memory;
// public constructor: initialize data
AllocatedPixmap(DocumentObserver *o, int p, qulonglong m)
: observer(o)
, page(p)
, memory(m)
{
}
};
struct ArchiveData {
ArchiveData()
{
}
QString originalFileName;
QTemporaryFile document;
QTemporaryFile metadataFile;
};
struct RunningSearch {
// store search properties
int continueOnPage;
RegularAreaRect continueOnMatch;
QSet<int> highlightedPages;
// fields related to previous searches (used for 'continueSearch')
QString cachedString;
Document::SearchType cachedType;
Qt::CaseSensitivity cachedCaseSensitivity;
bool cachedViewportMove : 1;
bool isCurrentlySearching : 1;
QColor cachedColor;
int pagesDone;
};
#define foreachObserver(cmd) \
{ \
for (auto *it : std::as_const(d->m_observers)) { \
it->cmd; \
} \
}
#define foreachObserverD(cmd) \
{ \
for (auto *it : std::as_const(m_observers)) { \
it->cmd; \
} \
}
#define OKULAR_HISTORY_MAXSTEPS 100
#define OKULAR_HISTORY_SAVEDSTEPS 10
// how often to run slotTimedMemoryCheck
constexpr int kMemCheckTime = 2000; // in msec
// getFreeMemory is called every two seconds when checking to see if the system is low on memory. If this timeout was left at kMemCheckTime, half of these checks are useless (when okular is idle) since the cache is used when the cache is
// <=2 seconds old. This means that after the system is out of memory, up to 4 seconds (instead of 2) could go by before okular starts to free memory.
constexpr int kFreeMemCacheTimeout = kMemCheckTime - 100;
/***** Document ******/
QString DocumentPrivate::pagesSizeString() const
{
if (m_generator) {
if (m_generator->pagesSizeMetric() != Generator::None) {
QSizeF size = m_parent->allPagesSize();
// Single page size
if (size.isValid()) {
return localizedSize(size);
}
// Multiple page sizes
QHash<QString, int> pageSizeFrequencies;
// Compute frequencies of each page size
for (const Page *page : std::as_const(m_pagesVector)) {
QString sizeString = localizedSize(QSizeF(page->width(), page->height()));
pageSizeFrequencies[sizeString] = pageSizeFrequencies.value(sizeString, 0) + 1;
}
// Figure out which page size is most frequent
int largestFrequencySeen = 0;
QString mostCommonPageSize;
for (const auto &[key, value] : pageSizeFrequencies.asKeyValueRange()) {
if (value > largestFrequencySeen) {
largestFrequencySeen = value;
mostCommonPageSize = key;
}
}
QString finalText = i18nc("@info %1 is a page size", "Most pages are %1.", mostCommonPageSize);
return finalText;
} else {
return QString();
}
} else {
return QString();
}
}
QString DocumentPrivate::namePaperSize(double inchesWidth, double inchesHeight) const
{
const QPageLayout::Orientation orientation = inchesWidth > inchesHeight ? QPageLayout::Landscape : QPageLayout::Portrait;
const QSize pointsSize(inchesWidth * 72.0, inchesHeight * 72.0);
const QPageSize::PageSizeId paperSize = QPageSize::id(pointsSize, QPageSize::FuzzyOrientationMatch);
const QString paperName = QPageSize::name(paperSize);
if (orientation == QPageLayout::Portrait) {
return i18nc("paper type and orientation (eg: Portrait A4)", "Portrait %1", paperName);
} else {
return i18nc("paper type and orientation (eg: Portrait A4)", "Landscape %1", paperName);
}
}
QString DocumentPrivate::localizedSize(const QSizeF size) const
{
double inchesWidth = 0, inchesHeight = 0;
switch (m_generator->pagesSizeMetric()) {
case Generator::Points:
inchesWidth = size.width() / 72.0;
inchesHeight = size.height() / 72.0;
break;
case Generator::Pixels: {
const QSizeF dpi = m_generator->dpi();
inchesWidth = size.width() / dpi.width();
inchesHeight = size.height() / dpi.height();
} break;
case Generator::None:
break;
}
if (QLocale::system().measurementSystem() == QLocale::ImperialSystem) {
return i18nc("%1 is width, %2 is height, %3 is paper size name", "%1 × %2 in (%3)", inchesWidth, inchesHeight, namePaperSize(inchesWidth, inchesHeight));
} else {
return i18nc("%1 is width, %2 is height, %3 is paper size name", "%1 × %2 mm (%3)", QString::number(inchesWidth * 25.4, 'd', 0), QString::number(inchesHeight * 25.4, 'd', 0), namePaperSize(inchesWidth, inchesHeight));
}
}
qulonglong DocumentPrivate::calculateMemoryToFree()
{
// [MEM] choose memory parameters based on configuration profile
qulonglong clipValue = 0;
qulonglong memoryToFree = 0;
switch (SettingsCore::memoryLevel()) {
case SettingsCore::EnumMemoryLevel::Low:
memoryToFree = m_allocatedPixmapsTotalMemory;
break;
case SettingsCore::EnumMemoryLevel::Normal: {
qulonglong thirdTotalMemory = getTotalMemory() / 3;
qulonglong freeMemory = getFreeMemory();
if (m_allocatedPixmapsTotalMemory > thirdTotalMemory) {
memoryToFree = m_allocatedPixmapsTotalMemory - thirdTotalMemory;
}
if (m_allocatedPixmapsTotalMemory > freeMemory) {
clipValue = (m_allocatedPixmapsTotalMemory - freeMemory) / 2;
}
} break;
case SettingsCore::EnumMemoryLevel::Aggressive: {
qulonglong freeMemory = getFreeMemory();
if (m_allocatedPixmapsTotalMemory > freeMemory) {
clipValue = (m_allocatedPixmapsTotalMemory - freeMemory) / 2;
}
} break;
case SettingsCore::EnumMemoryLevel::Greedy: {
qulonglong freeSwap;
qulonglong freeMemory = getFreeMemory(&freeSwap);
const qulonglong memoryLimit = qMin(qMax(freeMemory, getTotalMemory() / 2), freeMemory + freeSwap);
if (m_allocatedPixmapsTotalMemory > memoryLimit) {
clipValue = (m_allocatedPixmapsTotalMemory - memoryLimit) / 2;
}
} break;
}
if (clipValue > memoryToFree) {
memoryToFree = clipValue;
}
return memoryToFree;
}
void DocumentPrivate::cleanupPixmapMemory()
{
cleanupPixmapMemory(calculateMemoryToFree());
}
void DocumentPrivate::cleanupPixmapMemory(qulonglong memoryToFree)
{
if (memoryToFree < 1) {
return;
}
const int currentViewportPage = (*m_viewportIterator).pageNumber;
// Create a QMap of visible rects, indexed by page number
QMap<int, VisiblePageRect *> visibleRects;
for (auto *it : std::as_const(m_pageRects)) {
visibleRects.insert(it->pageNumber, it);
}
// Free memory starting from pages that are farthest from the current one
int pagesFreed = 0;
while (memoryToFree > 0) {
AllocatedPixmap *p = searchLowestPriorityPixmap(true, true);
if (!p) { // No pixmap to remove
break;
}
qCDebug(OkularCoreDebug).nospace() << "Evicting cache pixmap observer=" << p->observer << " page=" << p->page;
// m_allocatedPixmapsTotalMemory can't underflow because we always add or remove
// the memory used by the AllocatedPixmap so at most it can reach zero
m_allocatedPixmapsTotalMemory -= p->memory;
// Make sure memoryToFree does not underflow
if (p->memory > memoryToFree) {
memoryToFree = 0;
} else {
memoryToFree -= p->memory;
}
pagesFreed++;
// delete pixmap
m_pagesVector.at(p->page)->deletePixmap(p->observer);
// delete allocation descriptor
delete p;
}
// If we're still on low memory, try to free individual tiles
// Store pages that weren't completely removed
std::list<AllocatedPixmap *> pixmapsToKeep;
while (memoryToFree > 0) {
int clean_hits = 0;
for (DocumentObserver *observer : std::as_const(m_observers)) {
AllocatedPixmap *p = searchLowestPriorityPixmap(false, true, observer);
if (!p) { // No pixmap to remove
continue;
}
clean_hits++;
TilesManager *tilesManager = m_pagesVector.at(p->page)->d->tilesManager(observer);
if (tilesManager && tilesManager->totalMemory() > 0) {
qulonglong memoryDiff = p->memory;
NormalizedRect visibleRect;
if (visibleRects.contains(p->page)) {
visibleRect = visibleRects[p->page]->rect;
}
// Free non visible tiles
tilesManager->cleanupPixmapMemory(memoryToFree, visibleRect, currentViewportPage);
p->memory = tilesManager->totalMemory();
memoryDiff -= p->memory;
memoryToFree = (memoryDiff < memoryToFree) ? (memoryToFree - memoryDiff) : 0;
m_allocatedPixmapsTotalMemory -= memoryDiff;
if (p->memory > 0) {
pixmapsToKeep.push_back(p);
} else {
delete p;
}
} else {
pixmapsToKeep.push_back(p);
}
}
if (clean_hits == 0) {
break;
}
}
m_allocatedPixmaps.splice(m_allocatedPixmaps.end(), pixmapsToKeep);
Q_UNUSED(pagesFreed);
// p--rintf("freeMemory A:[%d -%d = %d] \n", m_allocatedPixmaps.count() + pagesFreed, pagesFreed, m_allocatedPixmaps.count() );
}
/* Returns the next pixmap to evict from cache, or NULL if no suitable pixmap
* if found. If unloadableOnly is set, only unloadable pixmaps are returned. If
* thenRemoveIt is set, the pixmap is removed from m_allocatedPixmaps before
* returning it
*/
AllocatedPixmap *DocumentPrivate::searchLowestPriorityPixmap(bool unloadableOnly, bool thenRemoveIt, DocumentObserver *observer)
{
auto pIt = m_allocatedPixmaps.begin();
auto pEnd = m_allocatedPixmaps.end();
auto farthestPixmap = pEnd;
const int currentViewportPage = m_viewportIterator->pageNumber;
/* Find the pixmap that is farthest from the current viewport */
int maxDistance = -1;
while (pIt != pEnd) {
const AllocatedPixmap *p = *pIt;
// Filter by observer
if (observer == nullptr || p->observer == observer) {
const int distance = qAbs(p->page - currentViewportPage);
if (maxDistance < distance && (!unloadableOnly || p->observer->canUnloadPixmap(p->page))) {
maxDistance = distance;
farthestPixmap = pIt;
}
}
++pIt;
}
/* No pixmap to remove */
if (farthestPixmap == pEnd) {
return nullptr;
}
AllocatedPixmap *selectedPixmap = *farthestPixmap;
if (thenRemoveIt) {
m_allocatedPixmaps.erase(farthestPixmap);
}
return selectedPixmap;
}
qulonglong DocumentPrivate::getTotalMemory()
{
static qulonglong cachedValue = 0;
if (cachedValue) {
return cachedValue;
}
#if defined(Q_OS_LINUX)
// if /proc/meminfo doesn't exist, return 128MB
QFile memFile(QStringLiteral("/proc/meminfo"));
if (!memFile.open(QIODevice::ReadOnly)) {
return (cachedValue = 134217728);
}
QTextStream readStream(&memFile);
while (true) {
QString entry = readStream.readLine();
if (entry.isNull()) {
break;
}
if (entry.startsWith(QLatin1String("MemTotal:"))) {
return (cachedValue = (Q_UINT64_C(1024) * entry.section(QLatin1Char(' '), -2, -2).toULongLong()));
}
}
#elif defined(Q_OS_FREEBSD)
qulonglong physmem;
int mib[] = {CTL_HW, HW_PHYSMEM};
size_t len = sizeof(physmem);
if (sysctl(mib, 2, &physmem, &len, NULL, 0) == 0) {
return (cachedValue = physmem);
}
#elif defined(Q_OS_WIN)
MEMORYSTATUSEX stat;
stat.dwLength = sizeof(stat);
GlobalMemoryStatusEx(&stat);
return (cachedValue = stat.ullTotalPhys);
#endif
return (cachedValue = 134217728);
}
qulonglong DocumentPrivate::getFreeMemory(qulonglong *freeSwap)
{
static QDeadlineTimer cacheTimer(0);
static qulonglong cachedValue = 0;
static qulonglong cachedFreeSwap = 0;
if (!cacheTimer.hasExpired()) {
if (freeSwap) {
*freeSwap = cachedFreeSwap;
}
return cachedValue;
}
/* Initialize the returned free swap value to 0. It is overwritten if the
* actual value is available */
if (freeSwap) {
*freeSwap = 0;
}
#if defined(Q_OS_LINUX)
// if /proc/meminfo doesn't exist, return MEMORY FULL
QFile memFile(QStringLiteral("/proc/meminfo"));
if (!memFile.open(QIODevice::ReadOnly)) {
return 0;
}
// read /proc/meminfo and sum up the contents of 'MemFree', 'Buffers'
// and 'Cached' fields. consider swapped memory as used memory.
qulonglong memoryFree = 0;
QString entry;
QTextStream readStream(&memFile);
static const int nElems = 5;
const QString names[nElems] = {QStringLiteral("MemFree:"), QStringLiteral("Buffers:"), QStringLiteral("Cached:"), QStringLiteral("SwapFree:"), QStringLiteral("SwapTotal:")};
qulonglong values[nElems] = {0, 0, 0, 0, 0};
bool foundValues[nElems] = {false, false, false, false, false};
while (true) {
entry = readStream.readLine();
if (entry.isNull()) {
break;
}
for (int i = 0; i < nElems; ++i) {
if (entry.startsWith(names[i])) {
values[i] = entry.section(QLatin1Char(' '), -2, -2).toULongLong(&foundValues[i]);
}
}
}
memFile.close();
bool found = true;
for (int i = 0; found && i < nElems; ++i) {
found = found && foundValues[i];
}
if (found) {
/* MemFree + Buffers + Cached - SwapUsed =
* = MemFree + Buffers + Cached - (SwapTotal - SwapFree) =
* = MemFree + Buffers + Cached + SwapFree - SwapTotal */
memoryFree = values[0] + values[1] + values[2] + values[3];
if (values[4] > memoryFree) {
memoryFree = 0;
} else {
memoryFree -= values[4];
}
} else {
return 0;
}
cacheTimer.setRemainingTime(kFreeMemCacheTimeout);
if (freeSwap) {
*freeSwap = (cachedFreeSwap = (Q_UINT64_C(1024) * values[3]));
}
return (cachedValue = (Q_UINT64_C(1024) * memoryFree));
#elif defined(Q_OS_FREEBSD)
qulonglong cache, inact, free, psize;
size_t cachelen, inactlen, freelen, psizelen;
cachelen = sizeof(cache);
inactlen = sizeof(inact);
freelen = sizeof(free);
psizelen = sizeof(psize);
// sum up inactive, cached and free memory
if (sysctlbyname("vm.stats.vm.v_cache_count", &cache, &cachelen, NULL, 0) == 0 && sysctlbyname("vm.stats.vm.v_inactive_count", &inact, &inactlen, NULL, 0) == 0 &&
sysctlbyname("vm.stats.vm.v_free_count", &free, &freelen, NULL, 0) == 0 && sysctlbyname("vm.stats.vm.v_page_size", &psize, &psizelen, NULL, 0) == 0) {
cacheTimer.setRemainingTime(kFreeMemCacheTimeout);
return (cachedValue = (cache + inact + free) * psize);
} else {
return 0;
}
#elif defined(Q_OS_WIN)
MEMORYSTATUSEX stat;
stat.dwLength = sizeof(stat);
GlobalMemoryStatusEx(&stat);
cacheTimer.setRemainingTime(kFreeMemCacheTimeout);
if (freeSwap)
*freeSwap = (cachedFreeSwap = stat.ullAvailPageFile);
return (cachedValue = stat.ullAvailPhys);
#else
// tell the memory is full.. will act as in LOW profile
return 0;
#endif
}
bool DocumentPrivate::loadDocumentInfo(LoadDocumentInfoFlags loadWhat)
// note: load data and stores it internally (document or pages). observers
// are still uninitialized at this point so don't access them
{
// qCDebug(OkularCoreDebug).nospace() << "Using '" << d->m_xmlFileName << "' as document info file.";
if (m_xmlFileName.isEmpty()) {
return false;
}
QFile infoFile(m_xmlFileName);
return loadDocumentInfo(infoFile, loadWhat);
}
bool DocumentPrivate::loadDocumentInfo(QFile &infoFile, LoadDocumentInfoFlags loadWhat)
{
if (!infoFile.exists() || !infoFile.open(QIODevice::ReadOnly)) {
// Use the default layout provided by the generator
if (loadWhat & LoadGeneralInfo) {
Generator::PageLayout defaultViewMode = m_generator->defaultPageLayout();
if (defaultViewMode == Generator::NoLayout) {
return false;
}
for (View *view : std::as_const(m_views)) {
setDefaultViewMode(view, defaultViewMode);
}
}
return false;
}
// Load DOM from XML file
QDomDocument doc(QStringLiteral("documentInfo"));
if (!doc.setContent(&infoFile)) {
qCDebug(OkularCoreDebug) << "Can't load XML pair! Check for broken xml.";
infoFile.close();
return false;
}
infoFile.close();
QDomElement root = doc.documentElement();
if (root.tagName() != QLatin1String("documentInfo")) {
return false;
}
bool loadedAnything = false; // set if something gets actually loaded
// Parse the DOM tree
QDomNode topLevelNode = root.firstChild();
while (topLevelNode.isElement()) {
QString catName = topLevelNode.toElement().tagName();
// Restore page attributes (bookmark, annotations, ...) from the DOM
if (catName == QLatin1String("pageList") && (loadWhat & LoadPageInfo)) {
QDomNode pageNode = topLevelNode.firstChild();
while (pageNode.isElement()) {
QDomElement pageElement = pageNode.toElement();
if (pageElement.hasAttribute(QStringLiteral("number"))) {
// get page number (node's attribute)
bool ok;
int pageNumber = pageElement.attribute(QStringLiteral("number")).toInt(&ok);
// pass the domElement to the right page, to read config data from
if (ok && pageNumber >= 0 && pageNumber < (int)m_pagesVector.count()) {
if (m_pagesVector[pageNumber]->d->restoreLocalContents(pageElement)) {
loadedAnything = true;
}
}
}
pageNode = pageNode.nextSibling();
}
}
// Restore 'general info' from the DOM
else if (catName == QLatin1String("generalInfo") && (loadWhat & LoadGeneralInfo)) {
QDomNode infoNode = topLevelNode.firstChild();
while (infoNode.isElement()) {
QDomElement infoElement = infoNode.toElement();
// restore viewports history
if (infoElement.tagName() == QLatin1String("history")) {
// clear history
m_viewportHistory.clear();
// append old viewports
QDomNode historyNode = infoNode.firstChild();
while (historyNode.isElement()) {
QDomElement historyElement = historyNode.toElement();
if (historyElement.hasAttribute(QStringLiteral("viewport"))) {
QString vpString = historyElement.attribute(QStringLiteral("viewport"));
m_viewportIterator = m_viewportHistory.insert(m_viewportHistory.end(), DocumentViewport(vpString));
loadedAnything = true;
}
historyNode = historyNode.nextSibling();
}
// consistency check
if (m_viewportHistory.empty()) {
m_viewportIterator = m_viewportHistory.insert(m_viewportHistory.end(), DocumentViewport());
}
} else if (infoElement.tagName() == QLatin1String("rotation")) {
QString str = infoElement.text();
bool ok = true;
int newrotation = !str.isEmpty() ? (str.toInt(&ok) % 4) : 0;
if (ok && newrotation != 0) {
setRotationInternal(newrotation, false);
loadedAnything = true;
}
} else if (infoElement.tagName() == QLatin1String("views")) {
QDomNode viewNode = infoNode.firstChild();
while (viewNode.isElement()) {
QDomElement viewElement = viewNode.toElement();
if (viewElement.tagName() == QLatin1String("view")) {
const QString viewName = viewElement.attribute(QStringLiteral("name"));
for (View *view : std::as_const(m_views)) {
if (view->name() == viewName) {
loadViewsInfo(view, viewElement);
loadedAnything = true;
break;
}
}
}
viewNode = viewNode.nextSibling();
}
}
infoNode = infoNode.nextSibling();
}
}
topLevelNode = topLevelNode.nextSibling();
} // </documentInfo>
return loadedAnything;
}
void DocumentPrivate::loadViewsInfo(View *view, const QDomElement &e)
{
QDomNode viewNode = e.firstChild();
while (viewNode.isElement()) {
QDomElement viewElement = viewNode.toElement();
if (viewElement.tagName() == QLatin1String("zoom")) {
const QString valueString = viewElement.attribute(QStringLiteral("value"));
bool newzoom_ok = true;
const double newzoom = !valueString.isEmpty() ? valueString.toDouble(&newzoom_ok) : 1.0;
if (newzoom_ok && newzoom != 0 && view->supportsCapability(View::Zoom) && (view->capabilityFlags(View::Zoom) & (View::CapabilityRead | View::CapabilitySerializable))) {
view->setCapability(View::Zoom, newzoom);
}
const QString modeString = viewElement.attribute(QStringLiteral("mode"));
bool newmode_ok = true;
const int newmode = !modeString.isEmpty() ? modeString.toInt(&newmode_ok) : 2;
if (newmode_ok && view->supportsCapability(View::ZoomModality) && (view->capabilityFlags(View::ZoomModality) & (View::CapabilityRead | View::CapabilitySerializable))) {
view->setCapability(View::ZoomModality, newmode);
}
} else if (viewElement.tagName() == QLatin1String("viewMode")) {
const QString modeString = viewElement.attribute(QStringLiteral("mode"));
bool newmode_ok = true;
const int newmode = !modeString.isEmpty() ? modeString.toInt(&newmode_ok) : 2;
if (newmode_ok && view->supportsCapability(View::ViewModeModality) && (view->capabilityFlags(View::ViewModeModality) & (View::CapabilityRead | View::CapabilitySerializable))) {
view->setCapability(View::ViewModeModality, newmode);
}
} else if (viewElement.tagName() == QLatin1String("continuous")) {
const QString modeString = viewElement.attribute(QStringLiteral("mode"));
bool newmode_ok = true;
const int newmode = !modeString.isEmpty() ? modeString.toInt(&newmode_ok) : 2;
if (newmode_ok && view->supportsCapability(View::Continuous) && (view->capabilityFlags(View::Continuous) & (View::CapabilityRead | View::CapabilitySerializable))) {
view->setCapability(View::Continuous, newmode);
}
} else if (viewElement.tagName() == QLatin1String("trimMargins")) {
const QString valueString = viewElement.attribute(QStringLiteral("value"));
bool newmode_ok = true;
const int newmode = !valueString.isEmpty() ? valueString.toInt(&newmode_ok) : 2;
if (newmode_ok && view->supportsCapability(View::TrimMargins) && (view->capabilityFlags(View::TrimMargins) & (View::CapabilityRead | View::CapabilitySerializable))) {
view->setCapability(View::TrimMargins, newmode);
}
}
viewNode = viewNode.nextSibling();
}
}
void DocumentPrivate::setDefaultViewMode(View *view, Generator::PageLayout defaultViewMode)
{
if (view->supportsCapability(View::ViewModeModality) && (view->capabilityFlags(View::ViewModeModality) & (View::CapabilityRead | View::CapabilitySerializable))) {
view->setCapability(View::ViewModeModality, (int)defaultViewMode);
}
if (SettingsCore::useFileInfoForViewContinuous()) {
if (view->supportsCapability(View::Continuous) && (view->capabilityFlags(View::Continuous) & (View::CapabilityRead | View::CapabilitySerializable))) {
view->setCapability(View::Continuous, (int)m_generator->defaultPageContinuous());
}
}
}
void DocumentPrivate::saveViewsInfo(View *view, QDomElement &e) const
{
if (view->supportsCapability(View::Zoom) && (view->capabilityFlags(View::Zoom) & (View::CapabilityRead | View::CapabilitySerializable)) && view->supportsCapability(View::ZoomModality) &&
(view->capabilityFlags(View::ZoomModality) & (View::CapabilityRead | View::CapabilitySerializable))) {
QDomElement zoomEl = e.ownerDocument().createElement(QStringLiteral("zoom"));
e.appendChild(zoomEl);
bool ok = true;
const double zoom = view->capability(View::Zoom).toDouble(&ok);
if (ok && zoom != 0) {
zoomEl.setAttribute(QStringLiteral("value"), QString::number(zoom));
}
const int mode = view->capability(View::ZoomModality).toInt(&ok);
if (ok) {
zoomEl.setAttribute(QStringLiteral("mode"), mode);
}
}
if (view->supportsCapability(View::Continuous) && (view->capabilityFlags(View::Continuous) & (View::CapabilityRead | View::CapabilitySerializable))) {
QDomElement contEl = e.ownerDocument().createElement(QStringLiteral("continuous"));
e.appendChild(contEl);
const bool mode = view->capability(View::Continuous).toBool();
contEl.setAttribute(QStringLiteral("mode"), mode);
}
if (view->supportsCapability(View::ViewModeModality) && (view->capabilityFlags(View::ViewModeModality) & (View::CapabilityRead | View::CapabilitySerializable))) {
QDomElement viewEl = e.ownerDocument().createElement(QStringLiteral("viewMode"));
e.appendChild(viewEl);
bool ok = true;
const int mode = view->capability(View::ViewModeModality).toInt(&ok);
if (ok) {
viewEl.setAttribute(QStringLiteral("mode"), mode);
}
}
if (view->supportsCapability(View::TrimMargins) && (view->capabilityFlags(View::TrimMargins) & (View::CapabilityRead | View::CapabilitySerializable))) {
QDomElement contEl = e.ownerDocument().createElement(QStringLiteral("trimMargins"));
e.appendChild(contEl);
const bool value = view->capability(View::TrimMargins).toBool();
contEl.setAttribute(QStringLiteral("value"), value);
}
}
QUrl DocumentPrivate::giveAbsoluteUrl(const QString &fileName) const
{
if (!QDir::isRelativePath(fileName)) {
return QUrl::fromLocalFile(fileName);
}
if (!m_url.isValid()) {
return QUrl();
}
return QUrl(KIO::upUrl(m_url).toString() + fileName);
}
bool DocumentPrivate::openRelativeFile(const QString &fileName)
{
const QUrl newUrl = giveAbsoluteUrl(fileName);
if (newUrl.isEmpty()) {
return false;
}
qCDebug(OkularCoreDebug).nospace() << "openRelativeFile: '" << newUrl << "'";
Q_EMIT m_parent->openUrl(newUrl);
return m_url == newUrl;
}
Generator *DocumentPrivate::loadGeneratorLibrary(const KPluginMetaData &service)
{
const auto result = KPluginFactory::instantiatePlugin<Okular::Generator>(service);
if (!result) {
qCWarning(OkularCoreDebug).nospace() << "Failed to load plugin " << service.fileName() << ": " << result.errorText;
return nullptr;
}
GeneratorInfo info(result.plugin, service);
m_loadedGenerators.insert(service.pluginId(), info);
return result.plugin;
}
void DocumentPrivate::loadAllGeneratorLibraries()
{
if (m_generatorsLoaded) {
return;
}
loadServiceList(availableGenerators());
m_generatorsLoaded = true;
}
void DocumentPrivate::loadServiceList(const QList<KPluginMetaData> &offers)
{
int count = offers.count();
if (count <= 0) {
return;
}
for (const auto &offer : std::as_const(offers)) {
auto id = offer.pluginId();
// don't load already loaded generators
if (m_loadedGenerators.contains(id)) {
continue;
}
auto *g = loadGeneratorLibrary(offer);
(void)g;
}
}
void DocumentPrivate::unloadGenerator(GeneratorInfo &info)
{
delete info.generator;
info.generator = nullptr;
}
void DocumentPrivate::cacheExportFormats()
{
if (m_exportCached) {
return;
}
const auto formats = m_generator->exportFormats();
for (const auto &format : formats) {
if (format.mimeType().name() == QLatin1String("text/plain")) {
m_exportToText = format;
} else {
m_exportFormats.append(format);
}
}
m_exportCached = true;
}
ConfigInterface *DocumentPrivate::generatorConfig(GeneratorInfo &info)
{
if (info.configChecked) {
return info.config;
}
info.config = qobject_cast<Okular::ConfigInterface *>(info.generator);
info.configChecked = true;
return info.config;
}
SaveInterface *DocumentPrivate::generatorSave(GeneratorInfo &info)
{
if (info.saveChecked) {
return info.save;
}
info.save = qobject_cast<Okular::SaveInterface *>(info.generator);
info.saveChecked = true;
return info.save;
}
Document::OpenResult DocumentPrivate::openDocumentInternal(const KPluginMetaData &offer, bool isstdin, const QString &docFile, const QByteArray &filedata, const QString &password)
{
QString propName = offer.pluginId();
QHash<QString, GeneratorInfo>::const_iterator genIt = m_loadedGenerators.constFind(propName);
m_walletGenerator = nullptr;
if (genIt != m_loadedGenerators.constEnd()) {
m_generator = genIt.value().generator;
} else {
m_generator = loadGeneratorLibrary(offer);
if (!m_generator) {
return Document::OpenError;
}
genIt = m_loadedGenerators.constFind(propName);
Q_ASSERT(genIt != m_loadedGenerators.constEnd());
}
Q_ASSERT_X(m_generator, "Document::load()", "null generator?!");
m_generator->d_func()->m_document = this;
// connect error reporting signals
m_openError.clear();
QMetaObject::Connection errorToOpenErrorConnection = QObject::connect(m_generator, &Generator::error, m_parent, [this](const QString &message) { m_openError = message; });
QObject::connect(m_generator, &Generator::warning, m_parent, &Document::warning);
QObject::connect(m_generator, &Generator::notice, m_parent, &Document::notice);
QApplication::setOverrideCursor(Qt::WaitCursor);
const QWindow *window = m_widget && m_widget->window() ? m_widget->window()->windowHandle() : nullptr;
const QSizeF dpi = Utils::realDpi(window);
qCDebug(OkularCoreDebug) << "Output DPI:" << dpi;
m_generator->setDPI(dpi);
Document::OpenResult openResult = Document::OpenError;
if (!isstdin) {
openResult = m_generator->loadDocumentWithPassword(docFile, m_pagesVector, password);
} else if (!filedata.isEmpty()) {
if (m_generator->hasFeature(Generator::ReadRawData)) {
openResult = m_generator->loadDocumentFromDataWithPassword(filedata, m_pagesVector, password);
} else {
m_tempFile = new QTemporaryFile();
if (!m_tempFile->open()) {
delete m_tempFile;
m_tempFile = nullptr;
} else {
m_tempFile->write(filedata);
QString tmpFileName = m_tempFile->fileName();
m_tempFile->close();
openResult = m_generator->loadDocumentWithPassword(tmpFileName, m_pagesVector, password);
}
}
}
QApplication::restoreOverrideCursor();
if (openResult != Document::OpenSuccess || m_pagesVector.size() <= 0) {
m_generator->d_func()->m_document = nullptr;
QObject::disconnect(m_generator, nullptr, m_parent, nullptr);
// TODO this is a bit of a hack, since basically means that
// you can only call walletDataForFile after calling openDocument
// but since in reality it's what happens I've decided not to refactor/break API
// One solution is just kill walletDataForFile and make OpenResult be an object
// where the wallet data is also returned when OpenNeedsPassword
m_walletGenerator = m_generator;
m_generator = nullptr;
qDeleteAll(m_pagesVector);
m_pagesVector.clear();
delete m_tempFile;
m_tempFile = nullptr;
// TODO: Q_EMIT a message telling the document is empty
if (openResult == Document::OpenSuccess) {
openResult = Document::OpenError;
}
} else {
/*
* Now that the document is opened, the tab (if using tabs) is visible, which means that
* we can now connect the error reporting signal directly to the parent
*/
QObject::disconnect(errorToOpenErrorConnection);
QObject::connect(m_generator, &Generator::error, m_parent, &Document::error);
}
return openResult;
}
bool DocumentPrivate::savePageDocumentInfo(QTemporaryFile *infoFile, int what) const
{
if (infoFile->open()) {
// 1. Create DOM
QDomDocument doc(QStringLiteral("documentInfo"));
QDomProcessingInstruction xmlPi = doc.createProcessingInstruction(QStringLiteral("xml"), QStringLiteral("version=\"1.0\" encoding=\"utf-8\""));
doc.appendChild(xmlPi);
QDomElement root = doc.createElement(QStringLiteral("documentInfo"));
doc.appendChild(root);
// 2.1. Save page attributes (bookmark state, annotations, ... ) to DOM
QDomElement pageList = doc.createElement(QStringLiteral("pageList"));
root.appendChild(pageList);
// <page list><page number='x'>.... </page> save pages that hold data
for (Page *const page : m_pagesVector) {
page->d->saveLocalContents(pageList, doc, PageItems(what));
}
// 3. Save DOM to XML file
QString xml = doc.toString();
QTextStream os(infoFile);
os.setEncoding(QStringConverter::Utf8);
os << xml;
return true;
}
return false;
}
DocumentViewport DocumentPrivate::nextDocumentViewport() const
{
DocumentViewport ret = m_nextDocumentViewport;
if (!m_nextDocumentDestination.isEmpty() && m_generator) {
DocumentViewport vp(m_parent->metaData(QStringLiteral("NamedViewport"), m_nextDocumentDestination).toString());
if (vp.isValid()) {
ret = vp;
}
}
return ret;
}
void DocumentPrivate::performAddPageAnnotation(int page, Annotation *annotation)
{
Okular::SaveInterface *iface = qobject_cast<Okular::SaveInterface *>(m_generator);
AnnotationProxy *proxy = iface ? iface->annotationProxy() : nullptr;
// find out the page to attach annotation
Page *kp = m_pagesVector[page];
if (!m_generator || !kp) {
return;
}
// the annotation belongs already to a page
if (annotation->d_ptr->m_page) {
return;
}
// add annotation to the page
kp->addAnnotation(annotation);
// tell the annotation proxy
if (proxy && proxy->supports(AnnotationProxy::Addition)) {
proxy->notifyAddition(annotation, page);
}
// notify observers about the change
notifyAnnotationChanges(page);
if (annotation->flags() & Annotation::ExternallyDrawn) {
// Redraw everything, including ExternallyDrawn annotations
refreshPixmaps(page);
}
}
void DocumentPrivate::performRemovePageAnnotation(int page, Annotation *annotation)
{
Okular::SaveInterface *iface = qobject_cast<Okular::SaveInterface *>(m_generator);
AnnotationProxy *proxy = iface ? iface->annotationProxy() : nullptr;
bool isExternallyDrawn;
// find out the page
Page *kp = m_pagesVector[page];
if (!m_generator || !kp) {
return;
}
if (annotation->flags() & Annotation::ExternallyDrawn) {
isExternallyDrawn = true;
} else {
isExternallyDrawn = false;
}
// try to remove the annotation
if (m_parent->canRemovePageAnnotation(annotation)) {
// tell the annotation proxy
if (proxy && proxy->supports(AnnotationProxy::Removal)) {
proxy->notifyRemoval(annotation, page);
}
kp->removeAnnotation(annotation); // Also destroys the object
// in case of success, notify observers about the change
notifyAnnotationChanges(page);
if (isExternallyDrawn) {
// Redraw everything, including ExternallyDrawn annotations
refreshPixmaps(page);
}
}
}
void DocumentPrivate::performModifyPageAnnotation(int page, Annotation *annotation, bool appearanceChanged)
{
Okular::SaveInterface *iface = qobject_cast<Okular::SaveInterface *>(m_generator);
AnnotationProxy *proxy = iface ? iface->annotationProxy() : nullptr;
// find out the page
const Page *kp = m_pagesVector[page];
if (!m_generator || !kp) {
return;
}
// tell the annotation proxy
if (proxy && proxy->supports(AnnotationProxy::Modification)) {
proxy->notifyModification(annotation, page, appearanceChanged);
}
// notify observers about the change
notifyAnnotationChanges(page);
if (appearanceChanged && (annotation->flags() & Annotation::ExternallyDrawn)) {
/* When an annotation is being moved, the generator will not render it.
* Therefore there's no need to refresh pixmaps after the first time */
if (annotation->flags() & (Annotation::BeingMoved | Annotation::BeingResized)) {
if (m_annotationBeingModified) {
return;
} else { // First time: take note
m_annotationBeingModified = true;
}
} else {
m_annotationBeingModified = false;
}
// Redraw everything, including ExternallyDrawn annotations
qCDebug(OkularCoreDebug) << "Refreshing Pixmaps";
refreshPixmaps(page);
}
}
void DocumentPrivate::performSetAnnotationContents(const QString &newContents, Annotation *annot, int pageNumber)
{
bool appearanceChanged = false;
// Check if appearanceChanged should be true
switch (annot->subType()) {
// If it's an in-place TextAnnotation, set the inplace text
case Okular::Annotation::AText: {
const Okular::TextAnnotation *txtann = static_cast<Okular::TextAnnotation *>(annot);
if (txtann->textType() == Okular::TextAnnotation::InPlace) {
appearanceChanged = true;
}
break;
}
// If it's a LineAnnotation, check if caption text is visible
case Okular::Annotation::ALine: {
const Okular::LineAnnotation *lineann = static_cast<Okular::LineAnnotation *>(annot);
if (lineann->showCaption()) {
appearanceChanged = true;
}
break;
}
default:
break;
}
// Set contents
annot->setContents(newContents);
// Tell the document the annotation has been modified
performModifyPageAnnotation(pageNumber, annot, appearanceChanged);
}
void DocumentPrivate::recalculateForms()
{
const QVariant fco = m_parent->metaData(QStringLiteral("FormCalculateOrder"));
const QList<int> formCalculateOrder = fco.value<QList<int>>();
for (int formId : formCalculateOrder) {
for (Page *const page : std::as_const(m_pagesVector)) {
if (page) {
bool pageNeedsRefresh = false;
const QList<Okular::FormField *> forms = page->formFields();
for (FormField *form : forms) {
if (form->id() == formId) {
const Action *action = form->additionalAction(FormField::CalculateField);
if (action) {
std::shared_ptr<Event> event;
if (dynamic_cast<FormFieldText *>(form) || dynamic_cast<FormFieldChoice *>(form)) {
// Prepare text calculate event
event = Event::createFormCalculateEvent(form, page);
const ScriptAction *linkscript = static_cast<const ScriptAction *>(action);
executeScriptEvent(event, linkscript);
// The value maybe changed in javascript so save it first.
QString oldVal = form->value().toString();
if (event) {
// Update text field from calculate
const QString newVal = event->value().toString();
if (newVal != oldVal) {
form->setValue(QVariant(newVal));
form->setAppearanceValue(QVariant(newVal));
bool returnCode = true;
if (form->additionalAction(Okular::FormField::FieldModified) && !form->isReadOnly()) {
m_parent->processKeystrokeCommitAction(form->additionalAction(Okular::FormField::FieldModified), form, returnCode);
}
if (const Okular::Action *validateAction = form->additionalAction(Okular::FormField::ValidateField)) {
if (returnCode) {
m_parent->processValidateAction(validateAction, form, returnCode);
}
}
if (!returnCode) {
continue;
} else {
form->commitValue(form->value().toString());
}
if (const Okular::Action *formatAction = form->additionalAction(Okular::FormField::FormatField)) {
// The format action handles the refresh.
m_parent->processFormatAction(formatAction, form);
} else {
form->commitFormattedValue(form->value().toString());
Q_EMIT m_parent->refreshFormWidget(form);
pageNeedsRefresh = true;
}
}
}
}
} else {
qWarning() << "Form that is part of calculate order doesn't have a calculate action";
}
}
}
if (pageNeedsRefresh) {
refreshPixmaps(page->number());
}
}
}
}
}
void DocumentPrivate::saveDocumentInfo() const
{
if (m_xmlFileName.isEmpty()) {
return;
}
QFile infoFile(m_xmlFileName);
qCDebug(OkularCoreDebug) << "About to save document info to" << m_xmlFileName;
if (!infoFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
qCWarning(OkularCoreDebug) << "Failed to open docdata file" << m_xmlFileName;
return;
}
// 1. Create DOM
QDomDocument doc(QStringLiteral("documentInfo"));
QDomProcessingInstruction xmlPi = doc.createProcessingInstruction(QStringLiteral("xml"), QStringLiteral("version=\"1.0\" encoding=\"utf-8\""));
doc.appendChild(xmlPi);
QDomElement root = doc.createElement(QStringLiteral("documentInfo"));
root.setAttribute(QStringLiteral("url"), m_url.toDisplayString(QUrl::PreferLocalFile));
doc.appendChild(root);
// 2.1. Save page attributes (bookmark state, annotations, ... ) to DOM
// -> do this if there are not-yet-migrated annots or forms in docdata/
if (m_docdataMigrationNeeded) {
QDomElement pageList = doc.createElement(QStringLiteral("pageList"));
root.appendChild(pageList);
// OriginalAnnotationPageItems and OriginalFormFieldPageItems tell to
// store the same unmodified annotation list and form contents that we
// read when we opened the file and ignore any change made by the user.
// Since we don't store annotations and forms in docdata/ any more, this is
// necessary to preserve annotations/forms that previous Okular version
// had stored there.
const PageItems saveWhat = AllPageItems | OriginalAnnotationPageItems | OriginalFormFieldPageItems;
// <page list><page number='x'>.... </page> save pages that hold data
for (Page *const page : std::as_const(m_pagesVector)) {
page->d->saveLocalContents(pageList, doc, saveWhat);
}
}
// 2.2. Save document info (current viewport, history, ... ) to DOM
QDomElement generalInfo = doc.createElement(QStringLiteral("generalInfo"));
root.appendChild(generalInfo);
// create rotation node
if (m_rotation != Rotation0) {
QDomElement rotationNode = doc.createElement(QStringLiteral("rotation"));
generalInfo.appendChild(rotationNode);
rotationNode.appendChild(doc.createTextNode(QString::number((int)m_rotation)));
}
// <general info><history> ... </history> save history up to OKULAR_HISTORY_SAVEDSTEPS viewports
const auto currentViewportIterator = std::list<DocumentViewport>::const_iterator(m_viewportIterator);
std::list<DocumentViewport>::const_iterator backIterator = currentViewportIterator;
if (backIterator != m_viewportHistory.end()) {
// go back up to OKULAR_HISTORY_SAVEDSTEPS steps from the current viewportIterator
int backSteps = OKULAR_HISTORY_SAVEDSTEPS;
while (backSteps-- && backIterator != m_viewportHistory.begin()) {
--backIterator;
}
// create history root node
QDomElement historyNode = doc.createElement(QStringLiteral("history"));
generalInfo.appendChild(historyNode);
// add old[backIterator] and present[viewportIterator] items
auto endIt = currentViewportIterator;
++endIt;
while (backIterator != endIt) {
QString name = (backIterator == currentViewportIterator) ? QStringLiteral("current") : QStringLiteral("oldPage");
QDomElement historyEntry = doc.createElement(name);
historyEntry.setAttribute(QStringLiteral("viewport"), (*backIterator).toString());
historyNode.appendChild(historyEntry);
++backIterator;
}
}
// create views root node
QDomElement viewsNode = doc.createElement(QStringLiteral("views"));
generalInfo.appendChild(viewsNode);
for (View *view : std::as_const(m_views)) {
QDomElement viewEntry = doc.createElement(QStringLiteral("view"));
viewEntry.setAttribute(QStringLiteral("name"), view->name());
viewsNode.appendChild(viewEntry);
saveViewsInfo(view, viewEntry);
}
// 3. Save DOM to XML file
QString xml = doc.toString();
QTextStream os(&infoFile);
os.setEncoding(QStringConverter::Utf8);
os << xml;
infoFile.close();
}
void DocumentPrivate::slotTimedMemoryCheck()
{
// [MEM] clean memory (for 'free mem dependent' profiles only)
if (SettingsCore::memoryLevel() != SettingsCore::EnumMemoryLevel::Low && m_allocatedPixmapsTotalMemory > 1024 * 1024) {
cleanupPixmapMemory();
}
}
void DocumentPrivate::sendGeneratorPixmapRequest()
{
/* If the pixmap cache will have to be cleaned in order to make room for the
* next request, get the distance from the current viewport of the page
* whose pixmap will be removed. We will ignore preload requests for pages
* that are at the same distance or farther */
const qulonglong memoryToFree = calculateMemoryToFree();
const int currentViewportPage = (*m_viewportIterator).pageNumber;
int maxDistance = INT_MAX; // Default: No maximum
if (memoryToFree) {
const AllocatedPixmap *pixmapToReplace = searchLowestPriorityPixmap(true);
if (pixmapToReplace) {
maxDistance = qAbs(pixmapToReplace->page - currentViewportPage);
}
}
// find a request
PixmapRequest *request = nullptr;
m_pixmapRequestsMutex.lock();
while (!m_pixmapRequestsStack.empty() && !request) {
PixmapRequest *r = m_pixmapRequestsStack.back();
if (!r) {
m_pixmapRequestsStack.pop_back();
continue;
}
QRect requestRect = r->isTile() ? r->normalizedRect().geometry(r->width(), r->height()) : QRect(0, 0, r->width(), r->height());
TilesManager *tilesManager = r->d->tilesManager();
const double normalizedArea = r->normalizedRect().width() * r->normalizedRect().height();
const QScreen *screen = nullptr;
if (m_widget) {
const QWindow *window = m_widget->window()->windowHandle();
if (window) {
screen = window->screen();
}
}
if (!screen) {
screen = QGuiApplication::primaryScreen();
}
const long screenSize = screen->devicePixelRatio() * screen->size().width() * screen->devicePixelRatio() * screen->size().height();
// Make sure the page is the right size to receive the pixmap
r->page()->setPageSize(r->observer(), r->width(), r->height());
// If it's a preload but the generator is not threaded no point in trying to preload
if (r->preload() && !m_generator->hasFeature(Generator::Threaded)) {
m_pixmapRequestsStack.pop_back();
delete r;
}
// request only if page isn't already present and request has valid id
else if ((!r->d->mForce && r->page()->hasPixmap(r->observer(), r->width(), r->height(), r->normalizedRect())) || !m_observers.contains(r->observer())) {
m_pixmapRequestsStack.pop_back();
delete r;
} else if (!r->d->mForce && r->preload() && qAbs(r->pageNumber() - currentViewportPage) >= maxDistance) {
m_pixmapRequestsStack.pop_back();
// qCDebug(OkularCoreDebug) << "Ignoring request that doesn't fit in cache";
delete r;
}
// Ignore requests for pixmaps that are already being generated
else if (tilesManager && tilesManager->isRequesting(r->normalizedRect(), r->width(), r->height())) {
m_pixmapRequestsStack.pop_back();
delete r;
}
// If the requested area is above 4*screenSize pixels, and we're not rendering most of the page, switch on the tile manager
else if (!tilesManager && m_generator->hasFeature(Generator::TiledRendering) && (long)r->width() * (long)r->height() > 4L * screenSize && normalizedArea < 0.75) {
// if the image is too big. start using tiles
qCDebug(OkularCoreDebug).nospace() << "Start using tiles on page " << r->pageNumber() << " (" << r->width() << "x" << r->height() << " px);";
// fill the tiles manager with the last rendered pixmap
const QPixmap *pixmap = r->page()->_o_nearestPixmap(r->observer(), r->width(), r->height());
if (pixmap) {
tilesManager = new TilesManager(r->pageNumber(), pixmap->width(), pixmap->height(), r->page()->rotation());
tilesManager->setPixmap(pixmap, NormalizedRect(0, 0, 1, 1), true /*isPartialPixmap*/);
tilesManager->setSize(r->width(), r->height());
} else {
// create new tiles manager
tilesManager = new TilesManager(r->pageNumber(), r->width(), r->height(), r->page()->rotation());
}
tilesManager->setRequest(r->normalizedRect(), r->width(), r->height());
r->page()->deletePixmap(r->observer());
r->page()->d->setTilesManager(r->observer(), tilesManager);
r->setTile(true);
// Change normalizedRect to the smallest rect that contains all
// visible tiles.
if (!r->normalizedRect().isNull()) {
NormalizedRect tilesRect;
const auto tiles = tilesManager->tilesAt(r->normalizedRect(), TilesManager::TerminalTile);
for (const Tile &tile : tiles) {
if (tilesRect.isNull()) {
tilesRect = tile.rect();
} else {
tilesRect |= tile.rect();
}
}
r->setNormalizedRect(tilesRect);
request = r;
} else {
// Discard request if normalizedRect is null. This happens in
// preload requests issued by PageView if the requested page is
// not visible and the user has just switched from a non-tiled
// zoom level to a tiled one
m_pixmapRequestsStack.pop_back();
delete r;
}
}
// If the requested area is below 3*screenSize pixels, switch off the tile manager
else if (tilesManager && (long)r->width() * (long)r->height() < 3L * screenSize) {
qCDebug(OkularCoreDebug).nospace() << "Stop using tiles on page " << r->pageNumber() << " (" << r->width() << "x" << r->height() << " px);";
// page is too small. stop using tiles.
r->page()->deletePixmap(r->observer());
r->setTile(false);
request = r;
} else if ((long)requestRect.width() * (long)requestRect.height() > 100L * screenSize && (SettingsCore::memoryLevel() != SettingsCore::EnumMemoryLevel::Greedy)) {
m_pixmapRequestsStack.pop_back();
if (!m_warnedOutOfMemory) {
qCWarning(OkularCoreDebug).nospace() << "Running out of memory on page " << r->pageNumber() << " (" << r->width() << "x" << r->height() << " px);";
qCWarning(OkularCoreDebug) << "this message will be reported only once.";
m_warnedOutOfMemory = true;
}
delete r;
} else {
request = r;
}
}
// if no request found (or already generated), return
if (!request) {
m_pixmapRequestsMutex.unlock();
return;
}
// [MEM] preventive memory freeing
qulonglong pixmapBytes = 0;
TilesManager *tm = request->d->tilesManager();
if (tm) {
pixmapBytes = tm->totalMemory();
} else {
pixmapBytes = 4 * qulonglong(request->width()) * request->height();
}
if (pixmapBytes > (1024 * 1024)) {
cleanupPixmapMemory(memoryToFree /* previously calculated value */);
}
// submit the request to the generator
if (m_generator->canGeneratePixmap()) {
QRect requestRect = !request->isTile() ? QRect(0, 0, request->width(), request->height()) : request->normalizedRect().geometry(request->width(), request->height());
qCDebug(OkularCoreDebug).nospace() << "sending request observer=" << request->observer() << " " << requestRect.width() << "x" << requestRect.height() << "@" << request->pageNumber() << " async == " << request->asynchronous()
<< " isTile == " << request->isTile();
m_pixmapRequestsStack.remove(request);
if (tm) {
tm->setRequest(request->normalizedRect(), request->width(), request->height());
}
if ((int)m_rotation % 2) {
request->d->swap();
}
if (m_rotation != Rotation0 && !request->normalizedRect().isNull()) {
request->setNormalizedRect(TilesManager::fromRotatedRect(request->normalizedRect(), m_rotation));
}
// If set elsewhere we already know we want it to be partial
if (!request->partialUpdatesWanted()) {
request->setPartialUpdatesWanted(request->asynchronous() && !request->page()->hasPixmap(request->observer()));
}
// we always have to unlock _before_ the generatePixmap() because
// a sync generation would end with requestDone() -> deadlock, and
// we can not really know if the generator can do async requests
m_executingPixmapRequests.push_back(request);
m_pixmapRequestsMutex.unlock();
m_generator->generatePixmap(request);
} else {
m_pixmapRequestsMutex.unlock();
// pino (7/4/2006): set the polling interval from 10 to 30
QTimer::singleShot(30, m_parent, [this] { sendGeneratorPixmapRequest(); });
}
}
void DocumentPrivate::rotationFinished(int page, Okular::Page *okularPage)
{
const Okular::Page *wantedPage = m_pagesVector.value(page, nullptr);
if (!wantedPage || wantedPage != okularPage) {
return;
}
for (DocumentObserver *o : std::as_const(m_observers)) {
o->notifyPageChanged(page, DocumentObserver::Pixmap | DocumentObserver::Annotations);
}
}
void DocumentPrivate::slotFontReadingProgress(int page)
{
Q_EMIT m_parent->fontReadingProgress(page);
if (page >= (int)m_parent->pages() - 1) {
Q_EMIT m_parent->fontReadingEnded();
m_fontThread = nullptr;
m_fontsCached = true;
}
}
void DocumentPrivate::fontReadingGotFont(const Okular::FontInfo &font)
{
// Try to avoid duplicate fonts
if (m_fontsCache.indexOf(font) == -1) {
m_fontsCache.append(font);
Q_EMIT m_parent->gotFont(font);
}
}
void DocumentPrivate::slotGeneratorConfigChanged()
{
if (!m_generator) {
return;
}
// reparse generator config and if something changed clear Pages
bool configchanged = false;
for (const auto &[key, value] : m_loadedGenerators.asKeyValueRange()) {
Okular::ConfigInterface *iface = generatorConfig(value);
if (iface) {
bool it_changed = iface->reparseConfig();
if (it_changed && (m_generator == value.generator)) {
configchanged = true;
}
}
}
if (configchanged) {
// invalidate pixmaps
for (Page *const page : std::as_const(m_pagesVector)) {
page->deletePixmaps();
}
// [MEM] remove allocation descriptors
qDeleteAll(m_allocatedPixmaps);
m_allocatedPixmaps.clear();
m_allocatedPixmapsTotalMemory = 0;
// send reload signals to observers
foreachObserverD(notifyContentsCleared(DocumentObserver::Pixmap));
}
// free memory if in 'low' profile
if (SettingsCore::memoryLevel() == SettingsCore::EnumMemoryLevel::Low && !m_allocatedPixmaps.empty() && !m_pagesVector.isEmpty()) {
cleanupPixmapMemory();
}
}
void DocumentPrivate::refreshPixmaps(int pageNumber)
{
Page *page = m_pagesVector.value(pageNumber, nullptr);
if (!page) {
return;
}
QList<Okular::PixmapRequest *> pixmapsToRequest;
for (const auto &[key, value] : page->d->m_pixmaps.asKeyValueRange()) {
const QSize size = value.m_pixmap->size();
PixmapRequest *p = new PixmapRequest(key, pageNumber, size.width(), size.height(), 1 /* dpr */, 1, PixmapRequest::Asynchronous);
p->d->mForce = true;
pixmapsToRequest << p;
}
// Need to do this ↑↓ in two steps since requestPixmaps can end up calling cancelRenderingBecauseOf
// which changes m_pixmaps and thus breaks the loop above
for (PixmapRequest *pr : std::as_const(pixmapsToRequest)) {
const QList<Okular::PixmapRequest *> requestedPixmaps {pr};
// TODO: Can it be called directly with the list, without the loop?
m_parent->requestPixmaps(requestedPixmaps, Okular::Document::NoOption);
}
for (DocumentObserver *observer : std::as_const(m_observers)) {
QList<Okular::PixmapRequest *> requestedPixmaps;
TilesManager *tilesManager = page->d->tilesManager(observer);
if (tilesManager) {
tilesManager->markDirty();
PixmapRequest *p = new PixmapRequest(observer, pageNumber, tilesManager->width(), tilesManager->height(), 1 /* dpr */, 1, PixmapRequest::Asynchronous);
// Get the visible page rect
NormalizedRect visibleRect;
for (const auto *it : std::as_const(m_pageRects)) {
if (it->pageNumber == pageNumber) {
visibleRect = it->rect;
break;
}
}
if (!visibleRect.isNull()) {
p->setNormalizedRect(visibleRect);
p->setTile(true);
p->d->mForce = true;
requestedPixmaps.push_back(p);
} else {
delete p;
}
}
m_parent->requestPixmaps(requestedPixmaps, Okular::Document::NoOption);
}
}
void DocumentPrivate::_o_configChanged()
{
// free text pages if needed
calculateMaxTextPages();
while (m_allocatedTextPagesFifo.count() > m_maxAllocatedTextPages) {
int pageToKick = m_allocatedTextPagesFifo.takeFirst();
m_pagesVector.at(pageToKick)->setTextPage(nullptr); // deletes the textpage
}
}
void DocumentPrivate::doContinueDirectionMatchSearch(DoContinueDirectionMatchSearchStruct *searchStruct)
{
RunningSearch *search = m_searches.value(searchStruct->searchID);
if ((m_searchCancelled && !searchStruct->match) || !search) {
// if the user cancelled but he just got a match, give him the match!
QApplication::restoreOverrideCursor();
if (search) {
search->isCurrentlySearching = false;
}
Q_EMIT m_parent->searchFinished(searchStruct->searchID, Document::SearchCancelled);
delete searchStruct->pagesToNotify;
delete searchStruct;
return;
}
const bool forward = search->cachedType == Document::NextMatch;
bool doContinue = false;
// if no match found, loop through the whole doc, starting from currentPage
if (!searchStruct->match) {
const int pageCount = m_pagesVector.count();
if (search->pagesDone < pageCount) {
doContinue = true;
if (searchStruct->currentPage >= pageCount) {
searchStruct->currentPage = 0;
Q_EMIT m_parent->notice(i18n("Continuing search from beginning"), 3000);
} else if (searchStruct->currentPage < 0) {
searchStruct->currentPage = pageCount - 1;
Q_EMIT m_parent->notice(i18n("Continuing search from bottom"), 3000);
}
}
}
if (doContinue) {
// get page
const Page *page = m_pagesVector[searchStruct->currentPage];
// request search page if needed
if (!page->hasTextPage()) {
m_parent->requestTextPage(page->number());
}
// if found a match on the current page, end the loop
searchStruct->match = page->findText(searchStruct->searchID, search->cachedString, forward ? FromTop : FromBottom, search->cachedCaseSensitivity);
if (!searchStruct->match) {
if (forward) {
searchStruct->currentPage++;
} else {
searchStruct->currentPage--;
}
search->pagesDone++;
} else {
search->pagesDone = 1;
}
// Both of the previous if branches need to call doContinueDirectionMatchSearch
QTimer::singleShot(0, m_parent, [this, searchStruct] { doContinueDirectionMatchSearch(searchStruct); });
} else {
doProcessSearchMatch(searchStruct->match, search, searchStruct->pagesToNotify, searchStruct->currentPage, searchStruct->searchID, search->cachedViewportMove, search->cachedColor);
delete searchStruct;
}
}
void DocumentPrivate::doProcessSearchMatch(RegularAreaRect *match, RunningSearch *search, QSet<int> *pagesToNotify, int currentPage, int searchID, bool moveViewport, const QColor &color)
{
// reset cursor to previous shape
QApplication::restoreOverrideCursor();
bool foundAMatch = false;
search->isCurrentlySearching = false;
// if a match has been found..
if (match) {
// update the RunningSearch structure adding this match..
foundAMatch = true;
search->continueOnPage = currentPage;
search->continueOnMatch = *match;
search->highlightedPages.insert(currentPage);
// ..add highlight to the page..
m_pagesVector[currentPage]->d->setHighlight(*match, color, searchID);
// ..queue page for notifying changes..
pagesToNotify->insert(currentPage);
// Create a normalized rectangle around the search match that includes a 5% buffer on all sides.
const Okular::NormalizedRect matchRectWithBuffer = Okular::NormalizedRect(match->first().left - 0.05, match->first().top - 0.05, match->first().right + 0.05, match->first().bottom + 0.05);
const bool matchRectFullyVisible = isNormalizedRectangleFullyVisible(matchRectWithBuffer, currentPage);
// ..move the viewport to show the first of the searched word sequence centered
if (moveViewport && !matchRectFullyVisible) {
DocumentViewport searchViewport(currentPage);
searchViewport.rePos.enabled = true;
searchViewport.rePos.normalizedX = (match->first().left + match->first().right) / 2.0;
searchViewport.rePos.normalizedY = (match->first().top + match->first().bottom) / 2.0;
m_parent->setViewport(searchViewport, nullptr, true);
}
delete match;
}
// notify observers about highlights changes
for (int pageNumber : std::as_const(*pagesToNotify)) {
for (DocumentObserver *observer : std::as_const(m_observers)) {
observer->notifyPageChanged(pageNumber, DocumentObserver::Highlights);
}
}
if (foundAMatch) {
Q_EMIT m_parent->searchFinished(searchID, Document::MatchFound);
} else {
Q_EMIT m_parent->searchFinished(searchID, Document::NoMatchFound);
}
delete pagesToNotify;
}
void DocumentPrivate::doContinueAllDocumentSearch(QSet<int> *pagesToNotify, QHash<Page *, QList<RegularAreaRect *>> *pageMatches, int currentPage, int searchID)
{
RunningSearch *search = m_searches.value(searchID);
if (m_searchCancelled || !search) {
typedef QList<RegularAreaRect *> Matches;
QApplication::restoreOverrideCursor();
if (search) {
search->isCurrentlySearching = false;
}
Q_EMIT m_parent->searchFinished(searchID, Document::SearchCancelled);
for (const Matches &mv : std::as_const(*pageMatches)) {
qDeleteAll(mv);
}
delete pageMatches;
delete pagesToNotify;
return;
}
if (currentPage < m_pagesVector.count()) {
// get page (from the first to the last)
Page *page = m_pagesVector.at(currentPage);
// request search page if needed
if (!page->hasTextPage()) {
int pageNumber = page->number(); // redundant? is it == currentPage ?
m_parent->requestTextPage(pageNumber);
}
// loop on a page adding highlights for all found items
RegularAreaRect *lastMatch = nullptr;
while (true) {
if (lastMatch) {
lastMatch = page->findText(searchID, search->cachedString, NextResult, search->cachedCaseSensitivity, lastMatch);
} else {
lastMatch = page->findText(searchID, search->cachedString, FromTop, search->cachedCaseSensitivity);
}
if (!lastMatch) {
break;
}
// add highlight rect to the matches map
(*pageMatches)[page].append(lastMatch);
}
delete lastMatch;
QTimer::singleShot(0, m_parent, [this, pagesToNotify, pageMatches, currentPage, searchID] { doContinueAllDocumentSearch(pagesToNotify, pageMatches, currentPage + 1, searchID); });
} else {
// reset cursor to previous shape
QApplication::restoreOverrideCursor();
search->isCurrentlySearching = false;
bool foundAMatch = pageMatches->count() != 0;
for (auto [key, value] : pageMatches->asKeyValueRange()) {
for (RegularAreaRect *&match : value) {
key->d->setHighlight(*match, search->cachedColor, searchID);
delete match;
match = nullptr;
}
search->highlightedPages.insert(key->number());
pagesToNotify->insert(key->number());
}
for (DocumentObserver *observer : std::as_const(m_observers)) {
observer->notifySetup(m_pagesVector, 0);
}
// notify observers about highlights changes
for (int pageNumber : std::as_const(*pagesToNotify)) {
for (DocumentObserver *observer : std::as_const(m_observers)) {
observer->notifyPageChanged(pageNumber, DocumentObserver::Highlights);
}
}
if (foundAMatch) {
Q_EMIT m_parent->searchFinished(searchID, Document::MatchFound);
} else {
Q_EMIT m_parent->searchFinished(searchID, Document::NoMatchFound);
}
delete pageMatches;
delete pagesToNotify;
}
}
void DocumentPrivate::doContinueGooglesDocumentSearch(QSet<int> *pagesToNotify, QHash<Page *, QList<MatchColor>> *pageMatches, int currentPage, int searchID, const QStringList &words)
{
RunningSearch *search = m_searches.value(searchID);
if (m_searchCancelled || !search) {
using Matches = QList<MatchColor>;
QApplication::restoreOverrideCursor();
if (search) {
search->isCurrentlySearching = false;
}
Q_EMIT m_parent->searchFinished(searchID, Document::SearchCancelled);
for (Matches &mv : *pageMatches) {
for (auto &[area, color] : mv) {
delete area;
area = nullptr;
}
}
delete pageMatches;
delete pagesToNotify;
return;
}
const int wordCount = words.count();
const int hueStep = (wordCount > 1) ? (60 / (wordCount - 1)) : 60;
int baseHue, baseSat, baseVal;
search->cachedColor.getHsv(&baseHue, &baseSat, &baseVal);
if (currentPage < m_pagesVector.count()) {
// get page (from the first to the last)
Page *page = m_pagesVector.at(currentPage);
// request search page if needed
if (!page->hasTextPage()) {
int pageNumber = page->number(); // redundant? is it == currentPage ?
m_parent->requestTextPage(pageNumber);
}
// loop on a page adding highlights for all found items
bool allMatched = wordCount > 0, anyMatched = false;
for (int w = 0; w < wordCount; w++) {
const QString &word = words[w];
int newHue = baseHue - w * hueStep;
if (newHue < 0) {
newHue += 360;
}
QColor wordColor = QColor::fromHsv(newHue, baseSat, baseVal);
RegularAreaRect *lastMatch = nullptr;
// add all highlights for current word
bool wordMatched = false;
while (true) {
if (lastMatch) {
lastMatch = page->findText(searchID, word, NextResult, search->cachedCaseSensitivity, lastMatch);
} else {
lastMatch = page->findText(searchID, word, FromTop, search->cachedCaseSensitivity);
}
if (!lastMatch) {
break;
}
// add highlight rect to the matches map
(*pageMatches)[page].append(MatchColor(lastMatch, wordColor));
wordMatched = true;
}
allMatched = allMatched && wordMatched;
anyMatched = anyMatched || wordMatched;
}
// if not all words are present in page, remove partial highlights
const bool matchAll = search->cachedType == Document::GoogleAll;
if (!allMatched && matchAll) {
auto &matches = (*pageMatches)[page];
for (auto &[area, color] : matches) {
delete area;
area = nullptr;
}
pageMatches->remove(page);
}
QTimer::singleShot(0, m_parent, [this, pagesToNotify, pageMatches, currentPage, searchID, words] { doContinueGooglesDocumentSearch(pagesToNotify, pageMatches, currentPage + 1, searchID, words); });
} else {
// reset cursor to previous shape
QApplication::restoreOverrideCursor();
search->isCurrentlySearching = false;
bool foundAMatch = pageMatches->count() != 0;
for (auto [page, matches] : pageMatches->asKeyValueRange()) {
for (auto &[area, color] : matches) {
page->d->setHighlight(*area, color, searchID);
delete area;
}
search->highlightedPages.insert(page->number());
pagesToNotify->insert(page->number());
}
// send page lists to update observers (since some filter on bookmarks)
for (DocumentObserver *observer : std::as_const(m_observers)) {
observer->notifySetup(m_pagesVector, 0);
}
// notify observers about highlights changes
for (int pageNumber : std::as_const(*pagesToNotify)) {
for (DocumentObserver *observer : std::as_const(m_observers)) {
observer->notifyPageChanged(pageNumber, DocumentObserver::Highlights);
}
}
if (foundAMatch) {
Q_EMIT m_parent->searchFinished(searchID, Document::MatchFound);
} else {
Q_EMIT m_parent->searchFinished(searchID, Document::NoMatchFound);
}
delete pageMatches;
delete pagesToNotify;
}
}
QVariant DocumentPrivate::documentMetaData(const Generator::DocumentMetaDataKey key, const QVariant &option) const
{
switch (key) {
case Generator::PaperColorMetaData: {
bool giveDefault = option.toBool();
QColor color;
if ((SettingsCore::renderMode() == SettingsCore::EnumRenderMode::Paper) && SettingsCore::changeColors()) {
color = SettingsCore::paperColor();
} else if (giveDefault) {
color = Qt::white;
}
return color;
}
case Generator::TextAntialiasMetaData:
switch (SettingsCore::textAntialias()) {
case SettingsCore::EnumTextAntialias::Enabled:
return true;
case SettingsCore::EnumTextAntialias::Disabled:
return false;
}
break;
case Generator::GraphicsAntialiasMetaData:
switch (SettingsCore::graphicsAntialias()) {
case SettingsCore::EnumGraphicsAntialias::Enabled:
return true;
case SettingsCore::EnumGraphicsAntialias::Disabled:
return false;
}
break;
case Generator::TextHintingMetaData:
switch (SettingsCore::textHinting()) {
case SettingsCore::EnumTextHinting::Enabled:
return true;
case SettingsCore::EnumTextHinting::Disabled:
return false;
}
break;
}
return QVariant();
}
bool DocumentPrivate::isNormalizedRectangleFullyVisible(const Okular::NormalizedRect &rectOfInterest, int rectPage)
{
const auto &visibleRects = m_parent->visiblePageRects();
return std::ranges::any_of(visibleRects, [&](VisiblePageRect *const it) {
return it->pageNumber == rectPage //
&& it->rect.contains(rectOfInterest.left, rectOfInterest.top) //
&& it->rect.contains(rectOfInterest.right, rectOfInterest.bottom);
});
}
struct pdfsyncpoint {
QString file;
qlonglong x;
qlonglong y;
int row;
int column;
int page;
};
void DocumentPrivate::loadSyncFile(const QString &filePath)
{
QFile f(filePath + QLatin1String("sync"));
if (!f.open(QIODevice::ReadOnly)) {
return;
}
QTextStream ts(&f);
// first row: core name of the pdf output
const QString coreName = ts.readLine();
// second row: version string, in the form 'Version %u'
const QString versionstr = ts.readLine();
// anchor the pattern with \A and \z to match the entire subject string
// TODO: with Qt 5.12 QRegularExpression::anchoredPattern() can be used instead
static QRegularExpression versionre(QStringLiteral("\\AVersion \\d+\\z"), QRegularExpression::CaseInsensitiveOption);
QRegularExpressionMatch match = versionre.match(versionstr);
if (!match.hasMatch()) {
return;
}
QHash<int, pdfsyncpoint> points;
QStack<QString> fileStack;
int currentpage = -1;
const QLatin1String texStr(".tex");
const QChar spaceChar = QChar::fromLatin1(' ');
fileStack.push(coreName + texStr);
const QSizeF dpi = m_generator->dpi();
QString line;
while (!ts.atEnd()) {
line = ts.readLine();
const QStringList tokens = line.split(spaceChar, Qt::SkipEmptyParts);
const int tokenSize = tokens.count();
if (tokenSize < 1) {
continue;
}
if (tokens.first() == QLatin1String("l") && tokenSize >= 3) {
int id = tokens.at(1).toInt();
QHash<int, pdfsyncpoint>::const_iterator it = points.constFind(id);
if (it == points.constEnd()) {
pdfsyncpoint pt;
pt.x = 0;
pt.y = 0;
pt.row = tokens.at(2).toInt();
pt.column = 0; // TODO
pt.page = -1;
pt.file = fileStack.top();
points[id] = pt;
}
} else if (tokens.first() == QLatin1String("s") && tokenSize >= 2) {
currentpage = tokens.at(1).toInt() - 1;
} else if (tokens.first() == QLatin1String("p*") && tokenSize >= 4) {
// TODO
qCDebug(OkularCoreDebug) << "PdfSync: 'p*' line ignored";
} else if (tokens.first() == QLatin1String("p") && tokenSize >= 4) {
int id = tokens.at(1).toInt();
QHash<int, pdfsyncpoint>::iterator it = points.find(id);
if (it != points.end()) {
it->x = tokens.at(2).toInt();
it->y = tokens.at(3).toInt();
it->page = currentpage;
}
} else if (line.startsWith(QLatin1Char('(')) && tokenSize == 1) {
QString newfile = line;
// chop the leading '('
newfile.remove(0, 1);
if (!newfile.endsWith(texStr)) {
newfile += texStr;
}
fileStack.push(newfile);
} else if (line == QLatin1String(")")) {
if (!fileStack.isEmpty()) {
fileStack.pop();
} else {
qCDebug(OkularCoreDebug) << "PdfSync: going one level down too much";
}
} else {
qCDebug(OkularCoreDebug).nospace() << "PdfSync: unknown line format: '" << line << "'";
}
}
QList<QList<Okular::SourceRefObjectRect *>> refRects(m_pagesVector.size());
for (const pdfsyncpoint &pt : std::as_const(points)) {
// drop pdfsync points not completely valid
if (pt.page < 0 || pt.page >= m_pagesVector.size()) {
continue;
}
// magic numbers for TeX's RSU's (Ridiculously Small Units) conversion to pixels
Okular::NormalizedPoint p((pt.x * dpi.width()) / (72.27 * 65536.0 * m_pagesVector[pt.page]->width()), (pt.y * dpi.height()) / (72.27 * 65536.0 * m_pagesVector[pt.page]->height()));
QString file = pt.file;
Okular::SourceReference *sourceRef = new Okular::SourceReference(file, pt.row, pt.column);
refRects[pt.page].append(new Okular::SourceRefObjectRect(p, sourceRef));
}
for (int i = 0; i < refRects.size(); ++i) {
if (!refRects.at(i).isEmpty()) {
m_pagesVector[i]->setSourceReferences(refRects.at(i));
}
}
}
void DocumentPrivate::clearAndWaitForRequests()
{
m_pixmapRequestsMutex.lock();
qDeleteAll(m_pixmapRequestsStack);
m_pixmapRequestsStack.clear();
m_pixmapRequestsMutex.unlock();
QEventLoop loop;
bool startEventLoop = false;
do {
m_pixmapRequestsMutex.lock();
startEventLoop = !m_executingPixmapRequests.empty();
if (m_generator->hasFeature(Generator::SupportsCancelling)) {
for (PixmapRequest *executingRequest : std::as_const(m_executingPixmapRequests)) {
executingRequest->d->mShouldAbortRender = 1;
}
if (m_generator->d_ptr->mTextPageGenerationThread) {
m_generator->d_ptr->mTextPageGenerationThread->abortExtraction();
}
}
m_pixmapRequestsMutex.unlock();
if (startEventLoop) {
m_closingLoop = &loop;
loop.exec();
m_closingLoop = nullptr;
}
} while (startEventLoop);
}
int DocumentPrivate::findFieldPageNumber(Okular::FormField *field)
{
// Lookup the page of the FormField
int foundPage = -1;
for (uint pageIdx = 0, nPages = m_parent->pages(); pageIdx < nPages; pageIdx++) {
const Page *p = m_parent->page(pageIdx);
if (p && p->formFields().contains(field)) {
foundPage = static_cast<int>(pageIdx);
break;
}
}
return foundPage;
}
void DocumentPrivate::executeScriptEvent(const std::shared_ptr<Event> &event, const Okular::ScriptAction *linkscript)
{
if (!m_scripter) {
m_scripter = new Scripter(this);
}
m_scripter->execute(event.get(), linkscript->scriptType(), linkscript->script());
}
Document::Document(QWidget *widget)
: QObject(nullptr)
, d(new DocumentPrivate(this))
{
d->m_widget = widget;
d->m_bookmarkManager = new BookmarkManager(d);
d->m_viewportIterator = d->m_viewportHistory.insert(d->m_viewportHistory.end(), DocumentViewport());
d->m_undoStack = new QUndoStack(this);
connect(SettingsCore::self(), &SettingsCore::configChanged, this, [this] { d->_o_configChanged(); });
connect(d->m_undoStack, &QUndoStack::canUndoChanged, this, &Document::canUndoChanged);
connect(d->m_undoStack, &QUndoStack::canRedoChanged, this, &Document::canRedoChanged);
connect(d->m_undoStack, &QUndoStack::cleanChanged, this, &Document::undoHistoryCleanChanged);
qRegisterMetaType<Okular::FontInfo>();
}
Document::~Document()
{
// delete generator, pages, and related stuff
closeDocument();
for (View *view : std::as_const(d->m_views)) {
view->d_func()->document = nullptr;
}
// delete the bookmark manager
delete d->m_bookmarkManager;
// delete the loaded generators
for (auto &generator : d->m_loadedGenerators) {
d->unloadGenerator(generator);
}
d->m_loadedGenerators.clear();
// delete the private structure
delete d;
}
QString DocumentPrivate::docDataFileName(const QUrl &url, qint64 document_size)
{
QString fn = url.fileName();
fn = QString::number(document_size) + QLatin1Char('.') + fn + QStringLiteral(".xml");
QString docdataDir = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QStringLiteral("/okular/docdata");
// make sure that the okular/docdata/ directory exists (probably this used to be handled by KStandardDirs)
if (!QFileInfo::exists(docdataDir)) {
qCDebug(OkularCoreDebug) << "creating docdata folder" << docdataDir;
QDir().mkpath(docdataDir);
}
QString newokularfile = docdataDir + QLatin1Char('/') + fn;
return newokularfile;
}
QList<KPluginMetaData> DocumentPrivate::availableGenerators()
{
static QList<KPluginMetaData> result;
if (result.isEmpty()) {
result = KPluginMetaData::findPlugins(QStringLiteral("okular_generators"));
}
return result;
}
KPluginMetaData DocumentPrivate::generatorForMimeType(const QMimeType &type, QWidget *widget, const QList<KPluginMetaData> &triedOffers)
{
// First try to find an exact match, and then look for more general ones (e. g. the plain text one)
// Ideally we would rank these by "closeness", but that might be overdoing it
const QList<KPluginMetaData> available = availableGenerators();
QList<KPluginMetaData> offers;
QList<KPluginMetaData> exactMatches;
QMimeDatabase mimeDatabase;
for (const KPluginMetaData &md : available) {
if (triedOffers.contains(md)) {
continue;
}
const QStringList mimetypes = md.mimeTypes();
for (const QString &supported : mimetypes) {
QMimeType mimeType = mimeDatabase.mimeTypeForName(supported);
if (mimeType == type && !exactMatches.contains(md)) {
exactMatches << md;
}
if (type.inherits(supported) && !offers.contains(md)) {
offers << md;
}
}
}
if (!exactMatches.isEmpty()) {
offers = exactMatches;
}
if (offers.isEmpty()) {
return KPluginMetaData();
}
int hRank = 0;
// best ranked offer search
if (offers.size() > 1) {
// sort the offers: the offers with an higher priority come before
auto cmp = [](const KPluginMetaData &s1, const KPluginMetaData &s2) {
const QString property = QStringLiteral("X-KDE-Priority");
return s1.rawData().value(property).toInt() > s2.rawData().value(property).toInt();
};
std::stable_sort(offers.begin(), offers.end(), cmp);
if (SettingsCore::chooseGenerators()) {
QStringList list;
list.reserve(offers.size());
for (const auto &offer : std::as_const(offers)) {
list << offer.pluginId();
}
ChooseEngineDialog choose(list, type, widget);
if (choose.exec() == QDialog::Rejected) {
return KPluginMetaData();
}
hRank = choose.selectedGenerator();
}
}
Q_ASSERT(hRank < offers.size());
return offers.at(hRank);
}
Document::OpenResult Document::openDocument(const QString &docFile, const QUrl &url, const QMimeType &_mime, const QString &password)
{
QMimeDatabase db;
QMimeType mime = _mime;
QByteArray filedata;
int fd = -1;
if (url.scheme() == QLatin1String("fd")) {
bool ok;
fd = QStringView {url.path()}.mid(1).toInt(&ok);
if (!ok) {
return OpenError;
}
} else if (url.fileName() == QLatin1String("-")) {
fd = 0;
}
bool triedMimeFromFileContent = false;
if (fd < 0) {
if (!mime.isValid()) {
return OpenError;
}
d->m_url = url;
d->m_docFileName = docFile;
if (!d->updateMetadataXmlNameAndDocSize()) {
return OpenError;
}
} else {
QFile qstdin;
const bool ret = qstdin.open(fd, QIODevice::ReadOnly, QFileDevice::AutoCloseHandle);
if (!ret) {
qWarning() << "failed to read" << url << filedata;
return OpenError;
}
filedata = qstdin.readAll();
mime = db.mimeTypeForData(filedata);
if (!mime.isValid() || mime.isDefault()) {
return OpenError;
}
d->m_docSize = filedata.size();
triedMimeFromFileContent = true;
}
const bool fromFileDescriptor = fd >= 0;
// 0. load Generator
// request only valid non-disabled plugins suitable for the mimetype
KPluginMetaData offer = DocumentPrivate::generatorForMimeType(mime, d->m_widget);
if (!offer.isValid() && !triedMimeFromFileContent) {
QMimeType newmime = db.mimeTypeForFile(docFile, QMimeDatabase::MatchContent);
triedMimeFromFileContent = true;
if (newmime != mime) {
mime = newmime;
offer = DocumentPrivate::generatorForMimeType(mime, d->m_widget);
}
if (!offer.isValid()) {
// There's still no offers, do a final mime search based on the filename
// We need this because sometimes (e.g. when downloading from a webserver) the mimetype we
// use is the one fed by the server, that may be wrong
newmime = db.mimeTypeForUrl(url);
if (!newmime.isDefault() && newmime != mime) {
mime = newmime;
offer = DocumentPrivate::generatorForMimeType(mime, d->m_widget);
}
}
}
if (!offer.isValid()) {
d->m_openError = i18n("Can not find a plugin which is able to handle the document being passed.");
Q_EMIT error(d->m_openError, -1);
qCWarning(OkularCoreDebug).nospace() << "No plugin for mimetype '" << mime.name() << "'.";
return OpenError;
}
// 1. load Document
OpenResult openResult = d->openDocumentInternal(offer, fromFileDescriptor, docFile, filedata, password);
if (openResult == OpenError) {
QList<KPluginMetaData> triedOffers;
triedOffers << offer;
offer = DocumentPrivate::generatorForMimeType(mime, d->m_widget, triedOffers);
while (offer.isValid()) {
openResult = d->openDocumentInternal(offer, fromFileDescriptor, docFile, filedata, password);
if (openResult == OpenError) {
triedOffers << offer;
offer = DocumentPrivate::generatorForMimeType(mime, d->m_widget, triedOffers);
} else {
break;
}
}
if (openResult == OpenError && !triedMimeFromFileContent) {
QMimeType newmime = db.mimeTypeForFile(docFile, QMimeDatabase::MatchContent);
triedMimeFromFileContent = true;
if (newmime != mime) {
mime = newmime;
offer = DocumentPrivate::generatorForMimeType(mime, d->m_widget, triedOffers);
while (offer.isValid()) {
openResult = d->openDocumentInternal(offer, fromFileDescriptor, docFile, filedata, password);
if (openResult == OpenError) {
triedOffers << offer;
offer = DocumentPrivate::generatorForMimeType(mime, d->m_widget, triedOffers);
} else {
break;
}
}
}
}
if (openResult == OpenSuccess) {
// Clear errors, since we're trying various generators, maybe one of them errored out
// but we finally succeeded
// TODO one can still see the error message animating out but since this is a very rare
// condition we can leave this for future work
Q_EMIT error(QString(), -1);
}
}
if (openResult != OpenSuccess) {
return openResult;
}
// no need to check for the existence of a synctex file, no parser will be
// created if none exists
d->m_synctex_scanner = synctex_scanner_new_with_output_file(QFile::encodeName(docFile).constData(), nullptr, 1);
if (!d->m_synctex_scanner && QFile::exists(docFile + QLatin1String("sync"))) {
d->loadSyncFile(docFile);
}
d->m_generatorName = offer.pluginId();
d->m_pageController = new PageController();
connect(d->m_pageController, &PageController::rotationFinished, this, [this](int p, Okular::Page *op) { d->rotationFinished(p, op); });
for (Page *p : std::as_const(d->m_pagesVector)) {
p->d->m_doc = d;
}
d->m_docdataMigrationNeeded = false;
// 2. load Additional Data (bookmarks, local annotations and metadata) about the document
if (d->m_archiveData) {
// QTemporaryFile is weird and will return false in exists if fileName wasn't called before
d->m_archiveData->metadataFile.fileName();
d->loadDocumentInfo(d->m_archiveData->metadataFile, LoadPageInfo);
d->loadDocumentInfo(LoadGeneralInfo);
} else {
if (d->loadDocumentInfo(LoadPageInfo)) {
d->m_docdataMigrationNeeded = true;
}
d->loadDocumentInfo(LoadGeneralInfo);
}
d->m_bookmarkManager->setUrl(d->m_url);
// 3. setup observers internal lists and data
foreachObserver(notifySetup(d->m_pagesVector, DocumentObserver::DocumentChanged | DocumentObserver::UrlChanged));
// 4. set initial page (restoring the page saved in xml if loaded)
DocumentViewport loadedViewport = (*d->m_viewportIterator);
if (loadedViewport.isValid()) {
(*d->m_viewportIterator) = DocumentViewport();
if (loadedViewport.pageNumber >= (int)d->m_pagesVector.size()) {
loadedViewport.pageNumber = d->m_pagesVector.size() - 1;
}
} else {
loadedViewport.pageNumber = 0;
}
setViewport(loadedViewport);
// start bookmark saver timer
if (!d->m_saveBookmarksTimer) {
d->m_saveBookmarksTimer = new QTimer(this);
connect(d->m_saveBookmarksTimer, &QTimer::timeout, this, [this] { d->saveDocumentInfo(); });
}
d->m_saveBookmarksTimer->start(5 * 60 * 1000);
// start memory check timer
if (!d->m_memCheckTimer) {
d->m_memCheckTimer = new QTimer(this);
connect(d->m_memCheckTimer, &QTimer::timeout, this, [this] { d->slotTimedMemoryCheck(); });
}
d->m_memCheckTimer->start(kMemCheckTime);
const DocumentViewport nextViewport = d->nextDocumentViewport();
if (nextViewport.isValid()) {
setViewport(nextViewport);
d->m_nextDocumentViewport = DocumentViewport();
d->m_nextDocumentDestination = QString();
}
AudioPlayer::instance()->setDocument(fromFileDescriptor ? QUrl() : d->m_url, this);
const QStringList docScripts = d->m_generator->metaData(QStringLiteral("DocumentScripts"), QStringLiteral("JavaScript")).toStringList();
if (!docScripts.isEmpty()) {
d->m_scripter = new Scripter(d);
for (const QString &docscript : docScripts) {
const Okular::ScriptAction *linkScript = new Okular::ScriptAction(Okular::JavaScript, docscript);
std::shared_ptr<Event> event = Event::createDocEvent(Event::DocOpen);
d->executeScriptEvent(event, linkScript);
}
}
return OpenSuccess;
}
bool DocumentPrivate::updateMetadataXmlNameAndDocSize()
{
// m_docFileName is always local so we can use QFileInfo on it
QFileInfo fileReadTest(m_docFileName);
if (!fileReadTest.isFile() && !fileReadTest.isReadable()) {
return false;
}
m_docSize = fileReadTest.size();
// determine the related "xml document-info" filename
if (m_url.isLocalFile()) {
const QString filePath = docDataFileName(m_url, m_docSize);
qCDebug(OkularCoreDebug) << "Metadata file is now:" << filePath;
m_xmlFileName = filePath;
} else {
qCDebug(OkularCoreDebug) << "Metadata file: disabled";
m_xmlFileName = QString();
}
return true;
}
KXMLGUIClient *Document::guiClient()
{
if (d->m_generator) {
Okular::GuiInterface *iface = qobject_cast<Okular::GuiInterface *>(d->m_generator);
if (iface) {
return iface->guiClient();
}
}
return nullptr;
}
void Document::closeDocument()
{
// check if there's anything to close...
if (!d->m_generator) {
return;
}
if (const Okular::Action *action = d->m_generator->additionalDocumentAction(CloseDocument)) {
processDocumentAction(action, CloseDocument);
}
Q_EMIT aboutToClose();
delete d->m_pageController;
d->m_pageController = nullptr;
delete d->m_scripter;
d->m_scripter = nullptr;
// remove requests left in queue
d->clearAndWaitForRequests();
if (d->m_fontThread) {
disconnect(d->m_fontThread, nullptr, this, nullptr);
d->m_fontThread->stopExtraction();
d->m_fontThread->wait();
d->m_fontThread = nullptr;
}
// stop any audio playback
AudioPlayer::instance()->stopPlaybacks();
// close the current document and save document info if a document is still opened
if (d->m_generator && d->m_pagesVector.size() > 0) {
d->saveDocumentInfo();
// free the content of the opaque backend actions (if any)
// this is a bit awkward since backends can store "random stuff" in the
// BackendOpaqueAction nativeId qvariant so we need to tell them to free it
// ideally we would just do that in the BackendOpaqueAction destructor
// but that's too late in the cleanup process, i.e. the generator has already closed its document
// and the document generator is nullptr
for (const Page *p : std::as_const(d->m_pagesVector)) {
const QList<ObjectRect *> &oRects = p->objectRects();
for (const ObjectRect *oRect : oRects) {
if (oRect->objectType() == ObjectRect::Action) {
const Action *a = static_cast<const Action *>(oRect->object());
const BackendOpaqueAction *backendAction = dynamic_cast<const BackendOpaqueAction *>(a);
if (backendAction) {
d->m_generator->freeOpaqueActionContents(*backendAction);
}
}
}
const QList<FormField *> forms = p->formFields();
for (const FormField *form : forms) {
const QList<Action *> additionalActions = form->additionalActions();
for (const Action *a : additionalActions) {
const BackendOpaqueAction *backendAction = dynamic_cast<const BackendOpaqueAction *>(a);
if (backendAction) {
d->m_generator->freeOpaqueActionContents(*backendAction);
}
}
}
}
d->m_generator->closeDocument();
}
if (d->m_synctex_scanner) {
synctex_scanner_free(d->m_synctex_scanner);
d->m_synctex_scanner = nullptr;
}
// stop timers
if (d->m_memCheckTimer) {
d->m_memCheckTimer->stop();
}
if (d->m_saveBookmarksTimer) {
d->m_saveBookmarksTimer->stop();
}
if (d->m_generator) {
// disconnect the generator from this document ...
d->m_generator->d_func()->m_document = nullptr;
// .. and this document from the generator signals
disconnect(d->m_generator, nullptr, this, nullptr);
Q_ASSERT(d->m_loadedGenerators.contains(d->m_generatorName));
}
d->m_generator = nullptr;
d->m_generatorName = QString();
d->m_url = QUrl();
d->m_walletGenerator = nullptr;
d->m_docFileName = QString();
d->m_xmlFileName = QString();
delete d->m_tempFile;
d->m_tempFile = nullptr;
delete d->m_archiveData;
d->m_archiveData = nullptr;
d->m_docSize = -1;
d->m_exportCached = false;
d->m_exportFormats.clear();
d->m_exportToText = ExportFormat();
d->m_fontsCached = false;
d->m_fontsCache.clear();
d->m_rotation = Rotation0;
// send an empty list to observers (to free their data)
foreachObserver(notifySetup({}, DocumentObserver::DocumentChanged | DocumentObserver::UrlChanged));
// delete pages and clear 'd->m_pagesVector' container
qDeleteAll(d->m_pagesVector);
d->m_pagesVector.clear();
// clear 'memory allocation' descriptors
qDeleteAll(d->m_allocatedPixmaps);
d->m_allocatedPixmaps.clear();
// clear 'running searches' descriptors
qDeleteAll(d->m_searches);
d->m_searches.clear();
// clear the visible areas and notify the observers
qDeleteAll(d->m_pageRects);
d->m_pageRects.clear();
foreachObserver(notifyVisibleRectsChanged());
// reset internal variables
d->m_viewportHistory.clear();
d->m_viewportHistory.emplace_back();
d->m_viewportIterator = d->m_viewportHistory.begin();
d->m_allocatedPixmapsTotalMemory = 0;
d->m_allocatedTextPagesFifo.clear();
d->m_pageSize = PageSize();
d->m_pageSizes.clear();
d->m_documentInfo = DocumentInfo();
d->m_documentInfoAskedKeys.clear();
AudioPlayer::instance()->resetDocument();
d->m_undoStack->clear();
d->m_docdataMigrationNeeded = false;
#if HAVE_MALLOC_TRIM
// trim unused memory, glibc should do this but it seems it does not
// this can greatly decrease the [perceived] memory consumption of okular
// see: https://sourceware.org/bugzilla/show_bug.cgi?id=14827
malloc_trim(0);
#endif
}
void Document::addObserver(DocumentObserver *pObserver)
{
Q_ASSERT(!d->m_observers.contains(pObserver));
d->m_observers << pObserver;
// if the observer is added while a document is already opened, tell it
if (!d->m_pagesVector.isEmpty()) {
pObserver->notifySetup(d->m_pagesVector, DocumentObserver::DocumentChanged | DocumentObserver::UrlChanged);
pObserver->notifyViewportChanged(false /*disables smoothMove*/);
}
}
void Document::removeObserver(DocumentObserver *pObserver)
{
// remove observer from the set. it won't receive notifications anymore
if (d->m_observers.contains(pObserver)) {
// free observer's pixmap data
for (Page *const page : std::as_const(d->m_pagesVector)) {
page->deletePixmap(pObserver);
}
// [MEM] free observer's allocation descriptors
auto aIt = d->m_allocatedPixmaps.begin();
auto aEnd = d->m_allocatedPixmaps.end();
while (aIt != aEnd) {
AllocatedPixmap *p = *aIt;
if (p->observer == pObserver) {
aIt = d->m_allocatedPixmaps.erase(aIt);
delete p;
} else {
++aIt;
}
}
for (PixmapRequest *executingRequest : std::as_const(d->m_executingPixmapRequests)) {
if (executingRequest->observer() == pObserver) {
d->cancelRenderingBecauseOf(executingRequest, nullptr);
}
}
// remove observer entry from the set
d->m_observers.remove(pObserver);
}
}
void Document::reparseConfig()
{
// reparse generator config and if something changed clear Pages
bool configchanged = false;
if (d->m_generator) {
Okular::ConfigInterface *iface = qobject_cast<Okular::ConfigInterface *>(d->m_generator);
if (iface) {
configchanged = iface->reparseConfig();
}
}
if (configchanged) {
// invalidate pixmaps
for (Page *const page : std::as_const(d->m_pagesVector)) {
page->deletePixmaps();
}
// [MEM] remove allocation descriptors
qDeleteAll(d->m_allocatedPixmaps);
d->m_allocatedPixmaps.clear();
d->m_allocatedPixmapsTotalMemory = 0;
// send reload signals to observers
foreachObserver(notifyContentsCleared(DocumentObserver::Pixmap));
}
// free memory if in 'low' profile
if (SettingsCore::memoryLevel() == SettingsCore::EnumMemoryLevel::Low && !d->m_allocatedPixmaps.empty() && !d->m_pagesVector.isEmpty()) {
d->cleanupPixmapMemory();
}
}
bool Document::isOpened() const
{
return d->m_generator;
}
bool Document::canConfigurePrinter() const
{
if (d->m_generator) {
const Okular::PrintInterface *iface = qobject_cast<Okular::PrintInterface *>(d->m_generator);
return iface ? true : false;
} else {
return false;
}
}
std::pair<SigningResult, QString> Document::sign(const NewSignatureData &data, const QString &newPath)
{
if (d->m_generator->canSign()) {
return d->m_generator->sign(data, newPath);
} else {
return {GenericSigningError, i18nc("Unsupported action", "Signing not implemented for this document type")};
}
}
Okular::CertificateStore *Document::certificateStore() const
{
return d->m_generator ? d->m_generator->certificateStore() : nullptr;
}
void Document::setEditorCommandOverride(const QString &editCmd)
{
d->editorCommandOverride = editCmd;
}
QString Document::editorCommandOverride() const
{
return d->editorCommandOverride;
}
DocumentInfo Document::documentInfo() const
{
QSet<DocumentInfo::Key> keys;
for (Okular::DocumentInfo::Key ks = Okular::DocumentInfo::Title; ks < Okular::DocumentInfo::Invalid; ks = Okular::DocumentInfo::Key(ks + 1)) {
keys << ks;
}
return documentInfo(keys);
}
DocumentInfo Document::documentInfo(const QSet<DocumentInfo::Key> &keys) const
{
DocumentInfo result = d->m_documentInfo;
const QSet<DocumentInfo::Key> missingKeys = keys - d->m_documentInfoAskedKeys;
if (d->m_generator && !missingKeys.isEmpty()) {
DocumentInfo info = d->m_generator->generateDocumentInfo(missingKeys);
if (missingKeys.contains(DocumentInfo::FilePath)) {
info.set(DocumentInfo::FilePath, currentDocument().toDisplayString());
}
if (d->m_docSize != -1 && missingKeys.contains(DocumentInfo::DocumentSize)) {
const QString sizeString = KFormat().formatByteSize(d->m_docSize);
info.set(DocumentInfo::DocumentSize, sizeString);
}
if (missingKeys.contains(DocumentInfo::PagesSize)) {
const QString pagesSize = d->pagesSizeString();
if (!pagesSize.isEmpty()) {
info.set(DocumentInfo::PagesSize, pagesSize);
}
}
if (missingKeys.contains(DocumentInfo::Pages) && info.get(DocumentInfo::Pages).isEmpty()) {
info.set(DocumentInfo::Pages, QString::number(this->pages()));
}
d->m_documentInfo.d->values.insert(info.d->values);
d->m_documentInfo.d->titles.insert(info.d->titles);
result.d->values.insert(info.d->values);
result.d->titles.insert(info.d->titles);
}
d->m_documentInfoAskedKeys += keys;
return result;
}
const DocumentSynopsis *Document::documentSynopsis() const
{
return d->m_generator ? d->m_generator->generateDocumentSynopsis() : nullptr;
}
void Document::startFontReading()
{
if (!d->m_generator || !d->m_generator->hasFeature(Generator::FontInfo) || d->m_fontThread) {
return;
}
if (d->m_fontsCached) {
// in case we have cached fonts, simulate a reading
// this way the API is the same, and users no need to care about the
// internal caching
for (int i = 0; i < d->m_fontsCache.count(); ++i) {
Q_EMIT gotFont(d->m_fontsCache.at(i));
Q_EMIT fontReadingProgress(i / pages());
}
Q_EMIT fontReadingEnded();
return;
}
d->m_fontThread = new FontExtractionThread(d->m_generator, pages());
connect(d->m_fontThread, &FontExtractionThread::gotFont, this, [this](const Okular::FontInfo &f) { d->fontReadingGotFont(f); });
connect(d->m_fontThread.data(), &FontExtractionThread::progress, this, [this](int p) { d->slotFontReadingProgress(p); });
d->m_fontThread->startExtraction(/*d->m_generator->hasFeature( Generator::Threaded )*/ true);
}
void Document::stopFontReading()
{
if (!d->m_fontThread) {
return;
}
disconnect(d->m_fontThread, nullptr, this, nullptr);
d->m_fontThread->stopExtraction();
d->m_fontThread = nullptr;
d->m_fontsCache.clear();
}
bool Document::canProvideFontInformation() const
{
return d->m_generator ? d->m_generator->hasFeature(Generator::FontInfo) : false;
}
bool Document::canSign() const
{
return d->m_generator ? d->m_generator->canSign() : false;
}
const QList<EmbeddedFile *> *Document::embeddedFiles() const
{
return d->m_generator ? d->m_generator->embeddedFiles() : nullptr;
}
const Page *Document::page(int n) const
{
return (n >= 0 && n < d->m_pagesVector.count()) ? d->m_pagesVector.at(n) : nullptr;
}
const DocumentViewport &Document::viewport() const
{
return (*d->m_viewportIterator);
}
const QList<VisiblePageRect *> &Document::visiblePageRects() const
{
return d->m_pageRects;
}
void Document::setVisiblePageRects(const QList<VisiblePageRect *> &visiblePageRects, DocumentObserver *excludeObserver)
{
qDeleteAll(d->m_pageRects);
d->m_pageRects = visiblePageRects;
// notify change to all other (different from id) observers
for (DocumentObserver *o : std::as_const(d->m_observers)) {
if (o != excludeObserver) {
o->notifyVisibleRectsChanged();
}
}
}
uint Document::currentPage() const
{
return (*d->m_viewportIterator).pageNumber;
}
uint Document::pages() const
{
return d->m_pagesVector.size();
}
QUrl Document::currentDocument() const
{
return d->m_url;
}
bool Document::isAllowed(Permission action) const
{
if (action == Okular::AllowNotes && (d->m_docdataMigrationNeeded || !d->m_annotationEditingEnabled)) {
return false;
}
if (action == Okular::AllowFillForms && d->m_docdataMigrationNeeded) {
return false;
}
#if !OKULAR_FORCE_DRM
if (KAuthorized::authorize(QStringLiteral("skip_drm")) && !SettingsCore::obeyDRM()) {
return true;
}
#endif
return d->m_generator ? d->m_generator->isAllowed(action) : false;
}
bool Document::supportsSearching() const
{
return d->m_generator ? d->m_generator->hasFeature(Generator::TextExtraction) : false;
}
bool Document::supportsPageSizes() const
{
return d->m_generator ? d->m_generator->hasFeature(Generator::PageSizes) : false;
}
bool Document::supportsTiles() const
{
return d->m_generator ? d->m_generator->hasFeature(Generator::TiledRendering) : false;
}
PageSize::List Document::pageSizes() const
{
if (d->m_generator) {
if (d->m_pageSizes.isEmpty()) {
d->m_pageSizes = d->m_generator->pageSizes();
}
return d->m_pageSizes;
}
return PageSize::List();
}
bool Document::canExportToText() const
{
if (!d->m_generator) {
return false;
}
d->cacheExportFormats();
return !d->m_exportToText.isNull();
}
bool Document::exportToText(const QString &fileName) const
{
if (!d->m_generator) {
return false;
}
d->cacheExportFormats();
if (d->m_exportToText.isNull()) {
return false;
}
return d->m_generator->exportTo(fileName, d->m_exportToText);
}
ExportFormat::List Document::exportFormats() const
{
if (!d->m_generator) {
return ExportFormat::List();
}
d->cacheExportFormats();
return d->m_exportFormats;
}
bool Document::exportTo(const QString &fileName, const ExportFormat &format) const
{
return d->m_generator ? d->m_generator->exportTo(fileName, format) : false;
}
bool Document::historyAtBegin() const
{
return d->m_viewportIterator == d->m_viewportHistory.begin();
}
bool Document::historyAtEnd() const
{
return d->m_viewportIterator == --(d->m_viewportHistory.end());
}
QVariant Document::metaData(const QString &key, const QVariant &option) const
{
// if option starts with "src:" assume that we are handling a
// source reference
if (key == QLatin1String("NamedViewport") && option.toString().startsWith(QLatin1String("src:"), Qt::CaseInsensitive) && d->m_synctex_scanner) {
const QString reference = option.toString();
// The reference is of form "src:1111Filename", where "1111"
// points to line number 1111 in the file "Filename".
// Extract the file name and the numeral part from the reference string.
// This will fail if Filename starts with a digit.
QString name, lineString;
// Remove "src:". Presence of substring has been checked before this
// function is called.
name = reference.mid(4);
// split
int nameLength = name.length();
int i = 0;
for (i = 0; i < nameLength; ++i) {
if (!name[i].isDigit()) {
break;
}
}
lineString = name.left(i);
name = name.mid(i);
// Remove spaces.
name = name.trimmed();
lineString = lineString.trimmed();
// Convert line to integer.
bool ok;
int line = lineString.toInt(&ok);
if (!ok) {
line = -1;
}
// Use column == -1 for now.
if (synctex_display_query(d->m_synctex_scanner, QFile::encodeName(name).constData(), line, -1, 0) > 0) {
synctex_node_p node;
// For now use the first hit. Could possibly be made smarter
// in case there are multiple hits.
while ((node = synctex_scanner_next_result(d->m_synctex_scanner))) {
Okular::DocumentViewport view;
// TeX pages start at 1.
view.pageNumber = synctex_node_page(node) - 1;
if (view.pageNumber >= 0) {
const QSizeF dpi = d->m_generator->dpi();
// TeX small points ...
double px = (synctex_node_visible_h(node) * dpi.width()) / 72.27;
double py = (synctex_node_visible_v(node) * dpi.height()) / 72.27;
view.rePos.normalizedX = px / page(view.pageNumber)->width();
view.rePos.normalizedY = (py + 0.5) / page(view.pageNumber)->height();
view.rePos.enabled = true;
view.rePos.pos = Okular::DocumentViewport::Center;
return view.toString();
}
}
}
}
return d->m_generator ? d->m_generator->metaData(key, option) : QVariant();
}
Rotation Document::rotation() const
{
return d->m_rotation;
}
QSizeF Document::allPagesSize() const
{
const auto getSize = [](const Page *page) { return QSizeF(page->width(), page->height()); };
if (d->m_pagesVector.count() != 0) {
const auto sample = getSize(d->m_pagesVector[0]);
const auto isSameSize = [&](const Page *page) { return getSize(page) == sample; };
if (std::ranges::all_of(d->m_pagesVector, isSameSize)) {
return sample;
}
}
return QSizeF();
}
QString Document::pageSizeString(int page) const
{
if (d->m_generator) {
if (d->m_generator->pagesSizeMetric() != Generator::None) {
const Page *p = d->m_pagesVector.at(page);
return d->localizedSize(QSizeF(p->width(), p->height()));
}
}
return QString();
}
static bool shouldCancelRenderingBecauseOf(const PixmapRequest &executingRequest, const PixmapRequest &otherRequest)
{
// New request has higher priority -> cancel
if (executingRequest.priority() > otherRequest.priority()) {
return true;
}
// New request has lower priority -> don't cancel
if (executingRequest.priority() < otherRequest.priority()) {
return false;
}
// New request has same priority and is from a different observer -> don't cancel
// AFAIK this never happens since all observers have different priorities
if (executingRequest.observer() != otherRequest.observer()) {
return false;
}
// Same priority and observer, different page number -> don't cancel
// may still end up cancelled later in the parent caller if none of the requests
// is of the executingRequest page and RemoveAllPrevious is specified
if (executingRequest.pageNumber() != otherRequest.pageNumber()) {
return false;
}
// Same priority, observer, page, different size -> cancel
if (executingRequest.width() != otherRequest.width()) {
return true;
}
// Same priority, observer, page, different size -> cancel
if (executingRequest.height() != otherRequest.height()) {
return true;
}
// Same priority, observer, page, different tiling -> cancel
if (executingRequest.isTile() != otherRequest.isTile()) {
return true;
}
// Same priority, observer, page, different tiling -> cancel
if (executingRequest.isTile()) {
const NormalizedRect bothRequestsRect = executingRequest.normalizedRect() | otherRequest.normalizedRect();
if (!(bothRequestsRect == executingRequest.normalizedRect())) {
return true;
}
}
return false;
}
bool DocumentPrivate::cancelRenderingBecauseOf(PixmapRequest *executingRequest, PixmapRequest *newRequest)
{
// No point in aborting the rendering already finished, let it go through
if (!executingRequest->d->mResultImage.isNull()) {
return false;
}
if (newRequest && newRequest->asynchronous() && executingRequest->partialUpdatesWanted()) {
newRequest->setPartialUpdatesWanted(true);
}
TilesManager *tm = executingRequest->d->tilesManager();
if (tm) {
tm->setPixmap(nullptr, executingRequest->normalizedRect(), true /*isPartialPixmap*/);
tm->setRequest(NormalizedRect(), 0, 0);
}
PagePrivate::PixmapObject object = executingRequest->page()->d->m_pixmaps.take(executingRequest->observer());
delete object.m_pixmap;
object.m_pixmap = nullptr;
if (executingRequest->d->mShouldAbortRender != 0) {
return false;
}
executingRequest->d->mShouldAbortRender = 1;
if (m_generator->d_ptr->mTextPageGenerationThread && m_generator->d_ptr->mTextPageGenerationThread->page() == executingRequest->page()) {
m_generator->d_ptr->mTextPageGenerationThread->abortExtraction();
}
return true;
}
void Document::requestPixmaps(const QList<PixmapRequest *> &requests)
{
requestPixmaps(requests, RemoveAllPrevious);
}
void Document::requestPixmaps(const QList<PixmapRequest *> &requests, PixmapRequestFlags reqOptions)
{
if (requests.isEmpty()) {
return;
}
if (!d->m_pageController) {
// delete requests..
qDeleteAll(requests);
// ..and return
return;
}
QSet<DocumentObserver *> observersPixmapCleared;
// 1. [CLEAN STACK] remove previous requests of requesterID
const DocumentObserver *requesterObserver = requests.first()->observer();
QSet<int> requestedPages;
{
for (const PixmapRequest *request : requests) {
Q_ASSERT(request->observer() == requesterObserver);
requestedPages.insert(request->pageNumber());
}
}
const bool removeAllPrevious = reqOptions & RemoveAllPrevious;
d->m_pixmapRequestsMutex.lock();
auto sIt = d->m_pixmapRequestsStack.begin();
auto sEnd = d->m_pixmapRequestsStack.end();
while (sIt != sEnd) {
if ((*sIt)->observer() == requesterObserver && (removeAllPrevious || requestedPages.contains((*sIt)->pageNumber()))) {
// delete request and remove it from stack
delete *sIt;
sIt = d->m_pixmapRequestsStack.erase(sIt);
} else {
++sIt;
}
}
// 1.B [PREPROCESS REQUESTS] tweak some values of the requests
for (PixmapRequest *request : requests) {
// set the 'page field' (see PixmapRequest) and check if it is valid
qCDebug(OkularCoreDebug).nospace() << "request observer=" << request->observer() << " " << request->width() << "x" << request->height() << "@" << request->pageNumber();
if (d->m_pagesVector.value(request->pageNumber()) == nullptr) {
// skip requests referencing an invalid page (must not happen)
delete request;
request = nullptr;
continue;
}
request->d->mPage = d->m_pagesVector.value(request->pageNumber());
if (request->isTile()) {
// Change the current request rect so that only invalid tiles are
// requested. Also make sure the rect is tile-aligned.
NormalizedRect tilesRect;
const QList<Tile> tiles = request->d->tilesManager()->tilesAt(request->normalizedRect(), TilesManager::TerminalTile);
for (const Tile &tile : tiles) {
if (!tile.isValid()) {
if (tilesRect.isNull()) {
tilesRect = tile.rect();
} else {
tilesRect |= tile.rect();
}
}
}
request->setNormalizedRect(tilesRect);
}
if (!request->asynchronous()) {
request->d->mPriority = 0;
}
}
// 1.C [CANCEL REQUESTS] cancel those requests that are running and should be cancelled because of the new requests coming in
if (d->m_generator->hasFeature(Generator::SupportsCancelling)) {
for (PixmapRequest *executingRequest : std::as_const(d->m_executingPixmapRequests)) {
bool newRequestsContainExecutingRequestPage = false;
bool requestCancelled = false;
for (PixmapRequest *newRequest : requests) {
if (newRequest->pageNumber() == executingRequest->pageNumber() && requesterObserver == executingRequest->observer()) {
newRequestsContainExecutingRequestPage = true;
}
if (shouldCancelRenderingBecauseOf(*executingRequest, *newRequest)) {
requestCancelled = d->cancelRenderingBecauseOf(executingRequest, newRequest);
}
}
// If we were told to remove all the previous requests and the executing request page is not part of the new requests, cancel it
if (!requestCancelled && removeAllPrevious && requesterObserver == executingRequest->observer() && !newRequestsContainExecutingRequestPage) {
requestCancelled = d->cancelRenderingBecauseOf(executingRequest, nullptr);
}
if (requestCancelled) {
observersPixmapCleared << executingRequest->observer();
}
}
}
// 2. [ADD TO STACK] add requests to stack
for (PixmapRequest *request : requests) {
// add request to the 'stack' at the right place
if (request->priority() == 0) {
// add priority zero requests to the top of the stack
d->m_pixmapRequestsStack.push_back(request);
} else {
// insert in stack sorted by priority
auto it = std::ranges::find_if(d->m_pixmapRequestsStack, [&](const auto &it) { //
return it->priority() <= request->priority();
});
d->m_pixmapRequestsStack.insert(it, request);
}
}
d->m_pixmapRequestsMutex.unlock();
// 3. [START FIRST GENERATION] if <NO>generator is ready, start a new generation,
// or else (if gen is running) it will be started when the new contents will
// come from generator (in requestDone())</NO>
// all handling of requests put into sendGeneratorPixmapRequest
// if ( generator->canRequestPixmap() )
d->sendGeneratorPixmapRequest();
for (DocumentObserver *o : std::as_const(observersPixmapCleared)) {
o->notifyContentsCleared(Okular::DocumentObserver::Pixmap);
}
}
void Document::requestTextPage(uint pageNumber)
{
Page *kp = d->m_pagesVector[pageNumber];
if (!d->m_generator || !kp) {
return;
}
// Memory management for TextPages
d->m_generator->generateTextPage(kp);
}
void DocumentPrivate::notifyAnnotationChanges(int page)
{
foreachObserverD(notifyPageChanged(page, DocumentObserver::Annotations));
}
void DocumentPrivate::notifyFormChanges(int /*page*/)
{
recalculateForms();
}
void Document::recalculateForms()
{
d->recalculateForms();
}
void Document::addPageAnnotation(int page, Annotation *annotation)
{
// Transform annotation's base boundary rectangle into unrotated coordinates
Page *p = d->m_pagesVector[page];
QTransform t = p->d->rotationMatrix();
annotation->d_ptr->baseTransform(t.inverted());
QUndoCommand *uc = new AddAnnotationCommand(this->d, annotation, page);
d->m_undoStack->push(uc);
}
bool Document::canModifyPageAnnotation(const Annotation *annotation) const
{
if (!annotation || (annotation->flags() & Annotation::DenyWrite)) {
return false;
}
if (!isAllowed(Okular::AllowNotes)) {
return false;
}
if ((annotation->flags() & Annotation::External) && !d->canModifyExternalAnnotations()) {
return false;
}
switch (annotation->subType()) {
case Annotation::AText:
case Annotation::ALine:
case Annotation::AGeom:
case Annotation::AHighlight:
case Annotation::AStamp:
case Annotation::AInk:
return true;
case Annotation::AWidget:
#if HAVE_NEW_SIGNATURE_API
return dynamic_cast<const SignatureAnnotation *>(annotation);
#endif
return false;
default:
return false;
}
}
void Document::prepareToModifyAnnotationProperties(Annotation *annotation)
{
Q_ASSERT(d->m_prevPropsOfAnnotBeingModified.isNull());
if (!d->m_prevPropsOfAnnotBeingModified.isNull()) {
qCCritical(OkularCoreDebug) << "Error: Document::prepareToModifyAnnotationProperties has already been called since last call to Document::modifyPageAnnotationProperties";
return;
}
d->m_prevPropsOfAnnotBeingModified = annotation->getAnnotationPropertiesDomNode();
}
void Document::modifyPageAnnotationProperties(int page, Annotation *annotation)
{
Q_ASSERT(!d->m_prevPropsOfAnnotBeingModified.isNull());
if (d->m_prevPropsOfAnnotBeingModified.isNull()) {
qCCritical(OkularCoreDebug) << "Error: Document::prepareToModifyAnnotationProperties must be called before Annotation is modified";
return;
}
QDomNode prevProps = d->m_prevPropsOfAnnotBeingModified;
QUndoCommand *uc = new Okular::ModifyAnnotationPropertiesCommand(d, annotation, page, prevProps, annotation->getAnnotationPropertiesDomNode());
d->m_undoStack->push(uc);
d->m_prevPropsOfAnnotBeingModified.clear();
}
void Document::translatePageAnnotation(int page, Annotation *annotation, const NormalizedPoint &delta)
{
int complete = (annotation->flags() & Okular::Annotation::BeingMoved) == 0;
QUndoCommand *uc = new Okular::TranslateAnnotationCommand(d, annotation, page, delta, complete);
d->m_undoStack->push(uc);
}
void Document::adjustPageAnnotation(int page, Annotation *annotation, const Okular::NormalizedPoint &delta1, const Okular::NormalizedPoint &delta2)
{
const bool complete = (annotation->flags() & Okular::Annotation::BeingResized) == 0;
QUndoCommand *uc = new Okular::AdjustAnnotationCommand(d, annotation, page, delta1, delta2, complete);
d->m_undoStack->push(uc);
}
void Document::editPageAnnotationContents(int page, Annotation *annotation, const QString &newContents, int newCursorPos, int prevCursorPos, int prevAnchorPos)
{
QString prevContents = annotation->contents();
QUndoCommand *uc = new EditAnnotationContentsCommand(d, annotation, page, newContents, newCursorPos, prevContents, prevCursorPos, prevAnchorPos);
d->m_undoStack->push(uc);
}
bool Document::canRemovePageAnnotation(const Annotation *annotation) const
{
if (!annotation || (annotation->flags() & Annotation::DenyDelete)) {
return false;
}
if ((annotation->flags() & Annotation::External) && !d->canRemoveExternalAnnotations()) {
return false;
}
switch (annotation->subType()) {
case Annotation::AText:
case Annotation::ALine:
case Annotation::AGeom:
case Annotation::AHighlight:
case Annotation::AStamp:
case Annotation::AInk:
case Annotation::ACaret:
return true;
default:
return false;
}
}
void Document::removePageAnnotation(int page, Annotation *annotation)
{
QUndoCommand *uc = new RemoveAnnotationCommand(this->d, annotation, page);
d->m_undoStack->push(uc);
}
void Document::removePageAnnotations(int page, const QList<Annotation *> &annotations)
{
d->m_undoStack->beginMacro(i18nc("remove a collection of annotations from the page", "remove annotations"));
for (Annotation *annotation : annotations) {
QUndoCommand *uc = new RemoveAnnotationCommand(this->d, annotation, page);
d->m_undoStack->push(uc);
}
d->m_undoStack->endMacro();
}
bool DocumentPrivate::canAddAnnotationsNatively() const
{
Okular::SaveInterface *iface = qobject_cast<Okular::SaveInterface *>(m_generator);
if (iface && iface->supportsOption(Okular::SaveInterface::SaveChanges) && iface->annotationProxy() && iface->annotationProxy()->supports(AnnotationProxy::Addition)) {
return true;
}
return false;
}
bool DocumentPrivate::canModifyExternalAnnotations() const
{
Okular::SaveInterface *iface = qobject_cast<Okular::SaveInterface *>(m_generator);
if (iface && iface->supportsOption(Okular::SaveInterface::SaveChanges) && iface->annotationProxy() && iface->annotationProxy()->supports(AnnotationProxy::Modification)) {
return true;
}
return false;
}
bool DocumentPrivate::canRemoveExternalAnnotations() const
{
Okular::SaveInterface *iface = qobject_cast<Okular::SaveInterface *>(m_generator);
if (iface && iface->supportsOption(Okular::SaveInterface::SaveChanges) && iface->annotationProxy() && iface->annotationProxy()->supports(AnnotationProxy::Removal)) {
return true;
}
return false;
}
void Document::setPageTextSelection(int page, std::unique_ptr<RegularAreaRect> &&rect, const QColor &color)
{
Page *kp = d->m_pagesVector[page];
if (!d->m_generator || !kp) {
return;
}
// add or remove the selection basing whether rect is null or not
if (rect) {
kp->d->setTextSelections(*rect, color);
} else {
kp->d->deleteTextSelections();
}
// notify observers about the change
foreachObserver(notifyPageChanged(page, DocumentObserver::TextSelection));
}
bool Document::canUndo() const
{
return d->m_undoStack->canUndo();
}
bool Document::canRedo() const
{
return d->m_undoStack->canRedo();
}
/* REFERENCE IMPLEMENTATION: better calling setViewport from other code
void Document::setNextPage()
{
// advance page and set viewport on observers
if ( (*d->m_viewportIterator).pageNumber < (int)d->m_pagesVector.count() - 1 )
setViewport( DocumentViewport( (*d->m_viewportIterator).pageNumber + 1 ) );
}
void Document::setPrevPage()
{
// go to previous page and set viewport on observers
if ( (*d->m_viewportIterator).pageNumber > 0 )
setViewport( DocumentViewport( (*d->m_viewportIterator).pageNumber - 1 ) );
}
*/
void Document::setViewport(const DocumentViewport &viewport, DocumentObserver *excludeObserver, bool smoothMove, bool updateHistory)
{
if (!viewport.isValid()) {
qCDebug(OkularCoreDebug) << "invalid viewport:" << viewport.toString();
return;
}
if (viewport.pageNumber >= int(d->m_pagesVector.count())) {
// qCDebug(OkularCoreDebug) << "viewport out of document:" << viewport.toString();
return;
}
// if already broadcasted, don't redo it
DocumentViewport &oldViewport = *d->m_viewportIterator;
// disabled by enrico on 2005-03-18 (less debug output)
// if ( viewport == oldViewport )
// qCDebug(OkularCoreDebug) << "setViewport with the same viewport.";
const int oldPageNumber = oldViewport.pageNumber;
// set internal viewport taking care of history
if (oldViewport.pageNumber == viewport.pageNumber || !oldViewport.isValid() || !updateHistory) {
// if page is unchanged save the viewport at current position in queue
oldViewport = viewport;
} else {
// remove elements after viewportIterator in queue
d->m_viewportHistory.erase(++d->m_viewportIterator, d->m_viewportHistory.end());
// keep the list to a reasonable size by removing head when needed
if (d->m_viewportHistory.size() >= OKULAR_HISTORY_MAXSTEPS) {
d->m_viewportHistory.pop_front();
}
// add the item at the end of the queue
d->m_viewportIterator = d->m_viewportHistory.insert(d->m_viewportHistory.end(), viewport);
}
const int currentViewportPage = (*d->m_viewportIterator).pageNumber;
const bool currentPageChanged = (oldPageNumber != currentViewportPage);
// notify change to all other (different from id) observers
for (DocumentObserver *o : std::as_const(d->m_observers)) {
if (o != excludeObserver) {
o->notifyViewportChanged(smoothMove);
}
if (currentPageChanged) {
o->notifyCurrentPageChanged(oldPageNumber, currentViewportPage);
}
}
}
void Document::setViewportPage(int page, DocumentObserver *excludeObserver, bool smoothMove)
{
// clamp page in range [0 ... numPages-1]
if (page < 0) {
page = 0;
} else if (page > (int)d->m_pagesVector.count()) {
page = d->m_pagesVector.count() - 1;
}
// make a viewport from the page and broadcast it
setViewport(DocumentViewport(page), excludeObserver, smoothMove);
}
void Document::setZoom(int factor, DocumentObserver *excludeObserver)
{
// notify change to all other (different from id) observers
for (DocumentObserver *o : std::as_const(d->m_observers)) {
if (o != excludeObserver) {
o->notifyZoom(factor);
}
}
}
void Document::setPrevViewport()
// restore viewport from the history
{
if (d->m_viewportIterator != d->m_viewportHistory.begin()) {
const int oldViewportPage = d->m_viewportIterator->pageNumber;
// restore previous viewport and notify it to observers
--d->m_viewportIterator;
foreachObserver(notifyViewportChanged(true));
const int currentViewportPage = d->m_viewportIterator->pageNumber;
if (oldViewportPage != currentViewportPage) {
foreachObserver(notifyCurrentPageChanged(oldViewportPage, currentViewportPage));
}
}
}
void Document::setNextViewport()
// restore next viewport from the history
{
std::list<DocumentViewport>::const_iterator nextIterator = d->m_viewportIterator;
++nextIterator;
if (nextIterator != d->m_viewportHistory.end()) {
const int oldViewportPage = d->m_viewportIterator->pageNumber;
// restore next viewport and notify it to observers
++d->m_viewportIterator;
foreachObserver(notifyViewportChanged(true));
const int currentViewportPage = d->m_viewportIterator->pageNumber;
if (oldViewportPage != currentViewportPage) {
foreachObserver(notifyCurrentPageChanged(oldViewportPage, currentViewportPage));
}
}
}
void Document::setNextDocumentViewport(const DocumentViewport &viewport)
{
d->m_nextDocumentViewport = viewport;
}
void Document::setNextDocumentDestination(const QString &namedDestination)
{
d->m_nextDocumentDestination = namedDestination;
}
void Document::searchText(int searchID, const QString &text, bool fromStart, Qt::CaseSensitivity caseSensitivity, SearchType type, bool moveViewport, const QColor &color)
{
d->m_searchCancelled = false;
// safety checks: don't perform searches on empty or unsearchable docs
if (!d->m_generator || !d->m_generator->hasFeature(Generator::TextExtraction) || d->m_pagesVector.isEmpty()) {
Q_EMIT searchFinished(searchID, NoMatchFound);
return;
}
// if searchID search not recorded, create new descriptor and init params
auto searchIt = d->m_searches.find(searchID);
if (searchIt == d->m_searches.end()) {
RunningSearch *search = new RunningSearch();
search->continueOnPage = -1;
searchIt = d->m_searches.insert(searchID, search);
}
RunningSearch *s = *searchIt;
// update search structure
bool newText = text != s->cachedString;
s->cachedString = text;
s->cachedType = type;
s->cachedCaseSensitivity = caseSensitivity;
s->cachedViewportMove = moveViewport;
s->cachedColor = color;
s->isCurrentlySearching = true;
// global data for search
QSet<int> *pagesToNotify = new QSet<int>;
// remove highlights from pages and queue them for notifying changes
*pagesToNotify += s->highlightedPages;
for (const int pageNumber : std::as_const(s->highlightedPages)) {
d->m_pagesVector.at(pageNumber)->d->deleteHighlights(searchID);
}
s->highlightedPages.clear();
// set hourglass cursor
QApplication::setOverrideCursor(Qt::WaitCursor);
// 1. ALLDOC - process all document marking pages
if (type == AllDocument) {
QHash<Page *, QList<RegularAreaRect *>> *pageMatches = new QHash<Page *, QList<RegularAreaRect *>>;
// search and highlight 'text' (as a solid phrase) on all pages
QTimer::singleShot(0, this, [this, pagesToNotify, pageMatches, searchID] { d->doContinueAllDocumentSearch(pagesToNotify, pageMatches, 0, searchID); });
}
// 2. NEXTMATCH - find next matching item (or start from top)
// 3. PREVMATCH - find previous matching item (or start from bottom)
else if (type == NextMatch || type == PreviousMatch) {
// find out from where to start/resume search from
const bool forward = type == NextMatch;
const int viewportPage = (*d->m_viewportIterator).pageNumber;
const int fromStartSearchPage = forward ? 0 : d->m_pagesVector.count() - 1;
int currentPageNumber = fromStart ? fromStartSearchPage : ((s->continueOnPage != -1) ? s->continueOnPage : viewportPage);
const Page *lastPage = fromStart ? nullptr : d->m_pagesVector[currentPageNumber];
int pagesDone = 0;
// continue checking last TextPage first (if it is the current page)
RegularAreaRect *match = nullptr;
if (lastPage && lastPage->number() == s->continueOnPage) {
if (newText) {
match = lastPage->findText(searchID, text, forward ? FromTop : FromBottom, caseSensitivity);
} else {
match = lastPage->findText(searchID, text, forward ? NextResult : PreviousResult, caseSensitivity, &s->continueOnMatch);
}
if (!match) {
if (forward) {
currentPageNumber++;
} else {
currentPageNumber--;
}
pagesDone++;
}
}
s->pagesDone = pagesDone;
DoContinueDirectionMatchSearchStruct *searchStruct = new DoContinueDirectionMatchSearchStruct();
searchStruct->pagesToNotify = pagesToNotify;
searchStruct->match = match;
searchStruct->currentPage = currentPageNumber;
searchStruct->searchID = searchID;
QTimer::singleShot(0, this, [this, searchStruct] { d->doContinueDirectionMatchSearch(searchStruct); });
}
// 4. GOOGLE* - process all document marking pages
else if (type == GoogleAll || type == GoogleAny) {
QHash<Page *, QList<QPair<RegularAreaRect *, QColor>>> *pageMatches = new QHash<Page *, QList<QPair<RegularAreaRect *, QColor>>>;
const QStringList words = text.split(QLatin1Char(' '), Qt::SkipEmptyParts);
// search and highlight every word in 'text' on all pages
QTimer::singleShot(0, this, [this, pagesToNotify, pageMatches, searchID, words] { d->doContinueGooglesDocumentSearch(pagesToNotify, pageMatches, 0, searchID, words); });
}
}
void Document::continueSearch(int searchID)
{
// check if searchID is present in runningSearches
auto it = d->m_searches.constFind(searchID);
if (it == d->m_searches.constEnd()) {
Q_EMIT searchFinished(searchID, NoMatchFound);
return;
}
// start search with cached parameters from last search by searchID
RunningSearch *p = *it;
if (!p->isCurrentlySearching) {
searchText(searchID, p->cachedString, false, p->cachedCaseSensitivity, p->cachedType, p->cachedViewportMove, p->cachedColor);
}
}
void Document::continueSearch(int searchID, SearchType type)
{
// check if searchID is present in runningSearches
auto it = d->m_searches.constFind(searchID);
if (it == d->m_searches.constEnd()) {
Q_EMIT searchFinished(searchID, NoMatchFound);
return;
}
// start search with cached parameters from last search by searchID
RunningSearch *p = *it;
if (!p->isCurrentlySearching) {
searchText(searchID, p->cachedString, false, p->cachedCaseSensitivity, type, p->cachedViewportMove, p->cachedColor);
}
}
void Document::resetSearch(int searchID)
{
// if we are closing down, don't bother doing anything
if (!d->m_generator) {
return;
}
// check if searchID is present in runningSearches
auto searchIt = d->m_searches.find(searchID);
if (searchIt == d->m_searches.end()) {
return;
}
// get previous parameters for search
RunningSearch *s = *searchIt;
// unhighlight pages and inform observers about that
for (const int pageNumber : std::as_const(s->highlightedPages)) {
d->m_pagesVector.at(pageNumber)->d->deleteHighlights(searchID);
foreachObserver(notifyPageChanged(pageNumber, DocumentObserver::Highlights));
}
// send the setup signal too (to update views that filter on matches)
foreachObserver(notifySetup(d->m_pagesVector, 0));
// remove search from the runningSearches list and delete it
d->m_searches.erase(searchIt);
delete s;
}
void Document::cancelSearch()
{
d->m_searchCancelled = true;
}
void Document::undo()
{
d->m_undoStack->undo();
}
void Document::redo()
{
d->m_undoStack->redo();
}
void Document::editFormText(int pageNumber, Okular::FormFieldText *form, const QString &newContents, int newCursorPos, int prevCursorPos, int prevAnchorPos)
{
QUndoCommand *uc = new EditFormTextCommand(this->d, form, pageNumber, newContents, newCursorPos, form->text(), prevCursorPos, prevAnchorPos);
d->m_undoStack->push(uc);
}
void Document::editFormText(int pageNumber, Okular::FormFieldText *form, const QString &newContents, int newCursorPos, int prevCursorPos, int prevAnchorPos, const QString &oldContents)
{
QUndoCommand *uc = new EditFormTextCommand(this->d, form, pageNumber, newContents, newCursorPos, oldContents, prevCursorPos, prevAnchorPos);
d->m_undoStack->push(uc);
}
void Document::editFormList(int pageNumber, FormFieldChoice *form, const QList<int> &newChoices)
{
const QList<int> prevChoices = form->currentChoices();
QUndoCommand *uc = new EditFormListCommand(this->d, form, pageNumber, newChoices, prevChoices);
d->m_undoStack->push(uc);
}
void Document::editFormCombo(int pageNumber, FormFieldChoice *form, const QString &newText, int newCursorPos, int prevCursorPos, int prevAnchorPos)
{
QString prevText;
if (form->currentChoices().isEmpty()) {
prevText = form->editChoice();
} else {
prevText = form->choices().at(form->currentChoices().constFirst());
}
QUndoCommand *uc = new EditFormComboCommand(this->d, form, pageNumber, newText, newCursorPos, prevText, prevCursorPos, prevAnchorPos);
d->m_undoStack->push(uc);
}
void Document::editFormButtons(int pageNumber, const QList<FormFieldButton *> &formButtons, const QList<bool> &newButtonStates)
{
QUndoCommand *uc = new EditFormButtonsCommand(this->d, pageNumber, formButtons, newButtonStates);
d->m_undoStack->push(uc);
}
void Document::reloadDocument() const
{
const int numOfPages = pages();
for (int i = currentPage(); i >= 0; i--) {
d->refreshPixmaps(i);
}
for (int i = currentPage() + 1; i < numOfPages; i++) {
d->refreshPixmaps(i);
}
}
BookmarkManager *Document::bookmarkManager() const
{
return d->m_bookmarkManager;
}
QList<int> Document::bookmarkedPageList() const
{
QList<int> list;
uint docPages = pages();
// pages are 0-indexed internally, but 1-indexed externally
for (uint i = 0; i < docPages; i++) {
if (bookmarkManager()->isBookmarked(i)) {
list << i + 1;
}
}
return list;
}
QString Document::bookmarkedPageRange() const
{
// Code formerly in Part::slotPrint()
// range detecting
QString range;
uint docPages = pages();
int startId = -1;
int endId = -1;
for (uint i = 0; i < docPages; ++i) {
if (bookmarkManager()->isBookmarked(i)) {
if (startId < 0) {
startId = i;
}
if (endId < 0) {
endId = startId;
} else {
++endId;
}
} else if (startId >= 0 && endId >= 0) {
if (!range.isEmpty()) {
range += QLatin1Char(',');
}
if (endId - startId > 0) {
range += QStringLiteral("%1-%2").arg(startId + 1).arg(endId + 1);
} else {
range += QString::number(startId + 1);
}
startId = -1;
endId = -1;
}
}
if (startId >= 0 && endId >= 0) {
if (!range.isEmpty()) {
range += QLatin1Char(',');
}
if (endId - startId > 0) {
range += QStringLiteral("%1-%2").arg(startId + 1).arg(endId + 1);
} else {
range += QString::number(startId + 1);
}
}
return range;
}
struct ExecuteNextActionsHelper : public QObject, private DocumentObserver {
Q_OBJECT
public:
explicit ExecuteNextActionsHelper(Document *doc)
: m_doc(doc)
{
doc->addObserver(this);
connect(doc, &Document::aboutToClose, this, [this] { b = false; });
}
~ExecuteNextActionsHelper() override
{
m_doc->removeObserver(this);
}
void notifySetup(const QList<Okular::Page *> & /*pages*/, int setupFlags) override
{
if (setupFlags == DocumentChanged || setupFlags == UrlChanged) {
b = false;
}
}
bool shouldExecuteNextAction() const
{
return b;
}
private:
Document *const m_doc;
bool b = true;
};
void Document::processAction(const Action *action)
{
if (!action) {
return;
}
// Don't execute next actions if the action itself caused the closing of the document
const ExecuteNextActionsHelper executeNextActionsHelper(this);
switch (action->actionType()) {
case Action::Goto: {
const GotoAction *go = static_cast<const GotoAction *>(action);
d->m_nextDocumentViewport = go->destViewport();
d->m_nextDocumentDestination = go->destinationName();
// Explanation of why d->m_nextDocumentViewport is needed:
// all openRelativeFile does is launch a signal telling we
// want to open another URL, the problem is that when the file is
// non local, the loading is done asynchronously so you can't
// do a setViewport after the if as it was because you are doing the setViewport
// on the old file and when the new arrives there is no setViewport for it and
// it does not show anything
// first open filename if link is pointing outside this document
const QString filename = go->fileName();
if (go->isExternal() && !d->openRelativeFile(filename)) {
qCWarning(OkularCoreDebug).nospace() << "Action: Error opening '" << filename << "'.";
break;
} else {
const DocumentViewport nextViewport = d->nextDocumentViewport();
// skip local links that point to nowhere (broken ones)
if (!nextViewport.isValid()) {
break;
}
setViewport(nextViewport, nullptr, true);
d->m_nextDocumentViewport = DocumentViewport();
d->m_nextDocumentDestination = QString();
}
} break;
case Action::Execute: {
const ExecuteAction *exe = static_cast<const ExecuteAction *>(action);
const QString fileName = exe->fileName();
if (fileName.endsWith(QLatin1String(".pdf"), Qt::CaseInsensitive)) {
d->openRelativeFile(fileName);
break;
}
// Albert: the only pdf i have that has that kind of link don't define
// an application and use the fileName as the file to open
QUrl url = d->giveAbsoluteUrl(fileName);
QMimeDatabase db;
QMimeType mime = db.mimeTypeForUrl(url);
// Check executables
if (KIO::OpenUrlJob::isExecutableFile(url, mime.name())) {
// Don't have any pdf that uses this code path, just a guess on how it should work
if (!exe->parameters().isEmpty()) {
url = d->giveAbsoluteUrl(exe->parameters());
mime = db.mimeTypeForUrl(url);
if (KIO::OpenUrlJob::isExecutableFile(url, mime.name())) {
// this case is a link pointing to an executable with a parameter
// that also is an executable, possibly a hand-crafted pdf
Q_EMIT error(i18n("The document is trying to execute an external application and, for your safety, Okular does not allow that."), -1);
break;
}
} else {
// this case is a link pointing to an executable with no parameters
// core developers find unacceptable executing it even after asking the user
Q_EMIT error(i18n("The document is trying to execute an external application and, for your safety, Okular does not allow that."), -1);
break;
}
}
KIO::OpenUrlJob *job = new KIO::OpenUrlJob(url, mime.name());
job->setUiDelegate(KIO::createDefaultJobUiDelegate(KJobUiDelegate::AutoHandlingEnabled, d->m_widget));
job->start();
connect(job, &KIO::OpenUrlJob::result, this, [this, mime](KJob *job) {
if (job->error()) {
Q_EMIT error(i18n("No application found for opening file of mimetype %1.", mime.name()), -1);
}
});
} break;
case Action::DocAction: {
const DocumentAction *docaction = static_cast<const DocumentAction *>(action);
switch (docaction->documentActionType()) {
case DocumentAction::PageFirst:
setViewportPage(0);
break;
case DocumentAction::PagePrev:
if ((*d->m_viewportIterator).pageNumber > 0) {
setViewportPage((*d->m_viewportIterator).pageNumber - 1);
}
break;
case DocumentAction::PageNext:
if ((*d->m_viewportIterator).pageNumber < (int)d->m_pagesVector.count() - 1) {
setViewportPage((*d->m_viewportIterator).pageNumber + 1);
}
break;
case DocumentAction::PageLast:
setViewportPage(d->m_pagesVector.count() - 1);
break;
case DocumentAction::HistoryBack:
setPrevViewport();
break;
case DocumentAction::HistoryForward:
setNextViewport();
break;
case DocumentAction::Quit:
Q_EMIT quit();
break;
case DocumentAction::Presentation:
Q_EMIT linkPresentation();
break;
case DocumentAction::EndPresentation:
Q_EMIT linkEndPresentation();
break;
case DocumentAction::Find:
Q_EMIT linkFind();
break;
case DocumentAction::GoToPage:
Q_EMIT linkGoToPage();
break;
case DocumentAction::Close:
Q_EMIT close();
break;
case DocumentAction::Print:
Q_EMIT requestPrint();
break;
case DocumentAction::SaveAs:
Q_EMIT requestSaveAs();
break;
}
} break;
case Action::Browse: {
const BrowseAction *browse = static_cast<const BrowseAction *>(action);
// if the url is a mailto one, invoke mailer
if (browse->url().scheme() == QLatin1String("mailto")) {
QDesktopServices::openUrl(browse->url());
} else if (auto ref = extractLilyPondSourceReference(browse->url())) {
processSourceReference(*ref);
} else {
const QUrl url = browse->url();
// fix for #100366, documents with relative links that are the form of http:foo.pdf
if ((url.scheme() == QLatin1String("http")) && url.host().isEmpty() && url.fileName().endsWith(QLatin1String("pdf"))) {
d->openRelativeFile(url.fileName());
break;
}
// handle documents with relative path
QUrl realUrl;
if (d->m_url.isValid()) {
realUrl = KIO::upUrl(d->m_url).resolved(url);
} else if (!url.isRelative()) {
realUrl = url;
}
if (realUrl.isValid()) {
auto *job = new KIO::OpenUrlJob(realUrl);
job->setUiDelegate(KIO::createDefaultJobUiDelegate(KJobUiDelegate::AutoHandlingEnabled, d->m_widget.data()));
job->start();
}
}
} break;
case Action::Sound: {
const SoundAction *linksound = static_cast<const SoundAction *>(action);
AudioPlayer::instance()->playSound(linksound->sound(), linksound);
} break;
case Action::Script: {
const ScriptAction *linkscript = static_cast<const ScriptAction *>(action);
if (!d->m_scripter) {
d->m_scripter = new Scripter(d);
}
d->m_scripter->execute(nullptr, linkscript->scriptType(), linkscript->script());
} break;
case Action::Movie:
Q_EMIT processMovieAction(static_cast<const MovieAction *>(action));
break;
case Action::Rendition: {
const RenditionAction *linkrendition = static_cast<const RenditionAction *>(action);
if (!linkrendition->script().isEmpty()) {
if (!d->m_scripter) {
d->m_scripter = new Scripter(d);
}
d->m_scripter->execute(nullptr, linkrendition->scriptType(), linkrendition->script());
}
Q_EMIT processRenditionAction(static_cast<const RenditionAction *>(action));
} break;
case Action::BackendOpaque: {
const BackendOpaqueAction *backendOpaqueAction = static_cast<const BackendOpaqueAction *>(action);
Okular::BackendOpaqueAction::OpaqueActionResult res = d->m_generator->opaqueAction(backendOpaqueAction);
if (res & Okular::BackendOpaqueAction::RefreshForms) {
for (const Page *p : std::as_const(d->m_pagesVector)) {
const QList<Okular::FormField *> forms = p->formFields();
for (FormField *form : forms) {
Q_EMIT refreshFormWidget(form);
}
d->refreshPixmaps(p->number());
}
}
} break;
}
if (executeNextActionsHelper.shouldExecuteNextAction()) {
const QList<Action *> nextActions = action->nextActions();
for (const Action *a : nextActions) {
processAction(a);
}
}
}
void Document::processFormatAction(const Action *action, Okular::FormFieldText *fft)
{
processFormatAction(action, static_cast<FormField *>(fft));
}
void Document::processFormatAction(const Action *action, Okular::FormField *ff)
{
if (action->actionType() != Action::Script) {
qCDebug(OkularCoreDebug) << "Unsupported action type" << action->actionType() << "for formatting.";
return;
}
// Lookup the page of the FormFieldText
int foundPage = d->findFieldPageNumber(ff);
if (foundPage == -1) {
qCDebug(OkularCoreDebug) << "Could not find page for formfield!";
return;
}
const QString unformattedText = ff->value().toString();
std::shared_ptr<Event> event = Event::createFormatEvent(ff, d->m_pagesVector[foundPage]);
const ScriptAction *linkscript = static_cast<const ScriptAction *>(action);
d->executeScriptEvent(event, linkscript);
const QString formattedText = event->value().toString();
ff->commitFormattedValue(formattedText);
if (formattedText != unformattedText) {
// We set the formattedText, because when we call refreshFormWidget
// It will set the QLineEdit to this formattedText
ff->setValue(QVariant(formattedText));
ff->setAppearanceValue(QVariant(formattedText));
Q_EMIT refreshFormWidget(ff);
d->refreshPixmaps(foundPage);
// Then we make the form have the unformatted text, to use
// in calculations and other things
ff->setValue(QVariant(unformattedText));
} else if (ff->additionalAction(FormField::CalculateField)) {
// When the field was calculated we need to refresh even
// if the format script changed nothing. e.g. on error.
// This is because the recalculateForms function delegated
// the responsibility for the refresh to us.
Q_EMIT refreshFormWidget(ff);
d->refreshPixmaps(foundPage);
}
}
QString DocumentPrivate::evaluateKeystrokeEventChange(const QString &oldVal, const QString &newVal, int selStart, int selEnd)
{
/*
The change needs to be evaluated here in accordance with code points.
selStart and selEnd parameters passed to this method should be been adjusted accordingly.
Since QString methods work in terms of code units, we convert the strings to UTF-32.
*/
const std::u32string oldUcs4 = oldVal.toStdU32String();
const std::u32string newUcs4 = newVal.toStdU32String();
if (selStart < 0 || selEnd < 0 || (selEnd - selStart) + (static_cast<int>(newUcs4.size()) - static_cast<int>(oldUcs4.size())) < 0) {
// Prevent Okular from crashing if incorrect parameters are passed or some bug causes incorrect calculation
return {};
}
const size_t changeLength = (selEnd - selStart) + (newUcs4.size() - oldUcs4.size());
if (selStart + changeLength > newUcs4.size()) {
return {};
}
auto subview = std::u32string_view {newUcs4}.substr(selStart, changeLength);
if (subview.empty()) {
// If subview is empty (in scenarios when selStart is at end and changeLength is non-zero) fromUcs4 returns \u0000.
// This should not happen, but just a guard.
return {};
}
Q_ASSERT(subview.length() == changeLength);
return QString::fromUcs4(subview.data(), subview.length());
}
void Document::processKeystrokeAction(const Action *action, Okular::FormField *ff, const QVariant &newValue, int prevCursorPos, int prevAnchorPos)
{
if (action->actionType() != Action::Script) {
qCDebug(OkularCoreDebug) << "Unsupported action type" << action->actionType() << "for keystroke.";
return;
}
// Lookup the page of the FormFieldText
int foundPage = d->findFieldPageNumber(ff);
if (foundPage == -1) {
qCDebug(OkularCoreDebug) << "Could not find page for formfield!";
return;
}
std::shared_ptr<Event> event = Event::createKeystrokeEvent(ff, d->m_pagesVector[foundPage]);
/* Set the selStart and selEnd event properties
QString using UTF-16 counts a code point as made up of 1 or 2 16-bit code units.
When encoded using 2 code units, the units are referred to as surrogate pairs.
selectionStart() and selectionEnd() methods evaluate prevCursorPos and prevAnchorPos based on code units during selection.
While this unit-based evaluation is suitable for detecting changes, for providing consistency with Adobe Reader for values of selStart and selEnd,
it would be best to evaluate in terms of code points rather than the code units.
To correct the values of selStart and selEnd accordingly, we iterate over the code units. If a surrogate pair is encountered, then selStart and
selEnd are accordingly decremented.
*/
int selStart = std::min(prevCursorPos, prevAnchorPos);
int selEnd = std::max(prevCursorPos, prevAnchorPos);
int codeUnit;
int initialSelStart = selStart;
int initialSelEnd = selEnd;
QString inputString = ff->value().toString();
for (codeUnit = 0; codeUnit < initialSelStart && codeUnit < inputString.size(); codeUnit++) {
if (inputString.at(codeUnit).isHighSurrogate()) {
// skip the low surrogate and decrement selStart and selEnd
codeUnit++;
selStart--;
selEnd--;
}
}
for (; codeUnit < initialSelEnd && codeUnit < inputString.size(); codeUnit++) {
if (inputString.at(codeUnit).isHighSurrogate()) {
// skip the low surrogate and decrement selEnd
codeUnit++;
selEnd--;
}
}
std::u32string oldUcs4 = inputString.toStdU32String();
std::u32string newUcs4 = newValue.toString().toStdU32String();
// It is necessary to count size in terms of code points rather than code units for deletion.
if (oldUcs4.size() - newUcs4.size() == 1 && selStart == selEnd) {
// consider a one character removal as selection of that character and then its removal.
selStart--;
}
event->setSelStart(selStart);
event->setSelEnd(selEnd);
// Use the corrected selStart and selEnd for evaluating the change.
event->setChange(DocumentPrivate::evaluateKeystrokeEventChange(inputString, newValue.toString(), selStart, selEnd));
const ScriptAction *linkscript = static_cast<const ScriptAction *>(action);
d->executeScriptEvent(event, linkscript);
if (event->returnCode()) {
ff->setValue(newValue);
} else {
Q_EMIT refreshFormWidget(ff);
}
}
void Document::processKeystrokeAction(const Action *action, Okular::FormFieldText *fft, const QVariant &newValue)
{
// use -1 as default
processKeystrokeAction(action, fft, newValue, -1, -1);
}
void Document::processKeystrokeCommitAction(const Action *action, Okular::FormFieldText *fft)
{
bool returnCode = false;
processKeystrokeCommitAction(action, fft, returnCode);
}
void Document::processKeystrokeCommitAction(const Action *action, Okular::FormField *ff, bool &returnCode)
{
if (action->actionType() != Action::Script) {
qCDebug(OkularCoreDebug) << "Unsupported action type" << action->actionType() << "for keystroke.";
return;
}
// Lookup the page of the FormFieldText
int foundPage = d->findFieldPageNumber(ff);
if (foundPage == -1) {
qCDebug(OkularCoreDebug) << "Could not find page for formfield!";
return;
}
std::shared_ptr<Event> event = Event::createKeystrokeEvent(ff, d->m_pagesVector[foundPage]);
event->setWillCommit(true);
const ScriptAction *linkscript = static_cast<const ScriptAction *>(action);
d->executeScriptEvent(event, linkscript);
if (!event->returnCode()) {
ff->setValue(QVariant(ff->committedFormattedValue()));
Q_EMIT refreshFormWidget(ff);
ff->setValue(QVariant(ff->committedValue()));
} else {
ff->setValue(QVariant(event->value().toString()));
Q_EMIT refreshFormWidget(ff);
}
returnCode = event->returnCode();
}
void Document::processFocusAction(const Action *action, Okular::FormField *field)
{
if (!action || action->actionType() != Action::Script) {
return;
}
// Lookup the page of the FormFieldText
int foundPage = d->findFieldPageNumber(field);
if (foundPage == -1) {
qCDebug(OkularCoreDebug) << "Could not find page for formfield!";
return;
}
std::shared_ptr<Event> event = Event::createFormFocusEvent(field, d->m_pagesVector[foundPage]);
const ScriptAction *linkscript = static_cast<const ScriptAction *>(action);
d->executeScriptEvent(event, linkscript);
}
void Document::processValidateAction(const Action *action, Okular::FormFieldText *fft, bool &returnCode)
{
processValidateAction(action, static_cast<FormField *>(fft), returnCode);
}
void Document::processValidateAction(const Action *action, Okular::FormField *ff, bool &returnCode)
{
if (!action || action->actionType() != Action::Script) {
return;
}
// Lookup the page of the FormFieldText
int foundPage = d->findFieldPageNumber(ff);
if (foundPage == -1) {
qCDebug(OkularCoreDebug) << "Could not find page for formfield!";
return;
}
std::shared_ptr<Event> event = Event::createFormValidateEvent(ff, d->m_pagesVector[foundPage]);
const ScriptAction *linkscript = static_cast<const ScriptAction *>(action);
d->executeScriptEvent(event, linkscript);
if (!event->returnCode()) {
ff->setValue(QVariant(ff->committedFormattedValue()));
Q_EMIT refreshFormWidget(ff);
ff->setValue(QVariant(ff->committedValue()));
} else {
ff->setValue(QVariant(event->value().toString()));
Q_EMIT refreshFormWidget(ff);
}
returnCode = event->returnCode();
}
void Document::processKVCFActions(Okular::FormField *ff)
{
if (ff->value().toString() == ff->committedValue()) {
ff->setValue(QVariant(ff->committedFormattedValue()));
Q_EMIT refreshFormWidget(ff);
ff->setValue(QVariant(ff->committedValue()));
return;
}
bool returnCode = true;
if (ff->additionalAction(Okular::FormField::FieldModified) && !ff->isReadOnly()) {
processKeystrokeCommitAction(ff->additionalAction(Okular::FormField::FieldModified), ff, returnCode);
}
if (const Okular::Action *action = ff->additionalAction(Okular::FormField::ValidateField)) {
if (returnCode) {
processValidateAction(action, ff, returnCode);
}
}
if (!returnCode) {
return;
} else {
ff->commitValue(ff->value().toString());
}
recalculateForms();
if (const Okular::Action *action = ff->additionalAction(Okular::FormField::FormatField)) {
processFormatAction(action, ff);
} else {
ff->commitFormattedValue(ff->value().toString());
}
}
void Document::processDocumentAction(const Action *action, DocumentAdditionalActionType type)
{
if (!action || action->actionType() != Action::Script) {
return;
}
Event::EventType eventType = Okular::Event::UnknownEvent;
switch (type) {
case Document::CloseDocument:
eventType = Okular::Event::DocWillClose;
break;
case Document::SaveDocumentStart:
eventType = Okular::Event::DocWillSave;
break;
case Document::SaveDocumentFinish:
eventType = Okular::Event::DocDidSave;
break;
case Document::PrintDocumentStart:
eventType = Okular::Event::DocWillPrint;
break;
case Document::PrintDocumentFinish:
eventType = Okular::Event::DocDidPrint;
break;
}
std::shared_ptr<Event> event = Event::createDocEvent(eventType);
const ScriptAction *linkScript = static_cast<const ScriptAction *>(action);
d->executeScriptEvent(event, linkScript);
}
void Document::processFormMouseScriptAction(const Action *action, Okular::FormField *ff, MouseEventType fieldMouseEventType)
{
if (!action || action->actionType() != Action::Script) {
return;
}
Okular::Event::EventType eventType = Okular::Event::UnknownEvent;
switch (fieldMouseEventType) {
case Document::FieldMouseDown:
eventType = Okular::Event::FieldMouseDown;
break;
case Document::FieldMouseEnter:
eventType = Okular::Event::FieldMouseEnter;
break;
case Document::FieldMouseExit:
eventType = Okular::Event::FieldMouseExit;
break;
case Document::FieldMouseUp:
eventType = Okular::Event::FieldMouseUp;
break;
}
// Lookup the page of the FormFieldText
int foundPage = d->findFieldPageNumber(ff);
if (foundPage == -1) {
qCDebug(OkularCoreDebug) << "Could not find page for formfield!";
return;
}
std::shared_ptr<Event> event = Event::createFieldMouseEvent(ff, d->m_pagesVector[foundPage], eventType);
const ScriptAction *linkscript = static_cast<const ScriptAction *>(action);
d->executeScriptEvent(event, linkscript);
}
void Document::processFormMouseUpScripAction(const Action *action, Okular::FormField *ff)
{
processFormMouseScriptAction(action, ff, FieldMouseUp);
}
void Document::processSourceReference(const SourceReference *ref)
{
if (ref) {
processSourceReference(*ref);
}
}
void Document::processSourceReference(const SourceReference &ref)
{
const QUrl url = d->giveAbsoluteUrl(ref.fileName());
if (!url.isLocalFile()) {
qCDebug(OkularCoreDebug) << url.url() << "is not a local file.";
return;
}
const QString absFileName = url.toLocalFile();
if (!QFile::exists(absFileName)) {
qCDebug(OkularCoreDebug) << "No such file:" << absFileName;
return;
}
bool handled = false;
Q_EMIT sourceReferenceActivated(absFileName, ref.row(), ref.column(), &handled);
if (handled) {
return;
}
static const QHash<int, QString> editors = buildEditorsMap();
// prefer the editor from the command line
QString p = d->editorCommandOverride;
if (p.isEmpty()) {
p = editors.value(SettingsCore::externalEditor());
}
if (p.isEmpty()) {
p = SettingsCore::externalEditorCommand();
}
// custom editor not yet configured
if (p.isEmpty()) {
return;
}
// manually append the %f placeholder if not specified
if (!p.contains(QLatin1String("%f"))) {
p.append(QLatin1String(" %f"));
}
// replacing the placeholders
QHash<QChar, QString> map;
map.insert(QLatin1Char('f'), absFileName);
map.insert(QLatin1Char('c'), QString::number(ref.column()));
map.insert(QLatin1Char('l'), QString::number(ref.row()));
const QString cmd = KMacroExpander::expandMacrosShellQuote(p, map);
if (cmd.isEmpty()) {
return;
}
QStringList args = KShell::splitArgs(cmd);
if (args.isEmpty()) {
return;
}
const QString prog = args.takeFirst();
// Make sure prog is in PATH and not just in the CWD
const QString progFullPath = QStandardPaths::findExecutable(prog);
if (progFullPath.isEmpty()) {
return;
}
KProcess::startDetached(progFullPath, args);
}
const SourceReference *Document::dynamicSourceReference(int pageNr, double absX, double absY)
{
if (!d->m_synctex_scanner) {
return nullptr;
}
const QSizeF dpi = d->m_generator->dpi();
if (synctex_edit_query(d->m_synctex_scanner, pageNr + 1, absX * 72. / dpi.width(), absY * 72. / dpi.height()) > 0) {
synctex_node_p node;
// TODO what should we do if there is really more than one node?
while ((node = synctex_scanner_next_result(d->m_synctex_scanner))) {
int line = synctex_node_line(node);
int col = synctex_node_column(node);
// column extraction does not seem to be implemented in synctex so far. set the SourceReference default value.
if (col == -1) {
col = 0;
}
const char *name = synctex_scanner_get_name(d->m_synctex_scanner, synctex_node_tag(node));
return new Okular::SourceReference(QFile::decodeName(name), line, col);
}
}
return nullptr;
}
Document::PrintingType Document::printingSupport() const
{
if (d->m_generator) {
if (d->m_generator->hasFeature(Generator::PrintNative)) {
return NativePrinting;
}
#ifndef Q_OS_WIN
if (d->m_generator->hasFeature(Generator::PrintPostscript)) {
return PostscriptPrinting;
}
#endif
}
return NoPrinting;
}
bool Document::supportsPrintToFile() const
{
return d->m_generator ? d->m_generator->hasFeature(Generator::PrintToFile) : false;
}
Document::PrintError Document::print(QPrinter &printer)
{
if (const Okular::Action *action = d->m_generator->additionalDocumentAction(PrintDocumentStart)) {
processDocumentAction(action, PrintDocumentStart);
}
const Document::PrintError printError = d->m_generator ? d->m_generator->print(printer) : Document::UnknownPrintError;
if (printError == Document::NoPrintError) {
if (const Okular::Action *action = d->m_generator->additionalDocumentAction(PrintDocumentFinish)) {
processDocumentAction(action, PrintDocumentFinish);
}
}
return printError;
}
QString Document::printErrorString(PrintError error)
{
switch (error) {
case TemporaryFileOpenPrintError:
return i18n("Could not open a temporary file");
case FileConversionPrintError:
return i18n("Print conversion failed");
case PrintingProcessCrashPrintError:
return i18n("Printing process crashed");
case PrintingProcessStartPrintError:
return i18n("Printing process could not start");
case PrintToFilePrintError:
return i18n("Printing to file failed");
case InvalidPrinterStatePrintError:
return i18n("Printer was in invalid state");
case UnableToFindFilePrintError:
return i18n("Unable to find file to print");
case NoFileToPrintError:
return i18n("There was no file to print");
case NoBinaryToPrintError:
return i18n("Could not find a suitable binary for printing. Make sure CUPS lpr binary is available");
case InvalidPageSizePrintError:
return i18n("The page print size is invalid");
case NoPrintError:
return QString();
case UnknownPrintError:
return QString();
}
return QString();
}
QWidget *Document::printConfigurationWidget() const
{
if (d->m_generator) {
PrintInterface *iface = qobject_cast<Okular::PrintInterface *>(d->m_generator);
return iface ? iface->printConfigurationWidget() : nullptr;
} else {
return nullptr;
}
}
void Document::fillConfigDialog(KConfigDialog *dialog)
{
if (!dialog) {
return;
}
// We know it's a BackendConfigDialog, but check anyway
BackendConfigDialog *bcd = dynamic_cast<BackendConfigDialog *>(dialog);
if (!bcd) {
return;
}
// ensure that we have all the generators with settings loaded
QList<KPluginMetaData> offers = DocumentPrivate::configurableGenerators();
d->loadServiceList(offers);
// We want the generators to be sorted by name so let's fill in a QMap
// this sorts by internal id which is not awesome, but at least the sorting
// is stable between runs that before it wasn't
QMap<QString, GeneratorInfo> sortedGenerators;
for (const auto &[key, value] : d->m_loadedGenerators.asKeyValueRange()) {
sortedGenerators.insert(key, value);
}
bool pagesAdded = false;
for (const auto &[key, value] : sortedGenerators.asKeyValueRange()) {
Okular::ConfigInterface *iface = d->generatorConfig(value);
if (iface) {
iface->addPages(dialog);
pagesAdded = true;
if (value.generator == d->m_generator) {
const int rowCount = bcd->thePageWidget()->model()->rowCount();
KPageView *view = bcd->thePageWidget();
view->setCurrentPage(view->model()->index(rowCount - 1, 0));
}
}
}
if (pagesAdded) {
connect(dialog, &KConfigDialog::settingsChanged, this, [this] { d->slotGeneratorConfigChanged(); });
}
}
QList<KPluginMetaData> DocumentPrivate::configurableGenerators()
{
const QList<KPluginMetaData> available = availableGenerators();
QList<KPluginMetaData> result;
for (const KPluginMetaData &md : available) {
if (md.rawData().value(QStringLiteral("X-KDE-okularHasInternalSettings")).toBool()) {
result << md;
}
}
return result;
}
KPluginMetaData Document::generatorInfo() const
{
if (!d->m_generator) {
return KPluginMetaData();
}
auto genIt = d->m_loadedGenerators.constFind(d->m_generatorName);
Q_ASSERT(genIt != d->m_loadedGenerators.constEnd());
return genIt.value().metadata;
}
int Document::configurableGenerators() const
{
return DocumentPrivate::configurableGenerators().size();
}
QStringList Document::supportedMimeTypes() const
{
// TODO: make it a static member of DocumentPrivate?
QStringList result = d->m_supportedMimeTypes;
if (result.isEmpty()) {
const QList<KPluginMetaData> available = DocumentPrivate::availableGenerators();
for (const KPluginMetaData &md : available) {
result << md.mimeTypes();
}
// Remove duplicate mimetypes represented by different names
QMimeDatabase mimeDatabase;
QSet<QMimeType> uniqueMimetypes;
for (const QString &mimeName : std::as_const(result)) {
uniqueMimetypes.insert(mimeDatabase.mimeTypeForName(mimeName));
}
result.clear();
for (const QMimeType &mimeType : uniqueMimetypes) {
result.append(mimeType.name());
}
// Add the Okular archive mimetype
result << QStringLiteral("application/vnd.kde.okular-archive");
// Sorting by mimetype name doesn't make a ton of sense,
// but ensures that the list is ordered the same way every time
std::sort(result.begin(), result.end());
d->m_supportedMimeTypes = result;
}
return result;
}
bool Document::canSwapBackingFile() const
{
if (!d->m_generator) {
return false;
}
return d->m_generator->hasFeature(Generator::SwapBackingFile);
}
bool Document::swapBackingFile(const QString &newFileName, const QUrl &url)
{
if (!d->m_generator) {
return false;
}
if (!d->m_generator->hasFeature(Generator::SwapBackingFile)) {
return false;
}
// Save metadata about the file we're about to close
d->saveDocumentInfo();
d->clearAndWaitForRequests();
qCDebug(OkularCoreDebug) << "Swapping backing file to" << newFileName;
QList<Page *> newPagesVector;
Generator::SwapBackingFileResult result = d->m_generator->swapBackingFile(newFileName, newPagesVector);
if (result != Generator::SwapBackingFileError) {
QList<ObjectRect *> rectsToDelete;
QList<Annotation *> annotationsToDelete;
QSet<PagePrivate *> pagePrivatesToDelete;
if (result == Generator::SwapBackingFileReloadInternalData) {
// Here we need to replace everything that the old generator
// had created with what the new one has without making it look like
// we have actually closed and opened the file again
// Simple sanity check
if (newPagesVector.count() != d->m_pagesVector.count()) {
return false;
}
// Update the undo stack contents
for (int i = 0; i < d->m_undoStack->count(); ++i) {
// Trust me on the const_cast ^_^
QUndoCommand *uc = const_cast<QUndoCommand *>(d->m_undoStack->command(i));
if (OkularUndoCommand *ouc = dynamic_cast<OkularUndoCommand *>(uc)) {
const bool success = ouc->refreshInternalPageReferences(newPagesVector);
if (!success) {
qWarning() << "Document::swapBackingFile: refreshInternalPageReferences failed" << ouc;
return false;
}
} else {
qWarning() << "Document::swapBackingFile: Unhandled undo command" << uc;
return false;
}
}
for (int i = 0; i < d->m_pagesVector.count(); ++i) {
// switch the PagePrivate* from newPage to oldPage
// this way everyone still holding Page* doesn't get
// disturbed by it
Page *oldPage = d->m_pagesVector[i];
Page *newPage = newPagesVector[i];
newPage->d->adoptGeneratedContents(oldPage->d);
pagePrivatesToDelete << oldPage->d;
oldPage->d = newPage->d;
oldPage->d->m_page = oldPage;
oldPage->d->m_doc = d;
newPage->d = nullptr;
annotationsToDelete << oldPage->m_annotations;
rectsToDelete << oldPage->m_rects;
oldPage->m_annotations = newPage->m_annotations;
oldPage->m_rects = newPage->m_rects;
}
qDeleteAll(newPagesVector);
newPagesVector.clear();
}
d->m_url = url;
d->m_docFileName = newFileName;
d->updateMetadataXmlNameAndDocSize();
d->m_bookmarkManager->setUrl(d->m_url);
d->m_documentInfo = DocumentInfo();
d->m_documentInfoAskedKeys.clear();
if (d->m_synctex_scanner) {
synctex_scanner_free(d->m_synctex_scanner);
d->m_synctex_scanner = synctex_scanner_new_with_output_file(QFile::encodeName(newFileName).constData(), nullptr, 1);
if (!d->m_synctex_scanner && QFile::exists(newFileName + QLatin1String("sync"))) {
d->loadSyncFile(newFileName);
}
}
foreachObserver(notifySetup(d->m_pagesVector, DocumentObserver::UrlChanged));
qDeleteAll(annotationsToDelete);
qDeleteAll(rectsToDelete);
qDeleteAll(pagePrivatesToDelete);
return true;
} else {
return false;
}
}
bool Document::swapBackingFileArchive(const QString &newFileName, const QUrl &url)
{
qCDebug(OkularCoreDebug) << "Swapping backing archive to" << newFileName;
ArchiveData *newArchive = DocumentPrivate::unpackDocumentArchive(newFileName);
if (!newArchive) {
return false;
}
const QString tempFileName = newArchive->document.fileName();
const bool success = swapBackingFile(tempFileName, url);
if (success) {
delete d->m_archiveData;
d->m_archiveData = newArchive;
}
return success;
}
void Document::setHistoryClean(bool clean)
{
if (clean) {
d->m_undoStack->setClean();
} else {
d->m_undoStack->resetClean();
}
}
bool Document::isHistoryClean() const
{
return d->m_undoStack->isClean();
}
void Document::clearHistory()
{
d->m_undoStack->clear();
}
bool Document::canSaveChanges() const
{
if (!d->m_generator) {
return false;
}
Q_ASSERT(!d->m_generatorName.isEmpty());
auto genIt = d->m_loadedGenerators.find(d->m_generatorName);
Q_ASSERT(genIt != d->m_loadedGenerators.end());
SaveInterface *saveIface = d->generatorSave(genIt.value());
if (!saveIface) {
return false;
}
return saveIface->supportsOption(SaveInterface::SaveChanges);
}
bool Document::canSaveChanges(SaveCapability cap) const
{
switch (cap) {
case SaveFormsCapability:
/* Assume that if the generator supports saving, forms can be saved.
* We have no means to actually query the generator at the moment
* TODO: Add some method to query the generator in SaveInterface */
return canSaveChanges();
case SaveAnnotationsCapability:
return d->canAddAnnotationsNatively();
}
return false;
}
bool Document::saveChanges(const QString &fileName)
{
QString errorText;
return saveChanges(fileName, &errorText);
}
bool Document::saveChanges(const QString &fileName, QString *errorText)
{
if (!d->m_generator || fileName.isEmpty()) {
return false;
}
Q_ASSERT(!d->m_generatorName.isEmpty());
auto genIt = d->m_loadedGenerators.find(d->m_generatorName);
Q_ASSERT(genIt != d->m_loadedGenerators.end());
SaveInterface *saveIface = d->generatorSave(genIt.value());
if (!saveIface || !saveIface->supportsOption(SaveInterface::SaveChanges)) {
return false;
}
if (const Okular::Action *action = d->m_generator->additionalDocumentAction(SaveDocumentStart)) {
processDocumentAction(action, SaveDocumentStart);
}
const bool success = saveIface->save(fileName, SaveInterface::SaveChanges, errorText);
if (success) {
if (const Okular::Action *action = d->m_generator->additionalDocumentAction(SaveDocumentFinish)) {
processDocumentAction(action, SaveDocumentFinish);
}
}
return success;
}
void Document::registerView(View *view)
{
if (!view) {
return;
}
Document *viewDoc = view->viewDocument();
if (viewDoc) {
// check if already registered for this document
if (viewDoc == this) {
return;
}
viewDoc->unregisterView(view);
}
d->m_views.insert(view);
view->d_func()->document = d;
}
void Document::unregisterView(View *view)
{
if (!view) {
return;
}
const Document *viewDoc = view->viewDocument();
if (!viewDoc || viewDoc != this) {
return;
}
view->d_func()->document = nullptr;
d->m_views.remove(view);
}
QByteArray Document::fontData(const FontInfo &font) const
{
if (d->m_generator) {
return d->m_generator->requestFontData(font);
}
return {};
}
ArchiveData *DocumentPrivate::unpackDocumentArchive(const QString &archivePath)
{
QMimeDatabase db;
const QMimeType mime = db.mimeTypeForFile(archivePath, QMimeDatabase::MatchExtension);
if (!mime.inherits(QStringLiteral("application/vnd.kde.okular-archive"))) {
return nullptr;
}
KZip okularArchive(archivePath);
if (!okularArchive.open(QIODevice::ReadOnly)) {
return nullptr;
}
const KArchiveDirectory *mainDir = okularArchive.directory();
// Check the archive doesn't have folders, we don't create them when saving the archive
// and folders mean paths and paths mean path traversal issues
const QStringList mainDirEntries = mainDir->entries();
for (const QString &entry : mainDirEntries) {
if (mainDir->entry(entry)->isDirectory()) {
qWarning() << "Warning: Found a directory inside" << archivePath << " - Okular does not create files like that so it is most probably forged.";
return nullptr;
}
}
const KArchiveEntry *mainEntry = mainDir->entry(QStringLiteral("content.xml"));
if (!mainEntry || !mainEntry->isFile()) {
return nullptr;
}
std::unique_ptr<QIODevice> mainEntryDevice(static_cast<const KZipFileEntry *>(mainEntry)->createDevice());
QDomDocument doc;
if (!doc.setContent(mainEntryDevice.get())) {
return nullptr;
}
mainEntryDevice.reset();
QDomElement root = doc.documentElement();
if (root.tagName() != QLatin1String("OkularArchive")) {
return nullptr;
}
QString documentFileName;
QString metadataFileName;
QDomElement el = root.firstChild().toElement();
for (; !el.isNull(); el = el.nextSibling().toElement()) {
if (el.tagName() == QLatin1String("Files")) {
QDomElement fileEl = el.firstChild().toElement();
for (; !fileEl.isNull(); fileEl = fileEl.nextSibling().toElement()) {
if (fileEl.tagName() == QLatin1String("DocumentFileName")) {
documentFileName = fileEl.text();
} else if (fileEl.tagName() == QLatin1String("MetadataFileName")) {
metadataFileName = fileEl.text();
}
}
}
}
if (documentFileName.isEmpty()) {
return nullptr;
}
const KArchiveEntry *docEntry = mainDir->entry(documentFileName);
if (!docEntry || !docEntry->isFile()) {
return nullptr;
}
std::unique_ptr<ArchiveData> archiveData(new ArchiveData());
const int dotPos = documentFileName.indexOf(QLatin1Char('.'));
if (dotPos != -1) {
archiveData->document.setFileTemplate(QDir::tempPath() + QLatin1String("/okular_XXXXXX") + documentFileName.mid(dotPos));
}
if (!archiveData->document.open()) {
return nullptr;
}
archiveData->originalFileName = documentFileName;
{
std::unique_ptr<QIODevice> docEntryDevice(static_cast<const KZipFileEntry *>(docEntry)->createDevice());
copyQIODevice(docEntryDevice.get(), &archiveData->document);
archiveData->document.close();
}
const KArchiveEntry *metadataEntry = mainDir->entry(metadataFileName);
if (metadataEntry && metadataEntry->isFile()) {
std::unique_ptr<QIODevice> metadataEntryDevice(static_cast<const KZipFileEntry *>(metadataEntry)->createDevice());
archiveData->metadataFile.setFileTemplate(QDir::tempPath() + QLatin1String("/okular_XXXXXX.xml"));
if (archiveData->metadataFile.open()) {
copyQIODevice(metadataEntryDevice.get(), &archiveData->metadataFile);
archiveData->metadataFile.close();
}
}
return archiveData.release();
}
Document::OpenResult Document::openDocumentArchive(const QString &docFile, const QUrl &url, const QString &password)
{
d->m_archiveData = DocumentPrivate::unpackDocumentArchive(docFile);
if (!d->m_archiveData) {
return OpenError;
}
const QString tempFileName = d->m_archiveData->document.fileName();
QMimeDatabase db;
const QMimeType docMime = db.mimeTypeForFile(tempFileName, QMimeDatabase::MatchExtension);
const OpenResult ret = openDocument(tempFileName, url, docMime, password);
if (ret != OpenSuccess) {
delete d->m_archiveData;
d->m_archiveData = nullptr;
}
return ret;
}
bool Document::saveDocumentArchive(const QString &fileName)
{
if (!d->m_generator) {
return false;
}
/* If we opened an archive, use the name of original file (eg foo.pdf)
* instead of the archive's one (eg foo.okular) */
QString docFileName = d->m_archiveData ? d->m_archiveData->originalFileName : d->m_url.fileName();
if (docFileName == QLatin1String("-")) {
return false;
}
QString docPath = d->m_docFileName;
const QFileInfo fi(docPath);
if (fi.isSymLink()) {
docPath = fi.symLinkTarget();
}
KZip okularArchive(fileName);
if (!okularArchive.open(QIODevice::WriteOnly)) {
return false;
}
const KUser user;
#ifndef Q_OS_WIN
const KUserGroup userGroup(user.groupId());
#else
const KUserGroup userGroup(QStringLiteral(""));
#endif
QDomDocument contentDoc(QStringLiteral("OkularArchive"));
QDomProcessingInstruction xmlPi = contentDoc.createProcessingInstruction(QStringLiteral("xml"), QStringLiteral("version=\"1.0\" encoding=\"utf-8\""));
contentDoc.appendChild(xmlPi);
QDomElement root = contentDoc.createElement(QStringLiteral("OkularArchive"));
contentDoc.appendChild(root);
QDomElement filesNode = contentDoc.createElement(QStringLiteral("Files"));
root.appendChild(filesNode);
QDomElement fileNameNode = contentDoc.createElement(QStringLiteral("DocumentFileName"));
filesNode.appendChild(fileNameNode);
fileNameNode.appendChild(contentDoc.createTextNode(docFileName));
QDomElement metadataFileNameNode = contentDoc.createElement(QStringLiteral("MetadataFileName"));
filesNode.appendChild(metadataFileNameNode);
metadataFileNameNode.appendChild(contentDoc.createTextNode(QStringLiteral("metadata.xml")));
// If the generator can save annotations natively, do it
QTemporaryFile modifiedFile;
bool annotationsSavedNatively = false;
bool formsSavedNatively = false;
if (d->canAddAnnotationsNatively() || canSaveChanges(SaveFormsCapability)) {
if (!modifiedFile.open()) {
return false;
}
const QString modifiedFileName = modifiedFile.fileName();
modifiedFile.close(); // We're only interested in the file name
QString errorText;
if (saveChanges(modifiedFileName, &errorText)) {
docPath = modifiedFileName; // Save this instead of the original file
annotationsSavedNatively = d->canAddAnnotationsNatively();
formsSavedNatively = canSaveChanges(SaveFormsCapability);
} else {
qCWarning(OkularCoreDebug) << "saveChanges failed: " << errorText;
qCDebug(OkularCoreDebug) << "Falling back to saving a copy of the original file";
}
}
PageItems saveWhat = None;
if (!annotationsSavedNatively) {
saveWhat |= AnnotationPageItems;
}
if (!formsSavedNatively) {
saveWhat |= FormFieldPageItems;
}
QTemporaryFile metadataFile;
if (!d->savePageDocumentInfo(&metadataFile, saveWhat)) {
return false;
}
const QByteArray contentDocXml = contentDoc.toByteArray();
const mode_t perm = 0100644;
okularArchive.writeFile(QStringLiteral("content.xml"), contentDocXml, perm, user.loginName(), userGroup.name());
okularArchive.addLocalFile(docPath, docFileName);
okularArchive.addLocalFile(metadataFile.fileName(), QStringLiteral("metadata.xml"));
if (!okularArchive.close()) {
return false;
}
return true;
}
bool Document::extractArchivedFile(const QString &destFileName)
{
if (!d->m_archiveData) {
return false;
}
// Remove existing file, if present (QFile::copy doesn't overwrite by itself)
QFile::remove(destFileName);
return d->m_archiveData->document.copy(destFileName);
}
QPageLayout::Orientation Document::orientation() const
{
int landscape, portrait;
// if some pages are landscape and others are not, the most common wins, as
// QPrinter does not accept a per-page setting
landscape = 0;
portrait = 0;
for (Page *const current : std::as_const(d->m_pagesVector)) {
double width = current->width();
double height = current->height();
if (current->orientation() == Okular::Rotation90 || current->orientation() == Okular::Rotation270) {
std::swap(width, height);
}
if (width > height) {
landscape++;
} else {
portrait++;
}
}
return (landscape > portrait) ? QPageLayout::Landscape : QPageLayout::Portrait;
}
void Document::setAnnotationEditingEnabled(bool enable)
{
d->m_annotationEditingEnabled = enable;
foreachObserver(notifySetup(d->m_pagesVector, 0));
}
void Document::walletDataForFile(const QString &fileName, QString *walletName, QString *walletFolder, QString *walletKey) const
{
if (d->m_generator) {
d->m_generator->walletDataForFile(fileName, walletName, walletFolder, walletKey);
} else if (d->m_walletGenerator) {
d->m_walletGenerator->walletDataForFile(fileName, walletName, walletFolder, walletKey);
}
}
bool Document::isDocdataMigrationNeeded() const
{
return d->m_docdataMigrationNeeded;
}
void Document::docdataMigrationDone()
{
if (d->m_docdataMigrationNeeded) {
d->m_docdataMigrationNeeded = false;
foreachObserver(notifySetup(d->m_pagesVector, 0));
}
}
QAbstractItemModel *Document::layersModel() const
{
return d->m_generator ? d->m_generator->layersModel() : nullptr;
}
QString Document::openError() const
{
return d->m_openError;
}
QByteArray Document::requestSignedRevisionData(const Okular::SignatureInfo &info)
{
QFile f(d->m_docFileName);
if (!f.open(QIODevice::ReadOnly)) {
Q_EMIT error(i18n("Could not open '%1'. File does not exist", d->m_docFileName), -1);
return {};
}
const QList<qint64> byteRange = info.signedRangeBounds();
f.seek(byteRange.first());
QByteArray data = f.read(byteRange.last() - byteRange.first());
f.close();
return data;
}
void Document::refreshPixmaps(int pageNumber)
{
d->refreshPixmaps(pageNumber);
}
void DocumentPrivate::executeScript(const QString &function)
{
if (!m_scripter) {
m_scripter = new Scripter(this);
}
m_scripter->execute(nullptr, JavaScript, function);
}
void DocumentPrivate::requestDone(PixmapRequest *req)
{
if (!req) {
return;
}
if (!m_generator || m_closingLoop) {
m_pixmapRequestsMutex.lock();
m_executingPixmapRequests.remove(req);
m_pixmapRequestsMutex.unlock();
delete req;
req = nullptr;
if (m_closingLoop) {
m_closingLoop->exit();
}
return;
}
#ifndef NDEBUG
if (!m_generator->canGeneratePixmap()) {
qCDebug(OkularCoreDebug) << "requestDone with generator not in READY state.";
}
#endif
if (!req->shouldAbortRender()) {
// [MEM] 1.1 find and remove a previous entry for the same page and id
auto it = std::ranges::find_if(m_allocatedPixmaps, [&](AllocatedPixmap *const p) { //
return p->page == req->pageNumber() && p->observer == req->observer();
});
if (it != m_allocatedPixmaps.end()) {
AllocatedPixmap *p = *it;
m_allocatedPixmaps.erase(it);
m_allocatedPixmapsTotalMemory -= p->memory;
delete p;
}
DocumentObserver *observer = req->observer();
if (m_observers.contains(observer)) {
// [MEM] 1.2 append memory allocation descriptor to the FIFO
qulonglong memoryBytes = 0;
const TilesManager *tm = req->d->tilesManager();
if (tm) {
memoryBytes = tm->totalMemory();
} else {
memoryBytes = 4 * qulonglong(req->width()) * req->height();
}
AllocatedPixmap *memoryPage = new AllocatedPixmap(req->observer(), req->pageNumber(), memoryBytes);
m_allocatedPixmaps.push_back(memoryPage);
m_allocatedPixmapsTotalMemory += memoryBytes;
// 2. notify an observer that its pixmap changed
observer->notifyPageChanged(req->pageNumber(), DocumentObserver::Pixmap);
}
#ifndef NDEBUG
else {
qCWarning(OkularCoreDebug) << "Receiving a done request for the defunct observer" << observer;
}
#endif
}
// 3. delete request
m_pixmapRequestsMutex.lock();
m_executingPixmapRequests.remove(req);
m_pixmapRequestsMutex.unlock();
delete req;
req = nullptr;
// 4. start a new generation if some is pending
m_pixmapRequestsMutex.lock();
bool hasPixmaps = !m_pixmapRequestsStack.empty();
m_pixmapRequestsMutex.unlock();
if (hasPixmaps) {
sendGeneratorPixmapRequest();
}
}
void DocumentPrivate::setPageBoundingBox(int page, const NormalizedRect &boundingBox)
{
Page *kp = m_pagesVector[page];
if (!m_generator || !kp) {
return;
}
if (kp->boundingBox() == boundingBox) {
return;
}
kp->setBoundingBox(boundingBox);
// notify observers about the change
foreachObserverD(notifyPageChanged(page, DocumentObserver::BoundingBox));
// TODO: For generators that generate the bbox by pixmap scanning, if the first generated pixmap is very small, the bounding box will forever be inaccurate.
// TODO: Crop computation should also consider annotations, actions, etc. to make sure they're not cropped away.
// TODO: Help compute bounding box for generators that create a QPixmap without a QImage, like text and plucker.
// TODO: Don't compute the bounding box if no one needs it (e.g., Trim Borders is off).
}
void DocumentPrivate::calculateMaxTextPages()
{
int multipliers = qMax(1, qRound(getTotalMemory() / 536870912.0)); // 512 MB
switch (SettingsCore::memoryLevel()) {
case SettingsCore::EnumMemoryLevel::Low:
m_maxAllocatedTextPages = multipliers * 2;
break;
case SettingsCore::EnumMemoryLevel::Normal:
m_maxAllocatedTextPages = multipliers * 50;
break;
case SettingsCore::EnumMemoryLevel::Aggressive:
m_maxAllocatedTextPages = multipliers * 250;
break;
case SettingsCore::EnumMemoryLevel::Greedy:
m_maxAllocatedTextPages = multipliers * 1250;
break;
}
}
void DocumentPrivate::textGenerationDone(Page *page)
{
if (!m_pageController) {
return;
}
// 1. If we reached the cache limit, delete the first text page from the fifo
if (m_allocatedTextPagesFifo.size() == m_maxAllocatedTextPages) {
int pageToKick = m_allocatedTextPagesFifo.takeFirst();
if (pageToKick != page->number()) // this should never happen but better be safe than sorry
{
m_pagesVector.at(pageToKick)->setTextPage(nullptr); // deletes the textpage
}
}
// 2. Add the page to the fifo of generated text pages
m_allocatedTextPagesFifo.append(page->number());
}
void Document::setRotation(int r)
{
d->setRotationInternal(r, true);
}
void DocumentPrivate::setRotationInternal(int r, bool notify)
{
Rotation rotation = (Rotation)r;
if (!m_generator || (m_rotation == rotation)) {
return;
}
// tell the pages to rotate
for (Page *const page : std::as_const(m_pagesVector)) {
page->d->rotateAt(rotation);
}
if (notify) {
// notify the generator that the current rotation has changed
m_generator->rotationChanged(rotation, m_rotation);
}
// set the new rotation
m_rotation = rotation;
if (notify) {
foreachObserverD(notifySetup(m_pagesVector, DocumentObserver::NewLayoutForPages));
foreachObserverD(notifyContentsCleared(DocumentObserver::Pixmap | DocumentObserver::Highlights | DocumentObserver::Annotations));
}
qCDebug(OkularCoreDebug) << "Rotated:" << r;
}
void Document::setPageSize(const PageSize &size)
{
if (!d->m_generator || !d->m_generator->hasFeature(Generator::PageSizes)) {
return;
}
if (d->m_pageSizes.isEmpty()) {
d->m_pageSizes = d->m_generator->pageSizes();
}
int sizeid = d->m_pageSizes.indexOf(size);
if (sizeid == -1) {
return;
}
// tell the pages to change size
for (Page *const page : std::as_const(d->m_pagesVector)) {
page->d->changeSize(size);
}
// clear 'memory allocation' descriptors
qDeleteAll(d->m_allocatedPixmaps);
d->m_allocatedPixmaps.clear();
d->m_allocatedPixmapsTotalMemory = 0;
// notify the generator that the current page size has changed
d->m_generator->pageSizeChanged(size, d->m_pageSize);
// set the new page size
d->m_pageSize = size;
foreachObserver(notifySetup(d->m_pagesVector, DocumentObserver::NewLayoutForPages));
foreachObserver(notifyContentsCleared(DocumentObserver::Pixmap | DocumentObserver::Highlights));
qCDebug(OkularCoreDebug) << "New PageSize id:" << sizeid;
}
/** DocumentViewport **/
DocumentViewport::DocumentViewport(int n)
: pageNumber(n)
{
// default settings
rePos.enabled = false;
rePos.normalizedX = 0.5;
rePos.normalizedY = 0.0;
rePos.pos = Center;
autoFit.enabled = false;
autoFit.width = false;
autoFit.height = false;
}
DocumentViewport::DocumentViewport(const QString &xmlDesc)
: pageNumber(-1)
{
// default settings (maybe overridden below)
rePos.enabled = false;
rePos.normalizedX = 0.5;
rePos.normalizedY = 0.0;
rePos.pos = Center;
autoFit.enabled = false;
autoFit.width = false;
autoFit.height = false;
// check for string presence
if (xmlDesc.isEmpty()) {
return;
}
// decode the string
bool ok;
int field = 0;
QString token = xmlDesc.section(QLatin1Char(';'), field, field);
while (!token.isEmpty()) {
// decode the current token
if (field == 0) {
pageNumber = token.toInt(&ok);
if (!ok) {
return;
}
} else if (token.startsWith(QLatin1String("C1"))) {
rePos.enabled = true;
rePos.normalizedX = token.section(QLatin1Char(':'), 1, 1).toDouble();
rePos.normalizedY = token.section(QLatin1Char(':'), 2, 2).toDouble();
rePos.pos = Center;
} else if (token.startsWith(QLatin1String("C2"))) {
rePos.enabled = true;
rePos.normalizedX = token.section(QLatin1Char(':'), 1, 1).toDouble();
rePos.normalizedY = token.section(QLatin1Char(':'), 2, 2).toDouble();
if (token.section(QLatin1Char(':'), 3, 3).toInt() == 1) {
rePos.pos = Center;
} else {
rePos.pos = TopLeft;
}
} else if (token.startsWith(QLatin1String("AF1"))) {
autoFit.enabled = true;
autoFit.width = token.section(QLatin1Char(':'), 1, 1) == QLatin1String("T");
autoFit.height = token.section(QLatin1Char(':'), 2, 2) == QLatin1String("T");
}
// proceed tokenizing string
field++;
token = xmlDesc.section(QLatin1Char(';'), field, field);
}
}
QString DocumentViewport::toString() const
{
// start string with page number
QString s = QString::number(pageNumber);
// if has center coordinates, save them on string
if (rePos.enabled) {
s += QStringLiteral(";C2:") + QString::number(rePos.normalizedX) + QLatin1Char(':') + QString::number(rePos.normalizedY) + QLatin1Char(':') + QString::number(rePos.pos);
}
// if has autofit enabled, save its state on string
if (autoFit.enabled) {
s += QStringLiteral(";AF1:") + (autoFit.width ? QLatin1Char('T') : QLatin1Char('F')) + QLatin1Char(':') + (autoFit.height ? QLatin1Char('T') : QLatin1Char('F'));
}
return s;
}
bool DocumentViewport::isValid() const
{
return pageNumber >= 0;
}
bool DocumentViewport::operator==(const DocumentViewport &other) const
{
bool equal = (pageNumber == other.pageNumber) && (rePos.enabled == other.rePos.enabled) && (autoFit.enabled == other.autoFit.enabled);
if (!equal) {
return false;
}
if (rePos.enabled && ((rePos.normalizedX != other.rePos.normalizedX) || (rePos.normalizedY != other.rePos.normalizedY) || rePos.pos != other.rePos.pos)) {
return false;
}
if (autoFit.enabled && ((autoFit.width != other.autoFit.width) || (autoFit.height != other.autoFit.height))) {
return false;
}
return true;
}
bool DocumentViewport::operator<(const DocumentViewport &other) const
{
// TODO: Check autoFit and Position
if (pageNumber != other.pageNumber) {
return pageNumber < other.pageNumber;
}
if (!rePos.enabled && other.rePos.enabled) {
return true;
}
if (!other.rePos.enabled) {
return false;
}
if (rePos.normalizedY != other.rePos.normalizedY) {
return rePos.normalizedY < other.rePos.normalizedY;
}
return rePos.normalizedX < other.rePos.normalizedX;
}
/** DocumentInfo **/
DocumentInfo::DocumentInfo()
: d(new DocumentInfoPrivate())
{
}
DocumentInfo::DocumentInfo(const DocumentInfo &info)
: d(new DocumentInfoPrivate())
{
*this = info;
}
DocumentInfo &DocumentInfo::operator=(const DocumentInfo &info)
{
if (this != &info) {
d->values = info.d->values;
d->titles = info.d->titles;
}
return *this;
}
DocumentInfo::~DocumentInfo()
{
delete d;
}
void DocumentInfo::set(const QString &key, const QString &value, const QString &title)
{
d->values[key] = value;
d->titles[key] = title;
}
void DocumentInfo::set(Key key, const QString &value)
{
d->values[getKeyString(key)] = value;
}
QStringList DocumentInfo::keys() const
{
return d->values.keys();
}
QString DocumentInfo::get(Key key) const
{
return get(getKeyString(key));
}
QString DocumentInfo::get(const QString &key) const
{
return d->values[key];
}
QString DocumentInfo::getKeyString(Key key) // const
{
switch (key) {
case Title:
return QStringLiteral("title");
break;
case Subject:
return QStringLiteral("subject");
break;
case Description:
return QStringLiteral("description");
break;
case Author:
return QStringLiteral("author");
break;
case Creator:
return QStringLiteral("creator");
break;
case Producer:
return QStringLiteral("producer");
break;
case Copyright:
return QStringLiteral("copyright");
break;
case Pages:
return QStringLiteral("pages");
break;
case CreationDate:
return QStringLiteral("creationDate");
break;
case ModificationDate:
return QStringLiteral("modificationDate");
break;
case MimeType:
return QStringLiteral("mimeType");
break;
case Category:
return QStringLiteral("category");
break;
case Keywords:
return QStringLiteral("keywords");
break;
case FilePath:
return QStringLiteral("filePath");
break;
case DocumentSize:
return QStringLiteral("documentSize");
break;
case PagesSize:
return QStringLiteral("pageSize");
break;
default:
qCWarning(OkularCoreDebug) << "Unknown" << key;
return QString();
break;
}
}
DocumentInfo::Key DocumentInfo::getKeyFromString(const QString &key) // const
{
if (key == QLatin1String("title")) {
return Title;
} else if (key == QLatin1String("subject")) {
return Subject;
} else if (key == QLatin1String("description")) {
return Description;
} else if (key == QLatin1String("author")) {
return Author;
} else if (key == QLatin1String("creator")) {
return Creator;
} else if (key == QLatin1String("producer")) {
return Producer;
} else if (key == QLatin1String("copyright")) {
return Copyright;
} else if (key == QLatin1String("pages")) {
return Pages;
} else if (key == QLatin1String("creationDate")) {
return CreationDate;
} else if (key == QLatin1String("modificationDate")) {
return ModificationDate;
} else if (key == QLatin1String("mimeType")) {
return MimeType;
} else if (key == QLatin1String("category")) {
return Category;
} else if (key == QLatin1String("keywords")) {
return Keywords;
} else if (key == QLatin1String("filePath")) {
return FilePath;
} else if (key == QLatin1String("documentSize")) {
return DocumentSize;
} else if (key == QLatin1String("pageSize")) {
return PagesSize;
} else {
return Invalid;
}
}
QString DocumentInfo::getKeyTitle(Key key) // const
{
switch (key) {
case Title:
return i18n("Title");
break;
case Subject:
return i18n("Subject");
break;
case Description:
return i18n("Description");
break;
case Author:
return i18n("Author");
break;
case Creator:
return i18n("Creator");
break;
case Producer:
return i18n("Producer");
break;
case Copyright:
return i18n("Copyright");
break;
case Pages:
return i18n("Pages");
break;
case CreationDate:
return i18n("Created");
break;
case ModificationDate:
return i18n("Modified");
break;
case MimeType:
return i18n("MIME Type");
break;
case Category:
return i18n("Category");
break;
case Keywords:
return i18n("Keywords");
break;
case FilePath:
return i18n("File Path");
break;
case DocumentSize:
return i18n("File Size");
break;
case PagesSize:
return i18n("Page Size");
break;
default:
return QString();
break;
}
}
QString DocumentInfo::getKeyTitle(const QString &key) const
{
QString title = getKeyTitle(getKeyFromString(key));
if (title.isEmpty()) {
title = d->titles[key];
}
return title;
}
/** DocumentSynopsis **/
DocumentSynopsis::DocumentSynopsis()
: QDomDocument(QStringLiteral("DocumentSynopsis"))
{
// void implementation, only subclassed for naming
}
DocumentSynopsis::DocumentSynopsis(const QDomDocument &document)
: QDomDocument(document)
{
}
/** EmbeddedFile **/
EmbeddedFile::EmbeddedFile()
{
}
EmbeddedFile::~EmbeddedFile()
{
}
VisiblePageRect::VisiblePageRect(int page, const NormalizedRect &rectangle)
: pageNumber(page)
, rect(rectangle)
{
}
/** NewSignatureData **/
struct Okular::NewSignatureDataPrivate {
NewSignatureDataPrivate() = default;
QString certNickname;
QString certSubjectCommonName;
QString password;
QString documentPassword;
QString location;
QString reason;
QString backgroundImagePath;
double fontSize = 10;
double leftFontSize = 20;
int page = -1;
NormalizedRect boundingRectangle;
};
NewSignatureData::NewSignatureData()
: d(new NewSignatureDataPrivate())
{
}
NewSignatureData::~NewSignatureData()
{
delete d;
}
QString NewSignatureData::certNickname() const
{
return d->certNickname;
}
void NewSignatureData::setCertNickname(const QString &certNickname)
{
d->certNickname = certNickname;
}
QString NewSignatureData::certSubjectCommonName() const
{
return d->certSubjectCommonName;
}
void NewSignatureData::setCertSubjectCommonName(const QString &certSubjectCommonName)
{
d->certSubjectCommonName = certSubjectCommonName;
}
QString NewSignatureData::password() const
{
return d->password;
}
void NewSignatureData::setPassword(const QString &password)
{
d->password = password;
}
int NewSignatureData::page() const
{
return d->page;
}
void NewSignatureData::setPage(int page)
{
d->page = page;
}
NormalizedRect NewSignatureData::boundingRectangle() const
{
return d->boundingRectangle;
}
void NewSignatureData::setBoundingRectangle(const NormalizedRect &rect)
{
d->boundingRectangle = rect;
}
QString NewSignatureData::documentPassword() const
{
return d->documentPassword;
}
void NewSignatureData::setDocumentPassword(const QString &password)
{
d->documentPassword = password;
}
QString NewSignatureData::location() const
{
return d->location;
}
void NewSignatureData::setLocation(const QString &location)
{
d->location = location;
}
QString NewSignatureData::reason() const
{
return d->reason;
}
void NewSignatureData::setReason(const QString &reason)
{
d->reason = reason;
}
QString Okular::NewSignatureData::backgroundImagePath() const
{
return d->backgroundImagePath;
}
void Okular::NewSignatureData::setBackgroundImagePath(const QString &path)
{
d->backgroundImagePath = path;
}
double Okular::NewSignatureData::fontSize() const
{
return d->fontSize;
}
void Okular::NewSignatureData::setFontSize(double fontSize)
{
d->fontSize = fontSize;
}
double Okular::NewSignatureData::leftFontSize() const
{
return d->leftFontSize;
}
void Okular::NewSignatureData::setLeftFontSize(double fontSize)
{
d->leftFontSize = fontSize;
}
#undef foreachObserver
#undef foreachObserverD
#include "document.moc"
/* kate: replace-tabs on; indent-width 4; */
|