Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/pdf/xpdf/XOutputDev.cc
blob: a156b5584dfcb2fcf554ee8ae4e918bae51488f2 (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
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
//========================================================================
//
// XOutputDev.cc
//
// Copyright 1996-2003 Glyph & Cog, LLC
//
//========================================================================

#include <aconf.h>

#ifdef USE_GCC_PRAGMAS
#pragma implementation
#endif

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include "gmem.h"
#include "gfile.h"
#include "GString.h"
#include "GList.h"
#include "Object.h"
#include "Stream.h"
#include "Link.h"
#include "GfxState.h"
#include "GfxFont.h"
#include "UnicodeMap.h"
#include "CharCodeToUnicode.h"
#include "FontFile.h"
#include "Error.h"
#include "TextOutputDev.h"
#include "XOutputDev.h"
#if HAVE_T1LIB_H
#include "T1Font.h"
#endif
#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
#include "FTFont.h"
#endif
#if !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
#include "TTFont.h"
#endif

#ifdef VMS
#if (__VMS_VER < 70000000)
extern "C" int unlink(char *filename);
#endif
#endif

#ifdef XlibSpecificationRelease
#if XlibSpecificationRelease < 5
typedef char *XPointer;
#endif
#else
typedef char *XPointer;
#endif

//------------------------------------------------------------------------
// Constants and macros
//------------------------------------------------------------------------

#define xoutRound(x) ((int)(x + 0.5))

#define maxCurveSplits 6	// max number of splits when recursively
				//   drawing Bezier curves

//------------------------------------------------------------------------
// Font substitutions
//------------------------------------------------------------------------

struct XOutFontSubst {
  char *name;
  double mWidth;
};

// index: {symbolic:12, fixed:8, serif:4, sans-serif:0} + bold*2 + italic
static XOutFontSubst xOutSubstFonts[16] = {
  {"Helvetica",             0.833},
  {"Helvetica-Oblique",     0.833},
  {"Helvetica-Bold",        0.889},
  {"Helvetica-BoldOblique", 0.889},
  {"Times-Roman",           0.788},
  {"Times-Italic",          0.722},
  {"Times-Bold",            0.833},
  {"Times-BoldItalic",      0.778},
  {"Courier",               0.600},
  {"Courier-Oblique",       0.600},
  {"Courier-Bold",          0.600},
  {"Courier-BoldOblique",   0.600},
  {"Symbol",                0.576},
  {"Symbol",                0.576},
  {"Symbol",                0.576},
  {"Symbol",                0.576}
};

//------------------------------------------------------------------------

static void outputToFile(void *stream, char *data, int len) {
  fwrite(data, 1, len, (FILE *)stream);
}

//------------------------------------------------------------------------
// XOutputFont
//------------------------------------------------------------------------

XOutputFont::XOutputFont(Ref *idA, double m11OrigA, double m12OrigA,
			 double m21OrigA, double m22OrigA,
			 double m11A, double m12A, double m21A, double m22A,
			 Display *displayA, XOutputDev *xOutA) {
  id = *idA;
  display = displayA;
  xOut = xOutA;
  m11Orig = m11OrigA;
  m12Orig = m12OrigA;
  m21Orig = m21OrigA;
  m22Orig = m22OrigA;
  m11 = m11A;
  m12 = m12A;
  m21 = m21A;
  m22 = m22A;
}

XOutputFont::~XOutputFont() {
}

void XOutputFont::getCharPath(GfxState *state,
			      CharCode c, Unicode *u, int ulen) {
}

#if HAVE_T1LIB_H
//------------------------------------------------------------------------
// XOutputT1Font
//------------------------------------------------------------------------

XOutputT1Font::XOutputT1Font(Ref *idA, T1FontFile *fontFileA,
			     double m11OrigA, double m12OrigA,
			     double m21OrigA, double m22OrigA,
			     double m11A, double m12A,
			     double m21A, double m22A,
			     Display *displayA, XOutputDev *xOutA):
  XOutputFont(idA, m11OrigA, m12OrigA, m21OrigA, m22OrigA,
	      m11A, m12A, m21A, m22A, displayA, xOutA)
{
  double matrix[4];

  fontFile = fontFileA;

  // create the transformed instance
  matrix[0] = m11;
  matrix[1] = -m12;
  matrix[2] = m21;
  matrix[3] = -m22;
  font = new T1Font(fontFile, matrix);
}

XOutputT1Font::~XOutputT1Font() {
  if (font) {
    delete font;
  }
}

GBool XOutputT1Font::isOk() {
  return font != NULL;
}

void XOutputT1Font::updateGC(GC gc) {
}

void XOutputT1Font::drawChar(GfxState *state, Pixmap pixmap, int w, int h,
			     GC gc, GfxRGB *rgb,
			     double x, double y, double dx, double dy,
			     CharCode c, Unicode *u, int uLen) {
  font->drawChar(pixmap, w, h, gc, xoutRound(x), xoutRound(y),
		 (int)(rgb->r * 65535), (int)(rgb->g * 65535),
		 (int)(rgb->b * 65535), c, u[0]);
}

void XOutputT1Font::getCharPath(GfxState *state,
				CharCode c, Unicode *u, int uLen) {
  font->getCharPath(c, u[0], state);
}
#endif // HAVE_T1LIB_H

#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
//------------------------------------------------------------------------
// XOutputFTFont
//------------------------------------------------------------------------

XOutputFTFont::XOutputFTFont(Ref *idA, FTFontFile *fontFileA,
			     double m11OrigA, double m12OrigA,
			     double m21OrigA, double m22OrigA,
			     double m11A, double m12A,
			     double m21A, double m22A,
			     Display *displayA, XOutputDev *xOutA):
  XOutputFont(idA, m11OrigA, m12OrigA, m21OrigA, m22OrigA,
	      m11A, m12A, m21A, m22A, displayA, xOutA)
{
  double matrix[4];

  fontFile = fontFileA;

  // create the transformed instance
  matrix[0] = m11;
  matrix[1] = -m12;
  matrix[2] = m21;
  matrix[3] = -m22;
  font = new FTFont(fontFile, matrix);
}

XOutputFTFont::~XOutputFTFont() {
  if (font) {
    delete font;
  }
}

GBool XOutputFTFont::isOk() {
  return font != NULL;
}

void XOutputFTFont::updateGC(GC gc) {
}

void XOutputFTFont::drawChar(GfxState *state, Pixmap pixmap, int w, int h,
			     GC gc, GfxRGB *rgb,
			     double x, double y, double dx, double dy,
			     CharCode c, Unicode *u, int uLen) {
  font->drawChar(pixmap, w, h, gc, xoutRound(x), xoutRound(y),
		 (int)(rgb->r * 65535), (int)(rgb->g * 65535),
		 (int)(rgb->b * 65535), c, uLen > 0 ? u[0] : 0);
}

void XOutputFTFont::getCharPath(GfxState *state,
				CharCode c, Unicode *u, int uLen) {
  font->getCharPath(c, u[0], state);
}
#endif // FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)

#if !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
//------------------------------------------------------------------------
// XOutputTTFont
//------------------------------------------------------------------------

XOutputTTFont::XOutputTTFont(Ref *idA, TTFontFile *fontFileA,
			     double m11OrigA, double m12OrigA,
			     double m21OrigA, double m22OrigA,
			     double m11A, double m12A,
			     double m21A, double m22A,
			     Display *displayA, XOutputDev *xOutA):
  XOutputFont(idA, m11OrigA, m12OrigA, m21OrigA, m22OrigA,
	      m11A, m12A, m21A, m22A, displayA, xOutA)
{
  double matrix[4];

  fontFile = fontFileA;

  // create the transformed instance
  matrix[0] = m11;
  matrix[1] = -m12;
  matrix[2] = m21;
  matrix[3] = -m22;
  font = new TTFont(fontFile, matrix);
}

XOutputTTFont::~XOutputTTFont() {
  if (font) {
    delete font;
  }
}

GBool XOutputTTFont::isOk() {
  return font != NULL;
}

void XOutputTTFont::updateGC(GC gc) {
}

void XOutputTTFont::drawChar(GfxState *state, Pixmap pixmap, int w, int h,
			     GC gc, GfxRGB *rgb,
			     double x, double y, double dx, double dy,
			     CharCode c, Unicode *u, int uLen) {
  font->drawChar(pixmap, w, h, gc, xoutRound(x), xoutRound(y),
		 (int)(rgb->r * 65535), (int)(rgb->g * 65535),
		 (int)(rgb->b * 65535), c, u[0]);
}
#endif // !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)

//------------------------------------------------------------------------
// XOutputServer8BitFont
//------------------------------------------------------------------------

// Copy <fmt>, substituting <val> for one occurrence of "%s", into
// <buf>.
static void stringSubst(char *buf, int bufSize, char *fmt, char *val) {
  char *p, *q;
  int i;

  i = 0;
  p = fmt;
  while (*p) {
    if (p[0] == '%' && p[1] == 's') {
      q = val;
      while (*q && i < bufSize - 1) {
	buf[i++] = *q++;
      }
      p += 2;
    } else {
      if (i < bufSize - 1) {
	buf[i++] = *p;
      }
      ++p;
    }
  }
  buf[i] = '\0';
}

XOutputServer8BitFont::XOutputServer8BitFont(Ref *idA, GString *xlfdFmt, 
					     UnicodeMap *xUMapA,
					     CharCodeToUnicode *fontUMap,
					     double m11OrigA, double m12OrigA,
					     double m21OrigA, double m22OrigA,
					     double m11A, double m12A,
					     double m21A, double m22A,
					     Display *displayA,
					     XOutputDev *xOutA):
  XOutputFont(idA, m11OrigA, m12OrigA, m21OrigA, m22OrigA,
	      m11A, m12A, m21A, m22A, displayA, xOutA)
{
  double size, ntm11, ntm12, ntm21, ntm22;
  GBool rotated;
  int startSize, sz;
  char fontName[500], fontSize[100];
  Unicode u;
  char buf;
  int i;

  // compute size and normalized transform matrix
  size = sqrt(m21*m21 + m22*m22);
  ntm11 = m11 / size;
  ntm12 = -m12 / size;
  ntm21 = m21 / size;
  ntm22 = -m22 / size;

  // try to get a rotated font?
  rotated = !(ntm11 > 0 && ntm22 > 0 &&
	      fabs(ntm11 / ntm22 - 1) < 0.2 &&
	      fabs(ntm12) < 0.01 &&
	      fabs(ntm21) < 0.01);

  // open X font -- if font is not found (which means the server can't
  // scale fonts), try progressively smaller and then larger sizes
  startSize = (int)size;
  if (rotated) {
    sprintf(fontSize, "[%s%0.2f %s%0.2f %s%0.2f %s%0.2f]",
	    ntm11<0 ? "~" : "", fabs(ntm11 * size),
	    ntm12<0 ? "~" : "", fabs(ntm12 * size),
	    ntm21<0 ? "~" : "", fabs(ntm21 * size),
	    ntm22<0 ? "~" : "", fabs(ntm22 * size));
  } else {
    sprintf(fontSize, "%d", startSize);
  }
  stringSubst(fontName, sizeof(fontName), xlfdFmt->getCString(), fontSize);
  xFont = XLoadQueryFont(display, fontName);
  if (!xFont) {
    for (sz = startSize; sz >= startSize/2 && sz >= 1; --sz) {
      sprintf(fontSize, "%d", sz);
      stringSubst(fontName, sizeof(fontName), xlfdFmt->getCString(), fontSize);
      if ((xFont = XLoadQueryFont(display, fontName)))
	break;
    }
    if (!xFont) {
      for (sz = startSize + 1; sz < startSize + 10; ++sz) {
	sprintf(fontSize, "%d", sz);
	stringSubst(fontName, sizeof(fontName), xlfdFmt->getCString(),
		    fontSize);
	if ((xFont = XLoadQueryFont(display, fontName))) {
	  break;
	}
      }
      if (!xFont) {
	sprintf(fontSize, "%d", startSize);
	stringSubst(fontName, sizeof(fontName), xlfdFmt->getCString(),
		    fontSize);
	error(-1, "Failed to open font: '%s'", fontName);
	return;
      }
    }
  }

  // Construct char code map.
  xUMap = xUMapA;
  for (i = 0; i < 256; ++i) {
    if (fontUMap->mapToUnicode((CID)i, &u, 1) == 1 &&
	xUMap->mapUnicode(u, &buf, 1) == 1) {
      map[i] = buf & 0xff;
    } else {
      map[i] = 0;
    }
  }
}

XOutputServer8BitFont::~XOutputServer8BitFont() {
  if (xFont) {
    XFreeFont(display, xFont);
  }
}

GBool XOutputServer8BitFont::isOk() {
  return xFont != NULL;
}

void XOutputServer8BitFont::updateGC(GC gc) {
  XSetFont(display, gc, xFont->fid);
}

void XOutputServer8BitFont::drawChar(GfxState *state, Pixmap pixmap,
				     int w, int h, GC gc, GfxRGB *rgb,
				     double x, double y, double dx, double dy,
				     CharCode c, Unicode *u, int uLen) {
  Gushort c1;
  char buf[8];
  double dx1, dy1;
  int m, n, i, j, k;

  c1 = map[c];
  if (c1 > 0) {
    buf[0] = (char)c1;
    XDrawString(display, pixmap, gc, xoutRound(x), xoutRound(y), buf, 1);
  } else {
    // substituted character, using more than one character
    n = 0;
    for (i = 0; i < uLen; ++i) {
      n += xUMap->mapUnicode(u[i], buf, sizeof(buf));
    }
    if (n > 0) {
      dx1 = dx / n;
      dy1 = dy / n;
      k = 0;
      for (i = 0; i < uLen; ++i) {
	m = xUMap->mapUnicode(u[i], buf, sizeof(buf));
	for (j = 0; j < m; ++j) {
	  XDrawString(display, pixmap, gc,
		      xoutRound(x + k*dx1), xoutRound(y + k*dy1),
		      buf + j, 1);
	  ++k;
	}
      }
    }
  }
}

//------------------------------------------------------------------------
// XOutputServer16BitFont
//------------------------------------------------------------------------

XOutputServer16BitFont::XOutputServer16BitFont(Ref *idA, GString *xlfdFmt, 
					       UnicodeMap *xUMapA,
					       CharCodeToUnicode *fontUMap,
					       double m11OrigA,
					       double m12OrigA,
					       double m21OrigA,
					       double m22OrigA,
					       double m11A, double m12A,
					       double m21A, double m22A,
					       Display *displayA,
					       XOutputDev *xOutA):
  XOutputFont(idA, m11OrigA, m12OrigA, m21OrigA, m22OrigA,
	      m11A, m12A, m21A, m22A, displayA, xOutA)
{
  double size, ntm11, ntm12, ntm21, ntm22;
  GBool rotated;
  int startSize, sz;
  char fontName[500], fontSize[100];

  xUMap = xUMapA;
  xUMap->incRefCnt();

  // compute size and normalized transform matrix
  size = sqrt(m21*m21 + m22*m22);
  ntm11 = m11 / size;
  ntm12 = -m12 / size;
  ntm21 = m21 / size;
  ntm22 = -m22 / size;

  // try to get a rotated font?
  rotated = !(ntm11 > 0 && ntm22 > 0 &&
	      fabs(ntm11 / ntm22 - 1) < 0.2 &&
	      fabs(ntm12) < 0.01 &&
	      fabs(ntm21) < 0.01);

  // open X font -- if font is not found (which means the server can't
  // scale fonts), try progressively smaller and then larger sizes
  startSize = (int)size;
  if (rotated) {
    sprintf(fontSize, "[%s%0.2f %s%0.2f %s%0.2f %s%0.2f]",
	    ntm11<0 ? "~" : "", fabs(ntm11 * size),
	    ntm12<0 ? "~" : "", fabs(ntm12 * size),
	    ntm21<0 ? "~" : "", fabs(ntm21 * size),
	    ntm22<0 ? "~" : "", fabs(ntm22 * size));
  } else {
    sprintf(fontSize, "%d", startSize);
  }
  stringSubst(fontName, sizeof(fontName), xlfdFmt->getCString(), fontSize);
  xFont = XLoadQueryFont(display, fontName);
  if (!xFont) {
    for (sz = startSize; sz >= startSize/2 && sz >= 1; --sz) {
      sprintf(fontSize, "%d", sz);
      stringSubst(fontName, sizeof(fontName), xlfdFmt->getCString(), fontSize);
      if ((xFont = XLoadQueryFont(display, fontName)))
	break;
    }
    if (!xFont) {
      for (sz = startSize + 1; sz < startSize + 10; ++sz) {
	sprintf(fontSize, "%d", sz);
	stringSubst(fontName, sizeof(fontName), xlfdFmt->getCString(),
		    fontSize);
	if ((xFont = XLoadQueryFont(display, fontName))) {
	  break;
	}
      }
      if (!xFont) {
	sprintf(fontSize, "%d", startSize);
	stringSubst(fontName, sizeof(fontName), xlfdFmt->getCString(),
		    fontSize);
	error(-1, "Failed to open font: '%s'", fontName);
	return;
      }
    }
  }
}

XOutputServer16BitFont::~XOutputServer16BitFont() {
  xUMap->decRefCnt();
  if (xFont) {
    XFreeFont(display, xFont);
  }
}

GBool XOutputServer16BitFont::isOk() {
  return xFont != NULL;
}

void XOutputServer16BitFont::updateGC(GC gc) {
  XSetFont(display, gc, xFont->fid);
}

void XOutputServer16BitFont::drawChar(GfxState *state, Pixmap pixmap,
				      int w, int h, GC gc, GfxRGB *rgb,
				      double x, double y, double dx, double dy,
				      CharCode c, Unicode *u, int uLen) {
  char buf[16];
  XChar2b c1;
  double dx1, dy1;
  int m, n, i, j, k;

  n = 0;
  for (i = 0; i < uLen; ++i) {
    n += xUMap->mapUnicode(u[i], buf, sizeof(buf));
  }
  if (n > 0) {
    dx1 = dx / n;
    dy1 = dy / n;
    k = 0;
    for (i = 0; i < uLen; ++i) {
      m = xUMap->mapUnicode(u[i], buf, sizeof(buf));
      for (j = 0; j+1 < m; j += 2) {
	c1.byte1 = buf[j];
	c1.byte2 = buf[j+1];
	XDrawString16(display, pixmap, gc,
		      xoutRound(x + k*dx1), xoutRound(y + k*dy1),
		      &c1, 1);
	++k;
      }
    }
  } else if (c != 0) {
    // some PDF files use CID 0, which is .notdef, so just ignore it
    error(-1, "Unknown character (CID=%d Unicode=%04x)",
	  c, uLen > 0 ? u[0] : (Unicode)0);
  }
}

//------------------------------------------------------------------------
// XOutputFontCache
//------------------------------------------------------------------------

#if HAVE_T1LIB_H
XOutputT1FontFile::~XOutputT1FontFile() {
  delete fontFile;
  if (tmpFileName) {
    unlink(tmpFileName->getCString());
    delete tmpFileName;
  }
}
#endif

#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
XOutputFTFontFile::~XOutputFTFontFile() {
  delete fontFile;
  if (tmpFileName) {
    unlink(tmpFileName->getCString());
    delete tmpFileName;
  }
}
#endif

#if !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
XOutputTTFontFile::~XOutputTTFontFile() {
  delete fontFile;
  if (tmpFileName) {
    unlink(tmpFileName->getCString());
    delete tmpFileName;
  }
}
#endif

XOutputFontCache::XOutputFontCache(Display *displayA, Guint depthA,
				   XOutputDev *xOutA,
				   FontRastControl t1libControlA,
				   FontRastControl freetypeControlA) {
  display = displayA;
  depth = depthA;
  xOut = xOutA;

#if HAVE_T1LIB_H
  t1libControl = t1libControlA;
  t1Engine = NULL;
  t1FontFiles = NULL;
#endif

#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
  freetypeControl = freetypeControlA;
  ftEngine = NULL;
  ftFontFiles = NULL;
#endif
#if !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
  freetypeControl = freetypeControlA;
  ttEngine = NULL;
  ttFontFiles = NULL;
#endif

  clear();
}

XOutputFontCache::~XOutputFontCache() {
  delFonts();
}

void XOutputFontCache::startDoc(int screenNum, Visual *visual,
				Colormap colormap, GBool trueColor,
				int rMul, int gMul, int bMul,
				int rShift, int gShift, int bShift,
				Gulong *colors, int numColors) {
  delFonts();
  clear();

#if HAVE_T1LIB_H
  if (t1libControl != fontRastNone) {
    t1Engine = new T1FontEngine(display, visual, depth, colormap,
				t1libControl == fontRastAALow ||
				  t1libControl == fontRastAAHigh,
				t1libControl == fontRastAAHigh);
    if (t1Engine->isOk()) {
      if (trueColor) {
	t1Engine->useTrueColor(rMul, rShift, gMul, gShift, bMul, bShift);
      } else {
	t1Engine->useColorCube(colors, numColors);
      }
    } else {
      delete t1Engine;
      t1Engine = NULL;
    }
  }
#endif // HAVE_T1LIB_H

#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
  if (freetypeControl != fontRastNone) {
    ftEngine = new FTFontEngine(display, visual, depth, colormap,
				freetypeControl == fontRastAALow ||
				  freetypeControl == fontRastAAHigh);
    if (ftEngine->isOk()) {
      if (trueColor) {
	ftEngine->useTrueColor(rMul, rShift, gMul, gShift, bMul, bShift);
      } else {
	ftEngine->useColorCube(colors, numColors);
      }
    } else {
      delete ftEngine;
      ftEngine = NULL;
    }
  }
#endif // FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)

#if !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
  if (freetypeControl != fontRastNone) {
    ttEngine = new TTFontEngine(display, visual, depth, colormap,
				freetypeControl == fontRastAALow ||
				  freetypeControl == fontRastAAHigh);
    if (ttEngine->isOk()) {
      if (trueColor) {
	ttEngine->useTrueColor(rMul, rShift, gMul, gShift, bMul, bShift);
      } else {
	ttEngine->useColorCube(colors, numColors);
      }
    } else {
      delete ttEngine;
      ttEngine = NULL;
    }
  }
#endif // !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
}

void XOutputFontCache::delFonts() {
  int i;

  for (i = 0; i < nFonts; ++i) {
    delete fonts[i];
  }

#if HAVE_T1LIB_H
  // delete Type 1 font files
  if (t1FontFiles) {
    deleteGList(t1FontFiles, XOutputT1FontFile);
    t1FontFiles = NULL;
  }
  if (t1Engine) {
    delete t1Engine;
    t1Engine = NULL;
  }
#endif

#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
  // delete FreeType font files
  if (ftFontFiles) {
    deleteGList(ftFontFiles, XOutputFTFontFile);
    ftFontFiles = NULL;
  }
  if (ftEngine) {
    delete ftEngine;
    ftEngine = NULL;
  }
#endif

#if !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
  // delete TrueType fonts
  if (ttFontFiles) {
    deleteGList(ttFontFiles, XOutputTTFontFile);
    ttFontFiles = NULL;
  }
  if (ttEngine) {
    delete ttEngine;
    ttEngine = NULL;
  }
#endif
}

void XOutputFontCache::clear() {
  int i;

  for (i = 0; i < xOutFontCacheSize; ++i) {
    fonts[i] = NULL;
  }
  nFonts = 0;

#if HAVE_T1LIB_H
  // clear Type 1 font files
  t1FontFiles = new GList();
#endif

#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
  // clear FreeType font cache
  ftFontFiles = new GList();
#endif

#if !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
  // clear TrueType font cache
  ttFontFiles = new GList();
#endif
}

XOutputFont *XOutputFontCache::getFont(XRef *xref, GfxFont *gfxFont,
				       double m11, double m12,
				       double m21, double m22) {
  XOutputFont *font;
  DisplayFontParam *dfp;
  GString *substName;
  double m11New, m12New, m21New, m22New;
  double w1, w2, v;
  double *fm;
  char *name;
  int index;
  int code;
  int i, j;

  // is it the most recently used font?
  if (nFonts > 0 && fonts[0]->matches(gfxFont->getID(), m11, m12, m21, m22)) {
    return fonts[0];
  }

  // is it in the cache?
  for (i = 1; i < nFonts; ++i) {
    if (fonts[i]->matches(gfxFont->getID(), m11, m12, m21, m22)) {
      font = fonts[i];
      for (j = i; j > 0; --j) {
	fonts[j] = fonts[j-1];
      }
      fonts[0] = font;
      return font;
    }
  }

  // try for a cached FontFile, an embedded font, or an external font
  // file
  font = NULL;
  switch (gfxFont->getType()) {
  case fontType1:
  case fontType1C:
#if HAVE_T1LIB_H
    if (t1libControl != fontRastNone) {
      font = tryGetT1Font(xref, gfxFont, m11, m12, m21, m22);
    }
#endif
#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
    if (!font) {
      if (freetypeControl != fontRastNone) {
	font = tryGetFTFont(xref, gfxFont, m11, m12, m21, m22);
      }
    }
#endif
    break;
  case fontTrueType:
  case fontCIDType2:
#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
    if (freetypeControl != fontRastNone) {
      font = tryGetFTFont(xref, gfxFont, m11, m12, m21, m22);
    }
#endif
#if !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
    if (freetypeControl != fontRastNone) {
      font = tryGetTTFont(xref, gfxFont, m11, m12, m21, m22);
    }
#endif
    break;
  case fontCIDType0:
  case fontCIDType0C:
#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
    if (freetypeControl != fontRastNone) {
      font = tryGetFTFont(xref, gfxFont, m11, m12, m21, m22);
    }
#endif
    break;
  default:
    break;
  }

  if (!font) {

    // search for a display font mapping
    dfp = NULL;
    if (gfxFont->isCIDFont()) {
      if (((GfxCIDFont *)gfxFont)->getCollection()) {
	dfp = globalParams->
	        getDisplayCIDFont(gfxFont->getName(),
				  ((GfxCIDFont *)gfxFont)->getCollection());
      } else {
	// this error (no CMap file) was already reported by GfxFont
	return NULL;
      }
    } else {
      if (gfxFont->getName()) {
	dfp = globalParams->getDisplayFont(gfxFont->getName());
      }
    }
    if (dfp) {
      font = tryGetFont(xref, dfp, gfxFont, m11, m12, m21, m22,
			m11, m12, m21, m22, gFalse);
    }

    // substitute a font (8-bit fonts only)
    if (!font && !gfxFont->isCIDFont()) {

      // choose a substitute font
      if (gfxFont->isFixedWidth()) {
	index = 8;
      } else if (gfxFont->isSerif()) {
	index = 4;
      } else {
	index = 0;
      }
      if (gfxFont->isBold()) {
	index += 2;
      }
      if (gfxFont->isItalic()) {
	index += 1;
      }
      substName = new GString(xOutSubstFonts[index].name);

      // adjust the font matrix -- compare the width of 'm' in the
      // original font and the substituted font
      m11New = m11;
      m12New = m12;
      m21New = m21;
      m22New = m22;
      for (code = 0; code < 256; ++code) {
	if ((name = ((Gfx8BitFont *)gfxFont)->getCharName(code)) &&
	    name[0] == 'm' && name[1] == '\0') {
	  break;
	}
      }
      if (code < 256) {
	w1 = ((Gfx8BitFont *)gfxFont)->getWidth(code);
	w2 = xOutSubstFonts[index].mWidth;
	if (gfxFont->getType() == fontType3) {
	  // This is a hack which makes it possible to substitute for some
	  // Type 3 fonts.  The problem is that it's impossible to know what
	  // the base coordinate system used in the font is without actually
	  // rendering the font.  This code tries to guess by looking at the
	  // width of the character 'm' (which breaks if the font is a
	  // subset that doesn't contain 'm').
	  if (w1 > 0 && (w1 > 1.1 * w2 || w1 < 0.9 * w2)) {
	    w1 /= w2;
	    m11New *= w1;
	    m12New *= w1;
	    m21New *= w1;
	    m22New *= w1;
	  }
	  fm = gfxFont->getFontMatrix();
	  v = (fm[0] == 0) ? 1 : (fm[3] / fm[0]);
	  m21New *= v;
	  m22New *= v;
	} else if (!gfxFont->isSymbolic()) {
	  // if real font is substantially narrower than substituted
	  // font, reduce the font size accordingly
	  if (w1 > 0.01 && w1 < 0.9 * w2) {
	    w1 /= w2;
	    m11New *= w1;
	    m21New *= w1;
	  }
	}
      }

      // get the font
      dfp = globalParams->getDisplayFont(substName);
      delete substName;
      if (!dfp) {
	// this should never happen since GlobalParams sets up default
	// mappings for the Base-14 fonts
	error(-1, "Couldn't find a font for '%s'",
	      gfxFont->getName()->getCString());
	return NULL;
      }
      font = tryGetFont(xref, dfp, gfxFont, m11, m12, m21, m22,
			m11New, m12New, m21New, m22New, gTrue);
    }
  }

  // check for error
  if (!font) {
    // This will happen if the user specifies a bogus font in the
    // config file (a non-existent font file or a font that requires a
    // rasterizer that is disabled or wasn't built in), or if a CID
    // font has no associated font in the config file.
    if (gfxFont->isCIDFont()) {
      error(-1, "Couldn't find a font for the '%s' character collection",
	    ((GfxCIDFont *)gfxFont)->getCollection()->getCString());
    } else {
      error(-1, "Couldn't find a font for '%s'",
	    gfxFont->getName() ?
	        gfxFont->getName()->getCString() : "[unnamed]");
    }
    return NULL;
  }

  // insert font in cache
  if (nFonts == xOutFontCacheSize) {
    --nFonts;
    delete fonts[nFonts];
  }
  for (j = nFonts; j > 0; --j) {
    fonts[j] = fonts[j-1];
  }
  fonts[0] = font;
  ++nFonts;

  return font;
}

XOutputFont *XOutputFontCache::tryGetFont(XRef *xref, DisplayFontParam *dfp,
					  GfxFont *gfxFont,
					  double m11Orig, double m12Orig,
					  double m21Orig, double m22Orig,
					  double m11, double m12,
					  double m21, double m22,
					  GBool subst) {
  XOutputFont *font;

  font = NULL;

  // create the new font
  switch (dfp->kind) {

  case displayFontX:
    font = tryGetServerFont(dfp->x.xlfd, dfp->x.encoding, gfxFont,
			    m11Orig, m12Orig, m21Orig, m22Orig,
			    m11, m12, m21, m22);
    break;

  case displayFontT1:
#if HAVE_T1LIB_H
    if (t1libControl != fontRastNone && !gfxFont->isCIDFont()) {
      font = tryGetT1FontFromFile(xref, dfp->t1.fileName, gFalse, gfxFont,
				  m11Orig, m12Orig, m21Orig, m22Orig,
				  m11, m12, m21, m22, subst);
    }
#endif
#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
    if (!font) {
      if (freetypeControl != fontRastNone) {
	font = tryGetFTFontFromFile(xref, dfp->t1.fileName, gFalse, gfxFont,
				    m11Orig, m12Orig, m21Orig, m22Orig,
				    m11, m12, m21, m22, gFalse, subst);
      }
    }
#endif
#if !((FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)) || defined(HAVE_T1LIB_H))
    error(-1, "Config file specifies a Type 1 font,");
    error(-1, "but xpdf was not built with t1lib or FreeType2 support");
#endif
    break;

  case displayFontTT:
#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
    if (freetypeControl != fontRastNone) {
      font = tryGetFTFontFromFile(xref, dfp->tt.fileName, gFalse, gfxFont,
				  m11Orig, m12Orig, m21Orig, m22Orig,
				  m11, m12, m21, m22, gFalse, subst);
    }
#endif
#if !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
    if (freetypeControl != fontRastNone) {
      font = tryGetTTFontFromFile(xref, dfp->tt.fileName, gFalse, gfxFont,
				  m11Orig, m12Orig, m21Orig, m22Orig,
				  m11, m12, m21, m22, subst);
    }
#endif
#if !(HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
    error(-1, "Config file specifies a TrueType font,");
    error(-1, "but xpdf was not built with FreeType support");
    dfp = NULL;
#endif
    break;
  }

  return font;
}

#if HAVE_T1LIB_H
XOutputFont *XOutputFontCache::tryGetT1Font(XRef *xref,
					    GfxFont *gfxFont,
					    double m11, double m12,
					    double m21, double m22) {
  Ref *id;
  XOutputT1FontFile *xFontFile;
  XOutputFont *font;
  Ref embRef;
  GString *fileName;
  FILE *f;
  char *fontBuf;
  int fontLen;
  Type1CFontFile *ff;
  Object refObj, strObj;
  int c;
  int i;

  // check the already available font files
  id = gfxFont->getID();
  for (i = 0; i < t1FontFiles->getLength(); ++i) {
    xFontFile = (XOutputT1FontFile *)t1FontFiles->get(i);
    if (xFontFile->num == id->num && xFontFile->gen == id->gen &&
	!xFontFile->subst) {
      font = new XOutputT1Font(id, xFontFile->fontFile,
			       m11, m12, m21, m22,
			       m11, m12, m21, m22, display, xOut);
      if (!font->isOk()) {
	delete font;
	return NULL;
      }
      return font;
    }
  }

  // check for an embedded font
  if (gfxFont->getEmbeddedFontID(&embRef)) {

    // create the font file
    fileName = NULL;
    if (!openTempFile(&fileName, &f, "wb", NULL)) {
      error(-1, "Couldn't create temporary Type 1 font file");
      return NULL;
    }
    if (gfxFont->getType() == fontType1C) {
      if (!(fontBuf = gfxFont->readEmbFontFile(xref, &fontLen))) {
	fclose(f);
	unlink(fileName->getCString());
	delete fileName;
	return NULL;
      }
      ff = new Type1CFontFile(fontBuf, fontLen);
      if (!ff->isOk()) {
	delete ff;
	gfree(fontBuf);
	unlink(fileName->getCString());
	delete fileName;
	return NULL;
      }
      ff->convertToType1(outputToFile, f);
      delete ff;
      gfree(fontBuf);
    } else { // fontType1
      refObj.initRef(embRef.num, embRef.gen);
      refObj.fetch(xref, &strObj);
      refObj.free();
      strObj.streamReset();
      while ((c = strObj.streamGetChar()) != EOF) {
	fputc(c, f);
      }
      strObj.streamClose();
      strObj.free();
    }
    fclose(f);

    // create the Font
    font = tryGetT1FontFromFile(xref, fileName, gTrue, gfxFont,
				m11, m12, m21, m22,
				m11, m12, m21, m22, gFalse);

    // on systems with Unix hard link semantics, this will remove the
    // last link to the temp file
    unlink(fileName->getCString());

    delete fileName;

  // check for an external font file
  } else if ((fileName = gfxFont->getExtFontFile())) {
    font = tryGetT1FontFromFile(xref, fileName, gFalse, gfxFont,
				m11, m12, m21, m22,
				m11, m12, m21, m22, gFalse);

  } else {
    font = NULL;
  }

  return font;
}

XOutputFont *XOutputFontCache::tryGetT1FontFromFile(XRef *xref,
						    GString *fileName,
						    GBool deleteFile,
						    GfxFont *gfxFont,
						    double m11Orig,
						    double m12Orig,
						    double m21Orig,
						    double m22Orig,
						    double m11, double m12,
						    double m21, double m22,
						    GBool subst) {
  Ref *id;
  T1FontFile *fontFile;
  XOutputFont *font;

  // create the t1lib font file
  fontFile = new T1FontFile(t1Engine, fileName->getCString(),
			    ((Gfx8BitFont *)gfxFont)->getEncoding(),
			    gfxFont->getFontBBox());
  if (!fontFile->isOk()) {
    error(-1, "Couldn't create t1lib font from '%s'",
	  fileName->getCString());
    delete fontFile;
    if (deleteFile) {
      unlink(fileName->getCString());
    }
    return NULL;
  }

  // add to list
  id = gfxFont->getID();
  t1FontFiles->append(new XOutputT1FontFile(id->num, id->gen,
					    subst, fontFile,
					    deleteFile ? fileName->copy()
					               : (GString *)NULL));

  // create the Font
  font = new XOutputT1Font(gfxFont->getID(), fontFile,
			   m11Orig, m12Orig, m21Orig, m22Orig,
			   m11, m12, m21, m22, display, xOut);
  if (!font->isOk()) {
    delete font;
    return NULL;
  }
  return font;
}
#endif // HAVE_T1LIB_H

#if FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
XOutputFont *XOutputFontCache::tryGetFTFont(XRef *xref,
					    GfxFont *gfxFont,
					    double m11, double m12,
					    double m21, double m22) {
  Ref *id;
  XOutputFTFontFile *xFontFile;
  XOutputFont *font;
  Ref embRef;
  GString *fileName;
  FILE *f;
#if 1 //~ need this until FT can handle fonts with missing tables
  char *fontBuf;
  int fontLen;
  TrueTypeFontFile *ff;
#endif
  Object refObj, strObj;
  int c;
  int i;

  // check the already available font files
  id = gfxFont->getID();
  for (i = 0; i < ftFontFiles->getLength(); ++i) {
    xFontFile = (XOutputFTFontFile *)ftFontFiles->get(i);
    if (xFontFile->num == id->num && xFontFile->gen == id->gen &&
	!xFontFile->subst) {
      font = new XOutputFTFont(id, xFontFile->fontFile,
			       m11, m12, m21, m22,
			       m11, m12, m21, m22, display, xOut);
      if (!font->isOk()) {
	delete font;
	return NULL;
      }
      return font;
    }
  }

  // check for an embedded font
  if (gfxFont->getEmbeddedFontID(&embRef)) {

    // create the font file
    fileName = NULL;
    if (!openTempFile(&fileName, &f, "wb", NULL)) {
      error(-1, "Couldn't create temporary TrueType font file");
      return NULL;
    }
#if 1 //~ need this until FT can handle fonts with missing tables
    if (gfxFont->getType() == fontTrueType ||
	gfxFont->getType() == fontCIDType2) {
      if (!(fontBuf = gfxFont->readEmbFontFile(xref, &fontLen))) {
	fclose(f);
	unlink(fileName->getCString());
	delete fileName;
	return NULL;
      }
      ff = new TrueTypeFontFile(fontBuf, fontLen);
      ff->writeTTF(f);
      delete ff;
      gfree(fontBuf);
    } else {
      refObj.initRef(embRef.num, embRef.gen);
      refObj.fetch(xref, &strObj);
      refObj.free();
      strObj.streamReset();
      while ((c = strObj.streamGetChar()) != EOF) {
	fputc(c, f);
      }
      strObj.streamClose();
      strObj.free();
    }
#else
    refObj.initRef(embRef.num, embRef.gen);
    refObj.fetch(xref, &strObj);
    refObj.free();
    strObj.streamReset();
    while ((c = strObj.streamGetChar()) != EOF) {
      fputc(c, f);
    }
    strObj.streamClose();
    strObj.free();
#endif
    fclose(f);

    // create the Font
    font = tryGetFTFontFromFile(xref, fileName, gTrue, gfxFont,
				m11, m12, m21, m22,
				m11, m12, m21, m22, gTrue, gFalse);

    // on systems with Unix hard link semantics, this will remove the
    // last link to the temp file
    unlink(fileName->getCString());

    delete fileName;

  // check for an external font file
  } else if ((fileName = gfxFont->getExtFontFile())) {
    font = tryGetFTFontFromFile(xref, fileName, gFalse, gfxFont,
				m11, m12, m21, m22,
				m11, m12, m21, m22, gFalse, gFalse);

  } else {
    font = NULL;
  }

  return font;
}

XOutputFont *XOutputFontCache::tryGetFTFontFromFile(XRef *xref,
						    GString *fileName,
						    GBool deleteFile,
						    GfxFont *gfxFont,
						    double m11Orig,
						    double m12Orig,
						    double m21Orig,
						    double m22Orig,
						    double m11, double m12,
						    double m21, double m22,
						    GBool embedded,
						    GBool subst) {
  Ref *id;
  FTFontFile *fontFile;
  XOutputFont *font;
  char *buf;
  int len;
  FILE *f;
  TrueTypeFontFile *ff;
  Gushort *codeToGID;

  // create the FreeType font file
  if (gfxFont->isCIDFont()) {
    if (gfxFont->getType() == fontCIDType2) {
      fontFile = new FTFontFile(ftEngine, fileName->getCString(),
				((GfxCIDFont *)gfxFont)->getCIDToGID(),
				((GfxCIDFont *)gfxFont)->getCIDToGIDLen(),
				embedded);
    } else { // fontCIDType0, fontCIDType0C
      fontFile = new FTFontFile(ftEngine, fileName->getCString(), embedded);
    }
  } else {
    if (!(f = fopen(fileName->getCString(), "rb"))) {
      return NULL;
    }
    fseek(f, 0, SEEK_END);
    len = (int)ftell(f);
    fseek(f, 0, SEEK_SET);
    buf = (char *)gmalloc(len);
    if ((int)fread(buf, 1, len, f) != len) {
      gfree(buf);
      fclose(f);
      return NULL;
    }
    fclose(f);
    ff = new TrueTypeFontFile(buf, len);
    codeToGID = ((Gfx8BitFont *)gfxFont)->getCodeToGIDMap(ff);
    fontFile = new FTFontFile(ftEngine, fileName->getCString(),
			      ((Gfx8BitFont *)gfxFont)->getEncoding(),
			      codeToGID);
    gfree(codeToGID);
    delete ff;
    gfree(buf);
  }
  if (!fontFile->isOk()) {
    error(-1, "Couldn't create FreeType font from '%s'",
	  fileName->getCString());
    delete fontFile;
    if (deleteFile) {
      unlink(fileName->getCString());
    }
    return NULL;
  }

  // add to list
  id = gfxFont->getID();
  ftFontFiles->append(new XOutputFTFontFile(id->num, id->gen,
					    subst, fontFile,
					    deleteFile ? fileName->copy()
					               : (GString *)NULL));

  // create the Font
  font = new XOutputFTFont(gfxFont->getID(), fontFile,
			   m11Orig, m12Orig, m21Orig, m22Orig,
			   m11, m12, m21, m22, display, xOut);
  if (!font->isOk()) {
    delete font;
    return NULL;
  }
  return font;
}
#endif // FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)

#if !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)
XOutputFont *XOutputFontCache::tryGetTTFont(XRef *xref,
					    GfxFont *gfxFont,
					    double m11, double m12,
					    double m21, double m22) {
  Ref *id;
  XOutputTTFontFile *xFontFile;
  XOutputFont *font;
  Ref embRef;
  GString *fileName;
  FILE *f;
  Object refObj, strObj;
  int c;
  int i;

  // check the already available font files
  id = gfxFont->getID();
  xFontFile = NULL;
  for (i = 0; i < ttFontFiles->getLength(); ++i) {
    xFontFile = (XOutputTTFontFile *)ttFontFiles->get(i);
    if (xFontFile->num == id->num && xFontFile->gen == id->gen &&
	!xFontFile->subst) {
      font = new XOutputTTFont(id, xFontFile->fontFile,
			       m11, m12, m21, m22,
			       m11, m12, m21, m22, display, xOut);
      if (!font->isOk()) {
	delete font;
	return NULL;
      }
      return font;
    }
  }

  // check for an embedded font
  if (gfxFont->getEmbeddedFontID(&embRef)) {

    // create the font file
    fileName = NULL;
    if (!openTempFile(&fileName, &f, "wb", NULL)) {
      error(-1, "Couldn't create temporary TrueType font file");
      return NULL;
    }
    refObj.initRef(embRef.num, embRef.gen);
    refObj.fetch(xref, &strObj);
    refObj.free();
    strObj.streamReset();
    while ((c = strObj.streamGetChar()) != EOF) {
      fputc(c, f);
    }
    strObj.streamClose();
    strObj.free();
    fclose(f);

    // create the Font
    font = tryGetTTFontFromFile(xref, fileName, gTrue, gfxFont,
				m11, m12, m21, m22,
				m11, m12, m21, m22, gFalse);

    // on systems with Unix hard link semantics, this will remove the
    // last link to the temp file
    unlink(fileName->getCString());

    delete fileName;

  } else if ((fileName = gfxFont->getExtFontFile())) {
    font = tryGetTTFontFromFile(xref, fileName, gFalse, gfxFont,
				m11, m12, m21, m22,
				m11, m12, m21, m22, gFalse);

  } else {
    font = NULL;
  }

  return font;
}

XOutputFont *XOutputFontCache::tryGetTTFontFromFile(XRef *xref,
						    GString *fileName,
						    GBool deleteFile,
						    GfxFont *gfxFont,
						    double m11Orig,
						    double m12Orig,
						    double m21Orig,
						    double m22Orig,
						    double m11, double m12,
						    double m21, double m22,
						    GBool subst) {
  Ref *id;
  TTFontFile *fontFile;
  XOutputFont *font;

  // create the FreeType font file
  if (gfxFont->isCIDFont()) {
    // fontCIDType2
    fontFile = new TTFontFile(ttEngine, fileName->getCString(),
			      ((GfxCIDFont *)gfxFont)->getCIDToGID(),
			      ((GfxCIDFont *)gfxFont)->getCIDToGIDLen());
  } else {
    fontFile = new TTFontFile(ttEngine, fileName->getCString(),
			      ((Gfx8BitFont *)gfxFont)->getEncoding(),
			      ((Gfx8BitFont *)gfxFont)->getHasEncoding());
  }
  if (!fontFile->isOk()) {
    error(-1, "Couldn't create FreeType font from '%s'",
	  fileName->getCString());
    delete fontFile;
    if (deleteFile) {
      unlink(fileName->getCString());
    }
    return NULL;
  }

  // add to list
  id = gfxFont->getID();
  ttFontFiles->append(new XOutputTTFontFile(id->num, id->gen,
					    subst, fontFile,
					    deleteFile ? fileName->copy()
					               : (GString *)NULL));

  // create the Font
  font = new XOutputTTFont(gfxFont->getID(), fontFile,
			   m11Orig, m12Orig, m21Orig, m22Orig,
			   m11, m12, m21, m22, display, xOut);
  if (!font->isOk()) {
    delete font;
    return NULL;
  }
  return font;
}
#endif // !FREETYPE2 && (HAVE_FREETYPE_FREETYPE_H || HAVE_FREETYPE_H)

XOutputFont *XOutputFontCache::tryGetServerFont(GString *xlfd,
						GString *encodingName,
						GfxFont *gfxFont,
						double m11Orig, double m12Orig,
						double m21Orig, double m22Orig,
						double m11, double m12,
						double m21, double m22) {
  XOutputFont *font;
  UnicodeMap *uMap;
  CharCodeToUnicode *ctu;

  uMap = globalParams->getUnicodeMap(encodingName);
  if (gfxFont->isCIDFont()) {
    ctu = ((GfxCIDFont *)gfxFont)->getToUnicode();
    font = new XOutputServer16BitFont(gfxFont->getID(), xlfd, uMap, ctu,
				      m11Orig, m12Orig, m21Orig, m22Orig,
				      m11, m12, m21, m22,
				      display, xOut);
    ctu->decRefCnt();
  } else {
    ctu = ((Gfx8BitFont *)gfxFont)->getToUnicode();
    font = new XOutputServer8BitFont(gfxFont->getID(), xlfd, uMap, ctu,
				     m11Orig, m12Orig, m21Orig, m22Orig,
				     m11, m12, m21, m22,
				     display, xOut);
    ctu->decRefCnt();
  }
  uMap->decRefCnt();
  if (!font->isOk()) {
    delete font;
    return NULL;
  }
  return font;
}

//------------------------------------------------------------------------
// T3FontCache
//------------------------------------------------------------------------

struct T3FontCacheTag {
  Gushort code;
  Gushort mru;			// valid bit (0x8000) and MRU index
  double wx, wy;		// untransformed glyph metrics
};

class T3FontCache {
public:

  T3FontCache(Ref *fontID, double m11A, double m12A,
	      double m21A, double m22A,
	      int glyphXA, int glyphYA, int glyphWA, int glyphHA,
	      Display *displayA, Visual *visual, Guint depth,
	      Pixmap origPixmap);
  ~T3FontCache();
  GBool matches(Ref *idA, double m11A, double m12A,
		double m21A, double m22A)
    { return fontID.num == idA->num && fontID.gen == idA->gen &&
	     m11 == m11A && m12 == m12A && m21 == m21A && m22 == m22A; }

  Ref fontID;			// PDF font ID
  double m11, m12, m21, m22;	// transform matrix
  int glyphX, glyphY;		// pixel offset of glyph pixmaps
  int glyphW, glyphH;		// size of glyph pixmaps, in pixels
  int glyphSize;		// size of glyph pixmaps, in bytes
  int cacheSets;		// number of sets in cache
  int cacheAssoc;		// cache associativity (glyphs per set)
  Guchar *cacheData;		// glyph pixmap cache
  T3FontCacheTag *cacheTags;	// cache tags, i.e., char codes
  Display *display;
  Pixmap pixmap;
  XImage *image;
};

T3FontCache::T3FontCache(Ref *fontIDA, double m11A, double m12A,
			 double m21A, double m22A,
			 int glyphXA, int glyphYA, int glyphWA, int glyphHA,
			 Display *displayA, Visual *visual, Guint depth,
			 Pixmap origPixmap) {
  int i;

  fontID = *fontIDA;
  m11 = m11A;
  m12 = m12A;
  m21 = m21A;
  m22 = m22A;
  glyphX = glyphXA;
  glyphY = glyphYA;
  glyphW = glyphWA;
  glyphH = glyphHA;
  glyphSize = glyphW * glyphH;
  cacheAssoc = 8;
  if (glyphSize <= 256) {
    cacheSets = 8;
  } else if (glyphSize <= 512) {
    cacheSets = 4;
  } else if (glyphSize <= 1024) {
    cacheSets = 2;
  } else {
    cacheSets = 1;
  }
  cacheData = (Guchar *)gmalloc(cacheSets * cacheAssoc * glyphSize);
  cacheTags = (T3FontCacheTag *)gmalloc(cacheSets * cacheAssoc *
					sizeof(T3FontCacheTag));
  for (i = 0; i < cacheSets * cacheAssoc; ++i) {
    cacheTags[i].mru = i & (cacheAssoc - 1);
  }
  display = displayA;
  pixmap = XCreatePixmap(display, origPixmap, glyphW, glyphH, depth);
  image = XCreateImage(display, visual, depth, ZPixmap, 0, NULL,
		       glyphW, glyphH, 8, 0);
  image->data = (char *)gmalloc(glyphH * image->bytes_per_line);
}

T3FontCache::~T3FontCache() {
  gfree(cacheData);
  gfree(cacheTags);
  XFreePixmap(display, pixmap);
  gfree(image->data);
  image->data = NULL;
  XDestroyImage(image);
}

struct T3GlyphStack {
  GBool cacheable;
  Gushort code;
  T3FontCache *cache;
  int cacheIdx;
  T3FontCacheTag *cacheTag;
  Guchar *cacheData;
  double x, y;
  Unicode *u;
  int uLen;
  GfxRGB color;
  int origPixmapW, origPixmapH;
  Pixmap origPixmap;
  GC origStrokeGC;
  GC origFillGC;
  Region origClipRegion;
  double origCTM4, origCTM5;
  double wx, wy;		// untransformed glyph metrics
  T3GlyphStack *next;
};

//------------------------------------------------------------------------
// XOutputDev
//------------------------------------------------------------------------

XOutputDev::XOutputDev(Display *displayA, int screenNumA,
		       Visual *visualA, Colormap colormapA,
		       GBool reverseVideoA, unsigned long paperColorA,
		       GBool installCmap, int rgbCubeSize,
		       int forceDepth) {
  XVisualInfo visualTempl;
  XVisualInfo *visualList;
  int nVisuals;
  Gulong mask;
  XColor xcolor;
  XColor *xcolors;
  int r, g, b, n, m;
  GBool ok;

  // no document yet
  xref = NULL;

  // display / screen / visual / colormap
  display = displayA;
  screenNum = screenNumA;
  visual = visualA;
  colormap = colormapA;

  // no pixmap yet
  pixmapW = pixmapH = 0;

  // check for TrueColor visual
  if (forceDepth != 0) {
    depth = forceDepth;
    trueColor = depth >= 16;
  } else {
    visualTempl.visualid = XVisualIDFromVisual(visual);
    visualList = XGetVisualInfo(display, VisualIDMask,
				&visualTempl, &nVisuals);
    if (nVisuals < 1) {
      // this shouldn't happen
      XFree((XPointer)visualList);
      visualList = XGetVisualInfo(display, VisualNoMask, &visualTempl,
				  &nVisuals);
    }
    depth = visualList->depth;
    if (visualList->c_class == TrueColor) {
      trueColor = gTrue;
      for (mask = visualList->red_mask, rShift = 0;
	   mask && !(mask & 1);
	   mask >>= 1, ++rShift) ;
      rMul = (int)mask;
      for (mask = visualList->green_mask, gShift = 0;
	   mask && !(mask & 1);
	   mask >>= 1, ++gShift) ;
      gMul = (int)mask;
      for (mask = visualList->blue_mask, bShift = 0;
	   mask && !(mask & 1);
	   mask >>= 1, ++bShift) ;
      bMul = (int)mask;
    } else {
      trueColor = gFalse;
    }
    XFree((XPointer)visualList);
  }

  // allocate a color cube
  if (!trueColor) {
    redMap[BlackPixel(display, screenNum) & 0xff] = 0;
    redMap[WhitePixel(display, screenNum) & 0xff] = 1;

    // set colors in private colormap
    if (installCmap) {
      for (numColors = 6; numColors >= 2; --numColors) {
	m = numColors * numColors * numColors;
	if (XAllocColorCells(display, colormap, False, NULL, 0, colors, m)) {
	  break;
	}
      }
      if (numColors >= 2) {
	m = numColors * numColors * numColors;
	xcolors = (XColor *)gmalloc(m * sizeof(XColor));
	n = 0;
	for (r = 0; r < numColors; ++r) {
	  for (g = 0; g < numColors; ++g) {
	    for (b = 0; b < numColors; ++b) {
	      xcolors[n].pixel = colors[n];
	      xcolors[n].red = (r * 65535) / (numColors - 1);
	      xcolors[n].green = (g * 65535) / (numColors - 1);
	      xcolors[n].blue = (b * 65535) / (numColors - 1);
	      xcolors[n].flags = DoRed | DoGreen | DoBlue;
	      redMap[xcolors[n].pixel & 0xff] = xcolors[n].red / 65535.0;
	      ++n;
	    }
	  }
	}
	XStoreColors(display, colormap, xcolors, m);
	gfree(xcolors);
      } else {
	numColors = 1;
	colors[0] = BlackPixel(display, screenNum);
	colors[1] = WhitePixel(display, screenNum);
      }

    // allocate colors in shared colormap
    } else {
      if (rgbCubeSize > maxRGBCube) {
	rgbCubeSize = maxRGBCube;
      }
      ok = gFalse;
      for (numColors = rgbCubeSize; numColors >= 2; --numColors) {
	ok = gTrue;
	n = 0;
	for (r = 0; r < numColors && ok; ++r) {
	  for (g = 0; g < numColors && ok; ++g) {
	    for (b = 0; b < numColors && ok; ++b) {
	      if (n == 0) {
		colors[n] = BlackPixel(display, screenNum);
		redMap[colors[n] & 0xff] = 0;
		++n;
	      } else {
		xcolor.red = (r * 65535) / (numColors - 1);
		xcolor.green = (g * 65535) / (numColors - 1);
		xcolor.blue = (b * 65535) / (numColors - 1);
		if (XAllocColor(display, colormap, &xcolor)) {
		  colors[n++] = xcolor.pixel;
		  redMap[xcolor.pixel & 0xff] = xcolor.red / 65535.0;
		} else {
		  ok = gFalse;
		}
	      }
	    }
	  }
	}
	if (ok) {
	  break;
	}
	XFreeColors(display, colormap, &colors[1], n-1, 0);
      }
      if (!ok) {
	numColors = 1;
	colors[0] = BlackPixel(display, screenNum);
	colors[1] = WhitePixel(display, screenNum);
      }
    }
  }

  // misc parameters
  reverseVideo = reverseVideoA;
  paperColor = paperColorA;

  // set up the font cache and fonts
  gfxFont = NULL;
  font = NULL;
  needFontUpdate = gFalse;
  fontCache = new XOutputFontCache(display, depth, this,
				   globalParams->getT1libControl(),
				   globalParams->getFreeTypeControl());
  nT3Fonts = 0;
  t3GlyphStack = NULL;

  // no text outline clipping path
  textClipPath = NULL;

  // empty state stack
  save = NULL;

  // create text object
  text = new TextPage(gFalse);
}

XOutputDev::~XOutputDev() {
  int i;

  delete fontCache;
  for (i = 0; i < nT3Fonts; ++i) {
    delete t3FontCache[i];
  }
  delete text;
}

void XOutputDev::startDoc(XRef *xrefA) {
  int i;

  xref = xrefA;
  fontCache->startDoc(screenNum, visual, colormap, trueColor, rMul, gMul, bMul,
		      rShift, gShift, bShift, colors, numColors);
  for (i = 0; i < nT3Fonts; ++i) {
    delete t3FontCache[i];
  }
  nT3Fonts = 0;
}

void XOutputDev::startPage(int pageNum, GfxState *state) {
  XGCValues gcValues;
  XRectangle rect;

  // default line flatness
  flatness = 0;

  // allocate GCs
  gcValues.foreground = BlackPixel(display, screenNum);
  gcValues.background = WhitePixel(display, screenNum);
  gcValues.line_width = 0;
  gcValues.line_style = LineSolid;
  strokeGC = XCreateGC(display, pixmap,
		       GCForeground | GCBackground | GCLineWidth | GCLineStyle,
                       &gcValues);
  fillGC = XCreateGC(display, pixmap,
		     GCForeground | GCBackground | GCLineWidth | GCLineStyle,
		     &gcValues);
  gcValues.foreground = paperColor;
  paperGC = XCreateGC(display, pixmap,
		      GCForeground | GCBackground | GCLineWidth | GCLineStyle,
		      &gcValues);

  // initialize clip region
  clipRegion = XCreateRegion();
  rect.x = rect.y = 0;
  rect.width = pixmapW;
  rect.height = pixmapH;
  XUnionRectWithRegion(&rect, clipRegion, clipRegion);
  XSetRegion(display, strokeGC, clipRegion);
  XSetRegion(display, fillGC, clipRegion);

  // clear font
  gfxFont = NULL;
  font = NULL;

  // clear window
  XFillRectangle(display, pixmap, paperGC, 0, 0, pixmapW, pixmapH);

  // clear text object
  text->startPage(state);
}

void XOutputDev::endPage() {
  XOutputState *s;

  text->coalesce(gTrue);

  // clear state stack, free all GCs, free the clip region
  while (save) {
    s = save;
    save = save->next;
    XFreeGC(display, s->strokeGC);
    XFreeGC(display, s->fillGC);
    XDestroyRegion(s->clipRegion);
    delete s;
  }
  XFreeGC(display, strokeGC);
  XFreeGC(display, fillGC);
  XFreeGC(display, paperGC);
  XDestroyRegion(clipRegion);
}

void XOutputDev::drawLink(Link *link, Catalog *catalog) {
  double x1, y1, x2, y2;
  LinkBorderStyle *borderStyle;
  GfxRGB rgb;
  double *dash;
  char dashList[20];
  int dashLength;
  XPoint points[5];
  int x, y, i;

  link->getRect(&x1, &y1, &x2, &y2);
  borderStyle = link->getBorderStyle();
  if (borderStyle->getWidth() > 0) {
    borderStyle->getColor(&rgb.r, &rgb.g, &rgb.b);
    XSetForeground(display, strokeGC, findColor(&rgb));
    borderStyle->getDash(&dash, &dashLength);
    if (borderStyle->getType() == linkBorderDashed && dashLength > 0) {
      if (dashLength > 20) {
	dashLength = 20;
      }
      for (i = 0; i < dashLength; ++i) {
	if ((dashList[i] = xoutRound(dash[i])) == 0) {
	  dashList[i] = 1;
	}
      }
      XSetLineAttributes(display, strokeGC, xoutRound(borderStyle->getWidth()),
			 LineOnOffDash, CapButt, JoinMiter);
      XSetDashes(display, strokeGC, 0, dashList, dashLength);
    } else {
      XSetLineAttributes(display, strokeGC, xoutRound(borderStyle->getWidth()),
			 LineSolid, CapButt, JoinMiter);
    }
    if (borderStyle->getType() == linkBorderUnderlined) {
      cvtUserToDev(x1, y1, &x, &y);
      points[0].x = x;
      points[0].y = y;
      cvtUserToDev(x2, y1, &x, &y);
      points[1].x = x;
      points[1].y = y;
      XDrawLine(display, pixmap, strokeGC, points[0].x, points[0].y,
		points[1].x, points[1].y);
    } else {
      cvtUserToDev(x1, y1, &x, &y);
      points[0].x = points[4].x = x;
      points[0].y = points[4].y = y;
      cvtUserToDev(x2, y1, &x, &y);
      points[1].x = x;
      points[1].y = y;
      cvtUserToDev(x2, y2, &x, &y);
      points[2].x = x;
      points[2].y = y;
      cvtUserToDev(x1, y2, &x, &y);
      points[3].x = x;
      points[3].y = y;
      XDrawLines(display, pixmap, strokeGC, points, 5, CoordModeOrigin);
    }
  }
}

void XOutputDev::saveState(GfxState *state) {
  XOutputState *s;
  XGCValues values;

  // save current state
  s = new XOutputState;
  s->strokeGC = strokeGC;
  s->fillGC = fillGC;
  s->clipRegion = clipRegion;

  // push onto state stack
  s->next = save;
  save = s;

  // create a new current state by copying
  strokeGC = XCreateGC(display, pixmap, 0, &values);
  XCopyGC(display, s->strokeGC, 0xffffffff, strokeGC);
  fillGC = XCreateGC(display, pixmap, 0, &values);
  XCopyGC(display, s->fillGC, 0xffffffff, fillGC);
  clipRegion = XCreateRegion();
  XUnionRegion(s->clipRegion, clipRegion, clipRegion);
  XSetRegion(display, strokeGC, clipRegion);
  XSetRegion(display, fillGC, clipRegion);
}

void XOutputDev::restoreState(GfxState *state) {
  XOutputState *s;

  if (save) {
    // kill current state
    XFreeGC(display, strokeGC);
    XFreeGC(display, fillGC);
    XDestroyRegion(clipRegion);

    // restore state
    flatness = state->getFlatness();
    strokeGC = save->strokeGC;
    fillGC = save->fillGC;
    clipRegion = save->clipRegion;
    XSetRegion(display, strokeGC, clipRegion);
    XSetRegion(display, fillGC, clipRegion);

    // pop state stack
    s = save;
    save = save->next;
    delete s;

    // we'll need to restore the font
    needFontUpdate = gTrue;
  }
}

void XOutputDev::updateAll(GfxState *state) {
  updateLineAttrs(state, gTrue);
  updateFlatness(state);
  updateMiterLimit(state);
  updateFillColor(state);
  updateStrokeColor(state);
  needFontUpdate = gTrue;
}

void XOutputDev::updateCTM(GfxState *state, double m11, double m12,
			   double m21, double m22, double m31, double m32) {
  updateLineAttrs(state, gTrue);
}

void XOutputDev::updateLineDash(GfxState *state) {
  updateLineAttrs(state, gTrue);
}

void XOutputDev::updateFlatness(GfxState *state) {
  flatness = state->getFlatness();
}

void XOutputDev::updateLineJoin(GfxState *state) {
  updateLineAttrs(state, gFalse);
}

void XOutputDev::updateLineCap(GfxState *state) {
  updateLineAttrs(state, gFalse);
}

// unimplemented
void XOutputDev::updateMiterLimit(GfxState *state) {
}

void XOutputDev::updateLineWidth(GfxState *state) {
  updateLineAttrs(state, gFalse);
}

void XOutputDev::updateLineAttrs(GfxState *state, GBool updateDash) {
  double width;
  int cap, join;
  double *dashPattern;
  int dashLength;
  double dashStart;
  char dashList[20];
  int i;

  width = state->getTransformedLineWidth();
  switch (state->getLineCap()) {
  case 0: cap = CapButt; break;
  case 1: cap = CapRound; break;
  case 2: cap = CapProjecting; break;
  default:
    error(-1, "Bad line cap style (%d)", state->getLineCap());
    cap = CapButt;
    break;
  }
  switch (state->getLineJoin()) {
  case 0: join = JoinMiter; break;
  case 1: join = JoinRound; break;
  case 2: join = JoinBevel; break;
  default:
    error(-1, "Bad line join style (%d)", state->getLineJoin());
    join = JoinMiter;
    break;
  }
  state->getLineDash(&dashPattern, &dashLength, &dashStart);
#if 1 //~ work around a bug in XFree86 (???)
  if (dashLength > 0 && cap == CapProjecting) {
    cap = CapButt;
  }
#endif
  XSetLineAttributes(display, strokeGC, xoutRound(width),
		     dashLength > 0 ? LineOnOffDash : LineSolid,
		     cap, join);
  if (updateDash && dashLength > 0) {
    if (dashLength > 20)
      dashLength = 20;
    for (i = 0; i < dashLength; ++i) {
      dashList[i] = xoutRound(state->transformWidth(dashPattern[i]));
      if (dashList[i] == 0)
	dashList[i] = 1;
    }
    XSetDashes(display, strokeGC, xoutRound(dashStart), dashList, dashLength);
  }
}

void XOutputDev::updateFillColor(GfxState *state) {
  GfxRGB rgb;

  state->getFillRGB(&rgb);
  if (reverseVideo) {
    rgb.r = 1 - rgb.r;
    rgb.g = 1 - rgb.g;
    rgb.b = 1 - rgb.b;
  }
  XSetForeground(display, fillGC, findColor(&rgb));
}

void XOutputDev::updateStrokeColor(GfxState *state) {
  GfxRGB rgb;

  state->getStrokeRGB(&rgb);
  if (reverseVideo) {
    rgb.r = 1 - rgb.r;
    rgb.g = 1 - rgb.g;
    rgb.b = 1 - rgb.b;
  }
  XSetForeground(display, strokeGC, findColor(&rgb));
}

void XOutputDev::updateFont(GfxState *state) {
  double m11, m12, m21, m22;

  needFontUpdate = gFalse;

  text->updateFont(state);

  if (!(gfxFont = state->getFont())) {
    font = NULL;
    return;
  }
  if (gfxFont->getType() == fontType3) {
    font = NULL;
    return;
  }
  state->getFontTransMat(&m11, &m12, &m21, &m22);
  m11 *= state->getHorizScaling();
  m12 *= state->getHorizScaling();
  font = fontCache->getFont(xref, gfxFont, m11, m12, m21, m22);
  if (font) {
    font->updateGC(fillGC);
    font->updateGC(strokeGC);
  }
}

void XOutputDev::stroke(GfxState *state) {
  XPoint *points;
  int *lengths;
  int n, size, numPoints, i, j;

  // transform points
  n = convertPath(state, state->getPath(),
		  &points, &size, &numPoints, &lengths, gFalse);

  // draw each subpath
  j = 0;
  for (i = 0; i < n; ++i) {
    XDrawLines(display, pixmap, strokeGC, points + j, lengths[i],
	       CoordModeOrigin);
    j += lengths[i];
  }

  // free points and lengths arrays
  if (points != tmpPoints)
    gfree(points);
  if (lengths != tmpLengths)
    gfree(lengths);
}

void XOutputDev::fill(GfxState *state) {
  doFill(state, WindingRule);
}

void XOutputDev::eoFill(GfxState *state) {
  doFill(state, EvenOddRule);
}

//
//  X doesn't color the pixels on the right-most and bottom-most
//  borders of a polygon.  This means that one-pixel-thick polygons
//  are not colored at all.  I think this is supposed to be a
//  feature, but I can't figure out why.  So after it fills a
//  polygon, it also draws lines around the border.  This is done
//  only for single-component polygons, since it's not very
//  compatible with the compound polygon kludge (see convertPath()).
//
void XOutputDev::doFill(GfxState *state, int rule) {
  XPoint *points;
  int *lengths;
  int n, size, numPoints, i, j;

  // set fill rule
  XSetFillRule(display, fillGC, rule);

  // transform points, build separate polygons
  n = convertPath(state, state->getPath(),
		  &points, &size, &numPoints, &lengths, gTrue);

  // fill them
  j = 0;
  for (i = 0; i < n; ++i) {
    XFillPolygon(display, pixmap, fillGC, points + j, lengths[i],
		 Complex, CoordModeOrigin);
    if (state->getPath()->getNumSubpaths() == 1) {
      XDrawLines(display, pixmap, fillGC, points + j, lengths[i],
		 CoordModeOrigin);
    }
    j += lengths[i] + 1;
  }

  // free points and lengths arrays
  if (points != tmpPoints)
    gfree(points);
  if (lengths != tmpLengths)
    gfree(lengths);
}

void XOutputDev::clip(GfxState *state) {
  doClip(state, state->getPath(), WindingRule);
}

void XOutputDev::eoClip(GfxState *state) {
  doClip(state, state->getPath(), EvenOddRule);
}

void XOutputDev::doClip(GfxState *state, GfxPath *path, int rule) {
  GfxSubpath *subpath;
  Region region, region2;
  XPoint rect[5];
  XPoint *points;
  int *lengths;
  double x0, y0, x1, y1, x2, y2, x3, y3;
  GBool gotRect;
  int n, size, numPoints, i, j;

  // special case for rectangular clipping paths -- this is a common
  // case, and we want to make sure not to clip an extra pixel on the
  // right and bottom edges due to the difference between the PDF and
  // X rendering models
  gotRect = gFalse;
  if (path->getNumSubpaths() == 1) {
    subpath = path->getSubpath(0);
    if ((subpath->isClosed() && subpath->getNumPoints() == 5) ||
	(!subpath->isClosed() && subpath->getNumPoints() == 4)) {
      state->transform(subpath->getX(0), subpath->getY(0), &x0, &y0);
      state->transform(subpath->getX(1), subpath->getY(1), &x1, &y1);
      state->transform(subpath->getX(2), subpath->getY(2), &x2, &y2);
      state->transform(subpath->getX(3), subpath->getY(3), &x3, &y3);
      if (fabs(x0-x1) < 1 && fabs(x2-x3) < 1 &&
	  fabs(y0-y3) < 1 && fabs(y1-y2) < 1) {
	if (x0 < x2) {
	  rect[0].x = rect[1].x = rect[4].x = (int)floor(x0);
	  rect[2].x = rect[3].x = (int)floor(x2) + 1;
	} else {
	  rect[0].x = rect[1].x = rect[4].x = (int)floor(x0) + 1;
	  rect[2].x = rect[3].x = (int)floor(x2);
	}
	if (y0 < y1) {
	  rect[0].y = rect[3].y = rect[4].y = (int)floor(y0);
	  rect[1].y = rect[2].y = (int)floor(y1) + 1;
	} else {
	  rect[0].y = rect[3].y = rect[4].y = (int)floor(y0) + 1;
	  rect[1].y = rect[2].y = (int)floor(y1);
	}
	gotRect = gTrue;
      } else if (fabs(x0-x3) < 1 && fabs(x1-x2) < 1 &&
		 fabs(y0-y1) < 1 && fabs(y2-y3) < 1) {
	if (x0 < x1) {
	  rect[0].x = rect[3].x = rect[4].x = (int)floor(x0);
	  rect[1].x = rect[2].x = (int)floor(x1) + 1;
	} else {
	  rect[0].x = rect[3].x = rect[4].x = (int)floor(x0) + 1;
	  rect[1].x = rect[2].x = (int)floor(x1);
	}
	if (y0 < y2) {
	  rect[0].y = rect[1].y = rect[4].y = (int)floor(y0);
	  rect[2].y = rect[3].y = (int)floor(y2) + 1;
	} else {
	  rect[0].y = rect[1].y = rect[4].y = (int)floor(y0) + 1;
	  rect[2].y = rect[3].y = (int)floor(y2);
	}
	gotRect = gTrue;
      }
    }
  }

  if (gotRect) {
    region = XPolygonRegion(rect, 5, EvenOddRule);

  } else {
    // transform points, build separate polygons
    n = convertPath(state, path, &points, &size, &numPoints, &lengths, gTrue);

    // construct union of subpath regions
    // (XPolygonRegion chokes if there aren't at least three points --
    // this happens if the PDF file does moveto/closepath/clip, which
    // sets an empty clipping region)
    if (lengths[0] > 2) {
      region = XPolygonRegion(points, lengths[0], rule);
    } else {
      region = XCreateRegion();
    }
    j = lengths[0] + 1;
    for (i = 1; i < n; ++i) {
      if (lengths[i] > 2) {
	region2 = XPolygonRegion(points + j, lengths[i], rule);
      } else {
	region2 = XCreateRegion();
      }
      XUnionRegion(region2, region, region);
      XDestroyRegion(region2);
      j += lengths[i] + 1;
    }

    // free points and lengths arrays
    if (points != tmpPoints) {
      gfree(points);
    }
    if (lengths != tmpLengths) {
      gfree(lengths);
    }
  }

  // intersect region with clipping region
  XIntersectRegion(region, clipRegion, clipRegion);
  XDestroyRegion(region);
  XSetRegion(display, strokeGC, clipRegion);
  XSetRegion(display, fillGC, clipRegion);
}

//
// Transform points in the path and convert curves to line segments.
// Builds a set of subpaths and returns the number of subpaths.
// If <fillHack> is set, close any unclosed subpaths and activate a
// kludge for polygon fills:  First, it divides up the subpaths into
// non-overlapping polygons by simply comparing bounding rectangles.
// Then it connects subaths within a single compound polygon to a single
// point so that X can fill the polygon (sort of).
//
int XOutputDev::convertPath(GfxState *state, GfxPath *path,
			    XPoint **points, int *size,
			    int *numPoints, int **lengths, GBool fillHack) {
  BoundingRect *rects;
  BoundingRect rect;
  int n, i, ii, j, k, k0;

  // get path and number of subpaths
  n = path->getNumSubpaths();

  // allocate lengths array
  if (n < numTmpSubpaths)
    *lengths = tmpLengths;
  else
    *lengths = (int *)gmalloc(n * sizeof(int));

  // allocate bounding rectangles array
  if (fillHack) {
    if (n < numTmpSubpaths)
      rects = tmpRects;
    else
      rects = (BoundingRect *)gmalloc(n * sizeof(BoundingRect));
  } else {
    rects = NULL;
  }

  // do each subpath
  *points = tmpPoints;
  *size = numTmpPoints;
  *numPoints = 0;
  for (i = 0; i < n; ++i) {

    // transform the points
    j = *numPoints;
    convertSubpath(state, path->getSubpath(i), points, size, numPoints);

    // construct bounding rectangle
    if (fillHack) {
      rects[i].xMin = rects[i].xMax = (*points)[j].x;
      rects[i].yMin = rects[i].yMax = (*points)[j].y;
      for (k = j + 1; k < *numPoints; ++k) {
	if ((*points)[k].x < rects[i].xMin)
	  rects[i].xMin = (*points)[k].x;
	else if ((*points)[k].x > rects[i].xMax)
	  rects[i].xMax = (*points)[k].x;
	if ((*points)[k].y < rects[i].yMin)
	  rects[i].yMin = (*points)[k].y;
	else if ((*points)[k].y > rects[i].yMax)
	  rects[i].yMax = (*points)[k].y;
      }
    }

    // close subpath if necessary
    if (fillHack && ((*points)[*numPoints-1].x != (*points)[j].x ||
		     (*points)[*numPoints-1].y != (*points)[j].y)) {
      addPoint(points, size, numPoints, (*points)[j].x, (*points)[j].y);
    }

    // length of this subpath
    (*lengths)[i] = *numPoints - j;

    // leave an extra point for compound fill hack
    if (fillHack)
      addPoint(points, size, numPoints, 0, 0);
  }

  // kludge: munge any points that are *way* out of bounds - these can
  // crash certain (buggy) X servers
  for (i = 0; i < *numPoints; ++i) {
    if ((*points)[i].x < -4 * pixmapW) {
      (*points)[i].x = -4 * pixmapW;
    } else if ((*points)[i].x > 4 * pixmapW) {
      (*points)[i].x = 4 * pixmapW;
    }
    if ((*points)[i].y < -pixmapH) {
      (*points)[i].y = -4 * pixmapH;
    } else if ((*points)[i].y > 4 * pixmapH) {
      (*points)[i].y = 4 * pixmapH;
    }
  }

  // combine compound polygons
  if (fillHack) {
    i = j = k = 0;
    while (i < n) {

      // start with subpath i
      rect = rects[i];
      (*lengths)[j] = (*lengths)[i];
      k0 = k;
      (*points)[k + (*lengths)[i]] = (*points)[k0];
      k += (*lengths)[i] + 1;
      ++i;

      // combine overlapping polygons
      do {

	// look for the first subsequent subpath, if any, which overlaps
	for (ii = i; ii < n; ++ii) {
	  if (rects[ii].xMax > rects[i].xMin &&
	      rects[ii].xMin < rects[i].xMax &&
	      rects[ii].yMax > rects[i].yMin &&
	      rects[ii].yMin < rects[i].yMax) {
	    break;
	  }
	}

	// if there is an overlap, combine the polygons
	if (ii < n) {
	  for (; i <= ii; ++i) {
	    if (rects[i].xMin < rect.xMin)
	      rect.xMin = rects[j].xMin;
	    if (rects[i].xMax > rect.xMax)
	      rect.xMax = rects[j].xMax;
	    if (rects[i].yMin < rect.yMin)
	      rect.yMin = rects[j].yMin;
	    if (rects[i].yMax > rect.yMax)
	      rect.yMax = rects[j].yMax;
	    (*lengths)[j] += (*lengths)[i] + 1;
	    (*points)[k + (*lengths)[i]] = (*points)[k0];
	    k += (*lengths)[i] + 1;
	  }
	}
      } while (ii < n && i < n);

      ++j;
    }

    // free bounding rectangles
    if (rects != tmpRects)
      gfree(rects);

    n = j;
  }

  return n;
}

//
// Transform points in a single subpath and convert curves to line
// segments.
//
void XOutputDev::convertSubpath(GfxState *state, GfxSubpath *subpath,
				XPoint **points, int *size, int *n) {
  double x0, y0, x1, y1, x2, y2, x3, y3;
  int m, i;

  m = subpath->getNumPoints();
  i = 0;
  while (i < m) {
    if (i >= 1 && subpath->getCurve(i)) {
      state->transform(subpath->getX(i-1), subpath->getY(i-1), &x0, &y0);
      state->transform(subpath->getX(i), subpath->getY(i), &x1, &y1);
      state->transform(subpath->getX(i+1), subpath->getY(i+1), &x2, &y2);
      state->transform(subpath->getX(i+2), subpath->getY(i+2), &x3, &y3);
      doCurve(points, size, n, x0, y0, x1, y1, x2, y2, x3, y3);
      i += 3;
    } else {
      state->transform(subpath->getX(i), subpath->getY(i), &x1, &y1);
      addPoint(points, size, n, xoutRound(x1), xoutRound(y1));
      ++i;
    }
  }
}

//
// Subdivide a Bezier curve.  This uses floating point to avoid
// propagating rounding errors.  (The curves look noticeably more
// jagged with integer arithmetic.)
//
void XOutputDev::doCurve(XPoint **points, int *size, int *n,
			 double x0, double y0, double x1, double y1,
			 double x2, double y2, double x3, double y3) {
  double x[(1<<maxCurveSplits)+1][3];
  double y[(1<<maxCurveSplits)+1][3];
  int next[1<<maxCurveSplits];
  int p1, p2, p3;
  double xx1, yy1, xx2, yy2;
  double dx, dy, mx, my, d1, d2;
  double xl0, yl0, xl1, yl1, xl2, yl2;
  double xr0, yr0, xr1, yr1, xr2, yr2, xr3, yr3;
  double xh, yh;
  double flat;

  flat = (double)(flatness * flatness);
  if (flat < 1)
    flat = 1;

  // initial segment
  p1 = 0;
  p2 = 1<<maxCurveSplits;
  x[p1][0] = x0;  y[p1][0] = y0;
  x[p1][1] = x1;  y[p1][1] = y1;
  x[p1][2] = x2;  y[p1][2] = y2;
  x[p2][0] = x3;  y[p2][0] = y3;
  next[p1] = p2;

  while (p1 < (1<<maxCurveSplits)) {

    // get next segment
    xl0 = x[p1][0];  yl0 = y[p1][0];
    xx1 = x[p1][1];  yy1 = y[p1][1];
    xx2 = x[p1][2];  yy2 = y[p1][2];
    p2 = next[p1];
    xr3 = x[p2][0];  yr3 = y[p2][0];

    // compute distances from control points to midpoint of the
    // straight line (this is a bit of a hack, but it's much faster
    // than computing the actual distances to the line)
    mx = (xl0 + xr3) * 0.5;
    my = (yl0 + yr3) * 0.5;
    dx = xx1 - mx;
    dy = yy1 - my;
    d1 = dx*dx + dy*dy;
    dx = xx2 - mx;
    dy = yy2 - my;
    d2 = dx*dx + dy*dy;

    // if curve is flat enough, or no more divisions allowed then
    // add the straight line segment
    if (p2 - p1 <= 1 || (d1 <= flat && d2 <= flat)) {
      addPoint(points, size, n, xoutRound(xr3), xoutRound(yr3));
      p1 = p2;

    // otherwise, subdivide the curve
    } else {
      xl1 = (xl0 + xx1) * 0.5;
      yl1 = (yl0 + yy1) * 0.5;
      xh = (xx1 + xx2) * 0.5;
      yh = (yy1 + yy2) * 0.5;
      xl2 = (xl1 + xh) * 0.5;
      yl2 = (yl1 + yh) * 0.5;
      xr2 = (xx2 + xr3) * 0.5;
      yr2 = (yy2 + yr3) * 0.5;
      xr1 = (xh + xr2) * 0.5;
      yr1 = (yh + yr2) * 0.5;
      xr0 = (xl2 + xr1) * 0.5;
      yr0 = (yl2 + yr1) * 0.5;

      // add the new subdivision points
      p3 = (p1 + p2) / 2;
      x[p1][1] = xl1;  y[p1][1] = yl1;
      x[p1][2] = xl2;  y[p1][2] = yl2;
      next[p1] = p3;
      x[p3][0] = xr0;  y[p3][0] = yr0;
      x[p3][1] = xr1;  y[p3][1] = yr1;
      x[p3][2] = xr2;  y[p3][2] = yr2;
      next[p3] = p2;
    }
  }
}

//
// Add a point to the points array.  (This would use a generic resizable
// array type if C++ supported parameterized types in some reasonable
// way -- templates are a disgusting kludge.)
//
void XOutputDev::addPoint(XPoint **points, int *size, int *k, int x, int y) {
  if (*k >= *size) {
    *size += 32;
    if (*points == tmpPoints) {
      *points = (XPoint *)gmalloc(*size * sizeof(XPoint));
      memcpy(*points, tmpPoints, *k * sizeof(XPoint));
    } else {
      *points = (XPoint *)grealloc(*points, *size * sizeof(XPoint));
    }
  }
  (*points)[*k].x = x;
  (*points)[*k].y = y;
  ++(*k);
}

void XOutputDev::beginString(GfxState *state, GString *s) {
  text->beginWord(state, state->getCurX(), state->getCurY());
}

void XOutputDev::endString(GfxState *state) {
  text->endWord();
}

void XOutputDev::drawChar(GfxState *state, double x, double y,
			  double dx, double dy,
			  double originX, double originY,
			  CharCode code, Unicode *u, int uLen) {
  int render;
  double x1, y1, dx1, dy1;
  GfxRGB rgb;
  double saveCurX, saveCurY;
  double *ctm;
  double saveCTM[6];

  if (needFontUpdate) {
    updateFont(state);
  }

  text->addChar(state, x, y, dx, dy, code, u, uLen);

  if (!font) {
    return;
  }

  // check for invisible text -- this is used by Acrobat Capture
  render = state->getRender();
  if (render == 3) {
    return;
  }

  x -= originX;
  y -= originY;
  state->transform(x, y, &x1, &y1);
  state->transformDelta(dx, dy, &dx1, &dy1);

  // fill
  if (!(render & 1)) {
    state->getFillRGB(&rgb);
    if (reverseVideo) {
      rgb.r = 1 - rgb.r;
      rgb.g = 1 - rgb.g;
      rgb.b = 1 - rgb.b;
    }
    font->drawChar(state, pixmap, pixmapW, pixmapH, fillGC, &rgb,
		   x1, y1, dx1, dy1, code, u, uLen);
  }

  // stroke
  if ((render & 3) == 1 || (render & 3) == 2) {
    if (font->hasGetCharPath()) {
      saveCurX = state->getCurX();
      saveCurY = state->getCurY();
      ctm = state->getCTM();
      memcpy(saveCTM, ctm, 6 * sizeof(double));
      state->setCTM(1, 0, 0, 1, x1, y1);
      font->getCharPath(state, code, u, uLen);
      stroke(state);
      state->clearPath();
      state->setCTM(saveCTM[0], saveCTM[1], saveCTM[2], saveCTM[3],
		    saveCTM[4], saveCTM[5]);
      state->moveTo(saveCurX, saveCurY);
    } else {
      // can't stroke the outline, so just fill it using the stroke
      // color
      state->getStrokeRGB(&rgb);
      if (reverseVideo) {
	rgb.r = 1 - rgb.r;
	rgb.g = 1 - rgb.g;
	rgb.b = 1 - rgb.b;
      }
      font->drawChar(state, pixmap, pixmapW, pixmapH, strokeGC, &rgb,
		     x1, y1, dx1, dy1, code, u, uLen);
    }
  }

  // clip
  if (render & 4) {
    if (font->hasGetCharPath()) {
      saveCurX = state->getCurX();
      saveCurY = state->getCurY();
      font->getCharPath(state, code, u, uLen);
      state->getPath()->offset(x1, y1);
      if (textClipPath) {
	textClipPath->append(state->getPath());
      } else {
	textClipPath = state->getPath()->copy();
      }
      state->clearPath();
      state->moveTo(saveCurX, saveCurY);
    }
  }
}

GBool XOutputDev::beginType3Char(GfxState *state,
				 CharCode code, Unicode *u, int uLen) {
  Ref *fontID;
  double *ctm, *bbox;
  GfxRGB color;
  T3FontCache *t3Font;
  T3GlyphStack *t3gs;
  double x1, y1, xMin, yMin, xMax, yMax, xt, yt;
  int i, j;

  if (needFontUpdate) {
    updateFont(state);
  }
  if (!gfxFont) {
    return gFalse;
  }
  fontID = gfxFont->getID();
  ctm = state->getCTM();
  state->transform(0, 0, &xt, &yt);

  // is it the first (MRU) font in the cache?
  if (!(nT3Fonts > 0 &&
	t3FontCache[0]->matches(fontID, ctm[0], ctm[1], ctm[2], ctm[3]))) {

    // is the font elsewhere in the cache?
    for (i = 1; i < nT3Fonts; ++i) {
      if (t3FontCache[i]->matches(fontID, ctm[0], ctm[1], ctm[2], ctm[3])) {
	t3Font = t3FontCache[i];
	for (j = i; j > 0; --j) {
	  t3FontCache[j] = t3FontCache[j - 1];
	}
	t3FontCache[0] = t3Font;
	break;
      }
    }
    if (i >= nT3Fonts) {

      // create new entry in the font cache
      if (nT3Fonts == xOutT3FontCacheSize) {
	delete t3FontCache[nT3Fonts - 1];
	--nT3Fonts;
      }
      for (j = nT3Fonts; j > 0; --j) {
	t3FontCache[j] = t3FontCache[j - 1];
      }
      ++nT3Fonts;
      bbox = gfxFont->getFontBBox();
      if (bbox[0] == 0 && bbox[1] == 0 && bbox[2] == 0 && bbox[3] == 0) {
	// broken bounding box -- just take a guess
	xMin = xt - 5;
	xMax = xMin + 30;
	yMax = yt + 15;
	yMin = yMax - 45;
      } else {
	state->transform(bbox[0], bbox[1], &x1, &y1);
	xMin = xMax = x1;
	yMin = yMax = y1;
	state->transform(bbox[0], bbox[3], &x1, &y1);
	if (x1 < xMin) {
	  xMin = x1;
	} else if (x1 > xMax) {
	  xMax = x1;
	}
	if (y1 < yMin) {
	  yMin = y1;
	} else if (y1 > yMax) {
	  yMax = y1;
	}
	state->transform(bbox[2], bbox[1], &x1, &y1);
	if (x1 < xMin) {
	  xMin = x1;
	} else if (x1 > xMax) {
	  xMax = x1;
	}
	if (y1 < yMin) {
	  yMin = y1;
	} else if (y1 > yMax) {
	  yMax = y1;
	}
	state->transform(bbox[2], bbox[3], &x1, &y1);
	if (x1 < xMin) {
	  xMin = x1;
	} else if (x1 > xMax) {
	  xMax = x1;
	}
	if (y1 < yMin) {
	  yMin = y1;
	} else if (y1 > yMax) {
	  yMax = y1;
	}
      }
      t3FontCache[0] = new T3FontCache(fontID, ctm[0], ctm[1], ctm[2], ctm[3],
	                               (int)floor(xMin - xt),
				       (int)floor(yMin - yt),
				       (int)ceil(xMax) - (int)floor(xMin) + 3,
				       (int)ceil(yMax) - (int)floor(yMin) + 3,
				       display, visual, depth, pixmap);
    }
  }
  t3Font = t3FontCache[0];

  // is the glyph in the cache?
  i = (code & (t3Font->cacheSets - 1)) * t3Font->cacheAssoc;
  for (j = 0; j < t3Font->cacheAssoc; ++j) {
    if ((t3Font->cacheTags[i+j].mru & 0x8000) &&
	t3Font->cacheTags[i+j].code == code) {
      state->getFillRGB(&color);
      if (reverseVideo) {
	color.r = 1 - color.r;
	color.g = 1 - color.g;
	color.b = 1 - color.b;
      }
      text->addChar(state, 0, 0,
		    t3Font->cacheTags[i+j].wx, t3Font->cacheTags[i+j].wy,
		    code, u, uLen);
      drawType3Glyph(t3Font, &t3Font->cacheTags[i+j],
		     t3Font->cacheData + (i+j) * t3Font->glyphSize,
		     xt, yt, &color);
      return gTrue;
    }
  }

  // push a new Type 3 glyph record
  t3gs = new T3GlyphStack();
  t3gs->next = t3GlyphStack;
  t3GlyphStack = t3gs;
  t3GlyphStack->cacheable = gFalse;
  t3GlyphStack->code = code;
  t3GlyphStack->cache = t3Font;
  t3GlyphStack->cacheIdx = i;
  t3GlyphStack->x = xt;
  t3GlyphStack->y = yt;
  t3GlyphStack->u = u;
  t3GlyphStack->uLen = uLen;

  return gFalse;
}

void XOutputDev::endType3Char(GfxState *state) {
  XImage *image;
  Guchar *p;
  int x, y;
  Gulong pixel;
  double alpha;
  T3GlyphStack *t3gs;
  double *ctm;

  if (t3GlyphStack->cacheable) {
    image = t3GlyphStack->cache->image;
    XGetSubImage(display, pixmap, 0, 0,
		 t3GlyphStack->cache->glyphW, t3GlyphStack->cache->glyphH,
		 (1 << depth) - 1, ZPixmap, image, 0, 0);
    p = t3GlyphStack->cacheData;
    for (y = 0; y < t3GlyphStack->cache->glyphH; ++y) {
      for (x = 0; x < t3GlyphStack->cache->glyphW; ++x) {
	pixel = XGetPixel(image, x, y);
	if (trueColor) {
	  alpha = (double)((pixel >> rShift) & rMul) / (double)rMul;
	} else {
	  alpha = redMap[pixel & 0xff];
	}
	if (alpha <= 0.2) {
	  *p++ = 4;
	} else if (alpha <= 0.4) {
	  *p++ = 3;
	} else if (alpha <= 0.6) {
	  *p++ = 2;
	} else if (alpha <= 0.8) {
	  *p++ = 1;
	} else {
	  *p++ = 0;
	}
      }
    }
    XDestroyRegion(clipRegion);
    XFreeGC(display, strokeGC);
    XFreeGC(display, fillGC);
    pixmapW = t3GlyphStack->origPixmapW;
    pixmapH = t3GlyphStack->origPixmapH;
    pixmap = t3GlyphStack->origPixmap;
    strokeGC = t3GlyphStack->origStrokeGC;
    fillGC = t3GlyphStack->origFillGC;
    clipRegion = t3GlyphStack->origClipRegion;
    drawType3Glyph(t3GlyphStack->cache,
		   t3GlyphStack->cacheTag, t3GlyphStack->cacheData,
		   t3GlyphStack->x, t3GlyphStack->y, &t3GlyphStack->color);
    // the CTM must be restored here in order for TextPage::addChar to
    // work correctly
    ctm = state->getCTM();
    state->setCTM(ctm[0], ctm[1], ctm[2], ctm[3],
		  t3GlyphStack->origCTM4, t3GlyphStack->origCTM5);
  }
  text->addChar(state, 0, 0, t3GlyphStack->wx, t3GlyphStack->wy,
		t3GlyphStack->code, t3GlyphStack->u, t3GlyphStack->uLen);
  t3gs = t3GlyphStack;
  t3GlyphStack = t3gs->next;
  delete t3gs;
}

void XOutputDev::drawType3Glyph(T3FontCache *t3Font,
				T3FontCacheTag *tag, Guchar *data,
				double x, double y, GfxRGB *color) {
  XImage *image;
  XColor xcolor;
  GfxRGB bg, rgb;
  Gulong map[5];
  Gulong pixel;
  Guchar *p;
  int x0, y0, w0, h0, x1, y1;
  int ix, iy;

  // compute: (x0,y0) = position in destination pixmap
  //          (x1,y1) = position in the XImage
  //          (w0,h0) = size of XImage transfer
  x0 = xoutRound(x + t3Font->glyphX);
  y0 = xoutRound(y + t3Font->glyphY);
  x1 = 0;
  y1 = 0;
  w0 = t3Font->glyphW;
  h0 = t3Font->glyphH;
  if (x0 < 0) {
    x1 = -x0;
    w0 += x0;
    x0 = 0;
  }
  if (x0 + w0 > pixmapW) {
    w0 = pixmapW - x0;
  }
  if (w0 <= 0) {
    return;
  }
  if (y0 < 0) {
    y1 = -y0;
    h0 += y0;
    y0 = 0;
  }
  if (y0 + h0 > pixmapH) {
    h0 = pixmapH - y0;
  }
  if (h0 <= 0) {
    return;
  }

  image = t3Font->image;
  XGetSubImage(display, pixmap, x0, y0, w0, h0,
	       (1 << depth) - 1, ZPixmap, image, x1, y1);
  xcolor.pixel = XGetPixel(image, t3Font->glyphW / 2, t3Font->glyphH / 2);
  XQueryColor(display, colormap, &xcolor);
  bg.r = xcolor.red / 65535.0;
  bg.g = xcolor.green / 65535.0;
  bg.b = xcolor.blue / 65535.0;
  rgb.r = 0.25 * (color->r + 3 * bg.r);
  rgb.g = 0.25 * (color->g + 3 * bg.g);
  rgb.b = 0.25 * (color->b + 3 * bg.b);
  map[1] = findColor(&rgb);
  rgb.r = 0.5 * (color->r + bg.r);
  rgb.g = 0.5 * (color->g + bg.g);
  rgb.b = 0.5 * (color->b + bg.b);
  map[2] = findColor(&rgb);
  rgb.r = 0.25 * (3 * color->r + bg.r);
  rgb.g = 0.25 * (3 * color->g + bg.g);
  rgb.b = 0.25 * (3 * color->b + bg.b);
  map[3] = findColor(&rgb);
  map[4] = findColor(color);
  p = data;
  for (iy = 0; iy < t3Font->glyphH; ++iy) {
    for (ix = 0; ix < t3Font->glyphW; ++ix) {
      pixel = *p++;
      if (pixel > 0) {
	XPutPixel(image, ix, iy, map[pixel]);
      }
    }
  }
  XPutImage(display, pixmap, fillGC, image, x1, y1, x0, y0, w0, h0);
}

void XOutputDev::type3D0(GfxState *state, double wx, double wy) {
  t3GlyphStack->wx = wx;
  t3GlyphStack->wy = wy;
}

void XOutputDev::type3D1(GfxState *state, double wx, double wy,
			 double llx, double lly, double urx, double ury) {
  GfxColor fgColor;
  XGCValues gcValues;
  XRectangle rect;
  double *ctm;
  T3FontCache *t3Font;
  double xt, yt, xMin, xMax, yMin, yMax, x1, y1;
  int i, j;

  t3Font = t3GlyphStack->cache;
  t3GlyphStack->wx = wx;
  t3GlyphStack->wy = wy;

  // check for a valid bbox
  state->transform(0, 0, &xt, &yt);
  state->transform(llx, lly, &x1, &y1);
  xMin = xMax = x1;
  yMin = yMax = y1;
  state->transform(llx, ury, &x1, &y1);
  if (x1 < xMin) {
    xMin = x1;
  } else if (x1 > xMax) {
    xMax = x1;
  }
  if (y1 < yMin) {
    yMin = y1;
  } else if (y1 > yMax) {
    yMax = y1;
  }
  state->transform(urx, lly, &x1, &y1);
  if (x1 < xMin) {
    xMin = x1;
  } else if (x1 > xMax) {
    xMax = x1;
  }
  if (y1 < yMin) {
    yMin = y1;
  } else if (y1 > yMax) {
    yMax = y1;
  }
  state->transform(urx, ury, &x1, &y1);
  if (x1 < xMin) {
    xMin = x1;
  } else if (x1 > xMax) {
    xMax = x1;
  }
  if (y1 < yMin) {
    yMin = y1;
  } else if (y1 > yMax) {
    yMax = y1;
  }
  if (xMin - xt < t3Font->glyphX ||
      yMin - yt < t3Font->glyphY ||
      xMax - xt > t3Font->glyphX + t3Font->glyphW ||
      yMax - yt > t3Font->glyphY + t3Font->glyphH) {
    error(-1, "Bad bounding box in Type 3 glyph");
    return;
  }

  // allocate a cache entry
  t3GlyphStack->cacheable = gTrue;
  i = t3GlyphStack->cacheIdx;
  for (j = 0; j < t3Font->cacheAssoc; ++j) {
    if ((t3Font->cacheTags[i+j].mru & 0x7fff) == t3Font->cacheAssoc - 1) {
      t3Font->cacheTags[i+j].mru = 0x8000;
      t3Font->cacheTags[i+j].code = t3GlyphStack->code;
      t3GlyphStack->cacheTag = &t3Font->cacheTags[i+j];
      t3GlyphStack->cacheData = t3Font->cacheData + (i+j) * t3Font->glyphSize;
    } else {
      ++t3Font->cacheTags[i+j].mru;
    }
  }
  t3GlyphStack->cacheTag->wx = wx;
  t3GlyphStack->cacheTag->wy = wy;

  // prepare to rasterize the glyph
  //~ do we need to handle both fill and stroke color?
  state->getFillRGB(&t3GlyphStack->color);
  if (reverseVideo) {
    t3GlyphStack->color.r = 1 - t3GlyphStack->color.r;
    t3GlyphStack->color.g = 1 - t3GlyphStack->color.g;
    t3GlyphStack->color.b = 1 - t3GlyphStack->color.b;
  }
  fgColor.c[0] = reverseVideo ? 1 : 0;
  state->setFillColorSpace(new GfxDeviceGrayColorSpace());
  state->setFillColor(&fgColor);
  state->setStrokeColorSpace(new GfxDeviceGrayColorSpace());
  state->setStrokeColor(&fgColor);
  t3GlyphStack->origPixmapW = pixmapW;
  t3GlyphStack->origPixmapH = pixmapH;
  t3GlyphStack->origPixmap = pixmap;
  t3GlyphStack->origStrokeGC = strokeGC;
  t3GlyphStack->origFillGC = fillGC;
  t3GlyphStack->origClipRegion = clipRegion;
  pixmapW = t3GlyphStack->cache->glyphW;
  pixmapH = t3GlyphStack->cache->glyphH;
  pixmap = t3GlyphStack->cache->pixmap;
  gcValues.foreground = BlackPixel(display, screenNum);
  gcValues.background = WhitePixel(display, screenNum);
  gcValues.line_width = 0;
  gcValues.line_style = LineSolid;
  strokeGC = XCreateGC(display, pixmap,
		       GCForeground | GCBackground | GCLineWidth | GCLineStyle,
		       &gcValues);
  updateLineAttrs(state, gTrue);
  gcValues.foreground = WhitePixel(display, screenNum);
  fillGC = XCreateGC(display, pixmap,
		     GCForeground | GCBackground | GCLineWidth | GCLineStyle,
		     &gcValues);
  XFillRectangle(display, pixmap, fillGC, 0, 0, pixmapW, pixmapH);
  XSetForeground(display, fillGC, BlackPixel(display, screenNum));
  clipRegion = XCreateRegion();
  rect.x = rect.y = 0;
  rect.width = pixmapW;
  rect.height = pixmapH;
  XUnionRectWithRegion(&rect, clipRegion, clipRegion);
  XSetRegion(display, strokeGC, clipRegion);
  XSetRegion(display, fillGC, clipRegion);
  ctm = state->getCTM();
  t3GlyphStack->origCTM4 = ctm[4];
  t3GlyphStack->origCTM5 = ctm[5];
  state->setCTM(ctm[0], ctm[1], ctm[2], ctm[3], 
		-t3GlyphStack->cache->glyphX, -t3GlyphStack->cache->glyphY);
}

void XOutputDev::endTextObject(GfxState *state) {
  double *ctm;
  double saveCTM[6];

  if (textClipPath) {
    ctm = state->getCTM();
    memcpy(saveCTM, ctm, 6 * sizeof(double));
    state->setCTM(1, 0, 0, 1, 0, 0);
    doClip(state, textClipPath, WindingRule);
    state->setCTM(saveCTM[0], saveCTM[1], saveCTM[2], saveCTM[3],
		  saveCTM[4], saveCTM[5]);
    delete textClipPath;
    textClipPath = NULL;
  }
}

inline Gulong XOutputDev::findColor(GfxRGB *x, GfxRGB *actual) {
  double gray;
  int r, g, b;
  Gulong pixel;

  if (trueColor) {
    r = xoutRound(x->r * rMul);
    g = xoutRound(x->g * gMul);
    b = xoutRound(x->b * bMul);
    pixel = ((Gulong)r << rShift) +
            ((Gulong)g << gShift) +
            ((Gulong)b << bShift);
    actual->r = (double)r / rMul;
    actual->g = (double)g / gMul;
    actual->b = (double)b / bMul;
  } else if (numColors == 1) {
    gray = 0.299 * x->r + 0.587 * x->g + 0.114 * x->b;
    if (gray < 0.5) {
      pixel = colors[0];
      actual->r = actual->g = actual->b = 0;
    } else {
      pixel = colors[1];
      actual->r = actual->g = actual->b = 1;
    }
  } else {
    r = xoutRound(x->r * (numColors - 1));
    g = xoutRound(x->g * (numColors - 1));
    b = xoutRound(x->b * (numColors - 1));
    pixel = colors[(r * numColors + g) * numColors + b];
    actual->r = (double)r / (numColors - 1);
    actual->g = (double)g / (numColors - 1); 
    actual->b = (double)b / (numColors - 1);
  }
  return pixel;
}

Gulong XOutputDev::findColor(GfxRGB *rgb) {
  int r, g, b;
  double gray;
  Gulong pixel;

  if (trueColor) {
    r = xoutRound(rgb->r * rMul);
    g = xoutRound(rgb->g * gMul);
    b = xoutRound(rgb->b * bMul);
    pixel = ((Gulong)r << rShift) +
            ((Gulong)g << gShift) +
            ((Gulong)b << bShift);
  } else if (numColors == 1) {
    gray = 0.299 * rgb->r + 0.587 * rgb->g + 0.114 * rgb->b;
    if (gray < 0.5)
      pixel = colors[0];
    else
      pixel = colors[1];
  } else {
    r = xoutRound(rgb->r * (numColors - 1));
    g = xoutRound(rgb->g * (numColors - 1));
    b = xoutRound(rgb->b * (numColors - 1));
#if 0 // this makes things worse as often as better
    // even a very light color shouldn't map to white
    if (r == numColors - 1 && g == numColors - 1 && b == numColors - 1) {
      if (color->getR() < 0.95)
	--r;
      if (color->getG() < 0.95)
	--g;
      if (color->getB() < 0.95)
	--b;
    }
#endif
    pixel = colors[(r * numColors + g) * numColors + b];
  }
  return pixel;
}

void XOutputDev::drawImageMask(GfxState *state, Object *ref, Stream *str,
			       int width, int height, GBool invert,
			       GBool inlineImg) {
  ImageStream *imgStr;
  XImage *image;
  double *ctm;
  GBool rot;
  double xScale, yScale, xShear, yShear;
  int tx, ty, scaledWidth, scaledHeight, xSign, ySign;
  int ulx, uly, llx, lly, urx, ury, lrx, lry;
  int ulx1, uly1, llx1, lly1, urx1, ury1, lrx1, lry1;
  int bx0, by0, bx1, by1, bw, bh;
  int cx0, cy0, cx1, cy1, cw, ch;
  int yp, yq, yt, yStep, lastYStep;
  int xp, xq, xt, xStep, xSrc;
  GfxRGB rgb;
  Guchar *pixBuf;
  int imgPix;
  double alpha;
  XColor xcolor;
  Gulong lastPixel;
  GfxRGB rgb2;
  double r0, g0, b0, r1, g1, b1;
  Gulong pix;
  Guchar *p;
  int x, y, x1, y1, x2, y2;
  int n, m, i, j;

  // get CTM, check for singular matrix
  ctm = state->getCTM();
  if (fabs(ctm[0] * ctm[3] - ctm[1] * ctm[2]) < 0.000001) {
    error(-1, "Singular CTM in drawImage");
    if (inlineImg) {
      j = height * ((width + 7) / 8);
      str->reset();
      for (i = 0; i < j; ++i) {
	str->getChar();
      }
      str->close();
    }
    return;
  }

  // compute scale, shear, rotation, translation parameters
  rot = fabs(ctm[1]) > fabs(ctm[0]);
  if (rot) {
    xScale = -ctm[1];
    yScale = -ctm[2] + (ctm[0] * ctm[3]) / ctm[1];
    xShear = ctm[3] / yScale;
    yShear = -ctm[0] / ctm[1];
  } else {
    xScale = ctm[0];
    yScale = -ctm[3] + (ctm[1] * ctm[2]) / ctm[0];
    xShear = -ctm[2] / yScale;
    yShear = ctm[1] / ctm[0];
  }
  tx = xoutRound(ctm[2] + ctm[4]);
  ty = xoutRound(ctm[3] + ctm[5]);
  // use ceil() to avoid gaps between "striped" images
  scaledWidth = (int)ceil(fabs(xScale));
  xSign = (xScale < 0) ? -1 : 1;
  scaledHeight = (int)ceil(fabs(yScale));
  ySign = (yScale < 0) ? -1 : 1;

  // compute corners in device space
  ulx1 = 0;
  uly1 = 0;
  urx1 = xSign * (scaledWidth - 1);
  ury1 = xoutRound(yShear * urx1);
  llx1 = xoutRound(xShear * ySign * (scaledHeight - 1));
  lly1 = ySign * (scaledHeight - 1) + xoutRound(yShear * llx1);
  lrx1 = xSign * (scaledWidth - 1) +
           xoutRound(xShear * ySign * (scaledHeight - 1));
  lry1 = ySign * (scaledHeight - 1) + xoutRound(yShear * lrx1);
  if (rot) {
    ulx = tx + uly1;    uly = ty - ulx1;
    urx = tx + ury1;    ury = ty - urx1;
    llx = tx + lly1;    lly = ty - llx1;
    lrx = tx + lry1;    lry = ty - lrx1;
  } else {
    ulx = tx + ulx1;    uly = ty + uly1;
    urx = tx + urx1;    ury = ty + ury1;
    llx = tx + llx1;    lly = ty + lly1;
    lrx = tx + lrx1;    lry = ty + lry1;
  }

  // bounding box:
  //   (bx0, by0) = upper-left corner
  //   (bx1, by1) = lower-right corner
  //   (bw, bh) = size
  bx0 = (ulx < urx) ? (ulx < llx) ? (ulx < lrx) ? ulx : lrx
                                  : (llx < lrx) ? llx : lrx
		    : (urx < llx) ? (urx < lrx) ? urx : lrx
                                  : (llx < lrx) ? llx : lrx;
  bx1 = (ulx > urx) ? (ulx > llx) ? (ulx > lrx) ? ulx : lrx
                                  : (llx > lrx) ? llx : lrx
		    : (urx > llx) ? (urx > lrx) ? urx : lrx
                                  : (llx > lrx) ? llx : lrx;
  by0 = (uly < ury) ? (uly < lly) ? (uly < lry) ? uly : lry
                                  : (lly < lry) ? lly : lry
		    : (ury < lly) ? (ury < lry) ? ury : lry
                                  : (lly < lry) ? lly : lry;
  by1 = (uly > ury) ? (uly > lly) ? (uly > lry) ? uly : lry
                                  : (lly > lry) ? lly : lry
		    : (ury > lly) ? (ury > lry) ? ury : lry
                                  : (lly > lry) ? lly : lry;
  bw = bx1 - bx0 + 1;
  bh = by1 - by0 + 1;

  // Bounding box clipped to pixmap, i.e., "valid" rectangle:
  //   (cx0, cy0) = upper-left corner of valid rectangle in Pixmap
  //   (cx1, cy1) = upper-left corner of valid rectangle in XImage
  //   (cw, ch) = size of valid rectangle
  // These values will be used to transfer the XImage from/to the
  // Pixmap.
  cw = (bx1 >= pixmapW) ? pixmapW - bx0 : bw;
  if (bx0 < 0) {
    cx0 = 0;
    cx1 = -bx0;
    cw += bx0;
  } else {
    cx0 = bx0;
    cx1 = 0;
  }
  ch = (by1 >= pixmapH) ? pixmapH - by0 : bh;
  if (by0 < 0) {
    cy0 = 0;
    cy1 = -by0;
    ch += by0;
  } else {
    cy0 = by0;
    cy1 = 0;
  }

  // check for tiny (zero width or height) images
  // and off-page images
  if (scaledWidth <= 0 || scaledHeight <= 0 || cw <= 0 || ch <= 0) {
    if (inlineImg) {
      j = height * ((width + 7) / 8);
      str->reset();
      for (i = 0; i < j; ++i) {
	str->getChar();
      }
      str->close();
    }
    return;
  }

  // compute Bresenham parameters for x and y scaling
  yp = height / scaledHeight;
  yq = height % scaledHeight;
  xp = width / scaledWidth;
  xq = width % scaledWidth;

  // allocate pixel buffer
  pixBuf = (Guchar *)gmalloc((yp + 1) * width * sizeof(Guchar));

  // allocate XImage and read from page pixmap
  image = XCreateImage(display, visual, depth, ZPixmap, 0, NULL, bw, bh, 8, 0);
  image->data = (char *)gmalloc(bh * image->bytes_per_line);
  XGetSubImage(display, pixmap, cx0, cy0, cw, ch, (1 << depth) - 1, ZPixmap,
	       image, cx1, cy1);

  // get mask color
  state->getFillRGB(&rgb);
  if (reverseVideo) {
    rgb.r = 1 - rgb.r;
    rgb.g = 1 - rgb.g;
    rgb.b = 1 - rgb.b;
  }
  r0 = rgb.r;
  g0 = rgb.g;
  b0 = rgb.b;

  // initialize background color
  // (the specific pixel value doesn't matter here, as long as
  // r1,g1,b1 correspond correctly to lastPixel)
  xcolor.pixel = lastPixel = 0;
  XQueryColor(display, colormap, &xcolor);
  r1 = (double)xcolor.red / 65535.0;
  g1 = (double)xcolor.green / 65535.0;
  b1 = (double)xcolor.blue / 65535.0;

  // initialize the image stream
  imgStr = new ImageStream(str, width, 1, 1);
  imgStr->reset();

  // init y scale Bresenham
  yt = 0;
  lastYStep = 1;

  for (y = 0; y < scaledHeight; ++y) {

    // y scale Bresenham
    yStep = yp;
    yt += yq;
    if (yt >= scaledHeight) {
      yt -= scaledHeight;
      ++yStep;
    }

    // read row(s) from image
    n = (yp > 0) ? yStep : lastYStep;
    if (n > 0) {
      p = pixBuf;
      for (i = 0; i < n; ++i) {
	memcpy(p, imgStr->getLine(), width);
	if (invert) {
	  for (j = 0; j < width; ++j) {
	    p[j] ^= 1;
	  }
	}
	p += width;
      }
    }
    lastYStep = yStep;

    // init x scale Bresenham
    xt = 0;
    xSrc = 0;

    for (x = 0; x < scaledWidth; ++x) {

      // x scale Bresenham
      xStep = xp;
      xt += xq;
      if (xt >= scaledWidth) {
	xt -= scaledWidth;
	++xStep;
      }

      // x shear
      x1 = xSign * x + xoutRound(xShear * ySign * y);

      // y shear
      y1 = ySign * y + xoutRound(yShear * x1);

      // rotation
      if (rot) {
	x2 = y1;
	y2 = -x1;
      } else {
	x2 = x1;
	y2 = y1;
      }

      // compute the filtered pixel at (x,y) after the
      // x and y scaling operations
      n = yStep > 0 ? yStep : 1;
      m = xStep > 0 ? xStep : 1;
      p = pixBuf + xSrc;
      imgPix = 0;
      for (i = 0; i < n; ++i) {
	for (j = 0; j < m; ++j) {
	  imgPix += *p++;
	}
	p += width - m;
      }

      // x scale Bresenham
      xSrc += xStep;

      // blend image pixel with background
      alpha = (double)imgPix / (double)(n * m);
      xcolor.pixel = XGetPixel(image, tx + x2 - bx0, ty + y2 - by0);
      if (xcolor.pixel != lastPixel) {
	XQueryColor(display, colormap, &xcolor);
	r1 = (double)xcolor.red / 65535.0;
	g1 = (double)xcolor.green / 65535.0;
	b1 = (double)xcolor.blue / 65535.0;
	lastPixel = xcolor.pixel;
      }
      rgb2.r = r0 * (1 - alpha) + r1 * alpha;
      rgb2.g = g0 * (1 - alpha) + g1 * alpha;
      rgb2.b = b0 * (1 - alpha) + b1 * alpha;
      pix = findColor(&rgb2);

      // set pixel
      XPutPixel(image, tx + x2 - bx0, ty + y2 - by0, pix);
    }
  }

  // blit the image into the pixmap
  XPutImage(display, pixmap, fillGC, image, cx1, cy1, cx0, cy0, cw, ch);

  // free memory
  delete imgStr;
  gfree(pixBuf);
  gfree(image->data);
  image->data = NULL;
  XDestroyImage(image);
}

void XOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
			   int width, int height, GfxImageColorMap *colorMap,
			   int *maskColors, GBool inlineImg) {
  ImageStream *imgStr;
  XImage *image;
  int nComps, nVals, nBits;
  GBool dither;
  double *ctm;
  GBool rot;
  double xScale, yScale, xShear, yShear;
  int tx, ty, scaledWidth, scaledHeight, xSign, ySign;
  int ulx, uly, llx, lly, urx, ury, lrx, lry;
  int ulx1, uly1, llx1, lly1, urx1, ury1, lrx1, lry1;
  int bx0, by0, bx1, by1, bw, bh;
  int cx0, cy0, cx1, cy1, cw, ch;
  int yp, yq, yt, yStep, lastYStep;
  int xp, xq, xt, xStep, xSrc;
  GfxRGB *pixBuf;
  Guchar *pixBuf1, *alphaBuf;
  Guchar pixBuf2[gfxColorMaxComps];
  GfxRGB color2, color3, actual, err, errRight;
  GfxRGB *errDown0, *errDown1, *errDownTmp;
  double r0, g0, b0, alpha, mul;
  Gulong pix;
  GfxRGB *p;
  Guchar *q, *p1, *p2;
  GBool oneBitMode;
  GfxRGB oneBitRGB[2];
  int x, y, x1, y1, x2, y2;
  int n, m, i, j, k;

  // image parameters
  nComps = colorMap->getNumPixelComps();
  nVals = width * nComps;
  nBits = colorMap->getBits();
  oneBitMode = nComps == 1 && nBits == 1 && !maskColors;
  dither = nComps > 1 || nBits > 1;

  // get CTM, check for singular matrix
  ctm = state->getCTM();
  if (fabs(ctm[0] * ctm[3] - ctm[1] * ctm[2]) < 0.000001) {
    error(-1, "Singular CTM in drawImage");
    if (inlineImg) {
      str->reset();
      j = height * ((nVals * nBits + 7) / 8);
      for (i = 0; i < j; ++i) {
	str->getChar();
      }
      str->close();
    }
    return;
  }

  // compute scale, shear, rotation, translation parameters
  rot = fabs(ctm[1]) > fabs(ctm[0]);
  if (rot) {
    xScale = -ctm[1];
    yScale = -ctm[2] + (ctm[0] * ctm[3]) / ctm[1];
    xShear = ctm[3] / yScale;
    yShear = -ctm[0] / ctm[1];
  } else {
    xScale = ctm[0];
    yScale = -ctm[3] + (ctm[1] * ctm[2]) / ctm[0];
    xShear = -ctm[2] / yScale;
    yShear = ctm[1] / ctm[0];
  }
  tx = xoutRound(ctm[2] + ctm[4]);
  ty = xoutRound(ctm[3] + ctm[5]);
  if (xScale < 0) {
    // this is the right edge which needs to be (left + width - 1)
    --tx;
  }
  if (yScale < 0) {
    // this is the bottom edge which needs to be (top + height - 1)
    --ty;
  }
  // use ceil() to avoid gaps between "striped" images
  scaledWidth = (int)ceil(fabs(xScale));
  xSign = (xScale < 0) ? -1 : 1;
  scaledHeight = (int)ceil(fabs(yScale));
  ySign = (yScale < 0) ? -1 : 1;

  // compute corners in device space
  ulx1 = 0;
  uly1 = 0;
  urx1 = xSign * (scaledWidth - 1);
  ury1 = xoutRound(yShear * urx1);
  llx1 = xoutRound(xShear * ySign * (scaledHeight - 1));
  lly1 = ySign * (scaledHeight - 1) + xoutRound(yShear * llx1);
  lrx1 = xSign * (scaledWidth - 1) +
           xoutRound(xShear * ySign * (scaledHeight - 1));
  lry1 = ySign * (scaledHeight - 1) + xoutRound(yShear * lrx1);
  if (rot) {
    ulx = tx + uly1;    uly = ty - ulx1;
    urx = tx + ury1;    ury = ty - urx1;
    llx = tx + lly1;    lly = ty - llx1;
    lrx = tx + lry1;    lry = ty - lrx1;
  } else {
    ulx = tx + ulx1;    uly = ty + uly1;
    urx = tx + urx1;    ury = ty + ury1;
    llx = tx + llx1;    lly = ty + lly1;
    lrx = tx + lrx1;    lry = ty + lry1;
  }

  // bounding box:
  //   (bx0, by0) = upper-left corner
  //   (bx1, by1) = lower-right corner
  //   (bw, bh) = size
  bx0 = (ulx < urx) ? (ulx < llx) ? (ulx < lrx) ? ulx : lrx
                                  : (llx < lrx) ? llx : lrx
		    : (urx < llx) ? (urx < lrx) ? urx : lrx
                                  : (llx < lrx) ? llx : lrx;
  bx1 = (ulx > urx) ? (ulx > llx) ? (ulx > lrx) ? ulx : lrx
                                  : (llx > lrx) ? llx : lrx
		    : (urx > llx) ? (urx > lrx) ? urx : lrx
                                  : (llx > lrx) ? llx : lrx;
  by0 = (uly < ury) ? (uly < lly) ? (uly < lry) ? uly : lry
                                  : (lly < lry) ? lly : lry
		    : (ury < lly) ? (ury < lry) ? ury : lry
                                  : (lly < lry) ? lly : lry;
  by1 = (uly > ury) ? (uly > lly) ? (uly > lry) ? uly : lry
                                  : (lly > lry) ? lly : lry
		    : (ury > lly) ? (ury > lry) ? ury : lry
                                  : (lly > lry) ? lly : lry;
  bw = bx1 - bx0 + 1;
  bh = by1 - by0 + 1;

  // Bounding box clipped to pixmap, i.e., "valid" rectangle:
  //   (cx0, cy0) = upper-left corner of valid rectangle in Pixmap
  //   (cx1, cy1) = upper-left corner of valid rectangle in XImage
  //   (cw, ch) = size of valid rectangle
  // These values will be used to transfer the XImage from/to the
  // Pixmap.
  cw = (bx1 >= pixmapW) ? pixmapW - bx0 : bw;
  if (bx0 < 0) {
    cx0 = 0;
    cx1 = -bx0;
    cw += bx0;
  } else {
    cx0 = bx0;
    cx1 = 0;
  }
  ch = (by1 >= pixmapH) ? pixmapH - by0 : bh;
  if (by0 < 0) {
    cy0 = 0;
    cy1 = -by0;
    ch += by0;
  } else {
    cy0 = by0;
    cy1 = 0;
  }

  // check for tiny (zero width or height) images
  // and off-page images
  if (scaledWidth <= 0 || scaledHeight <= 0 || cw <= 0 || ch <= 0) {
    if (inlineImg) {
      str->reset();
      j = height * ((nVals * nBits + 7) / 8);
      for (i = 0; i < j; ++i)
	str->getChar();
      str->close();
    }
    return;
  }

  // compute Bresenham parameters for x and y scaling
  yp = height / scaledHeight;
  yq = height % scaledHeight;
  xp = width / scaledWidth;
  xq = width % scaledWidth;

  // allocate pixel buffer
  if (oneBitMode) {
    pixBuf1 = (Guchar *)gmalloc((yp + 1) * width * sizeof(Guchar));
    pixBuf = NULL;
  } else {
    pixBuf = (GfxRGB *)gmalloc((yp + 1) * width * sizeof(GfxRGB));
    pixBuf1 = NULL;
  }
  if (maskColors) {
    alphaBuf = (Guchar *)gmalloc((yp + 1) * width * sizeof(Guchar));
  } else {
    alphaBuf = NULL;
  }

  // allocate XImage
  image = XCreateImage(display, visual, depth, ZPixmap, 0, NULL, bw, bh, 8, 0);
  image->data = (char *)gmalloc(bh * image->bytes_per_line);

  // if the transform is anything other than a 0/90/180/270 degree
  // rotation/flip, or if there is color key masking, read the
  // backgound pixmap to fill in the corners
  if (!((ulx == llx && uly == ury) ||
	(uly == lly && ulx == urx)) ||
      maskColors) {
    XGetSubImage(display, pixmap, cx0, cy0, cw, ch, (1 << depth) - 1, ZPixmap,
		 image, cx1, cy1);
  }

  // allocate error diffusion accumulators
  if (dither) {
    errDown0 = (GfxRGB *)gmalloc((scaledWidth + 2) * sizeof(GfxRGB));
    errDown1 = (GfxRGB *)gmalloc((scaledWidth + 2) * sizeof(GfxRGB));
    for (j = 0; j < scaledWidth + 2; ++j) {
      errDown0[j].r = errDown0[j].g = errDown0[j].b = 0;
      errDown1[j].r = errDown1[j].g = errDown1[j].b = 0;
    }
  } else {
    errDown0 = errDown1 = NULL;
  }

  // optimize the one-bit-deep image case
  if (oneBitMode) {
    pixBuf2[0] = 0;
    colorMap->getRGB(pixBuf2, &oneBitRGB[0]);
    pixBuf2[0] = 1;
    colorMap->getRGB(pixBuf2, &oneBitRGB[1]);
  }

  // initialize the image stream
  imgStr = new ImageStream(str, width, nComps, nBits);
  imgStr->reset();

  // init y scale Bresenham
  yt = 0;
  lastYStep = 1;

  for (y = 0; y < scaledHeight; ++y) {

    // initialize error diffusion accumulators
    if (dither) {
      errDownTmp = errDown0;
      errDown0 = errDown1;
      errDown1 = errDownTmp;
      for (j = 0; j < scaledWidth + 2; ++j) {
	errDown1[j].r = errDown1[j].g = errDown1[j].b = 0;
      }
      errRight.r = errRight.g = errRight.b = 0;
    }

    // y scale Bresenham
    yStep = yp;
    yt += yq;
    if (yt >= scaledHeight) {
      yt -= scaledHeight;
      ++yStep;
    }

    // read row(s) from image
    n = (yp > 0) ? yStep : lastYStep;
    if (n > 0) {
      if (oneBitMode) {
	p1 = pixBuf1;
	for (i = 0; i < n; ++i) {
	  p2 = imgStr->getLine();
	  memcpy(p1, p2, width);
	  p1 += width;
	}
      } else {
	p = pixBuf;
	q = alphaBuf;
	for (i = 0; i < n; ++i) {
	  p2 = imgStr->getLine();
	  for (j = 0; j < width; ++j) {
            colorMap->getRGB(p2, p);
	    ++p;
	    if (q) {
	      *q = 1;
	      for (k = 0; k < nComps; ++k) {
		if (p2[k] < maskColors[2*k] ||
		    p2[k] > maskColors[2*k+1]) {
		  *q = 0;
		  break;
		}
	      }
	      ++q;
	    }
	    p2 += nComps;
	  }
	}
      }
    }
    lastYStep = yStep;

    // init x scale Bresenham
    xt = 0;
    xSrc = 0;

    for (x = 0; x < scaledWidth; ++x) {

      // x scale Bresenham
      xStep = xp;
      xt += xq;
      if (xt >= scaledWidth) {
	xt -= scaledWidth;
	++xStep;
      }

      // x shear
      x1 = xSign * x + xoutRound(xShear * ySign * y);

      // y shear
      y1 = ySign * y + xoutRound(yShear * x1);

      // rotation
      if (rot) {
	x2 = y1;
	y2 = -x1;
      } else {
	x2 = x1;
	y2 = y1;
      }

      // compute the filtered pixel at (x,y) after the
      // x and y scaling operations
      n = yStep > 0 ? yStep : 1;
      m = xStep > 0 ? xStep : 1;
      if (oneBitMode) {
	p1 = pixBuf1 + xSrc;
	k = 0;
	for (i = 0; i < n; ++i) {
	  for (j = 0; j < m; ++j) {
	    k += *p1++;
	  }
	  p1 += width - m;
	}
	mul = (double)k / (double)(n * m);
	r0 = mul * oneBitRGB[1].r + (1 - mul) * oneBitRGB[0].r;
	g0 = mul * oneBitRGB[1].g + (1 - mul) * oneBitRGB[0].g;
	b0 = mul * oneBitRGB[1].b + (1 - mul) * oneBitRGB[0].b;
	alpha = 0;
      } else {
	p = pixBuf + xSrc;
	q = alphaBuf ? alphaBuf + xSrc : (Guchar *)NULL;
	alpha = 0;
	r0 = g0 = b0 = 0;
	for (i = 0; i < n; ++i) {
	  for (j = 0; j < m; ++j) {
	    r0 += p->r;
	    g0 += p->g;
	    b0 += p->b;
	    ++p;
	    if (q) {
	      alpha += *q++;
	    }
	  }
	  p += width - m;
	}
	mul = 1 / (double)(n * m);
	r0 *= mul;
	g0 *= mul;
	b0 *= mul;
	alpha *= mul;
      }

      // x scale Bresenham
      xSrc += xStep;

      // compute pixel
      if (dither) {
	color2.r = r0 + errRight.r + errDown0[x + 1].r;
	if (color2.r > 1) {
	  color3.r = 1;
	} else if (color2.r < 0) {
	  color3.r = 0;
	} else {
	  color3.r = color2.r;
	}
	color2.g = g0 + errRight.g + errDown0[x + 1].g;
	if (color2.g > 1) {
	  color3.g = 1;
	} else if (color2.g < 0) {
	  color3.g = 0;
	} else {
	  color3.g = color2.g;
	}
	color2.b = b0 + errRight.b + errDown0[x + 1].b;
	if (color2.b > 1) {
	  color3.b = 1;
	} else if (color2.b < 0) {
	  color3.b = 0;
	} else {
	  color3.b = color2.b;
	}
	pix = findColor(&color3, &actual);
	err.r = (color2.r - actual.r) / 16;
	err.g = (color2.g - actual.g) / 16;
	err.b = (color2.b - actual.b) / 16;
	errRight.r = 7 * err.r;
	errRight.g = 7 * err.g;
	errRight.b = 7 * err.b;
	errDown1[x].r += 3 * err.r;
	errDown1[x].g += 3 * err.g;
	errDown1[x].b += 3 * err.b;
	errDown1[x + 1].r += 5 * err.r;
	errDown1[x + 1].g += 5 * err.g;
	errDown1[x + 1].b += 5 * err.b;
	errDown1[x + 2].r = err.r;
	errDown1[x + 2].g = err.g;
	errDown1[x + 2].b = err.b;
      } else {
	color2.r = r0;
	color2.g = g0;
	color2.b = b0;
	pix = findColor(&color2, &actual);
      }

      // set pixel
      //~ this should do a blend when 0 < alpha < 1
      if (alpha < 0.75) {
	XPutPixel(image, tx + x2 - bx0, ty + y2 - by0, pix);
      }
    }
  }

  // blit the image into the pixmap
  XPutImage(display, pixmap, fillGC, image, cx1, cy1, cx0, cy0, cw, ch);

  // free memory
  delete imgStr;
  if (oneBitMode) {
    gfree(pixBuf1);
  } else {
    gfree(pixBuf);
  }
  if (maskColors) {
    gfree(alphaBuf);
  }
  gfree(image->data);
  image->data = NULL;
  XDestroyImage(image);
  gfree(errDown0);
  gfree(errDown1);
}

GBool XOutputDev::findText(Unicode *s, int len,
			   GBool startAtTop, GBool stopAtBottom,
			   GBool startAtLast, GBool stopAtLast,
			   int *xMin, int *yMin,
			   int *xMax, int *yMax) {
  double xMin1, yMin1, xMax1, yMax1;
  
  xMin1 = (double)*xMin;
  yMin1 = (double)*yMin;
  xMax1 = (double)*xMax;
  yMax1 = (double)*yMax;
  if (text->findText(s, len, startAtTop, stopAtBottom,
		     startAtLast, stopAtLast,
		     &xMin1, &yMin1, &xMax1, &yMax1)) {
    *xMin = xoutRound(xMin1);
    *xMax = xoutRound(xMax1);
    *yMin = xoutRound(yMin1);
    *yMax = xoutRound(yMax1);
    return gTrue;
  }
  return gFalse;
}

GString *XOutputDev::getText(int xMin, int yMin, int xMax, int yMax) {
  return text->getText((double)xMin, (double)yMin,
		       (double)xMax, (double)yMax);
}