Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/backend/pdf/ev-poppler.cc
blob: 6d1c937a9401d231b6e1cec1d9d73831c7657f41 (plain)
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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8; c-indent-level: 8 -*- */
/* this file is part of evince, a gnome document viewer
 *
 * Copyright (C) 2009, Juanjo Marín <juanj.marin@juntadeandalucia.es>
 * Copyright (C) 2004, Red Hat, Inc.
 *
 * 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, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include "config.h"

#include <math.h>
#include <string.h>
#include <gtk/gtk.h>
#include <poppler.h>
#include <poppler-document.h>
#include <poppler-page.h>
#ifdef HAVE_CAIRO_PDF
#include <cairo-pdf.h>
#endif
#ifdef HAVE_CAIRO_PS
#include <cairo-ps.h>
#endif
#include <glib/gi18n-lib.h>

#include "ev-poppler.h"
#include "ev-file-exporter.h"
#include "ev-mapping.h"
#include "ev-document-find.h"
#include "ev-document-misc.h"
#include "ev-document-links.h"
#include "ev-document-images.h"
#include "ev-document-fonts.h"
#include "ev-document-security.h"
#include "ev-document-thumbnails.h"
#include "ev-document-transition.h"
#include "ev-document-forms.h"
#include "ev-document-layers.h"
#include "ev-document-print.h"
#include "ev-document-annotations.h"
#include "ev-document-attachments.h"
#include "ev-selection.h"
#include "ev-transition-effect.h"
#include "ev-attachment.h"
#include "ev-image.h"

#include <libxml/tree.h>
#include <libxml/parser.h>
#include <libxml/xpath.h>
#include <libxml/xpathInternals.h>

#if (defined (HAVE_POPPLER_PAGE_RENDER)) && (defined (HAVE_CAIRO_PDF) || defined (HAVE_CAIRO_PS))
#define HAVE_CAIRO_PRINT
#endif

/* fields from the XMP Rights Management Schema, XMP Specification Sept 2005, pag. 45 */
#define LICENSE_MARKED "/x:xmpmeta/rdf:RDF/rdf:Description/xmpRights:Marked"
#define LICENSE_TEXT "/x:xmpmeta/rdf:RDF/rdf:Description/dc:rights/rdf:Alt/rdf:li[lang('%s')]"
#define LICENSE_WEB_STATEMENT "/x:xmpmeta/rdf:RDF/rdf:Description/xmpRights:WebStatement"
/* license field from Creative Commons schema, http://creativecommons.org/ns */
#define LICENSE_URI "/x:xmpmeta/rdf:RDF/rdf:Description/cc:license/@rdf:resource"

typedef struct {
	PdfDocument *document;
	char *text;
	GList **pages;
	guint idle;
	int start_page;
	int search_page;
} PdfDocumentSearch;

typedef struct {
	EvFileExporterFormat format;

	/* Pages per sheet */
	gint pages_per_sheet;
	gint pages_printed;
	gint pages_x;
	gint pages_y;
	gdouble paper_width;
	gdouble paper_height;
	
#ifdef HAVE_CAIRO_PRINT
	cairo_t *cr;
#else
	PopplerPSFile *ps_file;
#endif
} PdfPrintContext;

struct _PdfDocumentClass
{
	EvDocumentClass parent_class;
};

struct _PdfDocument
{
	EvDocument parent_instance;

	PopplerDocument *document;
	gchar *password;
	gboolean modified;

	PopplerFontInfo *font_info;
	PopplerFontsIter *fonts_iter;
	int fonts_scanned_pages;

	PdfDocumentSearch *search;
	PdfPrintContext *print_ctx;

	GList *layers;
};

static void pdf_document_security_iface_init             (EvDocumentSecurityIface    *iface);
static void pdf_document_document_thumbnails_iface_init  (EvDocumentThumbnailsIface  *iface);
static void pdf_document_document_links_iface_init       (EvDocumentLinksIface       *iface);
static void pdf_document_document_images_iface_init      (EvDocumentImagesIface      *iface);
static void pdf_document_document_forms_iface_init       (EvDocumentFormsIface       *iface);
static void pdf_document_document_fonts_iface_init       (EvDocumentFontsIface       *iface);
static void pdf_document_document_layers_iface_init      (EvDocumentLayersIface      *iface);
#ifdef HAVE_POPPLER_PAGE_RENDER
static void pdf_document_document_print_iface_init       (EvDocumentPrintIface       *iface);
#endif
static void pdf_document_document_annotations_iface_init (EvDocumentAnnotationsIface *iface);
static void pdf_document_document_attachments_iface_init (EvDocumentAttachmentsIface *iface);
static void pdf_document_find_iface_init                 (EvDocumentFindIface        *iface);
static void pdf_document_file_exporter_iface_init        (EvFileExporterIface        *iface);
static void pdf_selection_iface_init                     (EvSelectionIface           *iface);
static void pdf_document_page_transition_iface_init      (EvDocumentTransitionIface  *iface);
static void pdf_document_thumbnails_get_dimensions       (EvDocumentThumbnails       *document_thumbnails,
							  EvRenderContext            *rc,
							  gint                       *width,
							  gint                       *height);
static int  pdf_document_get_n_pages			 (EvDocument                 *document);

static EvLinkDest *ev_link_dest_from_dest    (PdfDocument       *pdf_document,
					      PopplerDest       *dest);
static EvLink     *ev_link_from_action       (PdfDocument       *pdf_document,
					      PopplerAction     *action);
static void        pdf_document_search_free  (PdfDocumentSearch *search);
static void        pdf_print_context_free    (PdfPrintContext   *ctx);
static gboolean    attachment_save_to_buffer (PopplerAttachment *attachment,
					      gchar            **buffer,
					      gsize             *buffer_size,
					      GError           **error);

EV_BACKEND_REGISTER_WITH_CODE (PdfDocument, pdf_document,
			 {
				 EV_BACKEND_IMPLEMENT_INTERFACE (EV_TYPE_DOCUMENT_SECURITY,
								 pdf_document_security_iface_init);
				 EV_BACKEND_IMPLEMENT_INTERFACE (EV_TYPE_DOCUMENT_THUMBNAILS,
								 pdf_document_document_thumbnails_iface_init);
				 EV_BACKEND_IMPLEMENT_INTERFACE (EV_TYPE_DOCUMENT_LINKS,
								 pdf_document_document_links_iface_init);
				 EV_BACKEND_IMPLEMENT_INTERFACE (EV_TYPE_DOCUMENT_IMAGES,
								 pdf_document_document_images_iface_init);
				 EV_BACKEND_IMPLEMENT_INTERFACE (EV_TYPE_DOCUMENT_FORMS,
								 pdf_document_document_forms_iface_init);
				 EV_BACKEND_IMPLEMENT_INTERFACE (EV_TYPE_DOCUMENT_FONTS,
								 pdf_document_document_fonts_iface_init);
				 EV_BACKEND_IMPLEMENT_INTERFACE (EV_TYPE_DOCUMENT_LAYERS,
								 pdf_document_document_layers_iface_init);
#ifdef HAVE_POPPLER_PAGE_RENDER
				 EV_BACKEND_IMPLEMENT_INTERFACE (EV_TYPE_DOCUMENT_PRINT,
								 pdf_document_document_print_iface_init);
#endif
				 EV_BACKEND_IMPLEMENT_INTERFACE (EV_TYPE_DOCUMENT_ANNOTATIONS,
								 pdf_document_document_annotations_iface_init);
				 EV_BACKEND_IMPLEMENT_INTERFACE (EV_TYPE_DOCUMENT_ATTACHMENTS,
								 pdf_document_document_attachments_iface_init);
				 EV_BACKEND_IMPLEMENT_INTERFACE (EV_TYPE_DOCUMENT_FIND,
								 pdf_document_find_iface_init);
				 EV_BACKEND_IMPLEMENT_INTERFACE (EV_TYPE_FILE_EXPORTER,
								 pdf_document_file_exporter_iface_init);
				 EV_BACKEND_IMPLEMENT_INTERFACE (EV_TYPE_SELECTION,
								 pdf_selection_iface_init);
				 EV_BACKEND_IMPLEMENT_INTERFACE (EV_TYPE_DOCUMENT_TRANSITION,
								 pdf_document_page_transition_iface_init);
			 });

static void
pdf_document_search_free (PdfDocumentSearch   *search)
{
        PdfDocument *pdf_document = search->document;
	int n_pages;
	int i;

        if (search->idle != 0)
                g_source_remove (search->idle);

	n_pages = pdf_document_get_n_pages (EV_DOCUMENT (pdf_document));
	for (i = 0; i < n_pages; i++) {
		g_list_foreach (search->pages[i], (GFunc) g_free, NULL);
		g_list_free (search->pages[i]);
	}
	g_free (search->pages);
	
	g_free (search->text);
	g_free (search);
}

static void
pdf_document_dispose (GObject *object)
{
	PdfDocument *pdf_document = PDF_DOCUMENT(object);

	if (pdf_document->print_ctx) {
		pdf_print_context_free (pdf_document->print_ctx);
		pdf_document->print_ctx = NULL;
	}
	
	if (pdf_document->search) {
		pdf_document_search_free (pdf_document->search);
		pdf_document->search = NULL;
	}

	if (pdf_document->document) {
		g_object_unref (pdf_document->document);
	}

	if (pdf_document->font_info) { 
		poppler_font_info_free (pdf_document->font_info);
	}

	if (pdf_document->fonts_iter) {
		poppler_fonts_iter_free (pdf_document->fonts_iter);
	}

	if (pdf_document->layers) {
		g_list_foreach (pdf_document->layers, (GFunc)g_object_unref, NULL);
		g_list_free (pdf_document->layers);
	}

	G_OBJECT_CLASS (pdf_document_parent_class)->dispose (object);
}

static void
pdf_document_init (PdfDocument *pdf_document)
{
	pdf_document->password = NULL;
}

static void
convert_error (GError  *poppler_error,
	       GError **error)
{
	if (poppler_error == NULL)
		return;

	if (poppler_error->domain == POPPLER_ERROR) {
		/* convert poppler errors into EvDocument errors */
		gint code = EV_DOCUMENT_ERROR_INVALID;
		if (poppler_error->code == POPPLER_ERROR_INVALID)
			code = EV_DOCUMENT_ERROR_INVALID;
		else if (poppler_error->code == POPPLER_ERROR_ENCRYPTED)
			code = EV_DOCUMENT_ERROR_ENCRYPTED;
			
		g_set_error_literal (error,
                                     EV_DOCUMENT_ERROR,
                                     code,
                                     poppler_error->message);

		g_error_free (poppler_error);
	} else {
		g_propagate_error (error, poppler_error);
	}
}


/* EvDocument */
static gboolean
pdf_document_save (EvDocument  *document,
		   const char  *uri,
		   GError     **error)
{
	PdfDocument *pdf_document = PDF_DOCUMENT (document);
	gboolean retval;
	GError *poppler_error = NULL;

	if (pdf_document->modified) {
		retval = poppler_document_save (pdf_document->document,
						uri, &poppler_error);
	} else {
		retval = poppler_document_save_a_copy (pdf_document->document,
						       uri, &poppler_error);
	}
						       
	if (! retval)
		convert_error (poppler_error, error);

	return retval;
}

static gboolean
pdf_document_load (EvDocument   *document,
		   const char   *uri,
		   GError      **error)
{
	GError *poppler_error = NULL;
	PdfDocument *pdf_document = PDF_DOCUMENT (document);

	pdf_document->document =
		poppler_document_new_from_file (uri, pdf_document->password, &poppler_error);

	if (pdf_document->document == NULL) {
		convert_error (poppler_error, error);
		return FALSE;
	}

	return TRUE;
}

static int
pdf_document_get_n_pages (EvDocument *document)
{
	return poppler_document_get_n_pages (PDF_DOCUMENT (document)->document);
}

static EvPage *
pdf_document_get_page (EvDocument *document,
		       gint        index)
{
	PdfDocument *pdf_document = PDF_DOCUMENT (document);
	PopplerPage *poppler_page;
	EvPage      *page;

	poppler_page = poppler_document_get_page (pdf_document->document, index);
	page = ev_page_new (index);
	page->backend_page = (EvBackendPage)g_object_ref (poppler_page);
	page->backend_destroy_func = (EvBackendPageDestroyFunc)g_object_unref;
	g_object_unref (poppler_page);

	return page;
}

static void
pdf_document_get_page_size (EvDocument *document,
			    EvPage     *page,
			    double     *width,
			    double     *height)
{
	g_return_if_fail (POPPLER_IS_PAGE (page->backend_page));
	
	poppler_page_get_size (POPPLER_PAGE (page->backend_page), width, height);
}

static char *
pdf_document_get_page_label (EvDocument *document,
			     EvPage     *page)
{
	char *label = NULL;

	g_return_val_if_fail (POPPLER_IS_PAGE (page->backend_page), NULL);

	g_object_get (G_OBJECT (page->backend_page),
		      "label", &label,
		      NULL);
	return label;
}

static cairo_surface_t *
pdf_page_render (PopplerPage     *page,
		 gint             width,
		 gint             height,
		 EvRenderContext *rc)
{
	cairo_surface_t *surface;

#ifdef HAVE_POPPLER_PAGE_RENDER
	cairo_t *cr;

	surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32,
					      width, height);
	cr = cairo_create (surface);

	switch (rc->rotation) {
	        case 90:
			cairo_translate (cr, width, 0);
			break;
	        case 180:
			cairo_translate (cr, width, height);
			break;
	        case 270:
			cairo_translate (cr, 0, height);
			break;
	        default:
			cairo_translate (cr, 0, 0);
	}
	cairo_scale (cr, rc->scale, rc->scale);
	cairo_rotate (cr, rc->rotation * G_PI / 180.0);
	poppler_page_render (page, cr);

	cairo_set_operator (cr, CAIRO_OPERATOR_DEST_OVER);
	cairo_set_source_rgb (cr, 1., 1., 1.);
	cairo_paint (cr);

	cairo_destroy (cr);
#else /* HAVE_POPPLER_PAGE_RENDER */
	GdkPixbuf *pixbuf;
	
	pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB,
				 FALSE, 8,
				 width, height);

	poppler_page_render_to_pixbuf (page,
				       0, 0,
				       width, height,
				       rc->scale,
				       rc->rotation,
				       pixbuf);
	surface = ev_document_misc_surface_from_pixbuf (pixbuf);
	g_object_unref (pixbuf);
#endif /* HAVE_POPPLER_PAGE_RENDER */

	return surface;	
}

static cairo_surface_t *
pdf_document_render (EvDocument      *document,
		     EvRenderContext *rc)
{
	PdfDocument *pdf_document;
	PopplerPage *poppler_page;
	double width_points, height_points;
	gint width, height;

	poppler_page = POPPLER_PAGE (rc->page->backend_page);

	poppler_page_get_size (poppler_page,
			       &width_points, &height_points);
	
	if (rc->rotation == 90 || rc->rotation == 270) {
		width = (int) ((height_points * rc->scale) + 0.5);
		height = (int) ((width_points * rc->scale) + 0.5);
	} else {
		width = (int) ((width_points * rc->scale) + 0.5);
		height = (int) ((height_points * rc->scale) + 0.5);
	}
	
	return pdf_page_render (poppler_page,
				width, height, rc);
}

/* reference:
http://www.pdfa.org/lib/exe/fetch.php?id=pdfa%3Aen%3Atechdoc&cache=cache&media=pdfa:techdoc:tn0001_pdfa-1_and_namespaces_2008-03-18.pdf */
static char *
pdf_document_get_format_from_metadata (xmlDocPtr          doc,
				       xmlXPathContextPtr xpathCtx)
{
	xmlXPathObjectPtr xpathObj;
	xmlChar *part = NULL;
	xmlChar *conf = NULL;
	char *result = NULL;
	int i;

	/* add pdf/a namespaces */
	xmlXPathRegisterNs (xpathCtx, BAD_CAST "x", BAD_CAST "adobe:ns:meta/");
	xmlXPathRegisterNs (xpathCtx, BAD_CAST "rdf", BAD_CAST "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
	xmlXPathRegisterNs (xpathCtx, BAD_CAST "pdfaid", BAD_CAST "http://www.aiim.org/pdfa/ns/id/");

	/* reads pdf/a part */
	/* first syntax: child node */
	xpathObj = xmlXPathEvalExpression (BAD_CAST "/x:xmpmeta/rdf:RDF/rdf:Description/pdfaid:part", xpathCtx);
	if (xpathObj != NULL) {
		if (xpathObj->nodesetval != NULL && xpathObj->nodesetval->nodeNr != 0)
			part = xmlNodeGetContent (xpathObj->nodesetval->nodeTab[0]);

		xmlXPathFreeObject (xpathObj);
	}
	if (part == NULL) {
		/* second syntax: attribute */
		xpathObj = xmlXPathEvalExpression (BAD_CAST "/x:xmpmeta/rdf:RDF/rdf:Description/@pdfaid:part", xpathCtx);
		if (xpathObj != NULL) {
			if (xpathObj->nodesetval != NULL && xpathObj->nodesetval->nodeNr != 0)
				part = xmlNodeGetContent (xpathObj->nodesetval->nodeTab[0]);

			xmlXPathFreeObject (xpathObj);
		}
	}

	/* reads pdf/a conformance */
	/* first syntax: child node */
	xpathObj = xmlXPathEvalExpression (BAD_CAST "/x:xmpmeta/rdf:RDF/rdf:Description/pdfaid:conformance", xpathCtx);
	if (xpathObj != NULL) {
		if (xpathObj->nodesetval != NULL && xpathObj->nodesetval->nodeNr != 0)
			conf = xmlNodeGetContent (xpathObj->nodesetval->nodeTab[0]);

		xmlXPathFreeObject (xpathObj);
	}
	if (conf == NULL) {
		/* second syntax: attribute */
		xpathObj = xmlXPathEvalExpression (BAD_CAST "/x:xmpmeta/rdf:RDF/rdf:Description/@pdfaid:conformance", xpathCtx);
		if (xpathObj != NULL) {
			if (xpathObj->nodesetval != NULL && xpathObj->nodesetval->nodeNr != 0)
				conf = xmlNodeGetContent (xpathObj->nodesetval->nodeTab[0]);

			xmlXPathFreeObject (xpathObj);
		}
	}

	if (part != NULL && conf != NULL) {
		/* makes conf lowercase */
		for (i = 0; conf[i]; i++)
			conf[i] = g_ascii_tolower (conf[i]);

		/* return buffer */
		result = g_strdup_printf ("PDF/A - %s%s", part, conf);
	}

	/* Cleanup */
	xmlFree (part);
	xmlFree (conf);

	return result;
}

static EvDocumentLicense *
pdf_document_get_license_from_metadata (xmlDocPtr          doc,
					xmlXPathContextPtr xpathCtx)
{
	xmlXPathObjectPtr xpathObj;
	xmlChar *marked = NULL;
	const char *language_string;
	char  *aux;
	gchar **tags;
	gchar *tag, *tag_aux;
	int i, j;
	EvDocumentLicense *license;

	/* register namespaces */
	xmlXPathRegisterNs (xpathCtx, BAD_CAST "x", BAD_CAST "adobe:ns:meta/");
	xmlXPathRegisterNs (xpathCtx, BAD_CAST "rdf", BAD_CAST "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
	xmlXPathRegisterNs (xpathCtx, BAD_CAST "dc", BAD_CAST "http://purl.org/dc/elements/1.1/");
	/* XMP Rights Management Schema */
	xmlXPathRegisterNs (xpathCtx, BAD_CAST "xmpRights", BAD_CAST "http://ns.adobe.com/xap/1.0/rights/");
	/* Creative Commons Schema */
	xmlXPathRegisterNs (xpathCtx, BAD_CAST "cc", BAD_CAST "http://creativecommons.org/ns#");

	/* checking if the document has been marked as defined on the XMP Rights
	 * Management Schema */
	xpathObj = xmlXPathEvalExpression (BAD_CAST LICENSE_MARKED, xpathCtx);
	if (xpathObj != NULL) {
		if (xpathObj->nodesetval != NULL &&
		    xpathObj->nodesetval->nodeNr != 0)
			marked = xmlNodeGetContent (xpathObj->nodesetval->nodeTab[0]);
		xmlXPathFreeObject (xpathObj);
	}

	/* a) Not marked => No XMP Rights information */
	if (!marked) {
		xmlFree (marked);
		return NULL;
	}

	license = ev_document_license_new ();

	/* b) Marked False => Public Domain, no copyrighted material and no
	 * license needed */
	if (g_strrstr ((char *) marked, "False") != NULL) {
		license->text = g_strdup (_("This work is in the Public Domain"));
	/* c) Marked True => Copyrighted material */
	} else {
		/* Checking usage terms as defined by the XMP Rights Management
		 * Schema. This field is recomended to be checked by Creative
		 * Commons */
		/* 1) checking for a suitable localized string */
		language_string = pango_language_to_string (gtk_get_default_language ());
		tags = g_strsplit (language_string, "-", -1);
		i = g_strv_length (tags);
		while (i-- && !license->text) {
			tag = g_strdup (tags[0]);
			for (j = 1; j <= i; j++) {
				tag_aux = g_strdup_printf ("%s-%s", tag, tags[j]);
				g_free (tag);
				tag = tag_aux;
			}
			aux = g_strdup_printf (LICENSE_TEXT, tag);
			xpathObj = xmlXPathEvalExpression (BAD_CAST aux, xpathCtx);
			if (xpathObj != NULL) {
				if (xpathObj->nodesetval != NULL &&
				    xpathObj->nodesetval->nodeNr != 0)
					license->text = (gchar *)xmlNodeGetContent (xpathObj->nodesetval->nodeTab[0]);
				xmlXPathFreeObject (xpathObj);
			}
			g_free (tag);
			g_free (aux);
		}
		g_strfreev(tags);

		/* 2) if not, use the default string */
		if (!license->text) {
			aux = g_strdup_printf (LICENSE_TEXT, "x-default");
			xpathObj = xmlXPathEvalExpression (BAD_CAST aux, xpathCtx);
			if (xpathObj != NULL) {
				if (xpathObj->nodesetval != NULL &&
				    xpathObj->nodesetval->nodeNr != 0)
					license->text = (gchar *)xmlNodeGetContent (xpathObj->nodesetval->nodeTab[0]);
				xmlXPathFreeObject (xpathObj);
			}
			g_free (aux);
		}

		/* Checking the license URI as defined by the Creative Commons
		 * Schema. This field is recomended to be checked by Creative
		 * Commons */
		xpathObj = xmlXPathEvalExpression (BAD_CAST LICENSE_URI, xpathCtx);
		if (xpathObj != NULL) {
			if (xpathObj->nodesetval != NULL &&
			    xpathObj->nodesetval->nodeNr != 0)
				license->uri = (gchar *)xmlNodeGetContent (xpathObj->nodesetval->nodeTab[0]);
			xmlXPathFreeObject (xpathObj);
		}

		/* Checking the web statement as defined by the XMP Rights
		 * Management Schema. Checking it out is a sort of above-and-beyond
		 * the basic recommendations by Creative Commons. It can be
		 * considered as a "reinforcement" approach to add certainty. */
		xpathObj = xmlXPathEvalExpression (BAD_CAST LICENSE_WEB_STATEMENT, xpathCtx);
		if (xpathObj != NULL) {
			if (xpathObj->nodesetval != NULL &&
			    xpathObj->nodesetval->nodeNr != 0)
				license->web_statement = (gchar *)xmlNodeGetContent (xpathObj->nodesetval->nodeTab[0]);
			xmlXPathFreeObject (xpathObj);
		}
	}
	xmlFree (marked);

	if (!license->text && !license->uri && !license->web_statement) {
		ev_document_license_free (license);
		return NULL;
	}

	return license;
}

static void
pdf_document_parse_metadata (const gchar    *metadata,
			     EvDocumentInfo *info)
{
	xmlDocPtr          doc;
	xmlXPathContextPtr xpathCtx;
	gchar             *fmt;

	doc = xmlParseMemory (metadata, strlen (metadata));
	if (doc == NULL)
		return;		/* invalid xml metadata */

	xpathCtx = xmlXPathNewContext (doc);
	if (xpathCtx == NULL) {
		xmlFreeDoc (doc);
		return;		/* invalid xpath context */
	}

	fmt = pdf_document_get_format_from_metadata (doc, xpathCtx);
	if (fmt != NULL) {
		g_free (info->format);
		info->format = fmt;
	}

	info->license = pdf_document_get_license_from_metadata (doc, xpathCtx);

	xmlXPathFreeContext (xpathCtx);
	xmlFreeDoc (doc);
}


static EvDocumentInfo *
pdf_document_get_info (EvDocument *document)
{
	EvDocumentInfo *info;
	PopplerPageLayout layout;
	PopplerPageMode mode;
	PopplerViewerPreferences view_prefs;
	PopplerPermissions permissions;
	EvPage *page;
	char *metadata;

	info = g_new0 (EvDocumentInfo, 1);

	info->fields_mask = EV_DOCUMENT_INFO_TITLE |
			    EV_DOCUMENT_INFO_FORMAT |
			    EV_DOCUMENT_INFO_AUTHOR |
			    EV_DOCUMENT_INFO_SUBJECT |
			    EV_DOCUMENT_INFO_KEYWORDS |
			    EV_DOCUMENT_INFO_LAYOUT |
			    EV_DOCUMENT_INFO_START_MODE |
		            EV_DOCUMENT_INFO_PERMISSIONS |
			    EV_DOCUMENT_INFO_UI_HINTS |
			    EV_DOCUMENT_INFO_CREATOR |
			    EV_DOCUMENT_INFO_PRODUCER |
			    EV_DOCUMENT_INFO_CREATION_DATE |
			    EV_DOCUMENT_INFO_MOD_DATE |
			    EV_DOCUMENT_INFO_LINEARIZED |
			    EV_DOCUMENT_INFO_N_PAGES |
			    EV_DOCUMENT_INFO_SECURITY | 
		            EV_DOCUMENT_INFO_PAPER_SIZE |
			    EV_DOCUMENT_INFO_LICENSE;

	g_object_get (PDF_DOCUMENT (document)->document,
		      "title", &(info->title),
		      "format", &(info->format),
		      "author", &(info->author),
		      "subject", &(info->subject),
		      "keywords", &(info->keywords),
		      "page-mode", &mode,
		      "page-layout", &layout,
		      "viewer-preferences", &view_prefs,
		      "permissions", &permissions,
		      "creator", &(info->creator),
		      "producer", &(info->producer),
		      "creation-date", &(info->creation_date),
		      "mod-date", &(info->modified_date),
		      "linearized", &(info->linearized),
		      "metadata", &metadata,
		      NULL);

	if (metadata != NULL) {
		pdf_document_parse_metadata (metadata, info);
		g_free (metadata);
	}

	info->n_pages = ev_document_get_n_pages (document);

	if (info->n_pages > 0) {
		ev_document_get_page_size (document, 0,
					   &(info->paper_width),
					   &(info->paper_height));
		// Convert to mm.
		info->paper_width = info->paper_width / 72.0f * 25.4f;
		info->paper_height = info->paper_height / 72.0f * 25.4f;
	}

	switch (layout) {
		case POPPLER_PAGE_LAYOUT_SINGLE_PAGE:
			info->layout = EV_DOCUMENT_LAYOUT_SINGLE_PAGE;
			break;
		case POPPLER_PAGE_LAYOUT_ONE_COLUMN:
			info->layout = EV_DOCUMENT_LAYOUT_ONE_COLUMN;
			break;
		case POPPLER_PAGE_LAYOUT_TWO_COLUMN_LEFT:
			info->layout = EV_DOCUMENT_LAYOUT_TWO_COLUMN_LEFT;
			break;
		case POPPLER_PAGE_LAYOUT_TWO_COLUMN_RIGHT:
			info->layout = EV_DOCUMENT_LAYOUT_TWO_COLUMN_RIGHT;
		case POPPLER_PAGE_LAYOUT_TWO_PAGE_LEFT:
			info->layout = EV_DOCUMENT_LAYOUT_TWO_PAGE_LEFT;
			break;
		case POPPLER_PAGE_LAYOUT_TWO_PAGE_RIGHT:
			info->layout = EV_DOCUMENT_LAYOUT_TWO_PAGE_RIGHT;
			break;
	        default:
			break;
	}

	switch (mode) {
		case POPPLER_PAGE_MODE_NONE:
			info->mode = EV_DOCUMENT_MODE_NONE;
			break;
		case POPPLER_PAGE_MODE_USE_THUMBS:
			info->mode = EV_DOCUMENT_MODE_USE_THUMBS;
			break;
		case POPPLER_PAGE_MODE_USE_OC:
			info->mode = EV_DOCUMENT_MODE_USE_OC;
			break;
		case POPPLER_PAGE_MODE_FULL_SCREEN:
			info->mode = EV_DOCUMENT_MODE_FULL_SCREEN;
			break;
		case POPPLER_PAGE_MODE_USE_ATTACHMENTS:
			info->mode = EV_DOCUMENT_MODE_USE_ATTACHMENTS;
	        default:
			break;
	}

	info->ui_hints = 0;
	if (view_prefs & POPPLER_VIEWER_PREFERENCES_HIDE_TOOLBAR) {
		info->ui_hints |= EV_DOCUMENT_UI_HINT_HIDE_TOOLBAR;
	}
	if (view_prefs & POPPLER_VIEWER_PREFERENCES_HIDE_MENUBAR) {
		info->ui_hints |= EV_DOCUMENT_UI_HINT_HIDE_MENUBAR;
	}
	if (view_prefs & POPPLER_VIEWER_PREFERENCES_HIDE_WINDOWUI) {
		info->ui_hints |= EV_DOCUMENT_UI_HINT_HIDE_WINDOWUI;
	}
	if (view_prefs & POPPLER_VIEWER_PREFERENCES_FIT_WINDOW) {
		info->ui_hints |= EV_DOCUMENT_UI_HINT_FIT_WINDOW;
	}
	if (view_prefs & POPPLER_VIEWER_PREFERENCES_CENTER_WINDOW) {
		info->ui_hints |= EV_DOCUMENT_UI_HINT_CENTER_WINDOW;
	}
	if (view_prefs & POPPLER_VIEWER_PREFERENCES_DISPLAY_DOC_TITLE) {
		info->ui_hints |= EV_DOCUMENT_UI_HINT_DISPLAY_DOC_TITLE;
	}
	if (view_prefs & POPPLER_VIEWER_PREFERENCES_DIRECTION_RTL) {
		info->ui_hints |=  EV_DOCUMENT_UI_HINT_DIRECTION_RTL;
	}

	info->permissions = 0;
	if (permissions & POPPLER_PERMISSIONS_OK_TO_PRINT) {
		info->permissions |= EV_DOCUMENT_PERMISSIONS_OK_TO_PRINT;
	}
	if (permissions & POPPLER_PERMISSIONS_OK_TO_MODIFY) {
		info->permissions |= EV_DOCUMENT_PERMISSIONS_OK_TO_MODIFY;
	}
	if (permissions & POPPLER_PERMISSIONS_OK_TO_COPY) {
		info->permissions |= EV_DOCUMENT_PERMISSIONS_OK_TO_COPY;
	}
	if (permissions & POPPLER_PERMISSIONS_OK_TO_ADD_NOTES) {
		info->permissions |= EV_DOCUMENT_PERMISSIONS_OK_TO_ADD_NOTES;
	}

	if (ev_document_security_has_document_security (EV_DOCUMENT_SECURITY (document))) {
		/* translators: this is the document security state */
		info->security = g_strdup (_("Yes"));
	} else {
		/* translators: this is the document security state */
		info->security = g_strdup (_("No"));
	}

	return info;
}

static void
pdf_document_class_init (PdfDocumentClass *klass)
{
	GObjectClass    *g_object_class = G_OBJECT_CLASS (klass);
	EvDocumentClass *ev_document_class = EV_DOCUMENT_CLASS (klass);

	g_object_class->dispose = pdf_document_dispose;

	ev_document_class->save = pdf_document_save;
	ev_document_class->load = pdf_document_load;
	ev_document_class->get_n_pages = pdf_document_get_n_pages;
	ev_document_class->get_page = pdf_document_get_page;
	ev_document_class->get_page_size = pdf_document_get_page_size;
	ev_document_class->get_page_label = pdf_document_get_page_label;
	ev_document_class->render = pdf_document_render;
	ev_document_class->get_info = pdf_document_get_info;
}

/* EvDocumentSecurity */
static gboolean
pdf_document_has_document_security (EvDocumentSecurity *document_security)
{
	/* FIXME: do we really need to have this? */
	return FALSE;
}

static void
pdf_document_set_password (EvDocumentSecurity *document_security,
			   const char         *password)
{
	PdfDocument *document = PDF_DOCUMENT (document_security);

	if (document->password)
		g_free (document->password);

	document->password = g_strdup (password);
}

static void
pdf_document_security_iface_init (EvDocumentSecurityIface *iface)
{
	iface->has_document_security = pdf_document_has_document_security;
	iface->set_password = pdf_document_set_password;
}

static gdouble
pdf_document_fonts_get_progress (EvDocumentFonts *document_fonts)
{
	PdfDocument *pdf_document = PDF_DOCUMENT (document_fonts);
	int n_pages;

        n_pages = pdf_document_get_n_pages (EV_DOCUMENT (pdf_document));

	return (double)pdf_document->fonts_scanned_pages / (double)n_pages;
}

static gboolean
pdf_document_fonts_scan (EvDocumentFonts *document_fonts,
			 int              n_pages)
{
	PdfDocument *pdf_document = PDF_DOCUMENT (document_fonts);
	gboolean result;

	g_return_val_if_fail (PDF_IS_DOCUMENT (document_fonts), FALSE);

	if (pdf_document->font_info == NULL) { 
		pdf_document->font_info = poppler_font_info_new (pdf_document->document);
	}

	if (pdf_document->fonts_iter) {
		poppler_fonts_iter_free (pdf_document->fonts_iter);
	}

	pdf_document->fonts_scanned_pages += n_pages;

	result = poppler_font_info_scan (pdf_document->font_info, n_pages,
				         &pdf_document->fonts_iter);
	if (!result) {
		pdf_document->fonts_scanned_pages = 0;
		poppler_font_info_free (pdf_document->font_info);
		pdf_document->font_info = NULL;	
	}

	return result;
}

static const char *
font_type_to_string (PopplerFontType type)
{
	switch (type) {
	        case POPPLER_FONT_TYPE_TYPE1:
			return _("Type 1");
	        case POPPLER_FONT_TYPE_TYPE1C:
			return _("Type 1C");
	        case POPPLER_FONT_TYPE_TYPE3:
			return _("Type 3");
	        case POPPLER_FONT_TYPE_TRUETYPE:
			return _("TrueType");
	        case POPPLER_FONT_TYPE_CID_TYPE0:
			return _("Type 1 (CID)");
	        case POPPLER_FONT_TYPE_CID_TYPE0C:
			return _("Type 1C (CID)");
	        case POPPLER_FONT_TYPE_CID_TYPE2:
			return _("TrueType (CID)");
	        default:
			return _("Unknown font type");
	}
}

static void
pdf_document_fonts_fill_model (EvDocumentFonts *document_fonts,
			       GtkTreeModel    *model)
{
	PdfDocument *pdf_document = PDF_DOCUMENT (document_fonts);
	PopplerFontsIter *iter = pdf_document->fonts_iter;

	g_return_if_fail (PDF_IS_DOCUMENT (document_fonts));

	if (!iter)
		return;

	do {
		GtkTreeIter list_iter;
		const char *name;
		const char *type;
		const char *embedded;
		char *details;
		
		name = poppler_fonts_iter_get_name (iter);

		if (name == NULL) {
			name = _("No name");
		}

		type = font_type_to_string (
			poppler_fonts_iter_get_font_type (iter));

		if (poppler_fonts_iter_is_embedded (iter)) {
			if (poppler_fonts_iter_is_subset (iter))
				embedded = _("Embedded subset");
			else
				embedded = _("Embedded");
		} else {
			embedded = _("Not embedded");
		}

		details = g_markup_printf_escaped ("%s\n%s", type, embedded);

		gtk_list_store_append (GTK_LIST_STORE (model), &list_iter);
		gtk_list_store_set (GTK_LIST_STORE (model), &list_iter,
				    EV_DOCUMENT_FONTS_COLUMN_NAME, name,
				    EV_DOCUMENT_FONTS_COLUMN_DETAILS, details,
				    -1);

		g_free (details);
	} while (poppler_fonts_iter_next (iter));
}

static void
pdf_document_document_fonts_iface_init (EvDocumentFontsIface *iface)
{
	iface->fill_model = pdf_document_fonts_fill_model;
	iface->scan = pdf_document_fonts_scan;
	iface->get_progress = pdf_document_fonts_get_progress;
}

static gboolean
pdf_document_links_has_document_links (EvDocumentLinks *document_links)
{
	PdfDocument *pdf_document = PDF_DOCUMENT (document_links);
	PopplerIndexIter *iter;

	g_return_val_if_fail (PDF_IS_DOCUMENT (document_links), FALSE);

	iter = poppler_index_iter_new (pdf_document->document);
	if (iter == NULL)
		return FALSE;
	poppler_index_iter_free (iter);

	return TRUE;
}

static EvLinkDest *
ev_link_dest_from_dest (PdfDocument *pdf_document,
			PopplerDest *dest)
{
	EvLinkDest *ev_dest = NULL;
	const char *unimplemented_dest = NULL;

	g_assert (dest != NULL);

	switch (dest->type) {
	        case POPPLER_DEST_XYZ: {
			PopplerPage *poppler_page;
			double height;

			poppler_page = poppler_document_get_page (pdf_document->document,
								  MAX (0, dest->page_num - 1));
			poppler_page_get_size (poppler_page, NULL, &height);
			ev_dest = ev_link_dest_new_xyz (dest->page_num - 1,
							dest->left,
							height - MIN (height, dest->top),
							dest->zoom,
							dest->change_left,
							dest->change_top,
							dest->change_zoom);
			g_object_unref (poppler_page);
		}
			break;
	        case POPPLER_DEST_FITB:
		case POPPLER_DEST_FIT:
			ev_dest = ev_link_dest_new_fit (dest->page_num - 1);
			break;
		case POPPLER_DEST_FITBH:
	        case POPPLER_DEST_FITH: {
			PopplerPage *poppler_page;
			double height;

			poppler_page = poppler_document_get_page (pdf_document->document,
								  MAX (0, dest->page_num - 1));
			poppler_page_get_size (poppler_page, NULL, &height);
			ev_dest = ev_link_dest_new_fith (dest->page_num - 1,
							 height - MIN (height, dest->top),
							 dest->change_top);
			g_object_unref (poppler_page);
		}
			break;
		case POPPLER_DEST_FITBV:
	        case POPPLER_DEST_FITV:
			ev_dest = ev_link_dest_new_fitv (dest->page_num - 1,
							 dest->left,
							 dest->change_left);
			break;
	        case POPPLER_DEST_FITR: {
			PopplerPage *poppler_page;
			double height;

			poppler_page = poppler_document_get_page (pdf_document->document,
								  MAX (0, dest->page_num - 1));
			poppler_page_get_size (poppler_page, NULL, &height);
			ev_dest = ev_link_dest_new_fitr (dest->page_num - 1,
							 dest->left,
							 height - MIN (height, dest->bottom),
							 dest->right,
							 height - MIN (height, dest->top));
			g_object_unref (poppler_page);
		}
			break;
	        case POPPLER_DEST_NAMED:
			ev_dest = ev_link_dest_new_named (dest->named_dest);
			break;
	        case POPPLER_DEST_UNKNOWN:
			unimplemented_dest = "POPPLER_DEST_UNKNOWN";
			break;
	}

	if (unimplemented_dest) {
		g_warning ("Unimplemented destination: %s, please post a "
		           "bug report in Evince bugzilla "
		           "(http://bugzilla.gnome.org) with a testcase.",
			   unimplemented_dest);
	}

	if (!ev_dest)
		ev_dest = ev_link_dest_new_page (dest->page_num - 1);
	
	return ev_dest;
}

static EvLink *
ev_link_from_action (PdfDocument   *pdf_document,
		     PopplerAction *action)
{
	EvLink       *link = NULL;
	EvLinkAction *ev_action = NULL;
	const char   *unimplemented_action = NULL;

	switch (action->type) {
	        case POPPLER_ACTION_NONE:
			break;
	        case POPPLER_ACTION_GOTO_DEST: {
			EvLinkDest *dest;
			
			dest = ev_link_dest_from_dest (pdf_document, action->goto_dest.dest);
			ev_action = ev_link_action_new_dest (dest);
		}
			break;
	        case POPPLER_ACTION_GOTO_REMOTE: {
			EvLinkDest *dest;
			
			dest = ev_link_dest_from_dest (pdf_document, action->goto_remote.dest);
			ev_action = ev_link_action_new_remote (dest, 
							       action->goto_remote.file_name);
			
		}
			break;
	        case POPPLER_ACTION_LAUNCH:
			ev_action = ev_link_action_new_launch (action->launch.file_name,
							       action->launch.params);
			break;
	        case POPPLER_ACTION_URI:
			ev_action = ev_link_action_new_external_uri (action->uri.uri);
			break;
	        case POPPLER_ACTION_NAMED:
			ev_action = ev_link_action_new_named (action->named.named_dest);
			break;
	        case POPPLER_ACTION_MOVIE:
			unimplemented_action = "POPPLER_ACTION_MOVIE";
			break;
	        case POPPLER_ACTION_UNKNOWN:
			unimplemented_action = "POPPLER_ACTION_UNKNOWN";
	}
	
	if (unimplemented_action) {
		g_warning ("Unimplemented action: %s, please post a bug report "
			   "in Evince bugzilla (http://bugzilla.gnome.org) "
			   "with a testcase.", unimplemented_action);
	}
	
	link = ev_link_new (action->any.title, ev_action);
	
	return link;	
}

static void
build_tree (PdfDocument      *pdf_document,
	    GtkTreeModel     *model,
	    GtkTreeIter      *parent,
	    PopplerIndexIter *iter)
{
	
	do {
		GtkTreeIter tree_iter;
		PopplerIndexIter *child;
		PopplerAction *action;
		EvLink *link = NULL;
		gboolean expand;
		char *title_markup;
		
		action = poppler_index_iter_get_action (iter);
		expand = poppler_index_iter_is_open (iter);

		if (!action)
			continue;

		switch (action->type) {
		        case POPPLER_ACTION_GOTO_DEST: {
				/* For bookmarks, solve named destinations */
				if (action->goto_dest.dest->type == POPPLER_DEST_NAMED) {
					PopplerDest *dest;
					EvLinkDest *ev_dest = NULL;
					EvLinkAction *ev_action;
					
					dest = poppler_document_find_dest (pdf_document->document,
									   action->goto_dest.dest->named_dest);
					if (!dest) {
						link = ev_link_from_action (pdf_document, action);
						break;
					}
					
					ev_dest = ev_link_dest_from_dest (pdf_document, dest);
					poppler_dest_free (dest);
					
					ev_action = ev_link_action_new_dest (ev_dest);
					link = ev_link_new (action->any.title, ev_action);
				} else {
					link = ev_link_from_action (pdf_document, action);
				}
			}
				break;
		        default:
				link = ev_link_from_action (pdf_document, action);
				break;
		}
		
		if (!link || strlen (ev_link_get_title (link)) <= 0) {
			poppler_action_free (action);
			if (link)
				g_object_unref (link);
			
			continue;
		}

		gtk_tree_store_append (GTK_TREE_STORE (model), &tree_iter, parent);
		title_markup = g_markup_escape_text (ev_link_get_title (link), -1);
		
		gtk_tree_store_set (GTK_TREE_STORE (model), &tree_iter,
				    EV_DOCUMENT_LINKS_COLUMN_MARKUP, title_markup,
				    EV_DOCUMENT_LINKS_COLUMN_LINK, link,
				    EV_DOCUMENT_LINKS_COLUMN_EXPAND, expand,
				    -1);
		
		g_free (title_markup);
		g_object_unref (link);
		
		child = poppler_index_iter_get_child (iter);
		if (child)
			build_tree (pdf_document, model, &tree_iter, child);
		poppler_index_iter_free (child);
		poppler_action_free (action);
		
	} while (poppler_index_iter_next (iter));
}

static GtkTreeModel *
pdf_document_links_get_links_model (EvDocumentLinks *document_links)
{
	PdfDocument *pdf_document = PDF_DOCUMENT (document_links);
	GtkTreeModel *model = NULL;
	PopplerIndexIter *iter;
	
	g_return_val_if_fail (PDF_IS_DOCUMENT (document_links), NULL);

	iter = poppler_index_iter_new (pdf_document->document);
	/* Create the model if we have items*/
	if (iter != NULL) {
		model = (GtkTreeModel *) gtk_tree_store_new (EV_DOCUMENT_LINKS_COLUMN_NUM_COLUMNS,
							     G_TYPE_STRING,
							     G_TYPE_OBJECT,
							     G_TYPE_BOOLEAN,
							     G_TYPE_STRING);
		build_tree (pdf_document, model, NULL, iter);
		poppler_index_iter_free (iter);
	}
	
	return model;
}

static GList *
pdf_document_links_get_links (EvDocumentLinks *document_links,
			      EvPage          *page)
{
	PdfDocument *pdf_document;
	PopplerPage *poppler_page;
	GList *retval = NULL;
	GList *mapping_list;
	GList *list;
	double height;

	pdf_document = PDF_DOCUMENT (document_links);
	poppler_page = POPPLER_PAGE (page->backend_page);
	mapping_list = poppler_page_get_link_mapping (poppler_page);
	poppler_page_get_size (poppler_page, NULL, &height);

	for (list = mapping_list; list; list = list->next) {
		PopplerLinkMapping *link_mapping;
		EvMapping *ev_link_mapping;

		link_mapping = (PopplerLinkMapping *)list->data;
		ev_link_mapping = g_new (EvMapping, 1);
		ev_link_mapping->data = ev_link_from_action (pdf_document,
							     link_mapping->action);
		ev_link_mapping->area.x1 = link_mapping->area.x1;
		ev_link_mapping->area.x2 = link_mapping->area.x2;
		/* Invert this for X-style coordinates */
		ev_link_mapping->area.y1 = height - link_mapping->area.y2;
		ev_link_mapping->area.y2 = height - link_mapping->area.y1;

		retval = g_list_prepend (retval, ev_link_mapping);
	}

	poppler_page_free_link_mapping (mapping_list);

	return g_list_reverse (retval);
}

static EvLinkDest *
pdf_document_links_find_link_dest (EvDocumentLinks  *document_links,
				   const gchar      *link_name)
{
	PdfDocument *pdf_document;
	PopplerDest *dest;
	EvLinkDest *ev_dest = NULL;

	pdf_document = PDF_DOCUMENT (document_links);
	dest = poppler_document_find_dest (pdf_document->document,
					   link_name);
	if (dest) {
		ev_dest = ev_link_dest_from_dest (pdf_document, dest);
		poppler_dest_free (dest);
	}

	return ev_dest;
}

static void
pdf_document_document_links_iface_init (EvDocumentLinksIface *iface)
{
	iface->has_document_links = pdf_document_links_has_document_links;
	iface->get_links_model = pdf_document_links_get_links_model;
	iface->get_links = pdf_document_links_get_links;
	iface->find_link_dest = pdf_document_links_find_link_dest;
}

static GList *
pdf_document_images_get_image_mapping (EvDocumentImages *document_images,
				       EvPage           *page)
{
	GList *retval = NULL;
	PdfDocument *pdf_document;
	PopplerPage *poppler_page;
	GList *mapping_list;
	GList *list;

	pdf_document = PDF_DOCUMENT (document_images);
	poppler_page = POPPLER_PAGE (page->backend_page);
	mapping_list = poppler_page_get_image_mapping (poppler_page);

	for (list = mapping_list; list; list = list->next) {
		PopplerImageMapping *image_mapping;
		EvMapping *ev_image_mapping;

		image_mapping = (PopplerImageMapping *)list->data;

		ev_image_mapping = g_new (EvMapping, 1);
		
		ev_image_mapping->data = ev_image_new (page->index, image_mapping->image_id);
		ev_image_mapping->area.x1 = image_mapping->area.x1;
		ev_image_mapping->area.y1 = image_mapping->area.y1;
		ev_image_mapping->area.x2 = image_mapping->area.x2;
		ev_image_mapping->area.y2 = image_mapping->area.y2;

		retval = g_list_prepend (retval, ev_image_mapping);
	}

	poppler_page_free_image_mapping (mapping_list);

	return g_list_reverse (retval);
}

GdkPixbuf *
pdf_document_images_get_image (EvDocumentImages *document_images,
			       EvImage          *image)
{
	GdkPixbuf       *retval = NULL;
#ifdef HAVE_POPPLER_PAGE_GET_IMAGE
	PdfDocument     *pdf_document;
	PopplerPage     *poppler_page;
	cairo_surface_t *surface;

	pdf_document = PDF_DOCUMENT (document_images);
	poppler_page = poppler_document_get_page (pdf_document->document,
						  ev_image_get_page (image));

	surface = poppler_page_get_image (poppler_page, ev_image_get_id (image));
	if (surface) {
		retval = ev_document_misc_pixbuf_from_surface (surface);
		cairo_surface_destroy (surface);
	}

	g_object_unref (poppler_page);
#endif
	return retval;
}

static void
pdf_document_document_images_iface_init (EvDocumentImagesIface *iface)
{
	iface->get_image_mapping = pdf_document_images_get_image_mapping;
	iface->get_image = pdf_document_images_get_image;
}

static GdkPixbuf *
make_thumbnail_for_page (PopplerPage     *poppler_page,
			 EvRenderContext *rc,
			 gint             width,
			 gint             height)
{
	GdkPixbuf *pixbuf;

#ifdef POPPLER_WITH_GDK
	pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB, FALSE, 8,
				 width, height);
	gdk_pixbuf_fill (pixbuf, 0xffffffff);

	ev_document_fc_mutex_lock ();
	poppler_page_render_to_pixbuf (poppler_page, 0, 0,
				       width, height,
				       rc->scale, rc->rotation, pixbuf);
	ev_document_fc_mutex_unlock ();
#else
	cairo_surface_t *surface;

	ev_document_fc_mutex_lock ();
	surface = pdf_page_render (poppler_page, width, height, rc);
	ev_document_fc_mutex_unlock ();
	
	pixbuf = ev_document_misc_pixbuf_from_surface (surface);
	cairo_surface_destroy (surface);
#endif /* POPPLER_WITH_GDK */

	return pixbuf;
}

static GdkPixbuf *
pdf_document_thumbnails_get_thumbnail (EvDocumentThumbnails *document_thumbnails,
				       EvRenderContext      *rc, 
				       gboolean              border)
{
	PdfDocument *pdf_document = PDF_DOCUMENT (document_thumbnails);
	PopplerPage *poppler_page;
	GdkPixbuf *pixbuf = NULL;
	GdkPixbuf *border_pixbuf;
	gint width, height;

	poppler_page = POPPLER_PAGE (rc->page->backend_page);

	pdf_document_thumbnails_get_dimensions (EV_DOCUMENT_THUMBNAILS (pdf_document),
						rc, &width, &height);
	
#ifdef POPPLER_WITH_GDK
	pixbuf = poppler_page_get_thumbnail_pixbuf (poppler_page);
#else
	cairo_surface_t *surface;
	
	surface = poppler_page_get_thumbnail (poppler_page);
	if (surface) {
		pixbuf = ev_document_misc_pixbuf_from_surface (surface);
		cairo_surface_destroy (surface);
	}
#endif /* POPPLER_WITH_GDK */

	if (pixbuf != NULL) {
		int thumb_width = (rc->rotation == 90 || rc->rotation == 270) ?
			gdk_pixbuf_get_height (pixbuf) :
			gdk_pixbuf_get_width (pixbuf);

		if (thumb_width == width) {
			GdkPixbuf *rotated_pixbuf;

			rotated_pixbuf = gdk_pixbuf_rotate_simple (pixbuf,
								   (GdkPixbufRotation) (360 - rc->rotation));
			g_object_unref (pixbuf);
			pixbuf = rotated_pixbuf;
		} else {
			/* The provided thumbnail has a different size */
			g_object_unref (pixbuf);
			pixbuf = make_thumbnail_for_page (poppler_page, rc, width, height);
		}
	} else {
		/* There is no provided thumbnail. We need to make one. */
		pixbuf = make_thumbnail_for_page (poppler_page, rc, width, height);
	}

        if (border && pixbuf) {
		border_pixbuf = ev_document_misc_get_thumbnail_frame (-1, -1, pixbuf);
		g_object_unref (pixbuf);
		pixbuf = border_pixbuf;
	}		

	return pixbuf;
}

static void
pdf_document_thumbnails_get_dimensions (EvDocumentThumbnails *document_thumbnails,
					EvRenderContext      *rc,
					gint                 *width,
					gint                 *height)
{
	double page_width, page_height;
	
	poppler_page_get_size (POPPLER_PAGE (rc->page->backend_page),
			       &page_width, &page_height);
	
	*width = MAX ((gint)(page_width * rc->scale + 0.5), 1);
	*height = MAX ((gint)(page_height * rc->scale + 0.5), 1);

	if (rc->rotation == 90 || rc->rotation == 270) {
		gint  temp;

		temp = *width;
		*width = *height;
		*height = temp;
	}
}

static void
pdf_document_document_thumbnails_iface_init (EvDocumentThumbnailsIface *iface)
{
	iface->get_thumbnail = pdf_document_thumbnails_get_thumbnail;
	iface->get_dimensions = pdf_document_thumbnails_get_dimensions;
}


static GList *
pdf_document_find_find_text (EvDocumentFind *document_find,
			     EvPage         *page,
			     const gchar    *text,
			     gboolean        case_sensitive)
{
	GList *matches, *l;
	PopplerPage *poppler_page;
	gdouble height;
	
	g_return_val_if_fail (POPPLER_IS_PAGE (page->backend_page), NULL);
	g_return_val_if_fail (text != NULL, NULL);

	poppler_page = POPPLER_PAGE (page->backend_page);
	
	matches = poppler_page_find_text (poppler_page, text);
	if (!matches)
		return NULL;

	poppler_page_get_size (poppler_page, NULL, &height);
	for (l = matches; l && l->data; l = g_list_next (l)) {
		PopplerRectangle *rect = (PopplerRectangle *)l->data;
		gdouble           tmp;

		tmp = rect->y1;
		rect->y1 = height - rect->y2;
		rect->y2 = height - tmp;
	}
	
	return matches;
}

static void
pdf_document_find_iface_init (EvDocumentFindIface *iface)
{
        iface->find_text = pdf_document_find_find_text;
}

static void
pdf_print_context_free (PdfPrintContext *ctx)
{
	if (!ctx)
		return;

#ifdef HAVE_CAIRO_PRINT
	if (ctx->cr) {
		cairo_destroy (ctx->cr);
		ctx->cr = NULL;
	}
#else
	if (ctx->ps_file) {
		poppler_ps_file_free (ctx->ps_file);
		ctx->ps_file = NULL;
	}
#endif
	g_free (ctx);
}

static void
pdf_document_file_exporter_begin (EvFileExporter        *exporter,
				  EvFileExporterContext *fc)
{
	PdfDocument *pdf_document = PDF_DOCUMENT (exporter);
	PdfPrintContext *ctx;
#ifdef HAVE_CAIRO_PRINT
	gdouble width, height;
	cairo_surface_t *surface = NULL;
#endif
	
	if (pdf_document->print_ctx)
		pdf_print_context_free (pdf_document->print_ctx);
	pdf_document->print_ctx = g_new0 (PdfPrintContext, 1);
	ctx = pdf_document->print_ctx;
	ctx->format = fc->format;
	
#ifdef HAVE_CAIRO_PRINT
	ctx->pages_per_sheet = CLAMP (fc->pages_per_sheet, 1, 16);

	ctx->paper_width = fc->paper_width;
	ctx->paper_height = fc->paper_height;
	
	switch (fc->pages_per_sheet) {
	        default:
	        case 1:
			ctx->pages_x = 1;
			ctx->pages_y = 1;
			break;
	        case 2:
			ctx->pages_x = 1;
			ctx->pages_y = 2;
			break;
	        case 4:
			ctx->pages_x = 2;
			ctx->pages_y = 2;
			break;
	        case 6:
			ctx->pages_x = 2;
			ctx->pages_y = 3;
			break;
	        case 9:
			ctx->pages_x = 3;
			ctx->pages_y = 3;
			break;
	        case 16:
			ctx->pages_x = 4;
			ctx->pages_y = 4;
			break;
	}

	ctx->pages_printed = 0;
	
	switch (fc->format) {
	        case EV_FILE_FORMAT_PS:
#ifdef HAVE_CAIRO_PS
			surface = cairo_ps_surface_create (fc->filename, fc->paper_width, fc->paper_height);
#endif
			break;
	        case EV_FILE_FORMAT_PDF:
#ifdef HAVE_CAIRO_PDF
			surface = cairo_pdf_surface_create (fc->filename, fc->paper_width, fc->paper_height);
#endif
			break;
	        default:
			g_assert_not_reached ();
	}

	ctx->cr = cairo_create (surface);
	cairo_surface_destroy (surface);

#else /* HAVE_CAIRO_PRINT */
	if (ctx->format == EV_FILE_FORMAT_PS) {
		ctx->ps_file = poppler_ps_file_new (pdf_document->document,
						    fc->filename, fc->first_page,
						    fc->last_page - fc->first_page + 1);
		poppler_ps_file_set_paper_size (ctx->ps_file, fc->paper_width, fc->paper_height);
		poppler_ps_file_set_duplex (ctx->ps_file, fc->duplex);
	}
#endif /* HAVE_CAIRO_PRINT */
}

static void
pdf_document_file_exporter_begin_page (EvFileExporter *exporter)
{
	PdfDocument *pdf_document = PDF_DOCUMENT (exporter);
	PdfPrintContext *ctx = pdf_document->print_ctx;
	
	g_return_if_fail (pdf_document->print_ctx != NULL);

	ctx->pages_printed = 0;
	
#ifdef HAVE_CAIRO_PRINT
	if (ctx->paper_width > ctx->paper_height) {
		if (ctx->format == EV_FILE_FORMAT_PS) {
			cairo_ps_surface_set_size (cairo_get_target (ctx->cr),
						   ctx->paper_height,
						   ctx->paper_width);
		} else if (ctx->format == EV_FILE_FORMAT_PDF) {
			cairo_pdf_surface_set_size (cairo_get_target (ctx->cr),
						    ctx->paper_height,
						    ctx->paper_width);
		}
	}
#endif /* HAVE_CAIRO_PRINT */
}

static void
pdf_document_file_exporter_do_page (EvFileExporter  *exporter,
				    EvRenderContext *rc)
{
	PdfDocument *pdf_document = PDF_DOCUMENT (exporter);
	PdfPrintContext *ctx = pdf_document->print_ctx;
	PopplerPage *poppler_page;
#ifdef HAVE_CAIRO_PRINT
	gdouble  page_width, page_height;
	gint     x, y;
	gboolean rotate;
	gdouble  width, height;
	gdouble  pwidth, pheight;
	gdouble  xscale, yscale;
#endif

	g_return_if_fail (pdf_document->print_ctx != NULL);

	poppler_page = POPPLER_PAGE (rc->page->backend_page);
	
#ifdef HAVE_CAIRO_PRINT
	x = (ctx->pages_printed % ctx->pages_per_sheet) % ctx->pages_x;
	y = (ctx->pages_printed % ctx->pages_per_sheet) / ctx->pages_x;
	poppler_page_get_size (poppler_page, &page_width, &page_height);

	if (page_width > page_height && page_width > ctx->paper_width) {
		rotate = TRUE;
	} else {
		rotate = FALSE;
	}

	/* Use always portrait mode and rotate when necessary */
	if (ctx->paper_width > ctx->paper_height) {
		width = ctx->paper_height;
		height = ctx->paper_width;
		rotate = !rotate;
	} else {
		width = ctx->paper_width;
		height = ctx->paper_height;
	}

	if (ctx->pages_per_sheet == 2 || ctx->pages_per_sheet == 6) {
		rotate = !rotate;
	}	

	if (rotate) {
		gint tmp1;
		gdouble tmp2;

		tmp1 = x;
		x = y;
		y = tmp1;

		tmp2 = page_width;
		page_width = page_height;
		page_height = tmp2;
	}

	pwidth = width / ctx->pages_x;
	pheight = height / ctx->pages_y;

	if ((page_width > pwidth || page_height > pheight) ||
	    (page_width < pwidth && page_height < pheight)) {
		xscale = pwidth / page_width;
		yscale = pheight / page_height;
		
		if (yscale < xscale) {
			xscale = yscale;
		} else {
			yscale = xscale;
		}
		
	} else {	
		xscale = yscale = 1;
	}

	/* TODO: center */

	cairo_save (ctx->cr);
	if (rotate) {
		cairo_matrix_t matrix;
		
		cairo_translate (ctx->cr, (2 * y + 1) * pwidth, 0);
		cairo_matrix_init (&matrix,
				   0,  1,
				   -1,  0,
				   0,  0);
		cairo_transform (ctx->cr, &matrix);
	}
	
	cairo_translate (ctx->cr,
			 x * (rotate ? pheight : pwidth),
			 y * (rotate ? pwidth : pheight));
	cairo_scale (ctx->cr, xscale, yscale);

	poppler_page_render_for_printing (poppler_page, ctx->cr);

	ctx->pages_printed++;
			
	cairo_restore (ctx->cr);
#else /* HAVE_CAIRO_PRINT */
	if (ctx->format == EV_FILE_FORMAT_PS)
		poppler_page_render_to_ps (poppler_page, ctx->ps_file);
#endif /* HAVE_CAIRO_PRINT */
}

static void
pdf_document_file_exporter_end_page (EvFileExporter *exporter)
{
	PdfDocument *pdf_document = PDF_DOCUMENT (exporter);
	PdfPrintContext *ctx = pdf_document->print_ctx;
	
	g_return_if_fail (pdf_document->print_ctx != NULL);

#ifdef HAVE_CAIRO_PRINT
	cairo_show_page (ctx->cr);
#endif
}

static void
pdf_document_file_exporter_end (EvFileExporter *exporter)
{
	PdfDocument *pdf_document = PDF_DOCUMENT (exporter);

	pdf_print_context_free (pdf_document->print_ctx);
	pdf_document->print_ctx = NULL;
}

static EvFileExporterCapabilities
pdf_document_file_exporter_get_capabilities (EvFileExporter *exporter)
{
	return  (EvFileExporterCapabilities) (
		EV_FILE_EXPORTER_CAN_PAGE_SET |
		EV_FILE_EXPORTER_CAN_COPIES |
		EV_FILE_EXPORTER_CAN_COLLATE |
		EV_FILE_EXPORTER_CAN_REVERSE |
		EV_FILE_EXPORTER_CAN_SCALE |
#ifdef HAVE_CAIRO_PRINT
#ifdef HAVE_POPPLER_PAGE_RENDER
		EV_FILE_EXPORTER_CAN_NUMBER_UP |
#endif
#endif
		
#ifdef HAVE_CAIRO_PDF
#ifdef HAVE_POPPLER_PAGE_RENDER
		EV_FILE_EXPORTER_CAN_GENERATE_PDF |
#endif
#endif
		EV_FILE_EXPORTER_CAN_GENERATE_PS);
}

static void
pdf_document_file_exporter_iface_init (EvFileExporterIface *iface)
{
        iface->begin = pdf_document_file_exporter_begin;
	iface->begin_page = pdf_document_file_exporter_begin_page;
        iface->do_page = pdf_document_file_exporter_do_page;
	iface->end_page = pdf_document_file_exporter_end_page;
        iface->end = pdf_document_file_exporter_end;
	iface->get_capabilities = pdf_document_file_exporter_get_capabilities;
}

#ifdef HAVE_POPPLER_PAGE_RENDER
/* EvDocumentPrint */
static void
pdf_document_print_print_page (EvDocumentPrint *document,
			       EvPage          *page,
			       cairo_t         *cr)
{
	PdfDocument *pdf_document = PDF_DOCUMENT (document);

	poppler_page_render_for_printing (POPPLER_PAGE (page->backend_page), cr);
}

static void
pdf_document_document_print_iface_init (EvDocumentPrintIface *iface)
{
	iface->print_page = pdf_document_print_print_page;
}
#endif /* HAVE_POPPLER_PAGE_RENDER */

static void
pdf_selection_render_selection (EvSelection      *selection,
				EvRenderContext  *rc,
				cairo_surface_t **surface,
				EvRectangle      *points,
				EvRectangle      *old_points,
				EvSelectionStyle  style,
				GdkColor         *text,
				GdkColor         *base)
{
	PopplerPage *poppler_page;
	double width_points, height_points;
	gint width, height;

	poppler_page = POPPLER_PAGE (rc->page->backend_page);

	poppler_page_get_size (poppler_page,
			       &width_points, &height_points);
	width = (int) ((width_points * rc->scale) + 0.5);
	height = (int) ((height_points * rc->scale) + 0.5);

#ifdef HAVE_POPPLER_PAGE_RENDER
	cairo_t *cr;
	PopplerColor text_color, base_color;
	
	text_color.red = text->red;
	text_color.green = text->green;
	text_color.blue = text->blue;

	base_color.red = base->red;
	base_color.green = base->green;
	base_color.blue = base->blue;

	if (*surface == NULL) {
		*surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32,
						       width, height);
		
	}

	cr = cairo_create (*surface);
	cairo_scale (cr, rc->scale, rc->scale);
	cairo_surface_set_device_offset (*surface, 0, 0);
	memset (cairo_image_surface_get_data (*surface), 0x00,
		cairo_image_surface_get_height (*surface) *
		cairo_image_surface_get_stride (*surface));
	poppler_page_render_selection (poppler_page,
				       cr,
				       (PopplerRectangle *)points,
				       (PopplerRectangle *)old_points,
				       (PopplerSelectionStyle)style,
				       &text_color,
				       &base_color);
	cairo_destroy (cr);
#else /* HAVE_POPPLER_PAGE_RENDER */
	GdkPixbuf *pixbuf;
	
	pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB,
				 TRUE, 8,
				 width, height);

	poppler_page_render_selection_to_pixbuf (poppler_page,
						 rc->scale, rc->rotation, pixbuf,
						 (PopplerRectangle *)points,
						 (PopplerRectangle *)old_points,
						 (PopplerSelectionStyle)style,
						 text,
						 base);
	if (*surface)
		cairo_surface_destroy (*surface);
	*surface = ev_document_misc_surface_from_pixbuf (pixbuf);
	g_object_unref (pixbuf);
#endif /* HAVE_POPPLER_PAGE_RENDER */
}

static gchar *
pdf_selection_get_selected_text (EvSelection     *selection,
				 EvRenderContext *rc,
				 EvSelectionStyle style,
				 EvRectangle     *points)
{
	PopplerPage *poppler_page;
	PopplerRectangle r;
	double height;
	char *retval;
	
	poppler_page = POPPLER_PAGE (rc->page->backend_page);

	poppler_page_get_size (poppler_page, NULL, &height);
	r.x1 = points->x1;
	r.y1 = height - points->y2;
	r.x2 = points->x2;
	r.y2 = height - points->y1;

	retval = poppler_page_get_text (poppler_page,
					(PopplerSelectionStyle)style,
					&r);

	return retval;
}

static GdkRegion *
create_gdk_region_from_poppler_region (GList *region)
{
	GList *l;
	GdkRegion *retval;
	
	retval = gdk_region_new ();
	
	for (l = region; l; l = g_list_next (l)) {
		PopplerRectangle *rectangle;
		GdkRectangle      rect;
		
		rectangle = (PopplerRectangle *)l->data;
		
		rect.x = (gint) rectangle->x1;
		rect.y = (gint) rectangle->y1;
		rect.width  = (gint) (rectangle->x2 - rectangle->x1);
		rect.height = (gint) (rectangle->y2 - rectangle->y1);
		gdk_region_union_with_rect (retval, &rect);
		
		poppler_rectangle_free (rectangle);
	}

	return retval;
}

static GdkRegion *
pdf_selection_get_selection_region (EvSelection     *selection,
				    EvRenderContext *rc,
				    EvSelectionStyle style,
				    EvRectangle     *points)
{
	PopplerPage *poppler_page;
	GdkRegion   *retval;
	GList       *region;

	poppler_page = POPPLER_PAGE (rc->page->backend_page);
	
	region = poppler_page_get_selection_region (poppler_page,
						    rc->scale,
						    (PopplerSelectionStyle)style,
						    (PopplerRectangle *) points);
	retval = create_gdk_region_from_poppler_region (region);
	g_list_free (region);
	
	return retval;
}

static GdkRegion *
pdf_selection_get_selection_map (EvSelection *selection,
				 EvPage      *page)
{
	PopplerPage *poppler_page;
	PopplerRectangle points;
	GList *region;
	GdkRegion *retval;

	poppler_page = POPPLER_PAGE (page->backend_page);

	points.x1 = 0.0;
	points.y1 = 0.0;
	poppler_page_get_size (poppler_page, &(points.x2), &(points.y2));
	
	region = poppler_page_get_selection_region (poppler_page, 1.0,
						    POPPLER_SELECTION_GLYPH,
						    &points);
	retval = create_gdk_region_from_poppler_region (region);
	g_list_free (region);

	return retval;
}

static void
pdf_selection_iface_init (EvSelectionIface *iface)
{
        iface->render_selection = pdf_selection_render_selection;
	iface->get_selected_text = pdf_selection_get_selected_text;
        iface->get_selection_region = pdf_selection_get_selection_region;
        iface->get_selection_map = pdf_selection_get_selection_map;
}

/* Page Transitions */
static gdouble
pdf_document_get_page_duration (EvDocumentTransition *trans,
				gint                  page)
{
	PdfDocument *pdf_document;
	PopplerPage *poppler_page;
	gdouble      duration = -1;

	pdf_document = PDF_DOCUMENT (trans);
	poppler_page = poppler_document_get_page (pdf_document->document, page);
	if (!poppler_page)
		return -1;

	duration = poppler_page_get_duration (poppler_page);
	g_object_unref (poppler_page);

	return duration;
}

static EvTransitionEffect *
pdf_document_get_effect (EvDocumentTransition *trans,
			 gint                  page)
{
	PdfDocument            *pdf_document;
	PopplerPage            *poppler_page;
	PopplerPageTransition  *page_transition;
	EvTransitionEffect     *effect;

	pdf_document = PDF_DOCUMENT (trans);
	poppler_page = poppler_document_get_page (pdf_document->document, page);

	if (!poppler_page)
		return NULL;

	page_transition = poppler_page_get_transition (poppler_page);

	if (!page_transition) {
		g_object_unref (poppler_page);
		return NULL;
	}

	/* enums in PopplerPageTransition match the EvTransitionEffect ones */
	effect = ev_transition_effect_new ((EvTransitionEffectType) page_transition->type,
					   "alignment", page_transition->alignment,
					   "direction", page_transition->direction,
					   "duration", page_transition->duration,
					   "angle", page_transition->angle,
					   "scale", page_transition->scale,
					   "rectangular", page_transition->rectangular,
					   NULL);

	poppler_page_transition_free (page_transition);
	g_object_unref (poppler_page);

	return effect;
}

static void
pdf_document_page_transition_iface_init (EvDocumentTransitionIface *iface)
{
	iface->get_page_duration = pdf_document_get_page_duration;
	iface->get_effect = pdf_document_get_effect;
}

/* Forms */
static void
pdf_document_get_crop_box (EvDocument  *document, 
			   int          page, 
			   EvRectangle *rect)
{
	PdfDocument *pdf_document;
	PopplerPage *poppler_page;
	PopplerRectangle poppler_rect;

	pdf_document = PDF_DOCUMENT (document);
	poppler_page = poppler_document_get_page (pdf_document->document, page);
	poppler_page_get_crop_box (poppler_page, &poppler_rect);
	rect->x1 = poppler_rect.x1;
	rect->x2 = poppler_rect.x2;
	rect->y1 = poppler_rect.y1;
	rect->y2 = poppler_rect.y2;
}

static EvFormField *
ev_form_field_from_poppler_field (PopplerFormField *poppler_field)
{
	EvFormField *ev_field = NULL;
	gint         id;
	gdouble      font_size;
	gboolean     is_read_only;

	id = poppler_form_field_get_id (poppler_field);
	font_size = poppler_form_field_get_font_size (poppler_field);
	is_read_only = poppler_form_field_is_read_only (poppler_field);

	switch (poppler_form_field_get_field_type (poppler_field)) {
	        case POPPLER_FORM_FIELD_TEXT: {
			EvFormFieldText    *field_text;
			EvFormFieldTextType ev_text_type = EV_FORM_FIELD_TEXT_NORMAL;

			switch (poppler_form_field_text_get_text_type (poppler_field)) {
			        case POPPLER_FORM_TEXT_NORMAL:
					ev_text_type = EV_FORM_FIELD_TEXT_NORMAL;
					break;
			        case POPPLER_FORM_TEXT_MULTILINE:
					ev_text_type = EV_FORM_FIELD_TEXT_MULTILINE;
					break;
			        case POPPLER_FORM_TEXT_FILE_SELECT:
					ev_text_type = EV_FORM_FIELD_TEXT_FILE_SELECT;
					break;
			}
			
			ev_field = ev_form_field_text_new (id, ev_text_type);
			field_text = EV_FORM_FIELD_TEXT (ev_field);

			field_text->do_spell_check = poppler_form_field_text_do_spell_check (poppler_field);
			field_text->do_scroll = poppler_form_field_text_do_scroll (poppler_field);
			field_text->is_rich_text = poppler_form_field_text_is_rich_text (poppler_field);
			field_text->is_password = poppler_form_field_text_is_password (poppler_field);
			field_text->max_len = poppler_form_field_text_get_max_len (poppler_field);
			field_text->text = poppler_form_field_text_get_text (poppler_field);

		}
			break;
	        case POPPLER_FORM_FIELD_BUTTON: {
			EvFormFieldButton    *field_button;
			EvFormFieldButtonType ev_button_type = EV_FORM_FIELD_BUTTON_PUSH;

			switch (poppler_form_field_button_get_button_type (poppler_field)) {
			        case POPPLER_FORM_BUTTON_PUSH:
					ev_button_type = EV_FORM_FIELD_BUTTON_PUSH;
					break;
			        case POPPLER_FORM_BUTTON_CHECK:
					ev_button_type = EV_FORM_FIELD_BUTTON_CHECK;
					break;
			        case POPPLER_FORM_BUTTON_RADIO:
					ev_button_type = EV_FORM_FIELD_BUTTON_RADIO;
					break;
			}

			ev_field = ev_form_field_button_new (id, ev_button_type);
			field_button = EV_FORM_FIELD_BUTTON (ev_field);
			
			field_button->state = poppler_form_field_button_get_state (poppler_field);
		}
			break;
	        case POPPLER_FORM_FIELD_CHOICE: {
			EvFormFieldChoice    *field_choice;
			EvFormFieldChoiceType ev_choice_type = EV_FORM_FIELD_CHOICE_COMBO;

			switch (poppler_form_field_choice_get_choice_type (poppler_field)) {
			        case POPPLER_FORM_CHOICE_COMBO:
					ev_choice_type = EV_FORM_FIELD_CHOICE_COMBO;
					break;
			        case EV_FORM_FIELD_CHOICE_LIST:
					ev_choice_type = EV_FORM_FIELD_CHOICE_LIST;
					break;
			}

			ev_field = ev_form_field_choice_new (id, ev_choice_type);
			field_choice = EV_FORM_FIELD_CHOICE (ev_field);

			field_choice->is_editable = poppler_form_field_choice_is_editable (poppler_field);
			field_choice->multi_select = poppler_form_field_choice_can_select_multiple (poppler_field);
			field_choice->do_spell_check = poppler_form_field_choice_do_spell_check (poppler_field);
			field_choice->commit_on_sel_change = poppler_form_field_choice_commit_on_change (poppler_field);

			/* TODO: we need poppler_form_field_choice_get_selected_items in poppler 
			field_choice->selected_items = poppler_form_field_choice_get_selected_items (poppler_field);*/
			if (field_choice->is_editable)
				field_choice->text = poppler_form_field_choice_get_text (poppler_field);
		}
			break;
	        case POPPLER_FORM_FIELD_SIGNATURE:
			/* TODO */
			ev_field = ev_form_field_signature_new (id);
			break;
	        case POPPLER_FORM_FIELD_UNKNOWN:
			return NULL;
	}

	ev_field->font_size = font_size;
	ev_field->is_read_only = is_read_only;

	return ev_field;
}

static GList *
pdf_document_forms_get_form_fields (EvDocumentForms *document, 
				    EvPage          *page)
{
 	PopplerPage *poppler_page;
 	GList *retval = NULL;
 	GList *fields;
 	GList *list;
 	double height;

	g_return_val_if_fail (POPPLER_IS_PAGE (page->backend_page), NULL);
	
 	poppler_page = POPPLER_PAGE (page->backend_page);
 	fields = poppler_page_get_form_field_mapping (poppler_page);
 	poppler_page_get_size (poppler_page, NULL, &height);

 	for (list = fields; list; list = list->next) {
 		PopplerFormFieldMapping *mapping;
 		EvMapping *field_mapping;
		EvFormField *ev_field;

 		mapping = (PopplerFormFieldMapping *)list->data;

		ev_field = ev_form_field_from_poppler_field (mapping->field);
		if (!ev_field)
			continue;

 		field_mapping = g_new0 (EvMapping, 1);
		field_mapping->area.x1 = mapping->area.x1;
		field_mapping->area.x2 = mapping->area.x2;
		field_mapping->area.y1 = height - mapping->area.y2;
		field_mapping->area.y2 = height - mapping->area.y1;
		field_mapping->data = ev_field;
		ev_field->page = EV_PAGE (g_object_ref (page));

		g_object_set_data_full (G_OBJECT (ev_field),
					"poppler-field",
					g_object_ref (mapping->field),
					(GDestroyNotify) g_object_unref);
		
		retval = g_list_prepend (retval, field_mapping);
	}
	
	poppler_page_free_form_field_mapping (fields);

	return g_list_reverse (retval);
}

static gchar *
pdf_document_forms_form_field_text_get_text (EvDocumentForms *document,
					     EvFormField     *field)
	
{
	PopplerFormField *poppler_field;
	gchar *text;

	poppler_field = POPPLER_FORM_FIELD (g_object_get_data (G_OBJECT (field), "poppler-field"));
	if (!poppler_field)
		return NULL;
	
	text = poppler_form_field_text_get_text (poppler_field);

	return text;
}

static void
pdf_document_forms_form_field_text_set_text (EvDocumentForms *document, 
					     EvFormField     *field,
					     const gchar     *text)
{
	PopplerFormField *poppler_field;

	poppler_field = POPPLER_FORM_FIELD (g_object_get_data (G_OBJECT (field), "poppler-field"));
	if (!poppler_field)
		return;
	
	poppler_form_field_text_set_text (poppler_field, text);
	PDF_DOCUMENT (document)->modified = TRUE;
}

static void
pdf_document_forms_form_field_button_set_state (EvDocumentForms *document, 
						EvFormField     *field,
						gboolean         state)
{
	PopplerFormField *poppler_field;

	poppler_field = POPPLER_FORM_FIELD (g_object_get_data (G_OBJECT (field), "poppler-field"));
	if (!poppler_field)
		return;
	
	poppler_form_field_button_set_state (poppler_field, state);
	PDF_DOCUMENT (document)->modified = TRUE;
}

static gboolean
pdf_document_forms_form_field_button_get_state (EvDocumentForms *document, 
						EvFormField     *field)
{
	PopplerFormField *poppler_field;
	gboolean state;

	poppler_field = POPPLER_FORM_FIELD (g_object_get_data (G_OBJECT (field), "poppler-field"));
	if (!poppler_field)
		return FALSE;

	state = poppler_form_field_button_get_state (poppler_field);

	return state;
}

static gchar *
pdf_document_forms_form_field_choice_get_item (EvDocumentForms *document, 
					       EvFormField     *field,
					       gint             index)
{
	PopplerFormField *poppler_field;
	gchar *text;

	poppler_field = POPPLER_FORM_FIELD (g_object_get_data (G_OBJECT (field), "poppler-field"));
	if (!poppler_field)
		return NULL;

	text = poppler_form_field_choice_get_item (poppler_field, index);

	return text;
}

static int
pdf_document_forms_form_field_choice_get_n_items (EvDocumentForms *document, 
						  EvFormField     *field)
{
	PopplerFormField *poppler_field;
	gint n_items;

	poppler_field = POPPLER_FORM_FIELD (g_object_get_data (G_OBJECT (field), "poppler-field"));
	if (!poppler_field)
		return -1;
	
	n_items = poppler_form_field_choice_get_n_items (poppler_field);

	return n_items;
}

static gboolean
pdf_document_forms_form_field_choice_is_item_selected (EvDocumentForms *document, 
						       EvFormField     *field,
						       gint             index)
{
	PopplerFormField *poppler_field;
	gboolean selected;

	poppler_field = POPPLER_FORM_FIELD (g_object_get_data (G_OBJECT (field), "poppler-field"));
	if (!poppler_field)
		return FALSE;

	selected = poppler_form_field_choice_is_item_selected (poppler_field, index);

	return selected;
}

static void
pdf_document_forms_form_field_choice_select_item (EvDocumentForms *document, 
						  EvFormField     *field,
						  gint             index)
{
	PopplerFormField *poppler_field;

	poppler_field = POPPLER_FORM_FIELD (g_object_get_data (G_OBJECT (field), "poppler-field"));
	if (!poppler_field)
		return;

	poppler_form_field_choice_select_item (poppler_field, index);
	PDF_DOCUMENT (document)->modified = TRUE;
}

static void
pdf_document_forms_form_field_choice_toggle_item (EvDocumentForms *document, 
						  EvFormField     *field,
						  gint             index)
{
	PopplerFormField *poppler_field;

	poppler_field = POPPLER_FORM_FIELD (g_object_get_data (G_OBJECT (field), "poppler-field"));
	if (!poppler_field)
		return;

	poppler_form_field_choice_toggle_item (poppler_field, index);
	PDF_DOCUMENT (document)->modified = TRUE;
}

static void
pdf_document_forms_form_field_choice_unselect_all (EvDocumentForms *document, 
						   EvFormField     *field)
{
	PopplerFormField *poppler_field;

	poppler_field = POPPLER_FORM_FIELD (g_object_get_data (G_OBJECT (field), "poppler-field"));
	if (!poppler_field)
		return;
	
	poppler_form_field_choice_unselect_all (poppler_field);
	PDF_DOCUMENT (document)->modified = TRUE;
}

static void
pdf_document_forms_form_field_choice_set_text (EvDocumentForms *document,
					       EvFormField     *field,
					       const gchar     *text)
{
	PopplerFormField *poppler_field;

	poppler_field = POPPLER_FORM_FIELD (g_object_get_data (G_OBJECT (field), "poppler-field"));
	if (!poppler_field)
		return;
	
	poppler_form_field_choice_set_text (poppler_field, text);
	PDF_DOCUMENT (document)->modified = TRUE;
}

static gchar *
pdf_document_forms_form_field_choice_get_text (EvDocumentForms *document,
					       EvFormField     *field)
{
	PopplerFormField *poppler_field;
	gchar *text;

	poppler_field = POPPLER_FORM_FIELD (g_object_get_data (G_OBJECT (field), "poppler-field"));
	if (!poppler_field)
		return NULL;

	text = poppler_form_field_choice_get_text (poppler_field);

	return text;
}

static void
pdf_document_document_forms_iface_init (EvDocumentFormsIface *iface)
{
	iface->get_form_fields = pdf_document_forms_get_form_fields;
	iface->form_field_text_get_text = pdf_document_forms_form_field_text_get_text;
	iface->form_field_text_set_text = pdf_document_forms_form_field_text_set_text;
	iface->form_field_button_set_state = pdf_document_forms_form_field_button_set_state;
	iface->form_field_button_get_state = pdf_document_forms_form_field_button_get_state;
	iface->form_field_choice_get_item = pdf_document_forms_form_field_choice_get_item;
	iface->form_field_choice_get_n_items = pdf_document_forms_form_field_choice_get_n_items;
	iface->form_field_choice_is_item_selected = pdf_document_forms_form_field_choice_is_item_selected;
	iface->form_field_choice_select_item = pdf_document_forms_form_field_choice_select_item;
	iface->form_field_choice_toggle_item = pdf_document_forms_form_field_choice_toggle_item;
	iface->form_field_choice_unselect_all = pdf_document_forms_form_field_choice_unselect_all;
	iface->form_field_choice_set_text = pdf_document_forms_form_field_choice_set_text;
	iface->form_field_choice_get_text = pdf_document_forms_form_field_choice_get_text;
}

/* Annotations */
static void
poppler_annot_color_to_gdk_color (PopplerAnnot *poppler_annot,
				  GdkColor     *color)
{
	PopplerColor *poppler_color;

	poppler_color = poppler_annot_get_color (poppler_annot);
	if (poppler_color) {
		color->red = poppler_color->red;
		color->green = poppler_color->green;
		color->blue = poppler_color->blue;

		g_free (poppler_color);
	} /* TODO: else use a default color */
}

static EvAnnotation *
ev_annot_from_poppler_annot (PopplerAnnot *poppler_annot,
			     EvPage       *page)
{
	EvAnnotation *ev_annot = NULL;
	const gchar  *unimplemented_annot = NULL;

	switch (poppler_annot_get_annot_type (poppler_annot)) {
	        case POPPLER_ANNOT_TEXT: {
			PopplerAnnotText *poppler_text;
			EvAnnotationText *ev_annot_text;

			poppler_text = POPPLER_ANNOT_TEXT (poppler_annot);

			ev_annot = ev_annotation_text_new (page);

			ev_annot_text = EV_ANNOTATION_TEXT (ev_annot);
			ev_annot_text->is_open = poppler_annot_text_get_is_open (poppler_text);
		}
			break;
#ifdef HAVE_POPPLER_ANNOT_FILE_ATTACHMENT_GET_ATTACHMENT
	        case POPPLER_ANNOT_FILE_ATTACHMENT: {
			PopplerAnnotFileAttachment *poppler_annot_attachment;
			EvAnnotationAttachment     *ev_annot_attachment;
			PopplerAttachment          *poppler_attachment;
			gchar                      *data = NULL;
			gsize                       size;
			GError                     *error = NULL;

			poppler_annot_attachment = POPPLER_ANNOT_FILE_ATTACHMENT (poppler_annot);
			poppler_attachment = poppler_annot_file_attachment_get_attachment (poppler_annot_attachment);

			if (poppler_attachment &&
			    attachment_save_to_buffer (poppler_attachment, &data, &size, &error)) {
				EvAttachment *ev_attachment;

				ev_attachment = ev_attachment_new (poppler_attachment->name,
								   poppler_attachment->description,
								   poppler_attachment->mtime,
								   poppler_attachment->ctime,
								   size, data);
				ev_annot = ev_annotation_attachment_new (page, ev_attachment);
				g_object_unref (ev_attachment);
			} else if (error) {
				g_warning ("%s", error->message);
				g_error_free (error);
			}

			if (poppler_attachment)
				g_object_unref (poppler_attachment);
		}
			break;
#endif /* HAVE_POPPLER_ANNOT_FILE_ATTACHMENT_GET_ATTACHMENT */
	        case POPPLER_ANNOT_LINK:
	        case POPPLER_ANNOT_WIDGET:
			/* Ignore link and widgets annots since they are already handled */
			break;
	        default: {
			GEnumValue *enum_value;

			enum_value = g_enum_get_value ((GEnumClass *) g_type_class_ref (POPPLER_TYPE_ANNOT_TYPE),
						       poppler_annot_get_annot_type (poppler_annot));
			unimplemented_annot = enum_value ? enum_value->value_name : "Unknown annotation";
		}
	}

	if (unimplemented_annot) {
		g_warning ("Unimplemented annotation: %s, please post a "
		           "bug report in Evince bugzilla "
		           "(http://bugzilla.gnome.org) with a testcase.",
			   unimplemented_annot);
	}

	if (ev_annot) {
		ev_annot->contents = poppler_annot_get_contents (poppler_annot);
		ev_annot->name = poppler_annot_get_name (poppler_annot);
		ev_annot->modified = poppler_annot_get_modified (poppler_annot);
		poppler_annot_color_to_gdk_color (poppler_annot, &ev_annot->color);

		if (POPPLER_IS_ANNOT_MARKUP (poppler_annot)) {
			PopplerAnnotMarkup *markup;
			gchar *label;
			gdouble opacity;
			PopplerRectangle poppler_rect;

			markup = POPPLER_ANNOT_MARKUP (poppler_annot);

			if (poppler_annot_markup_get_popup_rectangle (markup, &poppler_rect)) {
				EvRectangle ev_rect;
				gboolean is_open;
				gdouble height;

				poppler_page_get_size (POPPLER_PAGE (page->backend_page),
						       NULL, &height);
				ev_rect.x1 = poppler_rect.x1;
				ev_rect.x2 = poppler_rect.x2;
				ev_rect.y1 = height - poppler_rect.y2;
				ev_rect.y2 = height - poppler_rect.y1;

				is_open = poppler_annot_markup_get_popup_is_open (markup);

				g_object_set (ev_annot,
					      "rectangle", &ev_rect,
					      "is_open", is_open,
					      "has_popup", TRUE,
					      NULL);
			} else {
				/* FIXME: Use poppler_annot_markup_has_popup() when
				 * new poppler is released.
				 */
				g_object_set (ev_annot,
					      "has_popup", FALSE,
					      NULL);
			}

			label = poppler_annot_markup_get_label (markup);
			opacity = poppler_annot_markup_get_opacity (markup);

			g_object_set (ev_annot,
				      "label", label,
				      "opacity", opacity,
				      NULL);

			g_free (label);
		}
	}

	return ev_annot;
}

static GList *
pdf_document_annotations_get_annotations (EvDocumentAnnotations *document_annotations,
					  EvPage                *page)
{
	GList *retval = NULL;
	PdfDocument *pdf_document;
	PopplerPage *poppler_page;
	GList *annots;
	GList *list;
	gdouble height;
	gint i = 0;

	pdf_document = PDF_DOCUMENT (document_annotations);
	poppler_page = POPPLER_PAGE (page->backend_page);
	annots = poppler_page_get_annot_mapping (poppler_page);
	poppler_page_get_size (poppler_page, NULL, &height);

	for (list = annots; list; list = list->next) {
		PopplerAnnotMapping *mapping;
		EvMapping *annot_mapping;
		EvAnnotation        *ev_annot;

		mapping = (PopplerAnnotMapping *)list->data;

		ev_annot = ev_annot_from_poppler_annot (mapping->annot, page);
		if (!ev_annot)
			continue;

		i++;

		/* Make sure annot has a unique name */
		if (!ev_annot->name)
			ev_annot->name = g_strdup_printf ("annot-%d-%d", page->index, i);

		annot_mapping = g_new (EvMapping, 1);
		annot_mapping->area.x1 = mapping->area.x1;
		annot_mapping->area.x2 = mapping->area.x2;
		annot_mapping->area.y1 = height - mapping->area.y2;
		annot_mapping->area.y2 = height - mapping->area.y1;
		annot_mapping->data = ev_annot;

		g_object_set_data_full (G_OBJECT (ev_annot),
					"poppler-annot",
					g_object_ref (mapping->annot),
					(GDestroyNotify) g_object_unref);

		retval = g_list_prepend (retval, annot_mapping);
	}

	poppler_page_free_annot_mapping (annots);

	return g_list_reverse (retval);
}

static void
pdf_document_annotations_annotation_set_contents (EvDocumentAnnotations *document,
						  EvAnnotation          *annot,
						  const gchar           *contents)
{
	PopplerAnnot *poppler_annot;

	poppler_annot = POPPLER_ANNOT (g_object_get_data (G_OBJECT (annot), "poppler-annot"));
	if (!poppler_annot)
		return;

	poppler_annot_set_contents (poppler_annot, contents);
	PDF_DOCUMENT (document)->modified = TRUE;
}

static void
pdf_document_document_annotations_iface_init (EvDocumentAnnotationsIface *iface)
{
	iface->get_annotations = pdf_document_annotations_get_annotations;
	iface->annotation_set_contents = pdf_document_annotations_annotation_set_contents;
}

/* Attachments */
struct SaveToBufferData {
	gchar *buffer;
	gsize len, max;
};

static gboolean
attachment_save_to_buffer_callback (const gchar  *buf,
				    gsize         count,
				    gpointer      user_data,
				    GError      **error)
{
	struct SaveToBufferData *sdata = (SaveToBufferData *)user_data;
	gchar *new_buffer;
	gsize new_max;

	if (sdata->len + count > sdata->max) {
		new_max = MAX (sdata->max * 2, sdata->len + count);
		new_buffer = (gchar *)g_realloc (sdata->buffer, new_max);

		sdata->buffer = new_buffer;
		sdata->max = new_max;
	}

	memcpy (sdata->buffer + sdata->len, buf, count);
	sdata->len += count;

	return TRUE;
}

static gboolean
attachment_save_to_buffer (PopplerAttachment  *attachment,
			   gchar             **buffer,
			   gsize              *buffer_size,
			   GError            **error)
{
	static const gint initial_max = 1024;
	struct SaveToBufferData sdata;

	*buffer = NULL;
	*buffer_size = 0;

	sdata.buffer = (gchar *) g_malloc (initial_max);
	sdata.max = initial_max;
	sdata.len = 0;

	if (! poppler_attachment_save_to_callback (attachment,
						   attachment_save_to_buffer_callback,
						   &sdata,
						   error)) {
		g_free (sdata.buffer);
		return FALSE;
	}

	*buffer = sdata.buffer;
	*buffer_size = sdata.len;

	return TRUE;
}

static GList *
pdf_document_attachments_get_attachments (EvDocumentAttachments *document)
{
	PdfDocument *pdf_document = PDF_DOCUMENT (document);
	GList *attachments;
	GList *list;
	GList *retval = NULL;

	attachments = poppler_document_get_attachments (pdf_document->document);

	for (list = attachments; list; list = list->next) {
		PopplerAttachment *attachment;
		EvAttachment *ev_attachment;
		gchar *data = NULL;
		gsize size;
		GError *error = NULL;

		attachment = (PopplerAttachment *) list->data;

		if (attachment_save_to_buffer (attachment, &data, &size, &error)) {
			ev_attachment = ev_attachment_new (attachment->name,
							   attachment->description,
							   attachment->mtime,
							   attachment->ctime,
							   size, data);

			retval = g_list_prepend (retval, ev_attachment);
		} else {
			if (error) {
				g_warning ("%s", error->message);
				g_error_free (error);

				g_free (data);
			}
		}

		g_object_unref (attachment);
	}

	return g_list_reverse (retval);
}

static gboolean
pdf_document_attachments_has_attachments (EvDocumentAttachments *document)
{
	PdfDocument *pdf_document = PDF_DOCUMENT (document);

	return poppler_document_has_attachments (pdf_document->document);
}

static void
pdf_document_document_attachments_iface_init (EvDocumentAttachmentsIface *iface)
{
	iface->has_attachments = pdf_document_attachments_has_attachments;
	iface->get_attachments = pdf_document_attachments_get_attachments;
}

/* Layers */
static gboolean
pdf_document_layers_has_layers (EvDocumentLayers *document)
{
	PdfDocument *pdf_document = PDF_DOCUMENT (document);
	PopplerLayersIter *iter;

	iter = poppler_layers_iter_new (pdf_document->document);
	if (!iter)
		return FALSE;
	poppler_layers_iter_free (iter);

	return TRUE;
}

static void
build_layers_tree (PdfDocument       *pdf_document,
		   GtkTreeModel      *model,
		   GtkTreeIter       *parent,
		   PopplerLayersIter *iter)
{
	do {
		GtkTreeIter        tree_iter;
		PopplerLayersIter *child;
		PopplerLayer      *layer;
		EvLayer           *ev_layer = NULL;
		gboolean           visible;
		gchar             *markup;
		gint               rb_group = 0;

		layer = poppler_layers_iter_get_layer (iter);
		if (layer) {
			markup = g_markup_escape_text (poppler_layer_get_title (layer), -1);
			visible = poppler_layer_is_visible (layer);
			rb_group = poppler_layer_get_radio_button_group_id (layer);
			pdf_document->layers = g_list_append (pdf_document->layers,
							      g_object_ref (layer));
			ev_layer = ev_layer_new (g_list_length (pdf_document->layers) - 1,
						 poppler_layer_is_parent (layer),
						 rb_group);
		} else {
			gchar *title;

			title = poppler_layers_iter_get_title (iter);
			markup = g_markup_escape_text (title, -1);
			g_free (title);

			visible = FALSE;
			layer = NULL;
		}

		gtk_tree_store_append (GTK_TREE_STORE (model), &tree_iter, parent);
		gtk_tree_store_set (GTK_TREE_STORE (model), &tree_iter,
				    EV_DOCUMENT_LAYERS_COLUMN_TITLE, markup,
				    EV_DOCUMENT_LAYERS_COLUMN_VISIBLE, visible,
				    EV_DOCUMENT_LAYERS_COLUMN_ENABLED, TRUE, /* FIXME */
				    EV_DOCUMENT_LAYERS_COLUMN_SHOWTOGGLE, (layer != NULL),
				    EV_DOCUMENT_LAYERS_COLUMN_RBGROUP, rb_group,
				    EV_DOCUMENT_LAYERS_COLUMN_LAYER, ev_layer,
				    -1);
		if (ev_layer)
			g_object_unref (ev_layer);
		g_free (markup);

		child = poppler_layers_iter_get_child (iter);
		if (child)
			build_layers_tree (pdf_document, model, &tree_iter, child);
		poppler_layers_iter_free (child);
	} while (poppler_layers_iter_next (iter));
}

static GtkTreeModel *
pdf_document_layers_get_layers (EvDocumentLayers *document)
{
	GtkTreeModel *model = NULL;
	PdfDocument *pdf_document = PDF_DOCUMENT (document);
	PopplerLayersIter *iter;

	iter = poppler_layers_iter_new (pdf_document->document);
	if (iter) {
		model = (GtkTreeModel *) gtk_tree_store_new (EV_DOCUMENT_LAYERS_N_COLUMNS,
							     G_TYPE_STRING,  /* TITLE */
							     G_TYPE_OBJECT,  /* LAYER */
							     G_TYPE_BOOLEAN, /* VISIBLE */
							     G_TYPE_BOOLEAN, /* ENABLED */
							     G_TYPE_BOOLEAN, /* SHOWTOGGLE */
							     G_TYPE_INT);    /* RBGROUP */
		build_layers_tree (pdf_document, model, NULL, iter);
		poppler_layers_iter_free (iter);
	}
	return model;
}

static void
pdf_document_layers_show_layer (EvDocumentLayers *document,
				EvLayer          *layer)
{
	PdfDocument *pdf_document = PDF_DOCUMENT (document);
	guint        layer_id = ev_layer_get_id (layer);

	poppler_layer_show (POPPLER_LAYER (g_list_nth_data (pdf_document->layers, layer_id)));
}

static void
pdf_document_layers_hide_layer (EvDocumentLayers *document,
				EvLayer          *layer)
{
	PdfDocument *pdf_document = PDF_DOCUMENT (document);
	guint        layer_id = ev_layer_get_id (layer);

	poppler_layer_hide (POPPLER_LAYER (g_list_nth_data (pdf_document->layers, layer_id)));
}

static gboolean
pdf_document_layers_layer_is_visible (EvDocumentLayers *document,
				      EvLayer          *layer)
{
	PdfDocument *pdf_document = PDF_DOCUMENT (document);
	guint        layer_id = ev_layer_get_id (layer);

	return poppler_layer_is_visible (POPPLER_LAYER (g_list_nth_data (pdf_document->layers, layer_id)));
}

static void
pdf_document_document_layers_iface_init (EvDocumentLayersIface *iface)
{
	iface->has_layers = pdf_document_layers_has_layers;
	iface->get_layers = pdf_document_layers_get_layers;
	iface->show_layer = pdf_document_layers_show_layer;
	iface->hide_layer = pdf_document_layers_hide_layer;
	iface->layer_is_visible = pdf_document_layers_layer_is_visible;
}