File: document.cpp

package info (click to toggle)
okular 4%3A4.14.2-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 7,584 kB
  • ctags: 7,898
  • sloc: cpp: 73,406; ansic: 3,964; xml: 57; sh: 42; makefile: 7
file content (4840 lines) | stat: -rw-r--r-- 171,133 bytes parent folder | download
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
/***************************************************************************
 *   Copyright (C) 2004-2005 by Enrico Ros <eros.kde@email.it>             *
 *   Copyright (C) 2004-2008 by Albert Astals Cid <aacid@kde.org>          *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 ***************************************************************************/

#include "document.h"
#include "document_p.h"
#include "documentcommands_p.h"

#include <limits.h>
#ifdef Q_OS_WIN
#define _WIN32_WINNT 0x0500
#include <windows.h>
#elif defined(Q_OS_FREEBSD)
#include <sys/types.h>
#include <sys/sysctl.h>
#include <vm/vm_param.h>
#endif

// qt/kde/system includes
#include <QtCore/QtAlgorithms>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QFileInfo>
#include <QtCore/QMap>
#include <QtCore/QTextStream>
#include <QtCore/QTimer>
#include <QtGui/QApplication>
#include <QtGui/QLabel>
#include <QtGui/QPrinter>
#include <QtGui/QPrintDialog>
#include <QUndoCommand>

#include <kaboutdata.h>
#include <kauthorized.h>
#include <kcomponentdata.h>
#include <kconfigdialog.h>
#include <kdebug.h>
#include <klibloader.h>
#include <klocale.h>
#include <kmacroexpander.h>
#include <kmessagebox.h>
#include <kmimetypetrader.h>
#include <kprocess.h>
#include <krun.h>
#include <kshell.h>
#include <kstandarddirs.h>
#include <ktemporaryfile.h>
#include <ktoolinvocation.h>
#include <kzip.h>

// local includes
#include "action.h"
#include "annotations.h"
#include "annotations_p.h"
#include "audioplayer.h"
#include "audioplayer_p.h"
#include "bookmarkmanager.h"
#include "chooseenginedialog_p.h"
#include "debug_p.h"
#include "generator_p.h"
#include "interfaces/configinterface.h"
#include "interfaces/guiinterface.h"
#include "interfaces/printinterface.h"
#include "interfaces/saveinterface.h"
#include "observer.h"
#include "misc.h"
#include "page.h"
#include "page_p.h"
#include "pagecontroller_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_p.h"
#include "view.h"
#include "view_p.h"
#include "form.h"
#include "utils.h"

#include <memory>

#include <config-okular.h>

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()
    {
    }

    KTemporaryFile document;
    KTemporaryFile 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 ) {\
    QSet< DocumentObserver * >::const_iterator it=d->m_observers.constBegin(), end=d->m_observers.constEnd();\
    for ( ; it != end ; ++ it ) { (*it)-> cmd ; } }

#define foreachObserverD( cmd ) {\
    QSet< DocumentObserver * >::const_iterator it = m_observers.constBegin(), end = m_observers.constEnd();\
    for ( ; it != end ; ++ it ) { (*it)-> cmd ; } }

#define OKULAR_HISTORY_MAXSTEPS 100
#define OKULAR_HISTORY_SAVEDSTEPS 10

/***** Document ******/

QString DocumentPrivate::pagesSizeString() const
{
    if (m_generator)
    {
        if (m_generator->pagesSizeMetric() != Generator::None)
        {
            QSizeF size = m_parent->allPagesSize();
            if (size.isValid()) return localizedSize(size);
            else return QString();
        }
        else return QString();
    }
    else return QString();
}

QString DocumentPrivate::namePaperSize(double inchesWidth, double inchesHeight) const
{
    // Account for small deviations in paper sizes
    static const double marginFactor = 0.03;
    static const double lowerBoundFactor = 1.0 - marginFactor;
    static const double upperBoundFactor = 1.0 + marginFactor;

    const QPrinter::Orientation orientation = inchesWidth > inchesHeight ? QPrinter::Landscape : QPrinter::Portrait;
    // enforce portrait mode for further tests
    if (inchesWidth > inchesHeight)
        qSwap(inchesWidth, inchesHeight);

    // Use QPrinter to find which of the predefined paper sizes
    // matches best the given paper width and height
    QPrinter dummyPrinter;
    QPrinter::PaperSize paperSize = QPrinter::Custom;
    for (int i = 0; i < (int)QPrinter::NPaperSize; ++i)
    {
        const QPrinter::PaperSize ps = (QPrinter::PaperSize)i;
        dummyPrinter.setPaperSize(ps);
        const QSizeF definedPaperSize = dummyPrinter.paperSize(QPrinter::Inch);

        if (inchesWidth > definedPaperSize.width() * lowerBoundFactor && inchesWidth < definedPaperSize.width() * upperBoundFactor
            && inchesHeight > definedPaperSize.height() * lowerBoundFactor && inchesHeight < definedPaperSize.height() * upperBoundFactor)
        {
            paperSize = ps;
            break;
        }
    }

    // Handle all paper sizes defined in QPrinter,
    // return string depending if paper's orientation is landscape or portrait
    switch (paperSize) {
        case QPrinter::A0:
            return  orientation == QPrinter::Landscape ? i18nc("paper size", "landscape DIN/ISO A0") : i18nc("paper size", "portrait DIN/ISO A0");
        case QPrinter::A1:
            return  orientation == QPrinter::Landscape ? i18nc("paper size", "landscape DIN/ISO A1") : i18nc("paper size", "portrait DIN/ISO A1");
        case QPrinter::A2:
            return  orientation == QPrinter::Landscape ? i18nc("paper size", "landscape DIN/ISO A2") : i18nc("paper size", "portrait DIN/ISO A2");
        case QPrinter::A3:
            return  orientation == QPrinter::Landscape ? i18nc("paper size", "landscape DIN/ISO A3") : i18nc("paper size", "portrait DIN/ISO A3");
        case QPrinter::A4:
            return  orientation == QPrinter::Landscape ? i18nc("paper size", "landscape DIN/ISO A4") : i18nc("paper size", "portrait DIN/ISO A4");
        case QPrinter::A5:
            return  orientation == QPrinter::Landscape ? i18nc("paper size", "landscape DIN/ISO A5") : i18nc("paper size", "portrait DIN/ISO A5");
        case QPrinter::A6:
            return  orientation == QPrinter::Landscape ? i18nc("paper size", "landscape DIN/ISO A6") : i18nc("paper size", "portrait DIN/ISO A6");
        case QPrinter::A7:
            return  orientation == QPrinter::Landscape ? i18nc("paper size", "landscape DIN/ISO A7") : i18nc("paper size", "portrait DIN/ISO A7");
        case QPrinter::A8:
            return  orientation == QPrinter::Landscape ? i18nc("paper size", "landscape DIN/ISO A8") : i18nc("paper size", "portrait DIN/ISO A8");
        case QPrinter::A9:
            return  orientation == QPrinter::Landscape ? i18nc("paper size", "landscape DIN/ISO A9") : i18nc("paper size", "portrait DIN/ISO A9");
        case QPrinter::B0:
            return  orientation == QPrinter::Landscape ? i18nc("paper size", "landscape DIN/ISO B0") : i18nc("paper size", "portrait DIN/ISO B0");
        case QPrinter::B1:
            return  orientation == QPrinter::Landscape ? i18nc("paper size", "landscape DIN/ISO B1") : i18nc("paper size", "portrait DIN/ISO B1");
        case QPrinter::B2:
            return  orientation == QPrinter::Landscape ? i18nc("paper size", "landscape DIN/ISO B2") : i18nc("paper size", "portrait DIN/ISO B2");
        case QPrinter::B3:
            return  orientation == QPrinter::Landscape ? i18nc("paper size", "landscape DIN/ISO B3") : i18nc("paper size", "portrait DIN/ISO B3");
        case QPrinter::B4:
            return  orientation == QPrinter::Landscape ? i18nc("paper size", "landscape DIN/ISO B4") : i18nc("paper size", "portrait DIN/ISO B4");
        case QPrinter::B5:
            return  orientation == QPrinter::Landscape ? i18nc("paper size", "landscape DIN/ISO B5") : i18nc("paper size", "portrait DIN/ISO B5");
        case QPrinter::B6:
            return  orientation == QPrinter::Landscape ? i18nc("paper size", "landscape DIN/ISO B6") : i18nc("paper size", "portrait DIN/ISO B6");
        case QPrinter::B7:
            return  orientation == QPrinter::Landscape ? i18nc("paper size", "landscape DIN/ISO B7") : i18nc("paper size", "portrait DIN/ISO B7");
        case QPrinter::B8:
            return  orientation == QPrinter::Landscape ? i18nc("paper size", "landscape DIN/ISO B8") : i18nc("paper size", "portrait DIN/ISO B8");
        case QPrinter::B9:
            return  orientation == QPrinter::Landscape ? i18nc("paper size", "landscape DIN/ISO B9") : i18nc("paper size", "portrait DIN/ISO B9");
        case QPrinter::B10:
            return  orientation == QPrinter::Landscape ? i18nc("paper size", "landscape DIN/ISO B10") : i18nc("paper size", "portrait DIN/ISO B10");
        case QPrinter::Letter:
            return  orientation == QPrinter::Landscape ? i18nc("paper size", "landscape letter") : i18nc("paper size", "portrait letter");
        case QPrinter::Legal:
            return  orientation == QPrinter::Landscape ? i18nc("paper size", "landscape legal") : i18nc("paper size", "portrait legal");
        case QPrinter::Executive:
            return  orientation == QPrinter::Landscape ? i18nc("paper size", "landscape executive") : i18nc("paper size", "portrait executive");
        case QPrinter::C5E:
            return  orientation == QPrinter::Landscape ? i18nc("paper size", "landscape C5E") : i18nc("paper size", "portrait C5E");
        case QPrinter::Comm10E:
            return  orientation == QPrinter::Landscape ? i18nc("paper size", "landscape Comm10E") : i18nc("paper size", "portrait Comm10E");
        case QPrinter::DLE:
            return  orientation == QPrinter::Landscape ? i18nc("paper size", "landscape DLE") : i18nc("paper size", "portrait DLE");
        case QPrinter::Folio:
            return  orientation == QPrinter::Landscape ? i18nc("paper size", "landscape folio") : i18nc("paper size", "portrait folio");
        case QPrinter::Tabloid:
        case QPrinter::Ledger:
            /// Ledger and Tabloid are the same, just rotated by 90 degrees
            return  orientation == QPrinter::Landscape ? i18nc("paper size", "ledger") : i18nc("paper size", "tabloid");
        case QPrinter::Custom:
            return orientation == QPrinter::Landscape ? i18nc("paper size", "unknown landscape paper size") : i18nc("paper size", "unknown portrait paper size");
    }

    kWarning() << "PaperSize" << paperSize << "has not been covered";
    return QString();
}

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 (KGlobal::locale()->measureSystem() == KLocale::Imperial)
    {
        return i18nc("%1 is width, %2 is height, %3 is paper size name", "%1 x %2 in (%3)", inchesWidth, inchesHeight, namePaperSize(inchesWidth, inchesHeight));
    }
    else
    {
        return i18nc("%1 is width, %2 is height, %3 is paper size name", "%1 x %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;
    QVector< Okular::VisiblePageRect * >::const_iterator vIt = m_pageRects.constBegin(), vEnd = m_pageRects.constEnd();
    for ( ; vIt != vEnd; ++vIt )
        visibleRects.insert( (*vIt)->pageNumber, (*vIt) );

    // 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;

        kDebug().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

    QLinkedList< AllocatedPixmap * > pixmapsToKeep;
    while (memoryToFree > 0)
    {
        int clean_hits = 0;
        foreach (DocumentObserver *observer, 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.append( p );
                else
                    delete p;
            }
            else
                pixmapsToKeep.append( p );
        }

        if (clean_hits == 0) break;
    }

    m_allocatedPixmaps += pixmapsToKeep;
    //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 )
{
    QLinkedList< AllocatedPixmap * >::iterator pIt = m_allocatedPixmaps.begin();
    QLinkedList< AllocatedPixmap * >::iterator pEnd = m_allocatedPixmaps.end();
    QLinkedList< AllocatedPixmap * >::iterator 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 == 0 || 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 0;

    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( "/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( "MemTotal:" ) )
            return (cachedValue = (Q_UINT64_C(1024) * entry.section( ' ', -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 QTime lastUpdate = QTime::currentTime().addSecs(-3);
    static qulonglong cachedValue = 0;
    static qulonglong cachedFreeSwap = 0;

    if ( qAbs( lastUpdate.secsTo( QTime::currentTime() ) ) <= 2 )
    {
        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( "/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;
    QString names[nElems] = { "MemFree:", "Buffers:", "Cached:", "SwapFree:", "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( ' ', -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;
    }

    lastUpdate = QTime::currentTime();

    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 )
    {
        lastUpdate = QTime::currentTime();
        return (cachedValue = (cache + inact + free) * psize);
    }
    else
    {
        return 0;
    }
#elif defined(Q_OS_WIN)
    MEMORYSTATUSEX stat;
    stat.dwLength = sizeof(stat);
    GlobalMemoryStatusEx (&stat);

    lastUpdate = QTime::currentTime();

    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
}

void DocumentPrivate::loadDocumentInfo()
// note: load data and stores it internally (document or pages). observers
// are still uninitialized at this point so don't access them
{
    //kDebug(OkularDebug).nospace() << "Using '" << d->m_xmlFileName << "' as document info file.";
    if ( m_xmlFileName.isEmpty() )
        return;

    QFile infoFile( m_xmlFileName );
    loadDocumentInfo( infoFile );
}

void DocumentPrivate::loadDocumentInfo( QFile &infoFile )
{
    if ( !infoFile.exists() || !infoFile.open( QIODevice::ReadOnly ) )
        return;

    // Load DOM from XML file
    QDomDocument doc( "documentInfo" );
    if ( !doc.setContent( &infoFile ) )
    {
        kDebug(OkularDebug) << "Can't load XML pair! Check for broken xml.";
        infoFile.close();
        return;
    }
    infoFile.close();

    QDomElement root = doc.documentElement();
    if ( root.tagName() != "documentInfo" )
        return;

    KUrl documentUrl( root.attribute( "url" ) );

    // 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 == "pageList" )
        {
            QDomNode pageNode = topLevelNode.firstChild();
            while ( pageNode.isElement() )
            {
                QDomElement pageElement = pageNode.toElement();
                if ( pageElement.hasAttribute( "number" ) )
                {
                    // get page number (node's attribute)
                    bool ok;
                    int pageNumber = pageElement.attribute( "number" ).toInt( &ok );

                    // pass the domElement to the right page, to read config data from
                    if ( ok && pageNumber >= 0 && pageNumber < (int)m_pagesVector.count() )
                        m_pagesVector[ pageNumber ]->d->restoreLocalContents( pageElement );
                }
                pageNode = pageNode.nextSibling();
            }
        }

        // Restore 'general info' from the DOM
        else if ( catName == "generalInfo" )
        {
            QDomNode infoNode = topLevelNode.firstChild();
            while ( infoNode.isElement() )
            {
                QDomElement infoElement = infoNode.toElement();

                // restore viewports history
                if ( infoElement.tagName() == "history" )
                {
                    // clear history
                    m_viewportHistory.clear();
                    // append old viewports
                    QDomNode historyNode = infoNode.firstChild();
                    while ( historyNode.isElement() )
                    {
                        QDomElement historyElement = historyNode.toElement();
                        if ( historyElement.hasAttribute( "viewport" ) )
                        {
                            QString vpString = historyElement.attribute( "viewport" );
                            m_viewportIterator = m_viewportHistory.insert( m_viewportHistory.end(),
                                    DocumentViewport( vpString ) );
                        }
                        historyNode = historyNode.nextSibling();
                    }
                    // consistancy check
                    if ( m_viewportHistory.isEmpty() )
                        m_viewportIterator = m_viewportHistory.insert( m_viewportHistory.end(), DocumentViewport() );
                }
                else if ( infoElement.tagName() == "rotation" )
                {
                    QString str = infoElement.text();
                    bool ok = true;
                    int newrotation = !str.isEmpty() ? ( str.toInt( &ok ) % 4 ) : 0;
                    if ( ok && newrotation != 0 )
                    {
                        setRotationInternal( newrotation, false );
                    }
                }
                else if ( infoElement.tagName() == "views" )
                {
                    QDomNode viewNode = infoNode.firstChild();
                    while ( viewNode.isElement() )
                    {
                        QDomElement viewElement = viewNode.toElement();
                        if ( viewElement.tagName() == "view" )
                        {
                            const QString viewName = viewElement.attribute( "name" );
                            Q_FOREACH ( View * view, m_views )
                            {
                                if ( view->name() == viewName )
                                {
                                    loadViewsInfo( view, viewElement );
                                    break;
                                }
                            }
                        }
                        viewNode = viewNode.nextSibling();
                    }
                }
                infoNode = infoNode.nextSibling();
            }
        }

        topLevelNode = topLevelNode.nextSibling();
    } // </documentInfo>
}

void DocumentPrivate::loadViewsInfo( View *view, const QDomElement &e )
{
    QDomNode viewNode = e.firstChild();
    while ( viewNode.isElement() )
    {
        QDomElement viewElement = viewNode.toElement();

        if ( viewElement.tagName() == "zoom" )
        {
            const QString valueString = viewElement.attribute( "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( "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 );
            }
        }

        viewNode = viewNode.nextSibling();
    }
}

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( "zoom" );
        e.appendChild( zoomEl );
        bool ok = true;
        const double zoom = view->capability( View::Zoom ).toDouble( &ok );
        if ( ok && zoom != 0 )
        {
            zoomEl.setAttribute( "value", QString::number(zoom) );
        }
        const int mode = view->capability( View::ZoomModality ).toInt( &ok );
        if ( ok )
        {
            zoomEl.setAttribute( "mode", mode );
        }
    }
}

QString DocumentPrivate::giveAbsolutePath( const QString & fileName ) const
{
    if ( !QDir::isRelativePath( fileName ) )
        return fileName;

    if ( !m_url.isValid() )
        return QString();

    return m_url.upUrl().url() + fileName;
}

bool DocumentPrivate::openRelativeFile( const QString & fileName )
{
    QString absFileName = giveAbsolutePath( fileName );
    if ( absFileName.isEmpty() )
        return false;

    kDebug(OkularDebug).nospace() << "openDocument: '" << absFileName << "'";

    emit m_parent->openUrl( absFileName );
    return true;
}

Generator * DocumentPrivate::loadGeneratorLibrary( const KService::Ptr &service )
{
    KPluginFactory *factory = KPluginLoader( service->library() ).factory();
    if ( !factory )
    {
        kWarning(OkularDebug).nospace() << "Invalid plugin factory for " << service->library() << "!";
        return 0;
    }
    Generator * generator = factory->create< Okular::Generator >( service->pluginKeyword(), 0 );
    GeneratorInfo info( factory->componentData() );
    info.generator = generator;
    if ( info.data.isValid() && info.data.aboutData() )
        info.catalogName = info.data.aboutData()->catalogName();
    m_loadedGenerators.insert( service->name(), info );
    return generator;
}

void DocumentPrivate::loadAllGeneratorLibraries()
{
    if ( m_generatorsLoaded )
        return;

    m_generatorsLoaded = true;

    QString constraint("([X-KDE-Priority] > 0) and (exist Library)") ;
    KService::List offers = KServiceTypeTrader::self()->query( "okular/Generator", constraint );
    loadServiceList( offers );
}

void DocumentPrivate::loadServiceList( const KService::List& offers )
{
    int count = offers.count();
    if ( count <= 0 )
        return;

    for ( int i = 0; i < count; ++i )
    {
        QString propName = offers.at(i)->name();
        // don't load already loaded generators
        QHash< QString, GeneratorInfo >::const_iterator genIt = m_loadedGenerators.constFind( propName );
        if ( !m_loadedGenerators.isEmpty() && genIt != m_loadedGenerators.constEnd() )
            continue;

        Generator * g = loadGeneratorLibrary( offers.at(i) );
        (void)g;
    }
}

void DocumentPrivate::unloadGenerator( const GeneratorInfo& info )
{
    delete info.generator;
}

void DocumentPrivate::cacheExportFormats()
{
    if ( m_exportCached )
        return;

    const ExportFormat::List formats = m_generator->exportFormats();
    for ( int i = 0; i < formats.count(); ++i )
    {
        if ( formats.at( i ).mimeType()->name() == QLatin1String( "text/plain" ) )
            m_exportToText = formats.at( i );
        else
            m_exportFormats.append( formats.at( i ) );
    }

    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 KService::Ptr& offer, bool isstdin, const QString& docFile, const QByteArray& filedata, const QString& password )
{
    QString propName = offer->name();
    QHash< QString, GeneratorInfo >::const_iterator genIt = m_loadedGenerators.constFind( propName );
    QString catalogName;
    if ( genIt != m_loadedGenerators.constEnd() )
    {
        m_generator = genIt.value().generator;
        catalogName = genIt.value().catalogName;
    }
    else
    {
        m_generator = loadGeneratorLibrary( offer );
        if ( !m_generator )
            return Document::OpenError;
        genIt = m_loadedGenerators.constFind( propName );
        Q_ASSERT( genIt != m_loadedGenerators.constEnd() );
        catalogName = genIt.value().catalogName;
    }
    Q_ASSERT_X( m_generator, "Document::load()", "null generator?!" );

    if ( !catalogName.isEmpty() )
        KGlobal::locale()->insertCatalog( catalogName );

    m_generator->d_func()->m_document = this;

    // connect error reporting signals
    QObject::connect( m_generator, SIGNAL(error(QString,int)), m_parent, SIGNAL(error(QString,int)) );
    QObject::connect( m_generator, SIGNAL(warning(QString,int)), m_parent, SIGNAL(warning(QString,int)) );
    QObject::connect( m_generator, SIGNAL(notice(QString,int)), m_parent, SIGNAL(notice(QString,int)) );

    QApplication::setOverrideCursor( Qt::WaitCursor );

    const QSizeF dpi = Utils::realDpi(m_widget);
    kDebug() << "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 KTemporaryFile();
            if ( !m_tempFile->open() )
            {
                delete m_tempFile;
                m_tempFile = 0;
            }
            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 )
    {
        if ( !catalogName.isEmpty() )
            KGlobal::locale()->removeCatalog( catalogName );

        m_generator->d_func()->m_document = 0;
        QObject::disconnect( m_generator, 0, m_parent, 0 );
        m_generator = 0;

        qDeleteAll( m_pagesVector );
        m_pagesVector.clear();
        delete m_tempFile;
        m_tempFile = 0;

        // TODO: emit a message telling the document is empty
        if ( openResult == Document::OpenSuccess )
            openResult = Document::OpenError;
    }

    return openResult;
}

bool DocumentPrivate::savePageDocumentInfo( KTemporaryFile *infoFile, int what ) const
{
    if ( infoFile->open() )
    {
        // 1. Create DOM
        QDomDocument doc( "documentInfo" );
        QDomProcessingInstruction xmlPi = doc.createProcessingInstruction(
                QString::fromLatin1( "xml" ), QString::fromLatin1( "version=\"1.0\" encoding=\"utf-8\"" ) );
        doc.appendChild( xmlPi );
        QDomElement root = doc.createElement( "documentInfo" );
        doc.appendChild( root );

        // 2.1. Save page attributes (bookmark state, annotations, ... ) to DOM
        QDomElement pageList = doc.createElement( "pageList" );
        root.appendChild( pageList );
        // <page list><page number='x'>.... </page> save pages that hold data
        QVector< Page * >::const_iterator pIt = m_pagesVector.constBegin(), pEnd = m_pagesVector.constEnd();
        for ( ; pIt != pEnd; ++pIt )
            (*pIt)->d->saveLocalContents( pageList, doc, PageItems( what ) );

        // 3. Save DOM to XML file
        QString xml = doc.toString();
        QTextStream os( infoFile );
        os.setCodec( "UTF-8" );
        os << xml;
        return true;
    }
    return false;
}

DocumentViewport DocumentPrivate::nextDocumentViewport() const
{
    DocumentViewport ret = m_nextDocumentViewport;
    if ( !m_nextDocumentDestination.isEmpty() && m_generator )
    {
        DocumentViewport vp( m_generator->metaData( "NamedViewport", m_nextDocumentDestination ).toString() );
        if ( vp.isValid() )
        {
            ret = vp;
        }
    }
    return ret;
}

void DocumentPrivate::warnLimitedAnnotSupport()
{
    if ( !m_showWarningLimitedAnnotSupport )
        return;
    m_showWarningLimitedAnnotSupport = false; // Show the warning once

    if ( m_annotationsNeedSaveAs )
    {
        // Shown if the user is editing annotations in a file whose metadata is
        // not stored locally (.okular archives belong to this category)
        KMessageBox::information( m_widget, i18n("Your annotation changes will not be saved automatically. Use File -> Save As...\nor your changes will be lost once the document is closed"), QString(), "annotNeedSaveAs" );
    }
    else if ( !canAddAnnotationsNatively() )
    {
        // If the generator doesn't support native annotations
        KMessageBox::information( m_widget, i18n("Your annotations are saved internally by Okular.\nYou can export the annotated document using File -> Export As -> Document Archive"), QString(), "annotExportAsArchive" );
    }
}

void DocumentPrivate::performAddPageAnnotation( int page, Annotation * annotation )
{
    Okular::SaveInterface * iface = qobject_cast< Okular::SaveInterface * >( m_generator );
    AnnotationProxy *proxy = iface ? iface->annotationProxy() : 0;

    // 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 );
    }

    warnLimitedAnnotSupport();
}

void DocumentPrivate::performRemovePageAnnotation( int page, Annotation * annotation )
{
    Okular::SaveInterface * iface = qobject_cast< Okular::SaveInterface * >( m_generator );
    AnnotationProxy *proxy = iface ? iface->annotationProxy() : 0;
    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 );
        }
    }

    warnLimitedAnnotSupport();
}

void DocumentPrivate::performModifyPageAnnotation( int page, Annotation * annotation, bool appearanceChanged )
{
    Okular::SaveInterface * iface = qobject_cast< Okular::SaveInterface * >( m_generator );
    AnnotationProxy *proxy = iface ? iface->annotationProxy() : 0;

    // find out the page
    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 )
        {
            if ( m_annotationBeingMoved )
                return;
            else // First time: take note
                m_annotationBeingMoved = true;
        }
        else
        {
            m_annotationBeingMoved = false;
        }

        // Redraw everything, including ExternallyDrawn annotations
        kDebug(OkularDebug) << "Refreshing Pixmaps";
        refreshPixmaps( page );
    }

    // If the user is moving the annotation, don't steal the focus
    if ( (annotation->flags() & Annotation::BeingMoved) == 0 )
        warnLimitedAnnotSupport();
}

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:
        {
            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:
        {
            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::saveDocumentInfo() const
{
    if ( m_xmlFileName.isEmpty() )
        return;

    QFile infoFile( m_xmlFileName );
    if (infoFile.open( QIODevice::WriteOnly | QIODevice::Truncate) )
    {
        // 1. Create DOM
        QDomDocument doc( "documentInfo" );
        QDomProcessingInstruction xmlPi = doc.createProcessingInstruction(
                QString::fromLatin1( "xml" ), QString::fromLatin1( "version=\"1.0\" encoding=\"utf-8\"" ) );
        doc.appendChild( xmlPi );
        QDomElement root = doc.createElement( "documentInfo" );
        root.setAttribute( "url", m_url.pathOrUrl() );
        doc.appendChild( root );

        // 2.1. Save page attributes (bookmark state, annotations, ... ) to DOM
        QDomElement pageList = doc.createElement( "pageList" );
        root.appendChild( pageList );
        PageItems saveWhat = AllPageItems;
        if ( m_annotationsNeedSaveAs )
        {
            /* In this case, if the user makes a modification, he's requested to
             * save to a new document. Therefore, if there are existing local
             * annotations, we save them back unmodified in the original
             * document's metadata, so that it appears that it was not changed */
            saveWhat |= OriginalAnnotationPageItems;
        }
        // <page list><page number='x'>.... </page> save pages that hold data
        QVector< Page * >::const_iterator pIt = m_pagesVector.constBegin(), pEnd = m_pagesVector.constEnd();
        for ( ; pIt != pEnd; ++pIt )
            (*pIt)->d->saveLocalContents( pageList, doc, saveWhat );

        // 2.2. Save document info (current viewport, history, ... ) to DOM
        QDomElement generalInfo = doc.createElement( "generalInfo" );
        root.appendChild( generalInfo );
        // create rotation node
        if ( m_rotation != Rotation0 )
        {
            QDomElement rotationNode = doc.createElement( "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
        QLinkedList< DocumentViewport >::const_iterator backIterator = m_viewportIterator;
        if ( backIterator != m_viewportHistory.constEnd() )
        {
            // go back up to OKULAR_HISTORY_SAVEDSTEPS steps from the current viewportIterator
            int backSteps = OKULAR_HISTORY_SAVEDSTEPS;
            while ( backSteps-- && backIterator != m_viewportHistory.constBegin() )
                --backIterator;

            // create history root node
            QDomElement historyNode = doc.createElement( "history" );
            generalInfo.appendChild( historyNode );

            // add old[backIterator] and present[viewportIterator] items
            QLinkedList< DocumentViewport >::const_iterator endIt = m_viewportIterator;
            ++endIt;
            while ( backIterator != endIt )
            {
                QString name = (backIterator == m_viewportIterator) ? "current" : "oldPage";
                QDomElement historyEntry = doc.createElement( name );
                historyEntry.setAttribute( "viewport", (*backIterator).toString() );
                historyNode.appendChild( historyEntry );
                ++backIterator;
            }
        }
        // create views root node
        QDomElement viewsNode = doc.createElement( "views" );
        generalInfo.appendChild( viewsNode );
        Q_FOREACH ( View * view, m_views )
        {
            QDomElement viewEntry = doc.createElement( "view" );
            viewEntry.setAttribute( "name", view->name() );
            viewsNode.appendChild( viewEntry );
            saveViewsInfo( view, viewEntry );
        }

        // 3. Save DOM to XML file
        QString xml = doc.toString();
        QTextStream os( &infoFile );
        os.setCodec( "UTF-8" );
        os << xml;
    }
    infoFile.close();
}

void DocumentPrivate::slotTimedMemoryCheck()
{
    // [MEM] clean memory (for 'free mem dependant' 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 )
    {
        AllocatedPixmap *pixmapToReplace = searchLowestPriorityPixmap( true );
        if ( pixmapToReplace )
            maxDistance = qAbs( pixmapToReplace->page - currentViewportPage );
    }

    // find a request
    PixmapRequest * request = 0;
    m_pixmapRequestsMutex.lock();
    while ( !m_pixmapRequestsStack.isEmpty() && !request )
    {
        PixmapRequest * r = m_pixmapRequestsStack.last();
        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();

        // 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
        // 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();
            //kDebug() << "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 8000000 pixels, switch on the tile manager
        else if ( !tilesManager && m_generator->hasFeature( Generator::TiledRendering ) && (long)r->width() * (long)r->height() > 8000000L )
        {
            // if the image is too big. start using tiles
            kDebug(OkularDebug).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 ) );
                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 QList<Tile> tiles = tilesManager->tilesAt( r->normalizedRect(), TilesManager::TerminalTile );
                QList<Tile>::const_iterator tIt = tiles.constBegin(), tEnd = tiles.constEnd();
                while ( tIt != tEnd )
                {
                    Tile tile = *tIt;
                    if ( tilesRect.isNull() )
                        tilesRect = tile.rect();
                    else
                        tilesRect |= tile.rect();

                    ++tIt;
                }

                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 6000000 pixels, switch off the tile manager
        else if ( tilesManager && (long)r->width() * (long)r->height() < 6000000L )
        {
            kDebug(OkularDebug).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() > 20000000L )
        {
            m_pixmapRequestsStack.pop_back();
            if ( !m_warnedOutOfMemory )
            {
                kWarning(OkularDebug).nospace() << "Running out of memory on page " << r->pageNumber()
                    << " (" << r->width() << "x" << r->height() << " px);";
                kWarning(OkularDebug) << "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 * 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() );
        kDebug(OkularDebug).nospace() << "sending request observer=" << request->observer() << " " <<requestRect.width() << "x" << requestRect.height() << "@" << request->pageNumber() << " async == " << request->asynchronous() << " isTile == " << request->isTile();
        m_pixmapRequestsStack.removeAll ( 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 ) );

        // 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, SLOT(sendGeneratorPixmapRequest()) );
    }
}

void DocumentPrivate::rotationFinished( int page, Okular::Page *okularPage )
{
    Okular::Page *wantedPage = m_pagesVector.value( page, 0 );
    if ( !wantedPage || wantedPage != okularPage )
        return;

    foreach(DocumentObserver *o, m_observers)
        o->notifyPageChanged( page, DocumentObserver::Pixmap | DocumentObserver::Annotations );
}

void DocumentPrivate::fontReadingProgress( int page )
{
    emit m_parent->fontReadingProgress( page );

    if ( page >= (int)m_parent->pages() - 1 )
    {
        emit m_parent->fontReadingEnded();
        m_fontThread = 0;
        m_fontsCached = true;
    }
}

void DocumentPrivate::fontReadingGotFont( const Okular::FontInfo& font )
{
    // TODO try to avoid duplicate fonts
    m_fontsCache.append( font );

    emit m_parent->gotFont( font );
}

void DocumentPrivate::slotGeneratorConfigChanged( const QString& )
{
    if ( !m_generator )
        return;

    // reparse generator config and if something changed clear Pages
    bool configchanged = false;
    QHash< QString, GeneratorInfo >::iterator it = m_loadedGenerators.begin(), itEnd = m_loadedGenerators.end();
    for ( ; it != itEnd; ++it )
    {
        Okular::ConfigInterface * iface = generatorConfig( it.value() );
        if ( iface )
        {
            bool it_changed = iface->reparseConfig();
            if ( it_changed && ( m_generator == it.value().generator ) )
                configchanged = true;
        }
    }
    if ( configchanged )
    {
        // invalidate pixmaps
        QVector<Page*>::const_iterator it = m_pagesVector.constBegin(), end = m_pagesVector.constEnd();
        for ( ; it != end; ++it ) {
            (*it)->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.isEmpty() && !m_pagesVector.isEmpty() )
        cleanupPixmapMemory();
}

void DocumentPrivate::refreshPixmaps( int pageNumber )
{
    Page* page = m_pagesVector.value( pageNumber, 0 );
    if ( !page )
        return;

    QLinkedList< Okular::PixmapRequest * > requestedPixmaps;
    QMap< DocumentObserver*, PagePrivate::PixmapObject >::ConstIterator it = page->d->m_pixmaps.constBegin(), itEnd = page->d->m_pixmaps.constEnd();
    for ( ; it != itEnd; ++it )
    {
        QSize size = (*it).m_pixmap->size();
        PixmapRequest * p = new PixmapRequest( it.key(), pageNumber, size.width(), size.height(), 1, PixmapRequest::Asynchronous );
        p->d->mForce = true;
        requestedPixmaps.push_back( p );
    }

    foreach (DocumentObserver *observer, m_observers)
    {
        TilesManager *tilesManager = page->d->tilesManager( observer );
        if ( tilesManager )
        {
            tilesManager->markDirty();

            PixmapRequest * p = new PixmapRequest( observer, pageNumber, tilesManager->width(), tilesManager->height(), 1, PixmapRequest::Asynchronous );

            NormalizedRect tilesRect;

            // Get the visible page rect
            NormalizedRect visibleRect;
            QVector< Okular::VisiblePageRect * >::const_iterator vIt = m_pageRects.constBegin(), vEnd = m_pageRects.constEnd();
            for ( ; vIt != vEnd; ++vIt )
            {
                if ( (*vIt)->pageNumber == pageNumber )
                {
                    visibleRect = (*vIt)->rect;
                    break;
                }
            }

            if ( !visibleRect.isNull() )
            {
                p->setNormalizedRect( visibleRect );
                p->setTile( true );
                p->d->mForce = true;
                requestedPixmaps.push_back( p );
            }
            else
            {
                delete p;
            }
        }
    }

    if ( !requestedPixmaps.isEmpty() )
        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( 0 ); // deletes the textpage
    }
}

void DocumentPrivate::doContinueDirectionMatchSearch(void *doContinueDirectionMatchSearchStruct)
{
    DoContinueDirectionMatchSearchStruct *searchStruct = static_cast<DoContinueDirectionMatchSearchStruct *>(doContinueDirectionMatchSearchStruct);
    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;

        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 )
            {
                doContinue = false;
                search->isCurrentlySearching = false;
                search->continueOnPage = forward ? 0 : pageCount - 1;
                search->continueOnMatch = RegularAreaRect();
                emit m_parent->searchFinished ( searchStruct->searchID, Document::EndOfDocumentReached );
            }
        }
    }

    if (doContinue)
    {
        // get page
        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
        QMetaObject::invokeMethod(m_parent, "doContinueDirectionMatchSearch", Qt::QueuedConnection, Q_ARG(void *, 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( searchID, match, color );

        // ..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, 0, true );
        }
        delete match;
    }

    // notify observers about highlights changes
    foreach(int pageNumber, *pagesToNotify)
        foreach(DocumentObserver *observer, m_observers)
            observer->notifyPageChanged( pageNumber, DocumentObserver::Highlights );

    if (foundAMatch) emit m_parent->searchFinished( searchID, Document::MatchFound );
    else emit m_parent->searchFinished( searchID, Document::NoMatchFound );

    delete pagesToNotify;
}

void DocumentPrivate::doContinueAllDocumentSearch(void *pagesToNotifySet, void *pageMatchesMap, int currentPage, int searchID)
{
    QMap< Page *, QVector<RegularAreaRect *> > *pageMatches = static_cast< QMap< Page *, QVector<RegularAreaRect *> > * >(pageMatchesMap);
    QSet< int > *pagesToNotify = static_cast< QSet< int > * >( pagesToNotifySet );
    RunningSearch *search = m_searches.value(searchID);

    if (m_searchCancelled || !search)
    {
        typedef QVector<RegularAreaRect *> MatchesVector;

        QApplication::restoreOverrideCursor();

        if (search) search->isCurrentlySearching = false;

        emit m_parent->searchFinished( searchID, Document::SearchCancelled );
        foreach(const MatchesVector &mv, *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);
        int pageNumber = page->number(); // redundant? is it == currentPage ?

        // request search page if needed
        if ( !page->hasTextPage() )
            m_parent->requestTextPage( pageNumber );

        // loop on a page adding highlights for all found items
        RegularAreaRect * lastMatch = 0;
        while ( 1 )
        {
            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 highligh rect to the matches map
            (*pageMatches)[page].append(lastMatch);
        }
        delete lastMatch;

        QMetaObject::invokeMethod(m_parent, "doContinueAllDocumentSearch", Qt::QueuedConnection, Q_ARG(void *, pagesToNotifySet), Q_ARG(void *, pageMatches), Q_ARG(int, currentPage + 1), Q_ARG(int, searchID));
    }
    else
    {
        // reset cursor to previous shape
        QApplication::restoreOverrideCursor();

        search->isCurrentlySearching = false;
        bool foundAMatch = pageMatches->count() != 0;
        QMap< Page *, QVector<RegularAreaRect *> >::const_iterator it, itEnd;
        it = pageMatches->constBegin();
        itEnd = pageMatches->constEnd();
        for ( ; it != itEnd; ++it)
        {
            foreach(RegularAreaRect *match, it.value())
            {
                it.key()->d->setHighlight( searchID, match, search->cachedColor );
                delete match;
            }
            search->highlightedPages.insert( it.key()->number() );
            pagesToNotify->insert( it.key()->number() );
        }

        foreach(DocumentObserver *observer, m_observers)
            observer->notifySetup( m_pagesVector, 0 );

        // notify observers about highlights changes
        foreach(int pageNumber, *pagesToNotify)
            foreach(DocumentObserver *observer, m_observers)
                observer->notifyPageChanged( pageNumber, DocumentObserver::Highlights );

        if (foundAMatch) emit m_parent->searchFinished(searchID, Document::MatchFound );
        else emit m_parent->searchFinished( searchID, Document::NoMatchFound );

        delete pageMatches;
        delete pagesToNotify;
    }
}

void DocumentPrivate::doContinueGooglesDocumentSearch(void *pagesToNotifySet, void *pageMatchesMap, int currentPage, int searchID, const QStringList & words)
{
    typedef QPair<RegularAreaRect *, QColor> MatchColor;
    QMap< Page *, QVector<MatchColor> > *pageMatches = static_cast< QMap< Page *, QVector<MatchColor> > * >(pageMatchesMap);
    QSet< int > *pagesToNotify = static_cast< QSet< int > * >( pagesToNotifySet );
    RunningSearch *search = m_searches.value(searchID);

    if (m_searchCancelled || !search)
    {
        typedef QVector<MatchColor> MatchesVector;

        QApplication::restoreOverrideCursor();

        if (search) search->isCurrentlySearching = false;

        emit m_parent->searchFinished( searchID, Document::SearchCancelled );

        foreach(const MatchesVector &mv, *pageMatches)
        {
            foreach(const MatchColor &mc, mv) delete mc.first;
        }
        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);
        int pageNumber = page->number(); // redundant? is it == currentPage ?

        // request search page if needed
        if ( !page->hasTextPage() )
            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 = 0;
            // add all highlights for current word
            bool wordMatched = false;
            while ( 1 )
            {
                if ( lastMatch )
                    lastMatch = page->findText( searchID, word, NextResult, search->cachedCaseSensitivity, lastMatch );
                else
                    lastMatch = page->findText( searchID, word, FromTop, search->cachedCaseSensitivity);

                if ( !lastMatch )
                    break;

                // add highligh 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 )
        {
            QVector<MatchColor> &matches = (*pageMatches)[page];
            foreach(const MatchColor &mc, matches) delete mc.first;
            pageMatches->remove(page);
        }

        QMetaObject::invokeMethod(m_parent, "doContinueGooglesDocumentSearch", Qt::QueuedConnection, Q_ARG(void *, pagesToNotifySet), Q_ARG(void *, pageMatches), Q_ARG(int, currentPage + 1), Q_ARG(int, searchID), Q_ARG(QStringList, words));
    }
    else
    {
        // reset cursor to previous shape
        QApplication::restoreOverrideCursor();

        search->isCurrentlySearching = false;
        bool foundAMatch = pageMatches->count() != 0;
        QMap< Page *, QVector<MatchColor> >::const_iterator it, itEnd;
        it = pageMatches->constBegin();
        itEnd = pageMatches->constEnd();
        for ( ; it != itEnd; ++it)
        {
            foreach(const MatchColor &mc, it.value())
            {
                it.key()->d->setHighlight( searchID, mc.first, mc.second );
                delete mc.first;
            }
            search->highlightedPages.insert( it.key()->number() );
            pagesToNotify->insert( it.key()->number() );
        }

        // send page lists to update observers (since some filter on bookmarks)
        foreach(DocumentObserver *observer, m_observers)
            observer->notifySetup( m_pagesVector, 0 );

        // notify observers about highlights changes
        foreach(int pageNumber, *pagesToNotify)
            foreach(DocumentObserver *observer, m_observers)
                observer->notifyPageChanged( pageNumber, DocumentObserver::Highlights );

        if (foundAMatch) emit m_parent->searchFinished( searchID, Document::MatchFound );
        else emit m_parent->searchFinished( searchID, Document::NoMatchFound );

        delete pageMatches;
        delete pagesToNotify;
    }
}

QVariant DocumentPrivate::documentMetaData( const QString &key, const QVariant &option ) const
{
    if ( key == QLatin1String( "PaperColor" ) )
    {
        bool giveDefault = option.toBool();
        // load paper color from Settings, or use the default color (white)
        // if we were told to do so
        QColor color;
        if ( ( SettingsCore::renderMode() == SettingsCore::EnumRenderMode::Paper )
             && SettingsCore::changeColors() )
        {
            color = SettingsCore::paperColor();
        }
        else if ( giveDefault )
        {
            color = Qt::white;
        }
        return color;
    }
    else if ( key == QLatin1String( "TextAntialias" ) )
    {
        switch ( SettingsCore::textAntialias() )
        {
            case SettingsCore::EnumTextAntialias::Enabled:
                return true;
                break;
#if 0
            case Settings::EnumTextAntialias::UseKDESettings:
                // TODO: read the KDE configuration
                return true;
                break;
#endif
            case SettingsCore::EnumTextAntialias::Disabled:
                return false;
                break;
        }
    }
    else if ( key == QLatin1String( "GraphicsAntialias" ) )
    {
        switch ( SettingsCore::graphicsAntialias() )
        {
            case SettingsCore::EnumGraphicsAntialias::Enabled:
                return true;
                break;
            case SettingsCore::EnumGraphicsAntialias::Disabled:
                return false;
                break;
        }
    }
    else if ( key == QLatin1String( "TextHinting" ) )
    {
        switch ( SettingsCore::textHinting() )
        {
            case SettingsCore::EnumTextHinting::Enabled:
                return true;
                break;
            case SettingsCore::EnumTextHinting::Disabled:
                return false;
                break;
        }
    }
    return QVariant();
}

bool DocumentPrivate::isNormalizedRectangleFullyVisible( const Okular::NormalizedRect & rectOfInterest, int rectPage )
{
    bool rectFullyVisible = false;
    const QVector<Okular::VisiblePageRect *> & visibleRects = m_parent->visiblePageRects();
    QVector<Okular::VisiblePageRect *>::const_iterator vEnd = visibleRects.end();
    QVector<Okular::VisiblePageRect *>::const_iterator vIt = visibleRects.begin();

    for ( ; ( vIt != vEnd ) && !rectFullyVisible; ++vIt )
    {
        if ( (*vIt)->pageNumber == rectPage &&
            (*vIt)->rect.contains( rectOfInterest.left, rectOfInterest.top ) &&
            (*vIt)->rect.contains( rectOfInterest.right, rectOfInterest.bottom ) )
        {
            rectFullyVisible = true;
        }
    }
    return rectFullyVisible;
}

Document::Document( QWidget *widget )
    : QObject( 0 ), 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(), SIGNAL(configChanged()), this, SLOT(_o_configChanged()) );
    connect( d->m_undoStack, SIGNAL( canUndoChanged(bool) ), this, SIGNAL( canUndoChanged(bool)));
    connect( d->m_undoStack, SIGNAL( canRedoChanged(bool) ), this, SIGNAL( canRedoChanged(bool) ) );

    qRegisterMetaType<Okular::FontInfo>();
}

Document::~Document()
{
    // delete generator, pages, and related stuff
    closeDocument();

    QSet< View * >::const_iterator viewIt = d->m_views.constBegin(), viewEnd = d->m_views.constEnd();
    for ( ; viewIt != viewEnd; ++viewIt )
    {
        View *v = *viewIt;
        v->d_func()->document = 0;
    }

    // delete the bookmark manager
    delete d->m_bookmarkManager;

    // delete the loaded generators
    QHash< QString, GeneratorInfo >::const_iterator it = d->m_loadedGenerators.constBegin(), itEnd = d->m_loadedGenerators.constEnd();
    for ( ; it != itEnd; ++it )
        d->unloadGenerator( it.value() );
    d->m_loadedGenerators.clear();

    // delete the private structure
    delete d;
}

class kMimeTypeMoreThan {
public:
    kMimeTypeMoreThan( const KMimeType::Ptr &mime ) : _mime( mime ) {}
    bool operator()( const KService::Ptr &s1, const KService::Ptr &s2 )
    {
        const QString mimeName = _mime->name();
        if (s1->mimeTypes().contains( mimeName ) && !s2->mimeTypes().contains( mimeName ))
            return true;
        else if (s2->mimeTypes().contains( mimeName ) && !s1->mimeTypes().contains( mimeName ))
            return false;
        return s1->property( "X-KDE-Priority" ).toInt() > s2->property( "X-KDE-Priority" ).toInt();
    }

private:
    const KMimeType::Ptr &_mime;
};

QString DocumentPrivate::docDataFileName(const KUrl &url, qint64 document_size)
{
    QString fn = url.fileName();
    fn = QString::number( document_size ) + '.' + fn + ".xml";
    QString newokular = "okular/docdata/" + fn;
    QString newokularfile = KStandardDirs::locateLocal( "data", newokular );
    if ( !QFile::exists( newokularfile ) )
    {
        QString oldkpdf = "kpdf/" + fn;
        QString oldkpdffile = KStandardDirs::locateLocal( "data", oldkpdf );
        if ( QFile::exists( oldkpdffile ) )
        {
            // ### copy or move?
            if ( !QFile::copy( oldkpdffile, newokularfile ) )
                return QString();
        }
    }
    return newokularfile;
}

Document::OpenResult Document::openDocument( const QString & docFile, const KUrl& url, const KMimeType::Ptr &_mime, const QString & password )
{
    KMimeType::Ptr mime = _mime;
    QByteArray filedata;
    qint64 document_size = -1;
    bool isstdin = url.fileName( KUrl::ObeyTrailingSlash ) == QLatin1String( "-" );
    bool triedMimeFromFileContent = false;
    if ( !isstdin )
    {
        if ( mime.count() <= 0 )
            return OpenError;

        // docFile is always local so we can use QFileInfo on it
        QFileInfo fileReadTest( docFile );
        if ( fileReadTest.isFile() && !fileReadTest.isReadable() )
        {
            d->m_docFileName.clear();
            return OpenError;
        }
        // determine the related "xml document-info" filename
        d->m_url = url;
        d->m_docFileName = docFile;
        if ( url.isLocalFile() && !d->m_archiveData )
        {
            document_size = fileReadTest.size();
            d->m_xmlFileName = DocumentPrivate::docDataFileName(url, document_size);
        }
    }
    else
    {
        QFile qstdin;
        qstdin.open( stdin, QIODevice::ReadOnly );
        filedata = qstdin.readAll();
        mime = KMimeType::findByContent( filedata );
        if ( !mime || mime->name() == QLatin1String( "application/octet-stream" ) )
            return OpenError;
        document_size = filedata.size();
        triedMimeFromFileContent = true;
    }

    // 0. load Generator
    // request only valid non-disabled plugins suitable for the mimetype
    QString constraint("([X-KDE-Priority] > 0) and (exist Library)") ;
    KService::List offers = KMimeTypeTrader::self()->query(mime->name(),"okular/Generator",constraint);
    if ( offers.isEmpty() && !triedMimeFromFileContent )
    {
        KMimeType::Ptr newmime = KMimeType::findByFileContent( docFile );
        triedMimeFromFileContent = true;
        if ( newmime->name() != mime->name() )
        {
            mime = newmime;
            offers = KMimeTypeTrader::self()->query( mime->name(), "okular/Generator", constraint );
        }
        if ( offers.isEmpty() )
        {
            // 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 = KMimeType::findByUrl( docFile );
            if ( newmime->name() != mime->name() )
            {
                mime = newmime;
                offers = KMimeTypeTrader::self()->query( mime->name(), "okular/Generator", constraint );
            }
        }
    }
    if (offers.isEmpty())
    {
        emit error( i18n( "Can not find a plugin which is able to handle the document being passed." ), -1 );
        kWarning(OkularDebug).nospace() << "No plugin for mimetype '" << mime->name() << "'.";
        return OpenError;
    }
    int hRank=0;
    // best ranked offer search
    int offercount = offers.count();
    if ( offercount > 1 )
    {
        // sort the offers: the offers with an higher priority come before
        qStableSort( offers.begin(), offers.end(), kMimeTypeMoreThan( mime ) );

        if ( SettingsCore::chooseGenerators() )
        {
            QStringList list;
            for ( int i = 0; i < offercount; ++i )
            {
                list << offers.at(i)->name();
            }

            ChooseEngineDialog choose( list, mime, d->m_widget );

            if ( choose.exec() == QDialog::Rejected )
                return OpenError;

            hRank = choose.selectedGenerator();
        }
    }

    KService::Ptr offer = offers.at( hRank );
    // 1. load Document
    OpenResult openResult = d->openDocumentInternal( offer, isstdin, docFile, filedata, password );
    if ( openResult == OpenError && !triedMimeFromFileContent )
    {
        KMimeType::Ptr newmime = KMimeType::findByFileContent( docFile );
        triedMimeFromFileContent = true;
        if ( newmime->name() != mime->name() )
        {
            mime = newmime;
            offers = KMimeTypeTrader::self()->query( mime->name(), "okular/Generator", constraint );
            if ( !offers.isEmpty() )
            {
                offer = offers.first();
                openResult = d->openDocumentInternal( offer, isstdin, docFile, filedata, password );
            }
        }
    }
    if ( openResult != OpenSuccess )
    {
        return openResult;
    }

    d->m_generatorName = offer->name();
    d->m_pageController = new PageController();
    connect( d->m_pageController, SIGNAL(rotationFinished(int,Okular::Page*)),
             this, SLOT(rotationFinished(int,Okular::Page*)) );

    bool containsExternalAnnotations = false;
    foreach ( Page * p, d->m_pagesVector )
    {
        p->d->m_doc = d;
        if ( !p->annotations().empty() )
            containsExternalAnnotations = true;
    }

    // Be quiet while restoring local annotations
    d->m_showWarningLimitedAnnotSupport = false;
    d->m_annotationsNeedSaveAs = false;

    // 2. load Additional Data (bookmarks, local annotations and metadata) about the document
    if ( d->m_archiveData )
    {
        d->loadDocumentInfo( d->m_archiveData->metadataFile );
        d->m_annotationsNeedSaveAs = true;
    }
    else
    {
        d->loadDocumentInfo();
        d->m_annotationsNeedSaveAs = ( d->canAddAnnotationsNatively() && containsExternalAnnotations );
    }

    d->m_showWarningLimitedAnnotSupport = true;
    d->m_bookmarkManager->setUrl( d->m_url );

    // 3. setup observers inernal lists and data
    foreachObserver( notifySetup( d->m_pagesVector, DocumentObserver::DocumentChanged ) );

    // 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, SIGNAL(timeout()), this, SLOT(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, SIGNAL(timeout()), this, SLOT(slotTimedMemoryCheck()) );
    }
    d->m_memCheckTimer->start( 2000 );

    const DocumentViewport nextViewport = d->nextDocumentViewport();
    if ( nextViewport.isValid() )
    {
        setViewport( nextViewport );
        d->m_nextDocumentViewport = DocumentViewport();
        d->m_nextDocumentDestination = QString();
    }

    AudioPlayer::instance()->d->m_currentDocument = isstdin ? KUrl() : d->m_url;
    d->m_docSize = document_size;

    const QStringList docScripts = d->m_generator->metaData( "DocumentScripts", "JavaScript" ).toStringList();
    if ( !docScripts.isEmpty() )
    {
        d->m_scripter = new Scripter( d );
        Q_FOREACH ( const QString &docscript, docScripts )
        {
            d->m_scripter->execute( JavaScript, docscript );
        }
    }

    return OpenSuccess;
}


KXMLGUIClient* Document::guiClient()
{
    if ( d->m_generator )
    {
        Okular::GuiInterface * iface = qobject_cast< Okular::GuiInterface * >( d->m_generator );
        if ( iface )
            return iface->guiClient();
    }
    return 0;
}

void Document::closeDocument()
{
    // check if there's anything to close...
    if ( !d->m_generator )
        return;

    delete d->m_pageController;
    d->m_pageController = 0;

    delete d->m_scripter;
    d->m_scripter = 0;

     // remove requests left in queue
    d->m_pixmapRequestsMutex.lock();
    QLinkedList< PixmapRequest * >::const_iterator sIt = d->m_pixmapRequestsStack.constBegin();
    QLinkedList< PixmapRequest * >::const_iterator sEnd = d->m_pixmapRequestsStack.constEnd();
    for ( ; sIt != sEnd; ++sIt )
        delete *sIt;
    d->m_pixmapRequestsStack.clear();
    d->m_pixmapRequestsMutex.unlock();

    QEventLoop loop;
    bool startEventLoop = false;
    do
    {
        d->m_pixmapRequestsMutex.lock();
        startEventLoop = !d->m_executingPixmapRequests.isEmpty();
        d->m_pixmapRequestsMutex.unlock();
        if ( startEventLoop )
        {
            d->m_closingLoop = &loop;
            loop.exec();
            d->m_closingLoop = 0;
        }
    }
    while ( startEventLoop );

    if ( d->m_fontThread )
    {
        disconnect( d->m_fontThread, 0, this, 0 );
        d->m_fontThread->stopExtraction();
        d->m_fontThread->wait();
        d->m_fontThread = 0;
    }

    // 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();
        d->m_generator->closeDocument();
    }

    // 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 = 0;
        // .. and this document from the generator signals
        disconnect( d->m_generator, 0, this, 0 );

        QHash< QString, GeneratorInfo >::const_iterator genIt = d->m_loadedGenerators.constFind( d->m_generatorName );
        Q_ASSERT( genIt != d->m_loadedGenerators.constEnd() );
        if ( !genIt.value().catalogName.isEmpty() && !genIt.value().config )
            KGlobal::locale()->removeCatalog( genIt.value().catalogName );
    }
    d->m_generator = 0;
    d->m_generatorName = QString();
    d->m_url = KUrl();
    d->m_docFileName = QString();
    d->m_xmlFileName = QString();
    delete d->m_tempFile;
    d->m_tempFile = 0;
    delete d->m_archiveData;
    d->m_archiveData = 0;
    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( QVector< Page * >(), DocumentObserver::DocumentChanged ) );

    // delete pages and clear 'd->m_pagesVector' container
    QVector< Page * >::const_iterator pIt = d->m_pagesVector.constBegin();
    QVector< Page * >::const_iterator pEnd = d->m_pagesVector.constEnd();
    for ( ; pIt != pEnd; ++pIt )
        delete *pIt;
    d->m_pagesVector.clear();

    // clear 'memory allocation' descriptors
    qDeleteAll( d->m_allocatedPixmaps );
    d->m_allocatedPixmaps.clear();

    // clear 'running searches' descriptors
    QMap< int, RunningSearch * >::const_iterator rIt = d->m_searches.constBegin();
    QMap< int, RunningSearch * >::const_iterator rEnd = d->m_searches.constEnd();
    for ( ; rIt != rEnd; ++rIt )
        delete *rIt;
    d->m_searches.clear();

    // clear the visible areas and notify the observers
    QVector< VisiblePageRect * >::const_iterator vIt = d->m_pageRects.constBegin();
    QVector< VisiblePageRect * >::const_iterator vEnd = d->m_pageRects.constEnd();
    for ( ; vIt != vEnd; ++vIt )
        delete *vIt;
    d->m_pageRects.clear();
    foreachObserver( notifyVisibleRectsChanged() );

    // reset internal variables

    d->m_viewportHistory.clear();
    d->m_viewportHistory.append( DocumentViewport() );
    d->m_viewportIterator = d->m_viewportHistory.begin();
    d->m_allocatedPixmapsTotalMemory = 0;
    d->m_allocatedTextPagesFifo.clear();
    d->m_pageSize = PageSize();
    d->m_pageSizes.clear();

    delete d->m_documentInfo;
    d->m_documentInfo = 0;

    AudioPlayer::instance()->d->m_currentDocument = KUrl();

    d->m_undoStack->clear();
}

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 );
        pObserver->notifyViewportChanged( false /*disables smoothMove*/ );
    }
}

void Document::removeObserver( DocumentObserver * pObserver )
{
    // remove observer from the map. it won't receive notifications anymore
    if ( d->m_observers.contains( pObserver ) )
    {
        // free observer's pixmap data
        QVector<Page*>::const_iterator it = d->m_pagesVector.constBegin(), end = d->m_pagesVector.constEnd();
        for ( ; it != end; ++it )
            (*it)->deletePixmap( pObserver );

        // [MEM] free observer's allocation descriptors
        QLinkedList< AllocatedPixmap * >::iterator aIt = d->m_allocatedPixmaps.begin();
        QLinkedList< AllocatedPixmap * >::iterator 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;
        }

        // delete observer entry from the map
        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
        QVector<Page*>::const_iterator it = d->m_pagesVector.constBegin(), end = d->m_pagesVector.constEnd();
        for ( ; it != end; ++it ) {
            (*it)->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.isEmpty() && !d->m_pagesVector.isEmpty() )
        d->cleanupPixmapMemory();
}


bool Document::isOpened() const
{
    return d->m_generator;
}

bool Document::canConfigurePrinter( ) const
{
    if ( d->m_generator )
    {
        Okular::PrintInterface * iface = qobject_cast< Okular::PrintInterface * >( d->m_generator );
        return iface ? true : false;
    }
    else
        return 0;
}

const DocumentInfo * Document::documentInfo() const
{
    if ( d->m_documentInfo )
        return d->m_documentInfo;

    if ( d->m_generator )
    {
        DocumentInfo *info = new DocumentInfo();
        const DocumentInfo *tmp = d->m_generator->generateDocumentInfo();
        if ( tmp )
            *info = *tmp;

        info->set( DocumentInfo::FilePath, currentDocument().prettyUrl() );
        const QString pagesSize = d->pagesSizeString();
        if ( d->m_docSize != -1 )
        {
            const QString sizeString = KGlobal::locale()->formatByteSize( d->m_docSize );
            info->set( DocumentInfo::DocumentSize, sizeString );
        }
        if (!pagesSize.isEmpty())
        {
            info->set( DocumentInfo::PagesSize, pagesSize );
        }

        const DocumentInfo::Key keyPages = DocumentInfo::Pages;
        const QString keyString = DocumentInfo::getKeyString( keyPages );

        if ( info->get( keyString ).isEmpty() ) {
            info->set( keyString, QString::number( this->pages() ),
                       DocumentInfo::getKeyTitle( keyPages ) );
        }

        d->m_documentInfo = info;
        return info;
    }
    else return NULL;
}

const DocumentSynopsis * Document::documentSynopsis() const
{
    return d->m_generator ? d->m_generator->generateDocumentSynopsis() : NULL;
}

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 )
        {
            emit gotFont( d->m_fontsCache.at( i ) );
            emit fontReadingProgress( i / pages() );
        }
        emit fontReadingEnded();
        return;
    }

    d->m_fontThread = new FontExtractionThread( d->m_generator, pages() );
    connect( d->m_fontThread, SIGNAL(gotFont(Okular::FontInfo)), this, SLOT(fontReadingGotFont(Okular::FontInfo)) );
    connect( d->m_fontThread, SIGNAL(progress(int)), this, SLOT(fontReadingProgress(int)) );

    d->m_fontThread->startExtraction( /*d->m_generator->hasFeature( Generator::Threaded )*/true );
}

void Document::stopFontReading()
{
    if ( !d->m_fontThread )
        return;

    disconnect( d->m_fontThread, 0, this, 0 );
    d->m_fontThread->stopExtraction();
    d->m_fontThread = 0;
    d->m_fontsCache.clear();
}

bool Document::canProvideFontInformation() const
{
    return d->m_generator ? d->m_generator->hasFeature( Generator::FontInfo ) : false;
}

const QList<EmbeddedFile*> *Document::embeddedFiles() const
{
    return d->m_generator ? d->m_generator->embeddedFiles() : NULL;
}

const Page * Document::page( int n ) const
{
    return ( n < d->m_pagesVector.count() ) ? d->m_pagesVector.at(n) : 0;
}

const DocumentViewport & Document::viewport() const
{
    return (*d->m_viewportIterator);
}

const QVector< VisiblePageRect * > & Document::visiblePageRects() const
{
    return d->m_pageRects;
}

void Document::setVisiblePageRects( const QVector< VisiblePageRect * > & visiblePageRects, DocumentObserver *excludeObserver )
{
    QVector< VisiblePageRect * >::const_iterator vIt = d->m_pageRects.constBegin();
    QVector< VisiblePageRect * >::const_iterator vEnd = d->m_pageRects.constEnd();
    for ( ; vIt != vEnd; ++vIt )
        delete *vIt;
    d->m_pageRects = visiblePageRects;
    // notify change to all other (different from id) observers
    foreach(DocumentObserver *o, 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();
}

KUrl Document::currentDocument() const
{
    return d->m_url;
}

bool Document::isAllowed( Permission action ) const
{
    if ( action == Okular::AllowNotes && !d->m_annotationEditingEnabled )
        return false;

#if !OKULAR_FORCE_DRM
    if ( KAuthorized::authorize( "skip_drm" ) && !Okular::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
{
    return d->m_generator ? d->m_generator->metaData( key, option ) : QVariant();
}

Rotation Document::rotation() const
{
    return d->m_rotation;
}

QSizeF Document::allPagesSize() const
{
    bool allPagesSameSize = true;
    QSizeF size;
    for (int i = 0; allPagesSameSize && i < d->m_pagesVector.count(); ++i)
    {
        const Page *p = d->m_pagesVector.at(i);
        if (i == 0) size = QSizeF(p->width(), p->height());
        else
        {
            allPagesSameSize = (size == QSizeF(p->width(), p->height()));
        }
    }
    if (allPagesSameSize) return size;
    else 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();
}

void Document::requestPixmaps( const QLinkedList< PixmapRequest * > & requests )
{
    requestPixmaps( requests, RemoveAllPrevious );
}

void Document::requestPixmaps( const QLinkedList< PixmapRequest * > & requests, PixmapRequestFlags reqOptions )
{
    if ( requests.isEmpty() )
        return;

    if ( !d->m_pageController )
    {
        // delete requests..
        QLinkedList< PixmapRequest * >::const_iterator rIt = requests.constBegin(), rEnd = requests.constEnd();
        for ( ; rIt != rEnd; ++rIt )
            delete *rIt;
        // ..and return
        return;
    }

    // 1. [CLEAN STACK] remove previous requests of requesterID
    // FIXME This assumes all requests come from the same observer, that is true atm but not enforced anywhere
    DocumentObserver *requesterObserver = requests.first()->observer();
    QSet< int > requestedPages;
    {
        QLinkedList< PixmapRequest * >::const_iterator rIt = requests.constBegin(), rEnd = requests.constEnd();
        for ( ; rIt != rEnd; ++rIt )
            requestedPages.insert( (*rIt)->pageNumber() );
    }
    const bool removeAllPrevious = reqOptions & RemoveAllPrevious;
    d->m_pixmapRequestsMutex.lock();
    QLinkedList< PixmapRequest * >::iterator sIt = d->m_pixmapRequestsStack.begin(), 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;
    }

    // 2. [ADD TO STACK] add requests to stack
    QLinkedList< PixmapRequest * >::const_iterator rIt = requests.constBegin(), rEnd = requests.constEnd();
    for ( ; rIt != rEnd; ++rIt )
    {
        // set the 'page field' (see PixmapRequest) and check if it is valid
        PixmapRequest * request = *rIt;
        kDebug(OkularDebug).nospace() << "request observer=" << request->observer() << " " <<request->width() << "x" << request->height() << "@" << request->pageNumber();
        if ( d->m_pagesVector.value( request->pageNumber() ) == 0 )
        {
            // skip requests referencing an invalid page (must not happen)
            delete request;
            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 );
            QList<Tile>::const_iterator tIt = tiles.constBegin(), tEnd = tiles.constEnd();
            while ( tIt != tEnd )
            {
                const Tile &tile = *tIt;
                if ( !tile.isValid() )
                {
                    if ( tilesRect.isNull() )
                        tilesRect = tile.rect();
                    else
                        tilesRect |= tile.rect();
                }

                tIt++;
            }

            request->setNormalizedRect( tilesRect );
        }

        if ( !request->asynchronous() )
            request->d->mPriority = 0;

        // add request to the 'stack' at the right place
        if ( !request->priority() )
            // add priority zero requests to the top of the stack
            d->m_pixmapRequestsStack.append( request );
        else
        {
            // insert in stack sorted by priority
            sIt = d->m_pixmapRequestsStack.begin();
            sEnd = d->m_pixmapRequestsStack.end();
            while ( sIt != sEnd && (*sIt)->priority() > request->priority() )
                ++sIt;
            d->m_pixmapRequestsStack.insert( sIt, 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();
}

void Document::requestTextPage( uint page )
{
    Page * kp = d->m_pagesVector[ page ];
    if ( !d->m_generator || !kp )
        return;

    // Memory management for TextPages

    d->m_generator->generateTextPage( kp );
}

void DocumentPrivate::notifyAnnotationChanges( int page )
{
    int flags = DocumentObserver::Annotations;

    if ( m_annotationsNeedSaveAs )
        flags |= DocumentObserver::NeedSaveAs;

    foreachObserverD( notifyPageChanged( page, flags ) );
}

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;
        default:
            return false;
    }
}

void Document::prepareToModifyAnnotationProperties( Annotation * annotation )
{
    Q_ASSERT(d->m_prevPropsOfAnnotBeingModified.isNull());
    if (!d->m_prevPropsOfAnnotBeingModified.isNull())
    {
        kError(OkularDebug) << "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())
    {
        kError(OkularDebug) << "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::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:
            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"));
    foreach(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, 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::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::setViewport( const DocumentViewport & viewport, DocumentObserver *excludeObserver, bool smoothMove )
{
    if ( !viewport.isValid() )
    {
        kDebug(OkularDebug) << "invalid viewport:" << viewport.toString();
        return;
    }
    if ( viewport.pageNumber >= int(d->m_pagesVector.count()) )
    {
        //kDebug(OkularDebug) << "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 )
    //    kDebug(OkularDebug) << "setViewport with the same viewport.";

    const int oldPageNumber = oldViewport.pageNumber;

    // set internal viewport taking care of history
    if ( oldViewport.pageNumber == viewport.pageNumber || !oldViewport.isValid() )
    {
        // 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.count() >= 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
    foreach(DocumentObserver *o, d->m_observers)
    {
        if ( o != excludeObserver )
            o->notifyViewportChanged( smoothMove );

        if ( currentPageChanged )
            o->notifyCurrentPageChanged( oldPageNumber, currentViewportPage );
    }
}

void Document::setZoom(int factor, DocumentObserver *excludeObserver)
{
    // notify change to all other (different from id) observers
    foreach(DocumentObserver *o, 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
{
    QLinkedList< 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() )
    {
        emit searchFinished( searchID, NoMatchFound );
        return;
    }

    // if searchID search not recorded, create new descriptor and init params
    QMap< int, RunningSearch * >::iterator 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;
    foreach(int pageNumber, s->highlightedPages)
        d->m_pagesVector.at(pageNumber)->d->deleteHighlights( searchID );
    s->highlightedPages.clear();

    // set hourglass cursor
    QApplication::setOverrideCursor( Qt::WaitCursor );

    // 1. ALLDOC - proces all document marking pages
    if ( type == AllDocument )
    {
        QMap< Page *, QVector<RegularAreaRect *> > *pageMatches = new QMap< Page *, QVector<RegularAreaRect *> >;

        // search and highlight 'text' (as a solid phrase) on all pages
        QMetaObject::invokeMethod(this, "doContinueAllDocumentSearch", Qt::QueuedConnection, Q_ARG(void *, pagesToNotify), Q_ARG(void *, pageMatches), Q_ARG(int, 0), Q_ARG(int, 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 currentPage = fromStart ? fromStartSearchPage : ((s->continueOnPage != -1) ? s->continueOnPage : viewportPage);
        Page * lastPage = fromStart ? 0 : d->m_pagesVector[ currentPage ];
        int pagesDone = 0;

        // continue checking last TextPage first (if it is the current page)
        RegularAreaRect * match = 0;
        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) currentPage++;
                else currentPage--;
                pagesDone++;
            }
        }

        s->pagesDone = pagesDone;

        DoContinueDirectionMatchSearchStruct *searchStruct = new DoContinueDirectionMatchSearchStruct();
        searchStruct->pagesToNotify = pagesToNotify;
        searchStruct->match = match;
        searchStruct->currentPage = currentPage;
        searchStruct->searchID = searchID;

        QMetaObject::invokeMethod(this, "doContinueDirectionMatchSearch", Qt::QueuedConnection, Q_ARG(void *, searchStruct));
    }
    // 4. GOOGLE* - process all document marking pages
    else if ( type == GoogleAll || type == GoogleAny )
    {
        QMap< Page *, QVector< QPair<RegularAreaRect *, QColor> > > *pageMatches = new QMap< Page *, QVector<QPair<RegularAreaRect *, QColor> > >;
        const QStringList words = text.split( ' ', QString::SkipEmptyParts );

        // search and highlight every word in 'text' on all pages
        QMetaObject::invokeMethod(this, "doContinueGooglesDocumentSearch", Qt::QueuedConnection, Q_ARG(void *, pagesToNotify), Q_ARG(void *, pageMatches), Q_ARG(int, 0), Q_ARG(int, searchID), Q_ARG(QStringList, words));
    }
}

void Document::continueSearch( int searchID )
{
    // check if searchID is present in runningSearches
    QMap< int, RunningSearch * >::const_iterator it = d->m_searches.constFind( searchID );
    if ( it == d->m_searches.constEnd() )
    {
        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
    QMap< int, RunningSearch * >::const_iterator it = d->m_searches.constFind( searchID );
    if ( it == d->m_searches.constEnd() )
    {
        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
    QMap< int, RunningSearch * >::iterator 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
    foreach(int pageNumber, 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 serch 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::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()[form->currentChoices()[0]];
    }

    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 );
}

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 += ',';

            if ( endId - startId > 0 )
                range += QString( "%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 += ',';

        if ( endId - startId > 0 )
            range += QString( "%1-%2" ).arg( startId + 1 ).arg( endId + 1 );
        else
            range += QString::number( startId + 1 );
    }
    return range;
}

void Document::processAction( const Action * action )
{
    if ( !action )
        return;

    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 assynchronously 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
            if ( go->isExternal() && !d->openRelativeFile( go->fileName() ) )
            {
                kWarning(OkularDebug).nospace() << "Action: Error opening '" << go->fileName() << "'.";
                return;
            }
            else
            {
                const DocumentViewport nextViewport = d->nextDocumentViewport();
                // skip local links that point to nowhere (broken ones)
                if ( !nextViewport.isValid() )
                    return;

                setViewport( nextViewport, 0, true );
                d->m_nextDocumentViewport = DocumentViewport();
                d->m_nextDocumentDestination = QString();
            }

            } break;

        case Action::Execute: {
            const ExecuteAction * exe  = static_cast< const ExecuteAction * >( action );
            QString fileName = exe->fileName();
            if ( fileName.endsWith( ".pdf" ) || fileName.endsWith( ".PDF" ) )
            {
                d->openRelativeFile( fileName );
                return;
            }

            // 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
            fileName = d->giveAbsolutePath( fileName );
            KMimeType::Ptr mime = KMimeType::findByPath( fileName );
            // Check executables
            if ( KRun::isExecutableFile( fileName, mime->name() ) )
            {
                // Don't have any pdf that uses this code path, just a guess on how it should work
                if ( !exe->parameters().isEmpty() )
                {
                    fileName = d->giveAbsolutePath( exe->parameters() );
                    mime = KMimeType::findByPath( fileName );
                    if ( KRun::isExecutableFile( fileName, mime->name() ) )
                    {
                        // this case is a link pointing to an executable with a parameter
                        // that also is an executable, possibly a hand-crafted pdf
                        KMessageBox::information( d->m_widget, i18n("The document is trying to execute an external application and, for your safety, Okular does not allow that.") );
                        return;
                    }
                }
                else
                {
                    // this case is a link pointing to an executable with no parameters
                    // core developers find unacceptable executing it even after asking the user
                    KMessageBox::information( d->m_widget, i18n("The document is trying to execute an external application and, for your safety, Okular does not allow that.") );
                    return;
                }
            }

            KService::Ptr ptr = KMimeTypeTrader::self()->preferredService( mime->name(), "Application" );
            if ( ptr )
            {
                KUrl::List lst;
                lst.append( fileName );
                KRun::run( *ptr, lst, 0 );
            }
            else
                KMessageBox::information( d->m_widget, i18n( "No application found for opening file of mimetype %1.", mime->name() ) );
            } 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:
                    emit quit();
                    break;
                case DocumentAction::Presentation:
                    emit linkPresentation();
                    break;
                case DocumentAction::EndPresentation:
                    emit linkEndPresentation();
                    break;
                case DocumentAction::Find:
                    emit linkFind();
                    break;
                case DocumentAction::GoToPage:
                    emit linkGoToPage();
                    break;
                case DocumentAction::Close:
                    emit close();
                    break;
            }
            } break;

        case Action::Browse: {
            const BrowseAction * browse = static_cast< const BrowseAction * >( action );
            QString lilySource;
            int lilyRow = 0, lilyCol = 0;
            // if the url is a mailto one, invoke mailer
            if ( browse->url().startsWith( "mailto:", Qt::CaseInsensitive ) )
                KToolInvocation::invokeMailer( browse->url() );
            else if ( extractLilyPondSourceReference( browse->url(), &lilySource, &lilyRow, &lilyCol ) )
            {
                const SourceReference ref( lilySource, lilyRow, lilyCol );
                processSourceReference( &ref );
            }
            else
            {
                QString url = browse->url();

                // fix for #100366, documents with relative links that are the form of http:foo.pdf
                if (url.indexOf("http:") == 0 && url.indexOf("http://") == -1 && url.right(4) == ".pdf")
                {
                    d->openRelativeFile(url.mid(5));
                    return;
                }

                KUrl realUrl = KUrl( url );

                // handle documents with relative path
                if ( d->m_url.isValid() )
                {
                    realUrl = KUrl( d->m_url.upUrl(), url );
                }

                // Albert: this is not a leak!
                new KRun( realUrl, d->m_widget );
            }
            } 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( linkscript->scriptType(), linkscript->script() );
            } break;

        case Action::Movie:
            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( linkrendition->scriptType(), linkrendition->script() );
            }
            else
            {
                emit processRenditionAction( static_cast< const RenditionAction * >( action ) );
            }
            } break;
    }
}

void Document::processSourceReference( const SourceReference * ref )
{
    if ( !ref )
        return;

    const KUrl url( d->giveAbsolutePath( ref->fileName() ) );
    if ( !url.isLocalFile() )
    {
        kDebug(OkularDebug) << url.url() << "is not a local file.";
        return;
    }

    const QString absFileName = url.toLocalFile();
    if ( !QFile::exists( absFileName ) )
    {
        kDebug(OkularDebug) << "No such file:" << absFileName;
        return;
    }

    bool handled = false;
    emit sourceReferenceActivated(absFileName, ref->row(), ref->column(), &handled);
    if(handled) {
        return;
    }

    static QHash< int, QString > editors;
    // init the editors table if empty (on first run, usually)
    if ( editors.isEmpty() )
    {
        editors = buildEditorsMap();
    }

    QHash< int, QString >::const_iterator it = editors.constFind( SettingsCore::externalEditor() );
    QString p;
    if ( it != editors.constEnd() )
        p = *it;
    else
        p = SettingsCore::externalEditorCommand();
    // custom editor not yet configured
    if ( p.isEmpty() )
        return;

    // manually append the %f placeholder if not specified
    if ( p.indexOf( QLatin1String( "%f" ) ) == -1 )
        p.append( QLatin1String( " %f" ) );

    // replacing the placeholders
    QHash< QChar, QString > map;
    map.insert( 'f', absFileName );
    map.insert( 'c', QString::number( ref->column() ) );
    map.insert( 'l', QString::number( ref->row() ) );
    const QString cmd = KMacroExpander::expandMacrosShellQuote( p, map );
    if ( cmd.isEmpty() )
        return;
    const QStringList args = KShell::splitArgs( cmd );
    if ( args.isEmpty() )
        return;

    KProcess::startDetached( args );
}

const SourceReference * Document::dynamicSourceReference( int pageNr, double absX, double absY )
{
    const SourceReference * ref = 0;
    if ( d->m_generator )
    {
        QMetaObject::invokeMethod( d->m_generator, "dynamicSourceReference", Qt::DirectConnection, Q_RETURN_ARG(const Okular::SourceReference*, ref), Q_ARG(int, pageNr), Q_ARG(double, absX), Q_ARG(double, absY) );
    }
    return ref;
}

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;
}

bool Document::print( QPrinter &printer )
{
    return d->m_generator ? d->m_generator->print( printer ) : false;
}

QString Document::printError() const
{
    Okular::Generator::PrintError err = Generator::UnknownPrintError;
    if ( d->m_generator )
    {
        QMetaObject::invokeMethod( d->m_generator, "printError", Qt::DirectConnection, Q_RETURN_ARG(Okular::Generator::PrintError, err) );
    }
    Q_ASSERT( err != Generator::NoPrintError );
    switch ( err )
    {
        case Generator::TemporaryFileOpenPrintError:
            return i18n( "Could not open a temporary file" );
        case Generator::FileConversionPrintError:
            return i18n( "Print conversion failed" );
        case Generator::PrintingProcessCrashPrintError:
            return i18n( "Printing process crashed" );
        case Generator::PrintingProcessStartPrintError:
            return i18n( "Printing process could not start" );
        case Generator::PrintToFilePrintError:
            return i18n( "Printing to file failed" );
        case Generator::InvalidPrinterStatePrintError:
            return i18n( "Printer was in invalid state" );
        case Generator::UnableToFindFilePrintError:
            return i18n( "Unable to find file to print" );
        case Generator::NoFileToPrintError:
            return i18n( "There was no file to print" );
        case Generator::NoBinaryToPrintError:
            return i18n( "Could not find a suitable binary for printing. Make sure CUPS lpr binary is available" );
        case Generator::InvalidPageSizePrintError:
            return i18n( "The page print size is invalid" );
        case Generator::NoPrintError:
            return QString();
        case Generator::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() : 0;
    }
    else
        return 0;
}

void Document::fillConfigDialog( KConfigDialog * dialog )
{
    if ( !dialog )
        return;

    // ensure that we have all the generators with settings loaded
    QString constraint( "([X-KDE-Priority] > 0) and (exist Library) and ([X-KDE-okularHasInternalSettings])" );
    KService::List offers = KServiceTypeTrader::self()->query( "okular/Generator", constraint );
    d->loadServiceList( offers );

    bool pagesAdded = false;
    QHash< QString, GeneratorInfo >::iterator it = d->m_loadedGenerators.begin();
    QHash< QString, GeneratorInfo >::iterator itEnd = d->m_loadedGenerators.end();
    for ( ; it != itEnd; ++it )
    {
        Okular::ConfigInterface * iface = d->generatorConfig( it.value() );
        if ( iface )
        {
            iface->addPages( dialog );
            pagesAdded = true;
            if ( !it.value().catalogName.isEmpty() )
                KGlobal::locale()->insertCatalog( it.value().catalogName );
        }
    }
    if ( pagesAdded )
    {
        connect( dialog, SIGNAL(settingsChanged(QString)),
                 this, SLOT(slotGeneratorConfigChanged(QString)) );
    }
}

int Document::configurableGenerators() const
{
    QString constraint( "([X-KDE-Priority] > 0) and (exist Library) and ([X-KDE-okularHasInternalSettings])" );
    KService::List offers = KServiceTypeTrader::self()->query( "okular/Generator", constraint );
    return offers.count();
}

QStringList Document::supportedMimeTypes() const
{
    if ( !d->m_supportedMimeTypes.isEmpty() )
        return d->m_supportedMimeTypes;

    QString constraint( "(Library == 'okularpart')" );
    QLatin1String basePartService( "KParts/ReadOnlyPart" );
    KService::List offers = KServiceTypeTrader::self()->query( basePartService, constraint );
    KService::List::ConstIterator it = offers.constBegin(), itEnd = offers.constEnd();
    for ( ; it != itEnd; ++it )
    {
        KService::Ptr service = *it;
        QStringList mimeTypes = service->serviceTypes();
        foreach ( const QString& mimeType, mimeTypes )
            if ( mimeType != basePartService )
                d->m_supportedMimeTypes.append( mimeType );
    }

    return d->m_supportedMimeTypes;
}

const KComponentData* Document::componentData() const
{
    if ( !d->m_generator )
        return 0;

    QHash< QString, GeneratorInfo >::const_iterator genIt = d->m_loadedGenerators.constFind( d->m_generatorName );
    Q_ASSERT( genIt != d->m_loadedGenerators.constEnd() );
    const KComponentData* kcd = &genIt.value().data;

    // empty about data
    if ( kcd->isValid() && kcd->aboutData() && kcd->aboutData()->programName().isEmpty() )
        return 0;

    return kcd;
}

bool Document::canSaveChanges() const
{
    if ( !d->m_generator )
        return false;
    Q_ASSERT( !d->m_generatorName.isEmpty() );

    QHash< QString, GeneratorInfo >::iterator 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() );

    QHash< QString, GeneratorInfo >::iterator 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;

    return saveIface->save( fileName, SaveInterface::SaveChanges, errorText );
}

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;

    Document *viewDoc = view->viewDocument();
    if ( !viewDoc || viewDoc != this )
        return;

    view->d_func()->document = 0;
    d->m_views.remove( view );
}

QByteArray Document::fontData(const FontInfo &font) const
{
    QByteArray result;

    if (d->m_generator)
    {
        QMetaObject::invokeMethod(d->m_generator, "requestFontData", Qt::DirectConnection, Q_ARG(Okular::FontInfo, font), Q_ARG(QByteArray *, &result));
    }

    return result;
}

Document::OpenResult Document::openDocumentArchive( const QString & docFile, const KUrl & url, const QString & password )
{
    const KMimeType::Ptr mime = KMimeType::findByPath( docFile, 0, false /* content too */ );
    if ( !mime->is( "application/vnd.kde.okular-archive" ) )
        return OpenError;

    KZip okularArchive( docFile );
    if ( !okularArchive.open( QIODevice::ReadOnly ) )
        return OpenError;

    const KArchiveDirectory * mainDir = okularArchive.directory();
    const KArchiveEntry * mainEntry = mainDir->entry( "content.xml" );
    if ( !mainEntry || !mainEntry->isFile() )
        return OpenError;

    std::auto_ptr< QIODevice > mainEntryDevice( static_cast< const KZipFileEntry * >( mainEntry )->createDevice() );
    QDomDocument doc;
    if ( !doc.setContent( mainEntryDevice.get() ) )
        return OpenError;
    mainEntryDevice.reset();

    QDomElement root = doc.documentElement();
    if ( root.tagName() != "OkularArchive" )
        return OpenError;

    QString documentFileName;
    QString metadataFileName;
    QDomElement el = root.firstChild().toElement();
    for ( ; !el.isNull(); el = el.nextSibling().toElement() )
    {
        if ( el.tagName() == "Files" )
        {
            QDomElement fileEl = el.firstChild().toElement();
            for ( ; !fileEl.isNull(); fileEl = fileEl.nextSibling().toElement() )
            {
                if ( fileEl.tagName() == "DocumentFileName" )
                    documentFileName = fileEl.text();
                else if ( fileEl.tagName() == "MetadataFileName" )
                    metadataFileName = fileEl.text();
            }
        }
    }
    if ( documentFileName.isEmpty() )
        return OpenError;

    const KArchiveEntry * docEntry = mainDir->entry( documentFileName );
    if ( !docEntry || !docEntry->isFile() )
        return OpenError;

    std::auto_ptr< ArchiveData > archiveData( new ArchiveData() );
    const int dotPos = documentFileName.indexOf( '.' );
    if ( dotPos != -1 )
        archiveData->document.setSuffix( documentFileName.mid( dotPos ) );
    if ( !archiveData->document.open() )
        return OpenError;

    QString tempFileName = archiveData->document.fileName();
    {
    std::auto_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::auto_ptr< QIODevice > metadataEntryDevice( static_cast< const KZipFileEntry * >( metadataEntry )->createDevice() );
        archiveData->metadataFile.setSuffix( ".xml" );
        if ( archiveData->metadataFile.open() )
        {
            copyQIODevice( metadataEntryDevice.get(), &archiveData->metadataFile );
            archiveData->metadataFile.close();
        }
    }

    const KMimeType::Ptr docMime = KMimeType::findByPath( tempFileName, 0, true /* local file */ );
    d->m_archiveData = archiveData.get();
    d->m_archivedFileName = documentFileName;
    const OpenResult ret = openDocument( tempFileName, url, docMime, password );

    if ( ret == OpenSuccess )
    {
        archiveData.release();
    }
    else
    {
        d->m_archiveData = 0;
    }

    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_archivedFileName : 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.gid() );
#else
    const KUserGroup userGroup( QString( "" ) );
#endif

    QDomDocument contentDoc( "OkularArchive" );
    QDomProcessingInstruction xmlPi = contentDoc.createProcessingInstruction(
            QString::fromLatin1( "xml" ), QString::fromLatin1( "version=\"1.0\" encoding=\"utf-8\"" ) );
    contentDoc.appendChild( xmlPi );
    QDomElement root = contentDoc.createElement( "OkularArchive" );
    contentDoc.appendChild( root );

    QDomElement filesNode = contentDoc.createElement( "Files" );
    root.appendChild( filesNode );

    QDomElement fileNameNode = contentDoc.createElement( "DocumentFileName" );
    filesNode.appendChild( fileNameNode );
    fileNameNode.appendChild( contentDoc.createTextNode( docFileName ) );

    QDomElement metadataFileNameNode = contentDoc.createElement( "MetadataFileName" );
    filesNode.appendChild( metadataFileNameNode );
    metadataFileNameNode.appendChild( contentDoc.createTextNode( "metadata.xml" ) );

    // If the generator can save annotations natively, do it
    KTemporaryFile modifiedFile;
    bool annotationsSavedNatively = false;
    if ( d->canAddAnnotationsNatively() )
    {
        if ( !modifiedFile.open() )
            return false;

        modifiedFile.close(); // We're only interested in the file name

        QString errorText;
        if ( saveChanges( modifiedFile.fileName(), &errorText ) )
        {
            docPath = modifiedFile.fileName(); // Save this instead of the original file
            annotationsSavedNatively = true;
        }
        else
        {
            kWarning(OkularDebug) << "saveChanges failed: " << errorText;
            kDebug(OkularDebug) << "Falling back to saving a copy of the original file";
        }
    }

    KTemporaryFile metadataFile;
    PageItems saveWhat = annotationsSavedNatively ? None : AnnotationPageItems;
    if ( !d->savePageDocumentInfo( &metadataFile, saveWhat ) )
        return false;

    const QByteArray contentDocXml = contentDoc.toByteArray();
    okularArchive.writeFile( "content.xml", user.loginName(), userGroup.name(),
                             contentDocXml.constData(), contentDocXml.length() );

    okularArchive.addLocalFile( docPath, docFileName );
    okularArchive.addLocalFile( metadataFile.fileName(), "metadata.xml" );

    if ( !okularArchive.close() )
        return false;

    return true;
}

QPrinter::Orientation Document::orientation() const
{
    double width, height;
    int landscape, portrait;
    const Okular::Page *currentPage;

    // 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 (uint i = 0; i < pages(); i++)
    {
        currentPage = page(i);
        width = currentPage->width();
        height = currentPage->height();
        if (currentPage->orientation() == Okular::Rotation90 || currentPage->orientation() == Okular::Rotation270) qSwap(width, height);
        if (width > height) landscape++;
        else portrait++;
    }
    return (landscape > portrait) ? QPrinter::Landscape : QPrinter::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 );
    }
}

void DocumentPrivate::requestDone( PixmapRequest * req )
{
    if ( !req )
        return;

    if ( !m_generator || m_closingLoop )
    {
        m_pixmapRequestsMutex.lock();
        m_executingPixmapRequests.removeAll( req );
        m_pixmapRequestsMutex.unlock();
        delete req;
        if ( m_closingLoop )
            m_closingLoop->exit();
        return;
    }

#ifndef NDEBUG
    if ( !m_generator->canGeneratePixmap() )
        kDebug(OkularDebug) << "requestDone with generator not in READY state.";
#endif

    // [MEM] 1.1 find and remove a previous entry for the same page and id
    QLinkedList< AllocatedPixmap * >::iterator aIt = m_allocatedPixmaps.begin();
    QLinkedList< AllocatedPixmap * >::iterator aEnd = m_allocatedPixmaps.end();
    for ( ; aIt != aEnd; ++aIt )
        if ( (*aIt)->page == req->pageNumber() && (*aIt)->observer == req->observer() )
        {
            AllocatedPixmap * p = *aIt;
            m_allocatedPixmaps.erase( aIt );
            m_allocatedPixmapsTotalMemory -= p->memory;
            delete p;
            break;
        }

    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 * req->width() * req->height();

        AllocatedPixmap * memoryPage = new AllocatedPixmap( req->observer(), req->pageNumber(), memoryBytes );
        m_allocatedPixmaps.append( memoryPage );
        m_allocatedPixmapsTotalMemory += memoryBytes;

        // 2. notify an observer that its pixmap changed
        observer->notifyPageChanged( req->pageNumber(), DocumentObserver::Pixmap );
    }
#ifndef NDEBUG
    else
        kWarning(OkularDebug) << "Receiving a done request for the defunct observer" << observer;
#endif

    // 3. delete request
    m_pixmapRequestsMutex.lock();
    m_executingPixmapRequests.removeAll( req );
    m_pixmapRequestsMutex.unlock();
    delete req;

    // 4. start a new generation if some is pending
    m_pixmapRequestsMutex.lock();
    bool hasPixmaps = !m_pixmapRequestsStack.isEmpty();
    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( 0 ); // 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
    QVector< Okular::Page * >::const_iterator pIt = m_pagesVector.constBegin();
    QVector< Okular::Page * >::const_iterator pEnd = m_pagesVector.constEnd();
    for ( ; pIt != pEnd; ++pIt )
        (*pIt)->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 ) );
    }
    kDebug(OkularDebug) << "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
    QVector< Okular::Page * >::const_iterator pIt = d->m_pagesVector.constBegin();
    QVector< Okular::Page * >::const_iterator pEnd = d->m_pagesVector.constEnd();
    for ( ; pIt != pEnd; ++pIt )
        (*pIt)->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 ) );
    kDebug(OkularDebug) << "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( ';', field, field );
    while ( !token.isEmpty() )
    {
        // decode the current token
        if ( field == 0 )
        {
            pageNumber = token.toInt( &ok );
            if ( !ok )
                return;
        }
        else if ( token.startsWith( "C1" ) )
        {
            rePos.enabled = true;
            rePos.normalizedX = token.section( ':', 1, 1 ).toDouble();
            rePos.normalizedY = token.section( ':', 2, 2 ).toDouble();
            rePos.pos = Center;
        }
        else if ( token.startsWith( "C2" ) )
        {
            rePos.enabled = true;
            rePos.normalizedX = token.section( ':', 1, 1 ).toDouble();
            rePos.normalizedY = token.section( ':', 2, 2 ).toDouble();
            if (token.section( ':', 3, 3 ).toInt() == 1) rePos.pos = Center;
            else rePos.pos = TopLeft;
        }
        else if ( token.startsWith( "AF1" ) )
        {
            autoFit.enabled = true;
            autoFit.width = token.section( ':', 1, 1 ) == "T";
            autoFit.height = token.section( ':', 2, 2 ) == "T";
        }
        // proceed tokenizing string
        field++;
        token = xmlDesc.section( ';', 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 += QString( ";C2:" ) + QString::number( rePos.normalizedX ) +
             ':' + QString::number( rePos.normalizedY ) +
             ':' + QString::number( rePos.pos );
    // if has autofit enabled, save its state on string
    if ( autoFit.enabled )
        s += QString( ";AF1:" ) + (autoFit.width ? "T" : "F") +
             ':' + (autoFit.height ? "T" : "F");
    return s;
}

bool DocumentViewport::isValid() const
{
    return pageNumber >= 0;
}

bool DocumentViewport::operator==( const DocumentViewport & vp ) const
{
    bool equal = ( pageNumber == vp.pageNumber ) &&
                 ( rePos.enabled == vp.rePos.enabled ) &&
                 ( autoFit.enabled == vp.autoFit.enabled );
    if ( !equal )
        return false;
    if ( rePos.enabled &&
         (( rePos.normalizedX != vp.rePos.normalizedX) ||
         ( rePos.normalizedY != vp.rePos.normalizedY ) || rePos.pos != vp.rePos.pos) )
        return false;
    if ( autoFit.enabled &&
         (( autoFit.width != vp.autoFit.width ) ||
         ( autoFit.height != vp.autoFit.height )) )
        return false;
    return true;
}

bool DocumentViewport::operator<( const DocumentViewport & vp ) const
{
    // TODO: Check autoFit and Position

    if ( pageNumber != vp.pageNumber )
        return pageNumber < vp.pageNumber;

    if ( !rePos.enabled && vp.rePos.enabled )
        return true;

    if ( !vp.rePos.enabled )
        return false;

    if ( rePos.normalizedY != vp.rePos.normalizedY )
        return rePos.normalizedY < vp.rePos.normalizedY;

    return rePos.normalizedX < vp.rePos.normalizedX;
}


/** DocumentInfo **/

DocumentInfo::DocumentInfo()
  : QDomDocument( "DocumentInformation" )
{
    QDomElement docElement = createElement( "DocumentInfo" );
    appendChild( docElement );
}

void DocumentInfo::set( const QString &key, const QString &value,
                        const QString &title )
{
    QDomElement docElement = documentElement();
    QDomElement element;

    // check whether key already exists
    QDomNodeList list = docElement.elementsByTagName( key );
    if ( list.count() > 0 )
        element = list.item( 0 ).toElement();
    else
        element = createElement( key );

    element.setAttribute( "value", value );
    element.setAttribute( "title", title );

    if ( list.count() == 0 )
        docElement.appendChild( element );
}

void DocumentInfo::set( Key key, const QString &value )
{
    const QString keyString = getKeyString( key );
    if ( !keyString.isEmpty() )
        set( keyString, value, getKeyTitle( key ) );
    else
        kWarning(OkularDebug) << "Invalid key passed";
}

QString DocumentInfo::get( const QString &key ) const
{
    const QDomElement docElement = documentElement();

    // check whether key already exists
    const QDomNodeList list = docElement.elementsByTagName( key );
    if ( list.count() > 0 )
        return list.item( 0 ).toElement().attribute( "value" );
    else
        return QString();
}

QString DocumentInfo::getKeyString( Key key ) //const
{
    switch ( key ) {
        case Title:
            return "title";
            break;
        case Subject:
            return "subject";
            break;
        case Description:
            return "description";
            break;
        case Author:
            return "author";
            break;
        case Creator:
            return "creator";
            break;
        case Producer:
            return "producer";
            break;
        case Copyright:
            return "copyright";
            break;
        case Pages:
            return "pages";
            break;
        case CreationDate:
            return "creationDate";
            break;
        case ModificationDate:
            return "modificationDate";
            break;
        case MimeType:
            return "mimeType";
            break;
        case Category:
            return "category";
            break;
        case Keywords:
            return "keywords";
            break;
        case FilePath:
            return "filePath";
            break;
        case DocumentSize:
            return "documentSize";
            break;
        case PagesSize:
            return "pageSize";
            break;
        default:
            return QString();
            break;
    }
}

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;
    }
}


/** DocumentSynopsis **/

DocumentSynopsis::DocumentSynopsis()
  : QDomDocument( "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 )
{
}

#undef foreachObserver
#undef foreachObserverD

#include "document.moc"

/* kate: replace-tabs on; indent-width 4; */