File: xwin.c

package info (click to toggle)
emboss 6.6.0%2Bdfsg-7
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 571,544 kB
  • sloc: ansic: 460,579; java: 29,439; perl: 13,573; sh: 12,754; makefile: 3,283; csh: 706; asm: 351; xml: 239; pascal: 237; modula3: 8
file content (3419 lines) | stat: -rw-r--r-- 93,360 bytes parent folder | download | duplicates (9)
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
/* $Id: xwin.c,v 1.8 2007/05/17 10:37:26 ajb Exp $

	PLplot X-windows device driver.

   Copyright (C) 2004  Maurice LeBrun
   Copyright (C) 2004  Joao Cardoso
   Copyright (C) 2004  Rafael Laboissiere
   Copyright (C) 2004  Andrew Ross

   This file is part of PLplot.

   PLplot is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Library Public License as published
   by the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   PLplot is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with PLplot; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

*/
#include "plDevs.h"

#define DEBUG

#ifdef PLD_xwin
#define NEED_PLDEBUG
#include "plplotP.h"
#include "plxwd.h"
#include "drivers.h"
#include "plevent.h"

#ifdef HAVE_PTHREAD
#include <pthread.h>
#include <signal.h>
int    pthread_mutexattr_settype(pthread_mutexattr_t *attr, int kind);
static void events_thread(void *pls);
static pthread_mutex_t events_mutex;
static int already = 0;
#endif

/* Device info */
const char* plD_DEVICE_INFO_xwin = "xwin:X-Window (Xlib):1:xwin:5:xw";

static int synchronize = 0;	/* change to 1 for X synchronized operation */
                                /* Use "-drvopt sync" cmd line option to set. */

static int nobuffered = 0;      /* make it a buffered device by default */
                                /* use "-drvopt unbuffered" to make it unbuffered */

static int noinitcolors = 0;    /* Call InitColors by default */
                                /* use "-drvopt noinitcolors" to leave colors uninitialized */

static int defaultvisual = 1;   /* use "-drvopt defvis=0" to not use the default visual */

static int usepthreads = 1;     /* use "-drvopt usepth=0" to not use pthreads to redisplay */

/*
 * When -drvopt defvis is defined, DefaultVisual() is used to get the visual.
 * Otherwise, the visual is obtained using XGetVisualInfo() to make a match.
 */

/*#define HACK_STATICCOLOR*/

/* Number of instructions to skip between querying the X server for events */

#define MAX_INSTR 20

/* The xwin driver uses the xscale and yscale values to convert from virtual
 * to real pixels using the current size in pixels of the display window.
 * We define PHYSICAL here so that PLplot core knows about this rescaling
 * and mm values are converted to virtual pixels at a ratio consistent with
 * a constant ratio of DPMM real pixels per mm. */
#define PHYSICAL	1

/* These need to be distinguished since the handling is slightly different. */

#define LOCATE_INVOKED_VIA_API		1
#define LOCATE_INVOKED_VIA_DRIVER	2

/* Set constants for dealing with colormap.  In brief:
 *
 *      --- custom colormaps ---
 * ccmap		When set, turns on custom color map
 * CCMAP_XWM_COLORS	Number of low "pixel" values to copy.
 *
 *      --- r/w colormaps --
 * RWMAP_CMAP1_COLORS	Color map 1 entries.
 * RWMAP_MAX_COLORS	Maximum colors in RW colormaps
 *
 *      --- r/o colormaps --
 * ROMAP_CMAP1_COLORS	Color map 1 entries.
 * TC_CMAP1_COLORS	TrueColor visual Color map 1 entries.
 *
 * See Init_CustomCmap() and  Init_DefaultCmap() for more info.
 * Set ccmap at your own risk -- still under development.
 */

/* plplot_ccmap is statically defined in plxwd.h.  Note that
 * plframe.c also includes that header and uses the variable. */

#define CCMAP_XWM_COLORS 70

#define RWMAP_CMAP1_COLORS 50
#define RWMAP_MAX_COLORS 256

#define ROMAP_CMAP1_COLORS 50
#define TC_CMAP1_COLORS 200

/* Variables to hold RGB components of given colormap. */
/* Used in an ugly hack to get past some X11R5 and TK limitations. */

static int  sxwm_colors_set;
static XColor sxwm_colors[RWMAP_MAX_COLORS];

/* Keep pointers to all the displays in use */

static XwDisplay *xwDisplay[PLXDISPLAYS];

/* Function prototypes */

/* Driver entry and dispatch setup */

/* pmr: in drivers.h */
/* void plD_dispatch_init_xw	( PLDispatchTable *pdt ); */

void plD_init_xw		(PLStream *);
void plD_line_xw		(PLStream *, short, short, short, short);
void plD_polyline_xw		(PLStream *, short *, short *, PLINT);
void plD_eop_xw			(PLStream *);
void plD_bop_xw			(PLStream *);
void plD_tidy_xw		(PLStream *);
void plD_state_xw		(PLStream *, PLINT);
void plD_esc_xw			(PLStream *, PLINT, void *);

/* Initialization */

static void  OpenXwin		(PLStream *pls);
static void  Init		(PLStream *pls);
static void  InitMain		(PLStream *pls);
static void  InitColors		(PLStream *pls);
static void  AllocCustomMap	(PLStream *pls);
static void  AllocCmap0		(PLStream *pls);
static void  AllocCmap1		(PLStream *pls);
static void  MapMain		(PLStream *pls);
static void  CreatePixmap	(PLStream *pls);
static void  GetVisual		(PLStream *pls);
static void  AllocBGFG		(PLStream *pls);
static int   AreWeGrayscale	(Display *display);

/* Routines to poll the X-server */

static void  WaitForPage	(PLStream *pls);
static void  CheckForEvents	(PLStream *pls);
static void  HandleEvents	(PLStream *pls);

/* Event handlers */

static void  MasterEH		(PLStream *pls, XEvent *event);
static void  ExposeEH		(PLStream *pls, XEvent *event);
static void  ResizeEH		(PLStream *pls, XEvent *event);
static void  MotionEH		(PLStream *pls, XEvent *event);
static void  EnterEH		(PLStream *pls, XEvent *event);
static void  LeaveEH		(PLStream *pls, XEvent *event);
static void  KeyEH		(PLStream *pls, XEvent *event);
static void  ButtonEH		(PLStream *pls, XEvent *event);
static void  LookupXKeyEvent	(PLStream *pls, XEvent *event);
static void  LookupXButtonEvent	(PLStream *pls, XEvent *event);

static void  ProcessKey		(PLStream *pls);
static void  LocateKey		(PLStream *pls);
static void  ProcessButton	(PLStream *pls);
static void  LocateButton	(PLStream *pls);
static void  Locate		(PLStream *pls);

/* Routines for manipulating graphic crosshairs */

static void  CreateXhairs	(PLStream *pls);
static void  DestroyXhairs	(PLStream *pls);
static void  DrawXhairs		(PLStream *pls, int x0, int y0);
static void  UpdateXhairs	(PLStream *pls);

/* Escape function commands */

static void  ExposeCmd		(PLStream *pls, PLDisplay *ptr);
static void  RedrawCmd		(PLStream *pls);
static void  ResizeCmd		(PLStream *pls, PLDisplay *ptr);
static void  ConfigBufferingCmd (PLStream *pls, PLBufferingCB *ptr );
static void  GetCursorCmd	(PLStream *pls, PLGraphicsIn *ptr);
static void  FillPolygonCmd	(PLStream *pls);
static void  XorMod		(PLStream *pls, PLINT *mod);
static void  DrawImage          (PLStream *pls);

/* Miscellaneous */

static void  StoreCmap0		(PLStream *pls);
static void  StoreCmap1		(PLStream *pls);
static void  imageops           (PLStream *pls, PLINT *ptr);
static void  SetBGFG		(PLStream *pls);
#ifdef DUMMY
static void  SaveColormap	(Display *display, Colormap colormap);
#endif
static void  PLColor_to_XColor	(PLColor *plcolor, XColor *xcolor);
static void  PLColor_from_XColor(PLColor *plcolor, XColor *xcolor);

static DrvOpt xwin_options[] = {{"sync", DRV_INT, 0, &synchronize, "Synchronized X server operation (0|1)"},
				{"nobuffered", DRV_INT, 0, &nobuffered, "Sets unbuffered operation (0|1)"},
				{"noinitcolors", DRV_INT, 0, &noinitcolors, "Sets cmap0 allocation (0|1)"},
				{"defvis", DRV_INT, 0, &defaultvisual, "Use the Default Visual (0|1)"},
				{"usepth", DRV_INT, 0, &usepthreads, "Use pthreads (0|1)"},
				{NULL, DRV_INT, 0, NULL, NULL}};

void plD_dispatch_init_xw( PLDispatchTable *pdt )
{
#ifndef ENABLE_DYNDRIVERS
    pdt->pl_MenuStr  = "X-Window (Xlib)";
    pdt->pl_DevName  = "xwin";
#endif
    pdt->pl_type     = plDevType_Interactive;
    pdt->pl_seq      = 5;
    pdt->pl_init     = (plD_init_fp)     plD_init_xw;
    pdt->pl_line     = (plD_line_fp)     plD_line_xw;
    pdt->pl_polyline = (plD_polyline_fp) plD_polyline_xw;
    pdt->pl_eop      = (plD_eop_fp)      plD_eop_xw;
    pdt->pl_bop      = (plD_bop_fp)      plD_bop_xw;
    pdt->pl_tidy     = (plD_tidy_fp)     plD_tidy_xw;
    pdt->pl_state    = (plD_state_fp)    plD_state_xw;
    pdt->pl_esc      = (plD_esc_fp)      plD_esc_xw;
}

/*--------------------------------------------------------------------------*\
 * plD_init_xw()
 *
 * Initialize device.
 * X-dependent stuff done in OpenXwin() and Init().
\*--------------------------------------------------------------------------*/

void
plD_init_xw(PLStream *pls)
{
    XwDev *dev;
    PLFLT pxlx, pxly;
    int xmin = 0;
    int xmax = PIXELS_X - 1;
    int ymin = 0;
    int ymax = PIXELS_Y - 1;

    dbug_enter("plD_init_xw");

    pls->termin = 1;		/* Is an interactive terminal */
    pls->dev_flush = 1;		/* Handle our own flushes */
    pls->dev_fill0 = 1;		/* Handle solid fills */
    pls->plbuf_write = 1; 	/* Activate plot buffer */
    pls->dev_fastimg = 1;       /* is a fast image device */
    pls->dev_xor = 1;           /* device support xor mode */

#ifndef HAVE_PTHREAD
    usepthreads = 0;
#endif

    plParseDrvOpts(xwin_options);

#ifndef HAVE_PTHREAD
    if(usepthreads)
      plwarn("You said you want pthreads, but they are not available.");
#endif

    if (nobuffered)
      pls->plbuf_write = 0;	/* desactivate plot buffer */

/* The real meat of the initialization done here */

    if (pls->dev == NULL)
	OpenXwin(pls);

    dev = (XwDev *) pls->dev;

    Init(pls);

/* Get ready for plotting */

    dev->xlen = xmax - xmin;
    dev->ylen = ymax - ymin;

    dev->xscale_init = dev->init_width  / (double) dev->xlen;
    dev->yscale_init = dev->init_height / (double) dev->ylen;

    dev->xscale = dev->xscale_init;
    dev->yscale = dev->yscale_init;

#if PHYSICAL
    pxlx = DPMM/dev->xscale;
    pxly = DPMM/dev->yscale;
#else
    pxlx = (double) PIXELS_X / LPAGE_X;
    pxly = (double) PIXELS_Y / LPAGE_Y;
#endif

    plP_setpxl(pxlx, pxly);
    plP_setphy(xmin, xmax, ymin, ymax);

#ifdef HAVE_PTHREAD
    if (usepthreads) {
      pthread_mutexattr_t mutexatt;
      pthread_attr_t pthattr;

      if (!already) {
	pthread_mutexattr_init(&mutexatt);
	if( pthread_mutexattr_settype(&mutexatt, PLPLOT_MUTEX_RECURSIVE) )
	  plexit("xwin: pthread_mutexattr_settype() failed!\n");

	pthread_mutex_init(&events_mutex, &mutexatt);
	already = 1;
      } else {
	pthread_mutex_lock(&events_mutex);
	already++;
	pthread_mutex_unlock(&events_mutex);
      }

      pthread_attr_init(&pthattr);
      pthread_attr_setdetachstate(&pthattr, PTHREAD_CREATE_JOINABLE);

      if (pthread_create(&(dev->updater), &pthattr, (void *) &events_thread, (void *) pls)) {
	pthread_mutex_lock(&events_mutex);
	already--;
	pthread_mutex_unlock(&events_mutex);

	if (already == 0) {
	  pthread_mutex_destroy(&events_mutex);
	  plexit("xwin: pthread_create() failed!\n");
	} else
	  plwarn("xwin: couldn't create thread for this plot window!\n");
      }
    }
#endif
}

/*--------------------------------------------------------------------------*\
 * plD_line_xw()
 *
 * Draw a line in the current color from (x1,y1) to (x2,y2).
\*--------------------------------------------------------------------------*/

void
plD_line_xw(PLStream *pls, short x1a, short y1a, short x2a, short y2a)
{
    XwDev *dev = (XwDev *) pls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;

    int xx1 = x1a, yy1 = y1a, xx2 = x2a, yy2 = y2a;

    dbug_enter("plD_line_xw");

#ifdef HAVE_PTHREAD
    if (usepthreads)
      pthread_mutex_lock(&events_mutex);
#endif

    CheckForEvents(pls);

    yy1 = dev->ylen - yy1;
    yy2 = dev->ylen - yy2;

    xx1 = xx1 * dev->xscale;
    xx2 = xx2 * dev->xscale;
    yy1 = yy1 * dev->yscale;
    yy2 = yy2 * dev->yscale;

    if (dev->write_to_window)
	XDrawLine(xwd->display, dev->window, dev->gc, xx1, yy1, xx2, yy2);

    if (dev->write_to_pixmap)
	XDrawLine(xwd->display, dev->pixmap, dev->gc, xx1, yy1, xx2, yy2);

#ifdef HAVE_PTHREAD
    if (usepthreads)
      pthread_mutex_unlock(&events_mutex);
#endif
}

/*--------------------------------------------------------------------------*\
 * XorMod()
 *
 * Enter xor mode ( mod != 0) or leave it ( mode = 0)
\*--------------------------------------------------------------------------*/

static void
XorMod(PLStream *pls, PLINT *mod)
{
    XwDev *dev = (XwDev *) pls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;

    if (*mod == 0)
      XSetFunction(xwd->display, dev->gc, GXcopy);
    else
      XSetFunction(xwd->display, dev->gc, GXxor);
}

/*--------------------------------------------------------------------------*\
 * plD_polyline_xw()
 *
 * Draw a polyline in the current color from (x1,y1) to (x2,y2).
\*--------------------------------------------------------------------------*/

void
plD_polyline_xw(PLStream *pls, short *xa, short *ya, PLINT npts)
{
    XwDev *dev = (XwDev *) pls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;

    PLINT i;
    XPoint pts[PL_MAXPOLY];

    if (npts > PL_MAXPOLY)
	plexit("plD_polyline_xw: Too many points in polyline\n");

    dbug_enter("plD_polyline_xw");

#ifdef HAVE_PTHREAD
    if (usepthreads)
      pthread_mutex_lock(&events_mutex);
#endif

    CheckForEvents(pls);

    for (i = 0; i < npts; i++) {
	pts[i].x = dev->xscale * xa[i];
	pts[i].y = dev->yscale * (dev->ylen - ya[i]);
    }

    if (dev->write_to_window)
	XDrawLines(xwd->display, dev->window, dev->gc, pts, npts,
		   CoordModeOrigin);

    if (dev->write_to_pixmap)
	XDrawLines(xwd->display, dev->pixmap, dev->gc, pts, npts,
		   CoordModeOrigin);

#ifdef HAVE_PTHREAD
    if (usepthreads)
      pthread_mutex_unlock(&events_mutex);
#endif
}

/*--------------------------------------------------------------------------*\
 * plD_eop_xw()
 *
 * End of page.  User must hit return (or third mouse button) to continue.
\*--------------------------------------------------------------------------*/

void
plD_eop_xw(PLStream *pls)
{
    XwDev *dev = (XwDev *) pls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;

    dbug_enter("plD_eop_xw");

#ifdef HAVE_PTHREAD
    if (usepthreads)
      pthread_mutex_lock(&events_mutex);
#endif

    XFlush(xwd->display);
    if (pls->db)
	ExposeCmd(pls, NULL);

    if (dev->is_main && ! pls->nopause)
	WaitForPage(pls);

#ifdef HAVE_PTHREAD
    if (usepthreads)
      pthread_mutex_unlock(&events_mutex);
#endif
}

/*--------------------------------------------------------------------------*\
 * plD_bop_xw()
 *
 * Set up for the next page.
\*--------------------------------------------------------------------------*/

void
plD_bop_xw(PLStream *pls)
{
    XwDev *dev = (XwDev *) pls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;

    dbug_enter("plD_bop_xw");

#ifdef HAVE_PTHREAD
    if (usepthreads)
      pthread_mutex_lock(&events_mutex);
#endif

    if (dev->write_to_window) {
	XClearWindow(xwd->display, dev->window);
    }
    if (dev->write_to_pixmap) {
	XSetForeground(xwd->display, dev->gc, xwd->cmap0[0].pixel);
	XFillRectangle(xwd->display, dev->pixmap, dev->gc, 0, 0,
		       dev->width, dev->height);
	XSetForeground(xwd->display, dev->gc, dev->curcolor.pixel);
    }
    XSync(xwd->display, 0);
    pls->page++;

#ifdef HAVE_PTHREAD
    if (usepthreads)
      pthread_mutex_unlock(&events_mutex);
#endif
}

/*--------------------------------------------------------------------------*\
 * plD_tidy_xw()
 *
 * Close graphics file
\*--------------------------------------------------------------------------*/

void
plD_tidy_xw(PLStream *pls)
{
    XwDev *dev = (XwDev *) pls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;

    dbug_enter("plD_tidy_xw");

#ifdef HAVE_PTHREAD
    if (usepthreads)
      {
	pthread_mutex_lock(&events_mutex);
	if (pthread_cancel(dev->updater) == 0)
	  pthread_join(dev->updater, NULL);

	pthread_mutex_unlock(&events_mutex);
	if (--already == 0)
	  pthread_mutex_destroy(&events_mutex);
      }
#endif

    if (dev->is_main) {
	XDestroyWindow(xwd->display, dev->window);
	if (dev->write_to_pixmap)
	    XFreePixmap(xwd->display, dev->pixmap);
	XFlush(xwd->display);
    }

    xwd->nstreams--;
    if (xwd->nstreams == 0) {
	int ixwd = xwd->ixwd;
	XFreeGC(xwd->display, dev->gc);
	XFreeGC(xwd->display, xwd->gcXor);
	XCloseDisplay(xwd->display);
        free_mem(xwd->cmap0);
        free_mem(xwd->cmap1);
	free_mem(xwDisplay[ixwd]);
    }
    /* ANR: if we set this here the tmp file will not be closed */
    /* See also comment in tkwin.c */
    /*pls->plbuf_write = 0;*/
}

/*--------------------------------------------------------------------------*\
 * plD_state_xw()
 *
 * Handle change in PLStream state (color, pen width, fill attribute, etc).
\*--------------------------------------------------------------------------*/

void
plD_state_xw(PLStream *pls, PLINT op)
{
    XwDev *dev = (XwDev *) pls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;

    dbug_enter("plD_state_xw");

#ifdef HAVE_PTHREAD
    if (usepthreads)
      pthread_mutex_lock(&events_mutex);
#endif

    CheckForEvents(pls);

    switch (op) {

    case PLSTATE_WIDTH:
        XSetLineAttributes( xwd->display, dev->gc, pls->width,
			    LineSolid, CapRound, JoinMiter);
	break;

    case PLSTATE_COLOR0:{
	int icol0 = pls->icol0;
	if (xwd->color) {
	    if (icol0 == PL_RGB_COLOR) {
		PLColor_to_XColor(&pls->curcolor, &dev->curcolor);
		if ( ! XAllocColor(xwd->display, xwd->map, &dev->curcolor)) {
		    fprintf(stderr, "Warning: could not allocate color\n");
		    dev->curcolor.pixel = xwd->fgcolor.pixel;
		}
	    } else {
		dev->curcolor = xwd->cmap0[icol0];
	    }
	    XSetForeground(xwd->display, dev->gc, dev->curcolor.pixel);
	}
	else {
	    dev->curcolor = xwd->fgcolor;
	    XSetForeground(xwd->display, dev->gc, dev->curcolor.pixel);
	}
	break;
    }

    case PLSTATE_COLOR1:{
	int icol1;

	if (xwd->ncol1 == 0)
	    AllocCmap1(pls);

	if (xwd->ncol1 < 2)
	    break;

	icol1 = (pls->icol1 * (xwd->ncol1-1)) / (pls->ncol1-1);
	if (xwd->color)
	    dev->curcolor = xwd->cmap1[icol1];
	else
	    dev->curcolor = xwd->fgcolor;

	XSetForeground(xwd->display, dev->gc, dev->curcolor.pixel);
	break;
    }

    case PLSTATE_CMAP0:
	SetBGFG(pls);
    /* If ncol0 has changed, need to reallocate */
        if (pls->ncol0 != xwd->ncol0)
            AllocCmap0(pls);
	StoreCmap0(pls);
	break;

    case PLSTATE_CMAP1:
	StoreCmap1(pls);
	break;
    }

#ifdef HAVE_PTHREAD
    if (usepthreads)
      pthread_mutex_unlock(&events_mutex);
#endif
}

/*--------------------------------------------------------------------------*\
 * plD_esc_xw()
 *
 * Escape function.
 *
 * Functions:
 *
 *    PLESC_EH	Handle pending events
 *    PLESC_EXPOSE	Force an expose
 *    PLESC_FILL	Fill polygon
 *    PLESC_FLUSH	Flush X event buffer
 *    PLESC_GETC	Get coordinates upon mouse click
 *    PLESC_REDRAW	Force a redraw
 *    PLESC_RESIZE	Force a resize
 *    PLESC_XORMOD 	set/reset xor mode
 *    PLESC_IMAGE     draw the image in a fast way
 *    PLESC_IMAGEOPS: image related operations:
 * 	   ZEROW2D  	disable writing to display
 * 	   ZEROW2B  	disable writing to buffer
 * 	   ONEW2D 	enable  writing to display
 * 	   ONEW2B 	enable  writing to buffer
 *    PLESC_PL2DEVCOL	convert PLColor to device color (XColor)
 *    PLESC_DEV2PLCOL	convert device color (XColor) to PLColor
 *    PLESC_SETBGFG	set BG, FG colors
 *    PLESC_DEVINIT	alternate device initialization
 *
 * Note the [GET|SET]DEVCOL functions go through the intermediary stream
 * variable tmpcolor to keep the syntax simple.
\*--------------------------------------------------------------------------*/

void
plD_esc_xw(PLStream *pls, PLINT op, void *ptr)
{
    dbug_enter("plD_esc_xw");

#ifdef HAVE_PTHREAD
    if (usepthreads)
      pthread_mutex_lock(&events_mutex);
#endif

    switch (op) {
    case PLESC_EH:
	HandleEvents(pls);
	break;

    case PLESC_EXPOSE:
	ExposeCmd(pls, (PLDisplay *) ptr);
	break;

    case PLESC_FILL:
	FillPolygonCmd(pls);
	break;

    case PLESC_FLUSH:{
	XwDev *dev = (XwDev *) pls->dev;
	XwDisplay *xwd = (XwDisplay *) dev->xwd;
	HandleEvents(pls);
	XFlush(xwd->display);
	break;
    }
    case PLESC_GETC:
	GetCursorCmd(pls, (PLGraphicsIn *) ptr);
	break;

    case PLESC_REDRAW:
	RedrawCmd(pls);
	break;

    case PLESC_RESIZE:
	ResizeCmd(pls, (PLDisplay *) ptr);
	break;

    case PLESC_XORMOD:
	XorMod(pls, (PLINT *) ptr);
	break;

    case PLESC_DOUBLEBUFFERING:
	ConfigBufferingCmd(pls, (PLBufferingCB *) ptr );
	break;

    case PLESC_IMAGE:
	DrawImage(pls);
	break;

    case PLESC_IMAGEOPS:
	imageops(pls, (PLINT *) ptr);
	break;

    case PLESC_PL2DEVCOL:
	PLColor_to_XColor(&pls->tmpcolor, (XColor *) ptr);
	break;

    case PLESC_DEV2PLCOL:
	PLColor_from_XColor(&pls->tmpcolor, (XColor *) ptr);
	break;

    case PLESC_SETBGFG:
	SetBGFG(pls);
	break;

    case PLESC_DEVINIT:
	OpenXwin(pls);
	break;
    }

#ifdef HAVE_PTHREAD
    if (usepthreads)
      pthread_mutex_unlock(&events_mutex);
#endif
}

/*--------------------------------------------------------------------------*\
 * GetCursorCmd()
 *
 * Waits for a graphics input event and returns coordinates.
\*--------------------------------------------------------------------------*/

static void
GetCursorCmd(PLStream *pls, PLGraphicsIn *ptr)
{
    XwDev *dev = (XwDev *) pls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;
    XEvent event;
    PLGraphicsIn *gin = &(dev->gin);

/* Initialize */

    plGinInit(gin);
    dev->locate_mode = LOCATE_INVOKED_VIA_API;
    CreateXhairs(pls);

/* Run event loop until a point is selected */

    while (gin->pX < 0 && dev->locate_mode) {
	XWindowEvent(xwd->display, dev->window, dev->event_mask, &event);
	MasterEH(pls, &event);
    }
    *ptr = *gin;
    if (dev->locate_mode) {
	dev->locate_mode = 0;
	DestroyXhairs(pls);
    }
}

/*--------------------------------------------------------------------------*\
 * FillPolygonCmd()
 *
 * Fill polygon described in points pls->dev_x[] and pls->dev_y[].
 * Only solid color fill supported.
\*--------------------------------------------------------------------------*/

static void
FillPolygonCmd(PLStream *pls)
{
    XwDev *dev = (XwDev *) pls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;
    XPoint pts[PL_MAXPOLY];
    int i;

    if (pls->dev_npts > PL_MAXPOLY)
	plexit("FillPolygonCmd: Too many points in polygon\n");

    CheckForEvents(pls);

    for (i = 0; i < pls->dev_npts; i++) {
	pts[i].x = dev->xscale * pls->dev_x[i];
	pts[i].y = dev->yscale * (dev->ylen - pls->dev_y[i]);
    }

/* Fill polygons */

    if (dev->write_to_window)
	XFillPolygon(xwd->display, dev->window, dev->gc,
		     pts, pls->dev_npts, Nonconvex, CoordModeOrigin);

    if (dev->write_to_pixmap)
	XFillPolygon(xwd->display, dev->pixmap, dev->gc,
		     pts, pls->dev_npts, Nonconvex, CoordModeOrigin);

/* If in debug mode, draw outline of boxes being filled */

#ifdef DEBUG
    if (pls->debug) {
	XSetForeground(xwd->display, dev->gc, xwd->fgcolor.pixel);
	if (dev->write_to_window)
	    XDrawLines(xwd->display, dev->window, dev->gc, pts, pls->dev_npts,
		       CoordModeOrigin);

	if (dev->write_to_pixmap)
	    XDrawLines(xwd->display, dev->pixmap, dev->gc, pts, pls->dev_npts,
		       CoordModeOrigin);

	XSetForeground(xwd->display, dev->gc, dev->curcolor.pixel);
    }
#endif
}

/*--------------------------------------------------------------------------*\
 * OpenXwin()
 *
 * Performs basic driver initialization, without actually opening or
 * modifying a window.  May be called by the outside world before plinit
 * in case the caller needs early access to the driver internals (not
 * very common -- currently only used by the plframe widget).
\*--------------------------------------------------------------------------*/

static void
OpenXwin(PLStream *pls)
{
    XwDev *dev;
    XwDisplay *xwd;
    int i;

    dbug_enter("OpenXwin");

/* Allocate and initialize device-specific data */

    if (pls->dev != NULL)
	plwarn("OpenXwin: device pointer is already set");

    pls->dev = calloc(1, (size_t) sizeof(XwDev));
    if (pls->dev == NULL)
	plexit("plD_init_xw: Out of memory.");

    dev = (XwDev *) pls->dev;

/* Variables used in querying the X server for events */

    dev->instr = 0;
    dev->max_instr = MAX_INSTR;

/* See if display matches any already in use, and if so use that */

    dev->xwd = NULL;
    for (i = 0; i < PLXDISPLAYS; i++) {
	if (xwDisplay[i] == NULL) {
	    continue;
	}
	else if (pls->FileName == NULL && xwDisplay[i]->displayName == NULL) {
	    dev->xwd = xwDisplay[i];
	    break;
	}
	else if (pls->FileName == NULL || xwDisplay[i]->displayName == NULL) {
	    continue;
	}
	else if (strcmp(xwDisplay[i]->displayName, pls->FileName) == 0) {
	    dev->xwd = xwDisplay[i];
	    break;
	}
    }

/* If no display matched, create a new one */

    if (dev->xwd == NULL) {
	dev->xwd = (XwDisplay *) calloc(1, (size_t) sizeof(XwDisplay));
	if (dev->xwd == NULL)
	    plexit("Init: Out of memory.");

	for (i = 0; i < PLXDISPLAYS; i++) {
	    if (xwDisplay[i] == NULL)
		break;
	}
	if (i == PLXDISPLAYS)
	    plexit("Init: Out of xwDisplay's.");

	xwDisplay[i] = xwd = (XwDisplay *) dev->xwd;
	xwd->nstreams = 1;

/* Open display */
#ifdef HAVE_PTHREAD
	if (usepthreads)
	  if (! XInitThreads())
	    plexit("xwin: XInitThreads() not successful.\n");
#endif
	xwd->display = XOpenDisplay(pls->FileName);
	if (xwd->display == NULL) {
	    fprintf(stderr, "Can't open display\n");
	    exit(1);
	}
	xwd->displayName = pls->FileName;
	xwd->screen = DefaultScreen(xwd->display);
	if (synchronize)
	    XSynchronize(xwd->display, 1);

    /* Get colormap and visual */
	xwd->map = DefaultColormap(xwd->display, xwd->screen);
	GetVisual(pls);

    /*
     * Figure out if we have a color display or not.
     * Default is color IF the user hasn't specified and IF the output device
     * is not grayscale.
     */
	if (pls->colorset)
	    xwd->color = pls->color;
	else {
	    pls->color = 1;
	    xwd->color = ! AreWeGrayscale(xwd->display);
	}

    /* Allocate space for colors */
    /* Note cmap1 allocation is deferred */
        xwd->ncol0_alloc = pls->ncol0;
        xwd->cmap0 = (XColor *) calloc(pls->ncol0, (size_t) sizeof(XColor));
        if (xwd->cmap0 == 0)
            plexit("couldn't allocate space for cmap0 colors");

    /* Allocate & set background and foreground colors */
	AllocBGFG(pls);
	SetBGFG(pls);
    }

/* Display matched, so use existing display data */

    else {
	xwd = (XwDisplay *) dev->xwd;
	xwd->nstreams++;
    }
    xwd->ixwd = i;
}

/*--------------------------------------------------------------------------*\
 * Init()
 *
 * Xlib initialization routine.
 *
 * Controlling routine for X window creation and/or initialization.
 * The user may customize the window in the following ways:
 *
 * display:	pls->OutFile (use plsfnam() or -display option)
 * size:	pls->xlength, pls->ylength (use plspage() or -geo option)
 * bg color:	pls->cmap0[0] (use plscolbg() or -bg option)
\*--------------------------------------------------------------------------*/

static void
Init(PLStream *pls)
{
    XwDev *dev = (XwDev *) pls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;

    Window root;
    int x, y;

    dbug_enter("Init");

/* If not plotting into a child window, need to create main window now */

    if (pls->window_id == 0) {
	dev->is_main = TRUE;
	InitMain(pls);
    }
    else {
	dev->is_main = FALSE;
	dev->window = pls->window_id;
    }

/* Initialize colors */

    if (noinitcolors == 0) InitColors(pls);
    XSetWindowColormap( xwd->display, dev->window, xwd->map );

/* Set up GC for ordinary draws */

    if ( ! dev->gc)
	dev->gc = XCreateGC(xwd->display, dev->window, 0, 0);

/* Set up GC for rubber-band draws */

    if ( ! xwd->gcXor) {
	XGCValues gcValues;
	unsigned long mask;

	gcValues.background = xwd->cmap0[0].pixel;
	gcValues.foreground = 0xFF;
	gcValues.function = GXxor;
	mask = GCForeground | GCBackground | GCFunction;

	xwd->gcXor = XCreateGC(xwd->display, dev->window, mask, &gcValues);
    }

/* Get initial drawing area dimensions */

    (void) XGetGeometry(xwd->display, dev->window, &root, &x, &y,
			&dev->width, &dev->height, &dev->border, &xwd->depth);

    dev->init_width  = dev->width;
    dev->init_height = dev->height;

/* Set up flags that determine what we are writing to */
/* If nopixmap is set, ignore db */

    if (pls->nopixmap) {
	dev->write_to_pixmap = 0;
	pls->db = 0;
    }
    else {
	dev->write_to_pixmap = 1;
    }
    dev->write_to_window = ! pls->db;

/* Create pixmap for holding plot image (for expose events). */

    if (dev->write_to_pixmap)
	CreatePixmap(pls);

/* Set drawing color */

    plD_state_xw(pls, PLSTATE_COLOR0);

    XSetWindowBackground(xwd->display, dev->window, xwd->cmap0[0].pixel);
    XSetBackground(xwd->display, dev->gc, xwd->cmap0[0].pixel);

/* If main window, need to map it and wait for exposure */

    if (dev->is_main)
	MapMain(pls);
}

/*--------------------------------------------------------------------------*\
 * InitMain()
 *
 * Create main window using standard Xlib calls.
\*--------------------------------------------------------------------------*/

static void
InitMain(PLStream *pls)
{
    XwDev *dev = (XwDev *) pls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;

    Window root;
    XSizeHints hint;
    int x, y;
    U_INT width, height, border, depth;
    char header[1024];

    dbug_enter("InitMain");

/* Get root window geometry */

    (void) XGetGeometry(xwd->display, DefaultRootWindow(xwd->display),
			&root, &x, &y, &width, &height, &border, &depth);

/* Set window size */
/* Need to be careful to set XSizeHints flags correctly */

    hint.flags = 0;
    if (pls->xlength == 0 && pls->ylength == 0)
	hint.flags |= PSize;
    else
	hint.flags |= USSize;

    if (pls->xlength == 0) pls->xlength = width  * 0.75;
    if (pls->ylength == 0) pls->ylength = height * 0.75;

    if (pls->xlength > (short) width)  pls->xlength = width  - dev->border * 2;
    if (pls->ylength > (short) height) pls->ylength = height - dev->border * 2;

    hint.width  = (int) pls->xlength;
    hint.height = (int) pls->ylength;
    dev->border = 5;

/* Set window position if specified by the user. */
/* Otherwise leave up to the window manager */

    if (pls->xoffset != 0 || pls->yoffset != 0) {
	hint.flags |= USPosition;
	hint.x = (int) pls->xoffset;
	hint.y = (int) pls->yoffset;
    }
    else {
	hint.x = 0;
	hint.y = 0;
    }

/* Window title */

    if (pls->plwindow){    /* allow -plwindow to specify wm decoration name */
	sprintf(header, "%s", pls->plwindow);
    }
    else if(pls->program) {
	sprintf(header, "%s", pls->program); /* else program name */
    }
    else
	sprintf(header,"%s","Plplot");

/* Window creation */

    dev->window =
	XCreateWindow( xwd->display,
		       DefaultRootWindow(xwd->display),
		       hint.x, hint.y, hint.width, hint.height,
		       dev->border, xwd->depth,
		       InputOutput, xwd->visual,
		       0, NULL );

    XSetStandardProperties(xwd->display, dev->window, header, header,
			   None, 0, 0, &hint);
}

/*--------------------------------------------------------------------------*\
 * MapMain()
 *
 * Sets up event handlers, maps main window and waits for exposure.
\*--------------------------------------------------------------------------*/

static void
MapMain(PLStream *pls)
{
    XwDev *dev = (XwDev *) pls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;
    XEvent event;

    dbug_enter("MapMain");

/* Input event selection */

    dev->event_mask =
	ButtonPressMask      |
	KeyPressMask         |
	ExposureMask         |
	ButtonMotionMask     | /* drag */
	StructureNotifyMask;

    XSelectInput(xwd->display, dev->window, dev->event_mask);

/* Window mapping */

    XMapRaised(xwd->display, dev->window);

/* Wait for exposure */
/* Remove extraneous expose events from the event queue */

    for (;;) {
	XWindowEvent(xwd->display, dev->window, dev->event_mask, &event);
	if (event.type == Expose) {
	    while (XCheckWindowEvent(xwd->display, dev->window,
				     ExposureMask, &event));
	    break;
	}
    }
}

/*--------------------------------------------------------------------------*\
 * WaitForPage()
 *
 * This routine waits for the user to advance the plot, while handling
 * all other events.
\*--------------------------------------------------------------------------*/

static void
WaitForPage(PLStream *pls)
{
    XwDev *dev = (XwDev *) pls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;
    XEvent event;

    dbug_enter("WaitForPage");

    while ( ! dev->exit_eventloop) {
	XWindowEvent(xwd->display, dev->window, dev->event_mask, &event);
	MasterEH(pls, &event);
    }
    dev->exit_eventloop = FALSE;
}

/*------------------------------------------------------------\*
 * events_thread()
 *
 * This function is being running continously by a tread and is
 * responsible for dealing with expose and resize X events, in
 * the case that the main program is too busy to honor them.
 *
 * Dealing with other X events is possible, but not desirable,
 * e.g. treating the "Q" or right-mouse-button would terminate
 * the thread (if this is desirable, the thread should kill the
 * main program -- not thread aware -- and kill itself afterward).
 *
 * This works pretty well, but the main program *must* be linked
 * with the pthread library, although not being thread aware.
 * This happens automatically when linking against libplplot.so,
 * but when building modules for extending some language such as
 * Python or Octave, the language providing binary itself must be
 * relinked with -lpthread.
 *
\*------------------------------------------------------------*/

#ifdef HAVE_PTHREAD
static void
events_thread(void *pls)
{
  if (usepthreads) {
    PLStream *lpls = (PLStream *) pls;
    XwDev *dev = (XwDev *) lpls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;
    PLStream *oplsc;
    struct timespec delay;
    XEvent event;
    long event_mask;
    sigset_t set;

    /*
     * only treats exposures and resizes, but remove usual events from queue,
     * as it can be disturbing to not have them acknowledged in real time,
     * because the program is busy, and suddenly all being acknowledged.
     * Also, the locator ("L" key) is sluggish if driven by the thread.
     *
     * But this approach is a problem when the thread removes events
     * from the queue while the program is responsible! The user hits 'L'
     * and nothing happens, as the thread removes it.
     *
     * Perhaps the "Q" key should have a different treatment, quiting the
     * program anyway?
     *
     * Changed: does not remove non treated events from the queue
     */

    event_mask =  ExposureMask | StructureNotifyMask;

    /* block all signal for this thread */
    sigemptyset(&set);
    /* sigfillset(&set);  can't be all signals, decide latter */
    sigaddset(&set, SIGINT);

    sigprocmask(SIG_BLOCK, &set, NULL);

    pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
    pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);

    delay.tv_sec = 0;
    delay.tv_nsec = 10000000; /* this thread runs 10 times a second. (1/10 ms) */

    while(1) {
      pthread_mutex_lock(&events_mutex);

      if (dev->is_main && !lpls->plbuf_read &&
	  ++dev->instr % dev->max_instr == 0) {

	dev->instr = 0;
	while (XCheckWindowEvent(xwd->display, dev->window, event_mask, &event)) {
	  /* As ResizeEH() ends up calling plRemakePlot(), that
	   * indirectly uses the current stream, one needs to
	   * temporarily set plplot current stream to this thread's
	   * stream */

	  oplsc = plsc;
	  plsc = lpls;
	  switch (event.type) {
	  case Expose:
	    ExposeEH(lpls, &event);
	    break;
	  case ConfigureNotify:
	    ResizeEH(lpls, &event);
	    break;
	  }
	  plsc = oplsc;
	}
      }

      pthread_mutex_unlock(&events_mutex);
      nanosleep(&delay, NULL); /* 10ms in linux */
      /* pthread_yield(NULL); */ /* this puts too much load on the CPU */
    }
  }
}
#endif

/*--------------------------------------------------------------------------*\
 * CheckForEvents()
 *
 * A front-end to HandleEvents(), which is only called if certain conditions
 * are satisfied:
 *
 * - must be the creator of the main window (i.e. PLplot is handling the
 *   X event loop by polling).
 * - must not be in the middle of a plot redisplay (else the order of event
 *   handling can become circuitous).
 * - only query X for events and process them every dev->max_instr times
 *   this function is called (good for performance since querying X is a
 *   nontrivial performance hit).
\*--------------------------------------------------------------------------*/

static void
CheckForEvents(PLStream *pls)
{
    XwDev *dev = (XwDev *) pls->dev;

    if (dev->is_main &&
	! pls->plbuf_read &&
	++dev->instr % dev->max_instr == 0) {

	dev->instr = 0;
	HandleEvents(pls);
    }
}

/*--------------------------------------------------------------------------*\
 * HandleEvents()
 *
 * Just a front-end to MasterEH(), for use when not actually waiting for an
 * event but only checking the event queue.
\*--------------------------------------------------------------------------*/

static void
HandleEvents(PLStream *pls)
{
    XwDev *dev = (XwDev *) pls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;
    XEvent event;

    while (XCheckWindowEvent(xwd->display, dev->window,
			     dev->event_mask, &event))
	MasterEH(pls, &event);
}

/*--------------------------------------------------------------------------*\
 * MasterEH()
 *
 * Master X event handler routine.
 * Redirects control to routines to handle:
 *    - keyboard events
 *    - mouse events
 *    - expose events
 *    - resize events
 *
 * By supplying a master event handler, the user can take over all event
 * processing.  If events other than those trapped by PLplot need handling,
 * just call XSelectInput with the appropriate flags.  The default PLplot
 * event handling can be modified arbitrarily by changing the event struct.
\*--------------------------------------------------------------------------*/

static void
MasterEH(PLStream *pls, XEvent *event)
{
  XwDev *dev = (XwDev *) pls->dev;

  if (dev->MasterEH != NULL)
    (*dev->MasterEH) (pls, event);

  switch (event->type) {

    case KeyPress:
        KeyEH(pls, event);
	break;

    case ButtonPress:
	ButtonEH(pls, event);
	break;

    case Expose:
	ExposeEH(pls, event);
	break;

    case ConfigureNotify:
	ResizeEH(pls, event);
	break;

    case MotionNotify:
	if (event->xmotion.state)
	  ButtonEH(pls, event); /* drag */
	MotionEH(pls, event);
	break;

    case EnterNotify:
	EnterEH(pls, event);
	break;

    case LeaveNotify:
	LeaveEH(pls, event);
	break;
    }
}

/*--------------------------------------------------------------------------*\
 * KeyEH()
 *
 * Event handler routine for keyboard events.
\*--------------------------------------------------------------------------*/

static void
KeyEH(PLStream *pls, XEvent *event)
{
    XwDev *dev = (XwDev *) pls->dev;

    dbug_enter("KeyEH");

    LookupXKeyEvent(pls, event);
    if (dev->locate_mode)
	LocateKey(pls);
    else
	ProcessKey(pls);
}

/*--------------------------------------------------------------------------*\
 * ButtonEH()
 *
 * Event handler routine for ButtonPress events.
\*--------------------------------------------------------------------------*/

static void
ButtonEH(PLStream *pls, XEvent *event)
{
    XwDev *dev = (XwDev *) pls->dev;

    dbug_enter("ButtonEH");

    LookupXButtonEvent(pls, event);
    if (dev->locate_mode)
	LocateButton(pls);
    else
	ProcessButton(pls);
}

/*--------------------------------------------------------------------------*\
 * LookupXKeyEvent()
 *
 * Fills in the PLGraphicsIn from an XKeyEvent.  The PLGraphicsIn keysym is
 * the same as the X keysym for all cases except for control keys that have
 * ASCII equivalents, i.e.:
 *
 * Name		      X-keysym	ASCII	Ctrl-key
 * ----		      --------	-----	--------
 * XK_BackSpace        0xFF08   0x08      ^H
 * XK_Tab              0xFF09   0x09      ^I
 * XK_Linefeed         0xFF0A   0x0A      ^J
 * XK_Return           0xFF0D   0x0D      ^M
 * XK_Escape           0xFF1B   0x1B      ^[
 * XK_Delete           0xFFFF   0xFF     (none)
 *
 * The ASCII representation of these characters is used for the PLGraphicsIn
 * keysym to simplify code logic.  It turns out that the X keysyms are
 * identical to the ASCII values with the upper 8 bits set.
\*--------------------------------------------------------------------------*/

static void
LookupXKeyEvent(PLStream *pls, XEvent *event)
{
    XwDev *dev = (XwDev *) pls->dev;
    PLGraphicsIn *gin = &(dev->gin);
    XKeyEvent *keyEvent = (XKeyEvent *) event;
    KeySym keysym;
    int nchars, ncmax = PL_MAXKEY-1;
    XComposeStatus cs;

    gin->pX = keyEvent->x;
    gin->pY = keyEvent->y;
    gin->dX = (PLFLT) keyEvent->x / (dev->width - 1);
    gin->dY = 1.0 - (PLFLT) keyEvent->y / (dev->height - 1);

    gin->state = keyEvent->state;

    nchars = XLookupString(keyEvent, gin->string, ncmax, &keysym, &cs);
    gin->string[nchars] = '\0';

    pldebug("LookupXKeyEvent",
	    "Keysym %x, translation: %s\n", keysym, gin->string);

    switch (keysym) {

    case XK_BackSpace:
    case XK_Tab:
    case XK_Linefeed:
    case XK_Return:
    case XK_Escape:
    case XK_Delete:
	gin->keysym = 0xFF & keysym;
	break;

    default:
	gin->keysym = keysym;
    }
}

/*--------------------------------------------------------------------------*\
 * LookupXButtonEvent()
 *
 * Fills in the PLGraphicsIn from an XButtonEvent.
\*--------------------------------------------------------------------------*/

static void
LookupXButtonEvent(PLStream *pls, XEvent *event)
{
    XwDev *dev = (XwDev *) pls->dev;
    PLGraphicsIn *gin = &(dev->gin);
    XButtonEvent *buttonEvent = (XButtonEvent *) event;

    pldebug("LookupXButtonEvent",
	    "Button: %d, x: %d, y: %d\n",
	    buttonEvent->button, buttonEvent->x, buttonEvent->y);

    gin->pX = buttonEvent->x;
    gin->pY = buttonEvent->y;
    gin->dX = (PLFLT) buttonEvent->x / (dev->width - 1);
    gin->dY = 1.0 - (PLFLT) buttonEvent->y / (dev->height - 1);

    gin->button = buttonEvent->button;
    gin->state = buttonEvent->state;
    gin->keysym = 0x20;
}

/*--------------------------------------------------------------------------*\
 * ProcessKey()
 *
 * Process keyboard events other than locate input.
\*--------------------------------------------------------------------------*/

static void
ProcessKey(PLStream *pls)
{
    XwDev *dev = (XwDev *) pls->dev;
    PLGraphicsIn *gin = &(dev->gin);

    dbug_enter("ProcessKey");

/* Call user keypress event handler.  Since this is called first, the user
 * can disable all internal event handling by setting key.keysym to 0.
*/
    if (pls->KeyEH != NULL)
	(*pls->KeyEH) (gin, pls->KeyEH_data, &dev->exit_eventloop);

/* Handle internal events */

    switch (gin->keysym) {

    case PLK_Return:
    case PLK_Linefeed:
    case PLK_Next:
    /* Advance to next page (i.e. terminate event loop) on a <eol> */
    /* Check for both <CR> and <LF> for portability, also a <Page Down> */
	dev->exit_eventloop = TRUE;
	break;

    case 'Q':
    /* Terminate on a 'Q' (not 'q', since it's too easy to hit by mistake) */
	pls->nopause = TRUE;
	plexit("");
	break;

    case 'L':
    /* Begin locate mode */
	dev->locate_mode = LOCATE_INVOKED_VIA_DRIVER;
	CreateXhairs(pls);
	break;
    }
}

/*--------------------------------------------------------------------------*\
 * ProcessButton()
 *
 * Process ButtonPress events other than locate input.
 * On:
 *   Button1: nothing (except when in locate mode, see ButtonLocate)
 *   Button2: nothing
 *   Button3: set page advance flag
\*--------------------------------------------------------------------------*/

static void
ProcessButton(PLStream *pls)
{
    XwDev *dev = (XwDev *) pls->dev;
    PLGraphicsIn *gin = &(dev->gin);

    dbug_enter("ProcessButton");

/* Call user event handler.  Since this is called first, the user can
 * disable all PLplot internal event handling by setting gin->button to 0.
*/
    if (pls->ButtonEH != NULL)
	(*pls->ButtonEH) (gin, pls->ButtonEH_data, &dev->exit_eventloop);

/* Handle internal events */

    switch (gin->button) {
    case Button3:
	dev->exit_eventloop = TRUE;
	break;
    }
}

/*--------------------------------------------------------------------------*\
 * LocateKey()
 *
 * Front-end to locate handler for KeyPress events.
 * Provides for a number of special effects:
 *
 *  <Escape>		Ends locate mode
 *  <Cursor>		Moves cursor one pixel in the specified direction
 *  <Mod-Cursor>	Accelerated cursor movement (5x for each modifier)
\*--------------------------------------------------------------------------*/

static void
LocateKey(PLStream *pls)
{
    XwDev *dev = (XwDev *) pls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;
    PLGraphicsIn *gin = &(dev->gin);

/* End locate mode on <Escape> */

    if (gin->keysym == PLK_Escape) {
	dev->locate_mode = 0;
	DestroyXhairs(pls);
	plGinInit(gin);
    }

/* Ignore modifier keys */

    else if (IsModifierKey(gin->keysym)) {
	plGinInit(gin);
    }

/* Now handle cursor keys */

    else if (IsCursorKey(gin->keysym)) {
	int xx1, yy1, dx = 0, dy = 0;
	int xmin = 0, xmax = dev->width - 1, ymin = 0, ymax = dev->height - 1;

	switch (gin->keysym) {
	case PLK_Left:
	    dx = -1;
	    break;
	case PLK_Right:
	    dx = 1;
	    break;
	case PLK_Up:
	    dy = -1;
	    break;
	case PLK_Down:
	    dy = 1;
	    break;
	}

    /* Each modifier key added increases the multiplication factor by 5 */

    /* Shift */

	if (gin->state & 0x01) {
	    dx *= 5;
	    dy *= 5;
	}

    /* Caps Lock */

	if (gin->state & 0x02) {
	    dx *= 5;
	    dy *= 5;
	}

    /* Control */

	if (gin->state & 0x04) {
	    dx *= 5;
	    dy *= 5;
	}

    /* Alt */

	if (gin->state & 0x08) {
	    dx *= 5;
	    dy *= 5;
	}

    /* Bounds checking so that we don't send cursor out of window */

	xx1 = gin->pX + dx;
	yy1 = gin->pY + dy;

	if (xx1 < xmin) dx = xmin - gin->pX;
	if (yy1 < ymin) dy = ymin - gin->pY;
	if (xx1 > xmax) dx = xmax - gin->pX;
	if (yy1 > ymax) dy = ymax - gin->pY;

    /* Engage... */

	XWarpPointer(xwd->display, dev->window, None, 0, 0, 0, 0, dx, dy);
	plGinInit(gin);
    }

/* Call ordinary locate handler */

    else {
	Locate(pls);
    }
}

/*--------------------------------------------------------------------------*\
 * LocateButton()
 *
 * Front-end to locate handler for ButtonPress events.
 * Only passes control to Locate() for Button1 presses.
\*--------------------------------------------------------------------------*/

static void
LocateButton(PLStream *pls)
{
    XwDev *dev = (XwDev *) pls->dev;
    PLGraphicsIn *gin = &(dev->gin);

    switch (gin->button) {

    case Button1:
        Locate(pls);
        break;
    }
}

/*--------------------------------------------------------------------------*\
 * Locate()
 *
 * Handles locate mode events.
 *
 * In locate mode: move cursor to desired location and select by pressing a
 * key or by clicking on the mouse (if available).  Typically the world
 * coordinates of the selected point are reported.
 *
 * There are two ways to enter Locate mode -- via the API, or via a driver
 * command.  The API entry point is the call plGetCursor(), which initiates
 * locate mode and does not return until input has been obtained.  The
 * driver entry point is by entering a 'L' while the driver is waiting for
 * events.
 *
 * Locate mode input is reported in one of three ways:
 * 1. Through a returned PLGraphicsIn structure, when user has specified a
 *    locate handler via (*pls->LocateEH).
 * 2. Through a returned PLGraphicsIn structure, when locate mode is invoked
 *    by a plGetCursor() call.
 * 3. Through writes to stdout, when locate mode is invoked by a driver
 *    command and the user has not supplied a locate handler.
 *
 * Hitting <Escape> will at all times end locate mode.  Other keys will
 * typically be interpreted as locator input.  Selecting a point out of
 * bounds will end locate mode unless the user overrides with a supplied
 * Locate handler.
\*--------------------------------------------------------------------------*/

static void
Locate(PLStream *pls)
{
    XwDev *dev = (XwDev *) pls->dev;
    PLGraphicsIn *gin = &(dev->gin);

/* Call user locate mode handler if provided */

    if (pls->LocateEH != NULL)
	(*pls->LocateEH) (gin, pls->LocateEH_data, &dev->locate_mode);

/* Use default procedure */

    else {

    /* Try to locate cursor */

	if (plTranslateCursor(gin)) {

	/* If invoked by the API, we're done */
	/* Otherwise send report to stdout */

	    if (dev->locate_mode == LOCATE_INVOKED_VIA_DRIVER) {
		pltext();
		if (gin->keysym < 0xFF && isprint(gin->keysym))
		    printf("%f %f %c\n", gin->wX, gin->wY, gin->keysym);
		else
		    printf("%f %f 0x%02x\n", gin->wX, gin->wY, gin->keysym);

		plgra();
	    }
	}
	else {

	/* Selected point is out of bounds, so end locate mode */

	    dev->locate_mode = 0;
	    DestroyXhairs(pls);
	}
    }
}

/*--------------------------------------------------------------------------*\
 * MotionEH()
 *
 * Event handler routine for MotionNotify events.
 * If drawing crosshairs, the first and last draws must be done "by hand".
\*--------------------------------------------------------------------------*/

static void
MotionEH(PLStream *pls, XEvent *event)
{
    XwDev *dev = (XwDev *) pls->dev;
    XMotionEvent *motionEvent = (XMotionEvent *) event;

    if (dev->drawing_xhairs) {
	DrawXhairs(pls, motionEvent->x, motionEvent->y);
    }
}

/*--------------------------------------------------------------------------*\
 * EnterEH()
 *
 * Event handler routine for EnterNotify events.  Only called if drawing
 * crosshairs -- a draw must be done here to start off the new set.
\*--------------------------------------------------------------------------*/

static void
EnterEH(PLStream *pls, XEvent *event)
{
    XwDev *dev = (XwDev *) pls->dev;
    XCrossingEvent *crossingEvent = (XCrossingEvent *) event;

    DrawXhairs(pls, crossingEvent->x, crossingEvent->y);
    dev->drawing_xhairs = 1;
}

/*--------------------------------------------------------------------------*\
 * LeaveEH()
 *
 * Event handler routine for EnterNotify or LeaveNotify events.
 * If drawing crosshairs, a draw must be done here to start off the new
 * set or erase the last set.
\*--------------------------------------------------------------------------*/

static void
LeaveEH(PLStream *pls, XEvent *event)
{
    XwDev *dev = (XwDev *) pls->dev;

    (void) event;			/* pmr: make it used */
    UpdateXhairs(pls);
    dev->drawing_xhairs = 0;
}

/*--------------------------------------------------------------------------*\
 * CreateXhairs()
 *
 * Creates graphic crosshairs at current pointer location.
\*--------------------------------------------------------------------------*/

static void
CreateXhairs(PLStream *pls)
{
    XwDev *dev = (XwDev *) pls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;
    Window root, child;
    int root_x, root_y, win_x, win_y;
    unsigned int mask;
    XEvent event;

/* Get a crosshair cursor and switch to it. */

    if (!xwd->xhair_cursor)
	xwd->xhair_cursor = XCreateFontCursor(xwd->display, XC_crosshair);

    XDefineCursor(xwd->display, dev->window, xwd->xhair_cursor);

/* Find current pointer location and draw graphic crosshairs if pointer is */
/* inside our window */

    if (XQueryPointer(xwd->display, dev->window, &root, &child,
		      &root_x, &root_y, &win_x, &win_y, &mask)) {

	if (win_x >= 0 && win_x < (int) dev->width &&
	    win_y >= 0 && win_y < (int) dev->height) {
	    DrawXhairs(pls, win_x, win_y);
	    dev->drawing_xhairs = 1;
	}
    }

/* Sync the display and then throw away all pending motion events */

    XSync(xwd->display, 0);
    while (XCheckWindowEvent(xwd->display, dev->window,
			     PointerMotionMask, &event));

/* Catch PointerMotion and crossing events so we can update them properly */

    dev->event_mask |= PointerMotionMask | EnterWindowMask | LeaveWindowMask;
    XSelectInput(xwd->display, dev->window, dev->event_mask);
}

/*--------------------------------------------------------------------------*\
 * DestroyXhairs()
 *
 * Destroys graphic crosshairs.
\*--------------------------------------------------------------------------*/

static void
DestroyXhairs(PLStream *pls)
{
    XwDev *dev = (XwDev *) pls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;

/* Switch back to boring old pointer */

    XUndefineCursor(xwd->display, dev->window);

/* Don't catch PointerMotion or crossing events any more */

    dev->event_mask &=
	~PointerMotionMask & ~EnterWindowMask & ~LeaveWindowMask;
    XSelectInput(xwd->display, dev->window, dev->event_mask);

/* This draw removes the last set of graphic crosshairs */

    UpdateXhairs(pls);
    dev->drawing_xhairs = 0;
}

/*--------------------------------------------------------------------------*\
 * DrawXhairs()
 *
 * Draws graphic crosshairs at (x0, y0).  The first draw erases the old set.
\*--------------------------------------------------------------------------*/

static void
DrawXhairs(PLStream *pls, int xx0, int yy0)
{
    XwDev *dev = (XwDev *) pls->dev;

    int xmin = 0, xmax = dev->width - 1;
    int ymin = 0, ymax = dev->height - 1;

    if (dev->drawing_xhairs)
	UpdateXhairs(pls);

    dev->xhair_x[0].x = xmin; dev->xhair_x[0].y = yy0;
    dev->xhair_x[1].x = xmax; dev->xhair_x[1].y = yy0;

    dev->xhair_y[0].x = xx0; dev->xhair_y[0].y = ymin;
    dev->xhair_y[1].x = xx0; dev->xhair_y[1].y = ymax;

    UpdateXhairs(pls);
}

/*--------------------------------------------------------------------------*\
 * UpdateXhairs()
 *
 * Updates graphic crosshairs.  If already there, they are erased.
\*--------------------------------------------------------------------------*/

static void
UpdateXhairs(PLStream *pls)
{
    XwDev *dev = (XwDev *) pls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;

    XDrawLines(xwd->display, dev->window, xwd->gcXor, dev->xhair_x, 2,
	       CoordModeOrigin);

    XDrawLines(xwd->display, dev->window, xwd->gcXor, dev->xhair_y, 2,
	       CoordModeOrigin);
}

/*--------------------------------------------------------------------------*\
 * ExposeEH()
 *
 * Event handler routine for expose events.
 * Front end to ExposeCmd() to deal with wierdnesses of Xlib.
\*--------------------------------------------------------------------------*/

static void
ExposeEH(PLStream *pls, XEvent *event)
{
    XwDev *dev = (XwDev *) pls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;
    XExposeEvent *exposeEvent = (XExposeEvent *) event;
    PLDisplay pldis;
    int redrawn;

    dbug_enter("ExposeEH");

    pldebug("ExposeEH",
	    "x = %d, y = %d, width = %d, height = %d, count = %d, pending = %d\n",
	    exposeEvent->x, exposeEvent->y,
	    exposeEvent->width, exposeEvent->height,
	    exposeEvent->count, XPending(xwd->display));

/* Handle expose */
/* If we have anything overlaid (like crosshairs), we need to refresh the */
/* entire plot in order to have a predictable outcome.  In this case we */
/* need to first clear window.  Otherwise it's better to not clear it, for a */
/* smoother redraw (unobscured regions appear to stay the same). */

    if (dev->drawing_xhairs) {
	XClearWindow(xwd->display, dev->window);
	ExposeCmd(pls, NULL);
	UpdateXhairs(pls);
	redrawn = 1;
    } else {
      pldis.x      = exposeEvent->x;
      pldis.y      = exposeEvent->y;
      pldis.width  = exposeEvent->width;
      pldis.height = exposeEvent->height;

      ExposeCmd(pls, &pldis);
      redrawn = ! dev->write_to_pixmap;
    }

/* If entire plot was redrawn, remove extraneous events from the queue */

    if (redrawn)
	while (XCheckWindowEvent(xwd->display, dev->window,
				 ExposureMask | StructureNotifyMask, event));
}

/*--------------------------------------------------------------------------*\
 * ResizeEH()
 *
 * Event handler routine for resize events.
 * Front end to ResizeCmd() to deal with wierdnesses of Xlib.
\*--------------------------------------------------------------------------*/

static void
ResizeEH(PLStream *pls, XEvent *event)
{
    XwDev *dev = (XwDev *) pls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;
    XConfigureEvent *configEvent = (XConfigureEvent *) event;
    PLDisplay pldis;

    dbug_enter("ResizeEH");

    pldis.width  = configEvent->width;
    pldis.height = configEvent->height;

/* Only need to resize if size is actually changed */

    if (pldis.width == dev->width && pldis.height == dev->height)
	return;

    pldebug("ResizeEH",
	    "x = %d, y = %d, pending = %d\n",
	    configEvent->width, configEvent->height, XPending(xwd->display));

/* Handle resize */

    ResizeCmd(pls, &pldis);
    if (dev->drawing_xhairs) {
	UpdateXhairs(pls);
    }

/* Remove extraneous Expose and ConfigureNotify events from the event queue */
/* Exposes do not need to be handled since we've redrawn the whole plot */

    XFlush(xwd->display);
    while (XCheckWindowEvent(xwd->display, dev->window,
			     ExposureMask | StructureNotifyMask, event));
}

/*--------------------------------------------------------------------------*\
 * ExposeCmd()
 *
 * Event handler routine for expose events.
 * These are "pure" exposures (no resize), so don't need to clear window.
\*--------------------------------------------------------------------------*/

static void
ExposeCmd(PLStream *pls, PLDisplay *pldis)
{
    XwDev *dev = (XwDev *) pls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;
    int x, y, width, height;

    dbug_enter("ExposeCmd");

/* Return if plD_init_xw hasn't been called yet */

    if (dev == NULL) {
	plwarn("ExposeCmd: Illegal call -- driver uninitialized");
	return;
    }

/* Exposed area.  If unspecified, the entire window is used. */

    if (pldis == NULL) {
	x      = 0;
	y      = 0;
	width  = dev->width;
	height = dev->height;
    }
    else {
	x      = pldis->x;
	y      = pldis->y;
	width  = pldis->width;
	height = pldis->height;
    }

/* Usual case: refresh window from pixmap */
/* DEBUG option: draws rectangle around refreshed region */

    XSync(xwd->display, 0);
    if (dev->write_to_pixmap) {
	XCopyArea(xwd->display, dev->pixmap, dev->window, dev->gc,
		  x, y, width, height, x, y);
	XSync(xwd->display, 0);
#ifdef DEBUG
	if (pls->debug) {
	    XPoint pts[5];
	    int xx0 = x, xx1 = x+width, yy0 = y, yy1 = y+height;
	    pts[0].x = xx0; pts[0].y = yy0;
	    pts[1].x = xx1; pts[1].y = yy0;
	    pts[2].x = xx1; pts[2].y = yy1;
	    pts[3].x = xx0; pts[3].y = yy1;
	    pts[4].x = xx0; pts[4].y = yy0;

	    XDrawLines(xwd->display, dev->window, dev->gc, pts, 5,
		       CoordModeOrigin);
	}
#endif
    }
    else {
	plRemakePlot(pls);
	XFlush(xwd->display);
    }
}

/*--------------------------------------------------------------------------*\
 * ResizeCmd()
 *
 * Event handler routine for resize events.
\*--------------------------------------------------------------------------*/

static void
ResizeCmd(PLStream *pls, PLDisplay *pldis)
{
    XwDev *dev = (XwDev *) pls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;
    int write_to_window = dev->write_to_window;

    dbug_enter("ResizeCmd");

/* Return if plD_init_xw hasn't been called yet */

    if (dev == NULL) {
	plwarn("ResizeCmd: Illegal call -- driver uninitialized");
	return;
    }

/* Return if pointer to window not specified. */

    if (pldis == NULL) {
	plwarn("ResizeCmd: Illegal call -- window pointer uninitialized");
	return;
    }

/* Reset current window bounds */

    dev->width  = pldis->width;
    dev->height = pldis->height;

    dev->xscale = dev->width  / (double) dev->init_width;
    dev->yscale = dev->height / (double) dev->init_height;

    dev->xscale = dev->xscale * dev->xscale_init;
    dev->yscale = dev->yscale * dev->yscale_init;

#if PHYSICAL
    {
	PLFLT pxlx = DPMM/dev->xscale;
	PLFLT pxly = DPMM/dev->yscale;
	plP_setpxl(pxlx, pxly);
    }
#endif

/* Note: the following order MUST be obeyed -- if you instead redraw into
 * the window and then copy it to the pixmap, off-screen parts of the window
 * may contain garbage which is then transferred to the pixmap (and thus
 * will not go away after an expose).
 */

/* Resize pixmap using new dimensions */

    if (dev->write_to_pixmap) {
	dev->write_to_window = 0;
	XFreePixmap(xwd->display, dev->pixmap);
	CreatePixmap(pls);
    }

/* This allows an external agent to take over the redraw */
    if (pls->ext_resize_draw) return;

/* Initialize & redraw (to pixmap, if available). */

    plD_bop_xw(pls);
    plRemakePlot(pls);
    XSync(xwd->display, 0);

/* If pixmap available, fake an expose */

    if (dev->write_to_pixmap) {
	dev->write_to_window = write_to_window;
	XCopyArea(xwd->display, dev->pixmap, dev->window, dev->gc, 0, 0,
		  dev->width, dev->height, 0, 0);
	XSync(xwd->display, 0);
    }
}

/*--------------------------------------------------------------------------*\
 * ConfigBufferingCmd()
 *
 * Allows a widget to manipulate the double buffering support in the
 * xwin dirver.
\*--------------------------------------------------------------------------*/

static void ConfigBufferingCmd( PLStream *pls, PLBufferingCB *ptr )
{
    XwDev *dev = (XwDev *) pls->dev;

    switch (ptr->cmd) {

    case PLESC_DOUBLEBUFFERING_ENABLE:
	dev->write_to_window = 0;
	pls->db = 1;
	break;

    case PLESC_DOUBLEBUFFERING_DISABLE:
	dev->write_to_window = 1;
	pls->db = 0;
	break;

    case PLESC_DOUBLEBUFFERING_QUERY:
	ptr->result = pls->db;
	break;

    default:
	printf( "Unrecognized buffering request ignored.\n" );
	break;
    }
}

/*--------------------------------------------------------------------------*\
 * RedrawCmd()
 *
 * Handles page redraw without resize (pixmap does not get reallocated).
 * Calling this makes sure all necessary housekeeping gets done.
\*--------------------------------------------------------------------------*/

static void
RedrawCmd(PLStream *pls)
{
    XwDev *dev = (XwDev *) pls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;
    int write_to_window = dev->write_to_window;

    dbug_enter("RedrawCmd");

/* Return if plD_init_xw hasn't been called yet */

    if (dev == NULL) {
	plwarn("RedrawCmd: Illegal call -- driver uninitialized");
	return;
    }

/* Initialize & redraw (to pixmap, if available). */

    if (dev->write_to_pixmap)
	dev->write_to_window = 0;

    plD_bop_xw(pls);
    plRemakePlot(pls);
    XSync(xwd->display, 0);

    dev->write_to_window = write_to_window;

/* If pixmap available, fake an expose */

    if (dev->write_to_pixmap) {
	XCopyArea(xwd->display, dev->pixmap, dev->window, dev->gc, 0, 0,
		  dev->width, dev->height, 0, 0);
	XSync(xwd->display, 0);
    }
}

/*--------------------------------------------------------------------------*\
 * CreatePixmapErrorHandler()
 *
 * Error handler used in CreatePixmap() to catch errors in allocating
 * storage for pixmap.  This way we can nicely substitute redraws for
 * pixmap copies if the server has insufficient memory.
\*--------------------------------------------------------------------------*/

static unsigned char CreatePixmapStatus;

static int
CreatePixmapErrorHandler(Display *display, XErrorEvent *error)
{
    CreatePixmapStatus = error->error_code;
    if (error->error_code != BadAlloc) {
	char buffer[256];
	XGetErrorText(display, error->error_code, buffer, 256);
	fprintf(stderr, "Error in XCreatePixmap: %s.\n", buffer);
    }
    return 1;
}

/*--------------------------------------------------------------------------*\
 * CreatePixmap()
 *
 * This routine creates a pixmap, doing error trapping in case there
 * isn't enough memory on the server.
\*--------------------------------------------------------------------------*/

static void
CreatePixmap(PLStream *pls)
{
    XwDev *dev = (XwDev *) pls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;

    int (*oldErrorHandler)(Display*, XErrorEvent*);

    oldErrorHandler = XSetErrorHandler(CreatePixmapErrorHandler);

    CreatePixmapStatus = Success;
    pldebug("CreatePixmap",
	    "creating pixmap: width = %d, height = %d, depth = %d\n",
	    dev->width, dev->height, xwd->depth);

    dev->pixmap = XCreatePixmap(xwd->display, dev->window,
				dev->width, dev->height, xwd->depth);
    XSync(xwd->display, 0);
    if (CreatePixmapStatus != Success) {
	dev->write_to_pixmap = 0;
	dev->write_to_window = 1;
	pls->db = 0;
	fprintf(stderr, "\n\
Warning: pixmap could not be allocated (insufficient memory on server).\n\
Driver will redraw the entire plot to handle expose events.\n");
    }

    XSetErrorHandler(oldErrorHandler);
}

/*--------------------------------------------------------------------------*\
 * GetVisual()
 *
 * Get visual info.  In order to safely use a visual other than that of
 * the parent (which hopefully is that returned by DefaultVisual), you
 * must first find (using XGetRGBColormaps) or create a colormap matching
 * this visual and then set the colormap window attribute in the
 * XCreateWindow attributes and valuemask arguments.  I don't do this
 * right now, so this is turned off by default.
\*--------------------------------------------------------------------------*/

static void
GetVisual(PLStream *pls)
{
    XwDev *dev = (XwDev *) pls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;
    int visuals_matched = 0;

    dbug_enter("GetVisual");

    if (!defaultvisual)
    {
	XVisualInfo vTemplate, *visualList;

/* Try for an 8 plane display, if unavailable go for the default */

	vTemplate.screen = xwd->screen;
	vTemplate.depth = 8;

	visualList = XGetVisualInfo( xwd->display,
				     VisualScreenMask | VisualDepthMask,
				     &vTemplate, &visuals_matched );

#ifdef HACK_STATICCOLOR
	if (visuals_matched) {
	    int i, found = 0;
	    printf( "visuals_matched = %d\n", visuals_matched );
	    for( i=0; i < visuals_matched && !found; i++ ) {
		Visual *v = visualList[i].visual;
		printf( "Checking visual %d: ", i );
		switch( v->class ) {
		case PseudoColor:
		    printf( "PseudoColor\n" );
		    break;
		case GrayScale:
		    printf( "GrayScale\n" );
		    break;
		case DirectColor:
		    printf( "DirectColor\n" );
		    break;
		case TrueColor:
		    printf( "TrueColor\n" );
		    break;
		case StaticColor:
		    printf( "StaticColor\n" );
		    break;
		case StaticGray:
		    printf( "StaticGray\n" );
		    break;
		default:
		    printf( "Unknown.\n" );
		    break;
		}
		if (v->class == StaticColor) {
		    xwd->visual = v;
		    xwd->depth = visualList[i].depth;
		    found = 1;
		}
	    }
	    if (!found) {
		printf( "Unable to get a StaticColor visual.\n" );
		exit(1);
	    }
	    printf( "Found StaticColor visual, depth=%d\n", xwd->depth );
	}
#else
	if (visuals_matched) {
	    xwd->visual = visualList->visual;	/* Choose first match. */
	    xwd->depth = vTemplate.depth;
	}
#endif /* HACK_STATICCOLOR */
    }

    if ( ! visuals_matched) {
	xwd->visual = DefaultVisual( xwd->display, xwd->screen );
	xwd->depth = DefaultDepth( xwd->display, xwd->screen );
    }

/* Check to see if we expect to be able to allocate r/w color cells. */

    switch(xwd->visual->class) {
    case TrueColor:
    case StaticColor:
    case StaticGray:
	xwd->rw_cmap = 0;
	break;
    default:
	xwd->rw_cmap = 1;
    }

/*xwd->rw_cmap = 0;*/ /* debugging hack. */

/* Just for kicks, see what kind of visual we got. */

    if (pls->verbose) {
	fprintf( stderr, "XVisual class == " );
	switch(xwd->visual->class) {
	case PseudoColor:
	    fprintf( stderr, "PseudoColor\n" );
	    break;
	case GrayScale:
	    fprintf( stderr, "GrayScale\n" );
	    break;
	case DirectColor:
	    fprintf( stderr, "DirectColor\n" );
	    break;
	case TrueColor:
	    fprintf( stderr, "TrueColor\n" );
	    break;
	case StaticColor:
	    fprintf( stderr, "StaticColor\n" );
	    break;
	case StaticGray:
	    fprintf( stderr, "StaticGray\n" );
	    break;
	default:
	    fprintf( stderr, "Unknown.\n" );
	    break;
	}
	fprintf( stderr, "xwd->rw_cmap = %d\n", xwd->rw_cmap );
    }
}

/*--------------------------------------------------------------------------*\
 * AllocBGFG()
 *
 * Allocate background & foreground colors.  If possible, I choose pixel
 * values such that the fg pixel is the xor of the bg pixel, to make
 * rubber-banding easy to see.
\*--------------------------------------------------------------------------*/

static void
AllocBGFG(PLStream *pls)
{
    XwDev *dev = (XwDev *) pls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;

    int i, j, npixels;
    unsigned long plane_masks[1], pixels[RWMAP_MAX_COLORS];

    dbug_enter("AllocBGFG");

/* If not on a color system, just return */
    if ( ! xwd->color)
	return;

    if ( xwd->rw_cmap &&
     /* r/w color maps */
	 XAllocColorCells(xwd->display, xwd->map, False,
			  plane_masks, 0, pixels, 1) )
    {
    /* background */
	xwd->cmap0[0].pixel = pixels[0];
    }
    else {
    /* r/o color maps */
	xwd->cmap0[0].pixel = BlackPixel(xwd->display, xwd->screen);
	xwd->fgcolor.pixel = WhitePixel(xwd->display, xwd->screen);
	if ( xwd->rw_cmap && pls->verbose )
	    fprintf( stderr, "Downgrading to r/o cmap.\n" );
	xwd->rw_cmap = 0;
	return;
    }

/* Allocate as many colors as we can */

    npixels = RWMAP_MAX_COLORS;
    for (;;) {
	if (XAllocColorCells(xwd->display, xwd->map, False,
			     plane_masks, 0, pixels, npixels))
	    break;
	npixels--;
	if (npixels == 0)
	    break;
    }

/* Find the color with pixel = xor of the bg color pixel. */
/* If a match isn't found, the last pixel allocated is used. */

    for (i = 0; i < npixels-1; i++) {
	if (pixels[i] == (~xwd->cmap0[0].pixel & 0xFF))
	    break;
    }

/* Use this color cell for our foreground color.  Then free the rest. */

    xwd->fgcolor.pixel = pixels[i];
    for (j = 0; j < npixels; j++) {
	if (j != i)
	    XFreeColors(xwd->display, xwd->map, &pixels[j], 1, 0);
    }
}

/*--------------------------------------------------------------------------*\
 * SetBGFG()
 *
 * Set background & foreground colors.  Foreground over background should
 * have high contrast.
\*--------------------------------------------------------------------------*/

static void
SetBGFG(PLStream *pls)
{
    XwDev *dev = (XwDev *) pls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;

    PLColor fgcolor;
    int gslevbg, gslevfg;

    dbug_enter("SetBGFG");

/*
 * Set background color.
 *
 * Background defaults to black on color screens, white on grayscale (many
 * grayscale monitors have poor contrast, and black-on-white looks better).
 */

    if ( ! xwd->color) {
	pls->cmap0[0].r = pls->cmap0[0].g = pls->cmap0[0].b = 0xFF;
    }
    gslevbg = ((long) pls->cmap0[0].r +
	       (long) pls->cmap0[0].g +
	       (long) pls->cmap0[0].b) / 3;

    PLColor_to_XColor(&pls->cmap0[0], &xwd->cmap0[0]);

/*
 * Set foreground color.
 *
 * Used for grayscale output, since otherwise the plots can become nearly
 * unreadable (i.e. if colors get mapped onto grayscale values).  In this
 * case it becomes the grayscale level for all draws, and is taken to be
 * black if the background is light, and white if the background is dark.
 * Note that white/black allocations never fail.
 */

    if (gslevbg > 0x7F)
	gslevfg = 0;
    else
	gslevfg = 0xFF;

    fgcolor.r = fgcolor.g = fgcolor.b = gslevfg;

    PLColor_to_XColor(&fgcolor, &xwd->fgcolor);

/* Now store */

    if (xwd->rw_cmap && xwd->color) {
	XStoreColor(xwd->display, xwd->map, &xwd->fgcolor);
	XStoreColor(xwd->display, xwd->map, &xwd->cmap0[0]);
    } else {
	XAllocColor(xwd->display, xwd->map, &xwd->cmap0[0]);
	XAllocColor(xwd->display, xwd->map, &xwd->fgcolor);
    }
}

/*--------------------------------------------------------------------------*\
 * InitColors()
 *
 * Does all color initialization.
\*--------------------------------------------------------------------------*/

static void
InitColors(PLStream *pls)
{
    XwDev *dev = (XwDev *) pls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;

    dbug_enter("InitColors");

/* Allocate and initialize color maps. */
/* Defer cmap1 allocation until it's actually used */

    if (xwd->color) {
	if (plplot_ccmap) {
	    AllocCustomMap(pls);
	}
	else {
	    AllocCmap0(pls);
	}
    }
}

/*--------------------------------------------------------------------------*\
 * AllocCustomMap()
 *
 * Initializes custom color map and all the cruft that goes with it.
 *
 * Assuming all color X displays do 256 colors, the breakdown is as follows:
 *
 * CCMAP_XWM_COLORS
 *	Number of low "pixel" values to copy.  These are typically allocated
 *	first, thus are in use by the window manager. I copy them to reduce
 *	flicker.

 *
 * RWMAP_CMAP1_COLORS
 *	Color map 1 entries.  There should be as many as practical available
 *	for smooth shading.  On the order of 50-100 is pretty reasonable.  You
 *	don't really need all 256, especially if all you're going to do is to
 *	print it to postscript (which doesn't have any intrinsic limitation on
 *	the number of colors).
 *
 * It's important to leave some extra colors unallocated for Tk.  In
 * particular the palette tools require a fair amount.  I recommend leaving
 * at least 40 or so free.
\*--------------------------------------------------------------------------*/

static void
AllocCustomMap(PLStream *pls)
{
    XwDev *dev = (XwDev *) pls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;

    XColor xwm_colors[RWMAP_MAX_COLORS];
    int i, npixels;
    unsigned long plane_masks[1], pixels[RWMAP_MAX_COLORS];

    dbug_enter("AllocCustomMap");

/* Determine current default colors */

    for (i = 0; i < RWMAP_MAX_COLORS; i++) {
	xwm_colors[i].pixel = i;
    }
    XQueryColors(xwd->display, xwd->map, xwm_colors, RWMAP_MAX_COLORS);

/* Allocate cmap0 colors in the default colormap.
 * The custom cmap0 colors are later stored at the same pixel values.
 * This is a really cool trick to reduce the flicker when changing colormaps.
 */

    AllocCmap0(pls);
    XAllocColor(xwd->display, xwd->map, &xwd->fgcolor);

/* Create new color map */

    xwd->map = XCreateColormap( xwd->display, DefaultRootWindow(xwd->display),
				xwd->visual, AllocNone );

/* Now allocate all colors so we can fill the ones we want to copy */

    npixels = RWMAP_MAX_COLORS;
    for (;;) {
	if (XAllocColorCells(xwd->display, xwd->map, False,
			     plane_masks, 0, pixels, npixels))
	    break;
	npixels--;
	if (npixels == 0)
	    plexit("couldn't allocate any colors");
    }

/* Fill the low colors since those are in use by the window manager */

    for (i = 0; i < CCMAP_XWM_COLORS; i++) {
	XStoreColor(xwd->display, xwd->map, &xwm_colors[i]);
	pixels[xwm_colors[i].pixel] = 0;
    }

/* Fill the ones we will use in cmap0 */

    for (i = 0; i < xwd->ncol0; i++) {
	XStoreColor(xwd->display, xwd->map, &xwd->cmap0[i]);
	pixels[xwd->cmap0[i].pixel] = 0;
    }

/* Finally, if the colormap was saved by an external agent, see if there are
 * any differences from the current default map and save those!  A very cool
 * (or sick, depending on how you look at it) trick to get over some X and
 * Tk limitations.
 */

    if (sxwm_colors_set) {
	for (i = 0; i < RWMAP_MAX_COLORS; i++) {
	    if ((xwm_colors[i].red != sxwm_colors[i].red) ||
		(xwm_colors[i].green != sxwm_colors[i].green) ||
		(xwm_colors[i].blue != sxwm_colors[i].blue) ) {

		if (pixels[i] != 0) {
		    XStoreColor(xwd->display, xwd->map, &xwm_colors[i]);
		    pixels[i] = 0;
		}
	    }
	}
    }

/* Now free the ones we're not interested in */

    for (i = 0; i < npixels; i++) {
	if (pixels[i] != 0)
	    XFreeColors(xwd->display, xwd->map, &pixels[i], 1, 0);
    }

/* Allocate colors in cmap 1 */

    AllocCmap1(pls);
}

/*--------------------------------------------------------------------------*\
 * AllocCmap0()
 *
 * Allocate & initialize cmap0 entries.
\*--------------------------------------------------------------------------*/

static void
AllocCmap0(PLStream *pls)
{
    XwDev *dev = (XwDev *) pls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;
    int i;

    dbug_enter("AllocCmap0");

/* Free all previous colors.  This should work for both rw & ro colormaps */ 
    for (i = 1; i < xwd->ncol0; i++) {
        unsigned long pixel = xwd->cmap0[i].pixel;
        XFreeColors(xwd->display, xwd->map, &pixel, 1, 0);
    }

/* If the number of colors increased, need to allocate enough space for them */
    if ( pls->ncol0 > xwd->ncol0_alloc ) {
        xwd->ncol0_alloc = pls->ncol0;
        xwd->cmap0 = (XColor *)
            realloc( xwd->cmap0, (size_t) pls->ncol0 * sizeof(XColor) );
        if (xwd->cmap0 == 0)
            plexit("couldn't allocate space for cmap0 colors");
    }

    if (xwd->rw_cmap) {
        int npixels;
        unsigned long plane_masks[1], pixels[RWMAP_MAX_COLORS];

    /* Allocate and assign colors in cmap 0 */

	npixels = pls->ncol0-1;
	for (;;) {
	    if (XAllocColorCells(xwd->display, xwd->map, False,
				 plane_masks, 0, &pixels[1], npixels))
		break;
	    npixels--;
	    if (npixels == 0)
		plexit("couldn't allocate any colors");
	}

	xwd->ncol0 = npixels+1;
	for (i = 1; i < xwd->ncol0; i++) {
	    xwd->cmap0[i].pixel = pixels[i];
	}

	StoreCmap0(pls);
    }
    else {
	if (pls->verbose)
	    fprintf( stderr, "Attempting to allocate r/o colors in cmap0.\n" );

	for (i = 1; i < pls->ncol0; i++) {
	    int r;
	    XColor c;
	    PLColor_to_XColor(&pls->cmap0[i], &c);
	    r = XAllocColor( xwd->display, xwd->map, &c );
	    if (pls->verbose)
		fprintf( stderr, "i=%d, r=%d, pixel=%d\n", i, r, (int) c.pixel );
	    if ( r ) {
		xwd->cmap0[i] = c;
		xwd->cmap0[i].pixel = c.pixel; /* needed for deallocation */
            }
            else
            {
                XColor screen_def, exact_def;

                if (pls->verbose)
                    fprintf( stderr,
                             "color alloc failed, trying by name: %s.\n",
                             pls->cmap0[i].name );

            /* Hmm, didn't work, try another approach. */
                r = XAllocNamedColor( xwd->display, xwd->map,
                                      pls->cmap0[i].name,
                                      &screen_def, &exact_def );

/*                 xwd->cmap0[i] = screen_def; */

                if (r) {
                    if (pls->verbose)
                        fprintf( stderr, "yes, got a color by name.\n" );

                    xwd->cmap0[i] = screen_def;
                    xwd->cmap0[i].pixel = screen_def.pixel;
                } 
                else {
                    r = XAllocNamedColor( xwd->display, xwd->map,
                                          "white",
                                          &screen_def, &exact_def );
                    if (r) {
                        xwd->cmap0[i] = screen_def;
                        xwd->cmap0[i].pixel = screen_def.pixel;
                    }
                    else
                        printf( "Can't find white?! Giving up...\n" );
                }
            }
	}
	xwd->ncol0 = i;

	if (pls->verbose)
	    fprintf( stderr, "Allocated %d colors in cmap0.\n", xwd->ncol0 );
    }
}

/*--------------------------------------------------------------------------*\
 * AllocCmap1()
 *
 * Allocate & initialize cmap1 entries.
\*--------------------------------------------------------------------------*/

static void
AllocCmap1(PLStream *pls)
{
    XwDev *dev = (XwDev *) pls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;

    int i, j, npixels;
    unsigned long plane_masks[1], pixels[RWMAP_MAX_COLORS];

    dbug_enter("AllocCmap1");

    if (xwd->rw_cmap) {

	if (pls->verbose)
	    fprintf( stderr, "Attempting to allocate r/w colors in cmap1.\n" );

    /* If using the default color map, must severely limit number of colors
       otherwise TK won't have enough. */

	npixels = MAX(2, MIN(RWMAP_CMAP1_COLORS, pls->ncol1));
	for (;;) {
	    if (XAllocColorCells(xwd->display, xwd->map, False,
				 plane_masks, 0, pixels, npixels))
		break;
	    npixels--;
	    if (npixels == 0)
		break;
	}

	if (npixels < 2) {
	    xwd->ncol1 = -1;
	    fprintf(stderr, "Warning: unable to allocate sufficient colors in cmap1.\n");
	    return;
	}

        xwd->ncol1 = npixels;
        if (pls->verbose)
            fprintf(stderr, "AllocCmap1 (xwin.c): Allocated %d colors in cmap1.\n", npixels);

    /* Allocate space if it hasn't been done yet */
        if ( !xwd->cmap1 ) {
            xwd->ncol1_alloc = xwd->ncol1;
            xwd->cmap1 = (XColor *) calloc(xwd->ncol1, (size_t) sizeof(XColor));
            if ( !xwd->cmap1 )
                plexit("couldn't allocate space for cmap1 colors");
        }

    /* Don't assign pixels sequentially, to avoid strange problems with xor
       GC's.  Skipping by 2 seems to do the job best. */

	for (j = i = 0; i < xwd->ncol1; i++) {
	    while (pixels[j] == 0) j++;

	    xwd->cmap1[i].pixel = pixels[j];
	    pixels[j] = 0;

	    j += 2;
	    if (j >= xwd->ncol1) j = 0;
	}

	StoreCmap1(pls);
    }
    else {
	int ii, r, ncolors;
	PLColor cmap1color;
	XColor xcol;

	if (pls->verbose)
	    fprintf( stderr, "Attempting to allocate r/o colors in cmap1.\n" );

	switch(xwd->visual->class) {
	case TrueColor:
	    ncolors = TC_CMAP1_COLORS;
	    break;
	default:
	    ncolors = ROMAP_CMAP1_COLORS;
	}

    /* Allocate space if it hasn't been done yet */
        if ( !xwd->cmap1 ) {
            xwd->ncol1_alloc = ncolors;
            xwd->cmap1 = (XColor *) calloc(ncolors, (size_t) sizeof(XColor));
            if ( !xwd->cmap1 )
                plexit("couldn't allocate space for cmap1 colors");
        }

	for( ii = 0; ii < ncolors; ii++ ) {
	    plcol_interp( pls, &cmap1color, ii, ncolors );
	    PLColor_to_XColor( &cmap1color, &xcol );

	    r = XAllocColor( xwd->display, xwd->map, &xcol );
	    if (pls->verbose)
		fprintf(stderr, "i=%d, r=%d, pixel=%d\n", ii, r, (int) xcol.pixel );
	    if ( r )
		xwd->cmap1[ii] = xcol;
	    else
		break;

	}
	if (ii < ncolors) {
	    xwd->ncol1 = -1;
	    fprintf(stderr,
		    "Warning: unable to allocate sufficient colors in cmap1\n");
	    return;
	}
	else {
	    xwd->ncol1 = ncolors;
	    if (pls->verbose)
		fprintf(stderr, "AllocCmap1 (xwin.c): Allocated %d colors in cmap1\n", ncolors );
	}
    }
}

/*--------------------------------------------------------------------------*\
 * StoreCmap0()
 *
 * Stores cmap 0 entries in X-server colormap.
\*--------------------------------------------------------------------------*/

static void
StoreCmap0(PLStream *pls)
{
    XwDev *dev = (XwDev *) pls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;
    int i;

    if ( ! xwd->color)
	return;

    for (i = 1; i < xwd->ncol0; i++) {
	PLColor_to_XColor(&pls->cmap0[i], &xwd->cmap0[i]);
	if (xwd->rw_cmap)
	  XStoreColor(xwd->display, xwd->map, &xwd->cmap0[i]);
	else
	  XAllocColor( xwd->display, xwd->map, &xwd->cmap0[i]);
    }
}

/*--------------------------------------------------------------------------*\
 * StoreCmap1()
 *
 * Stores cmap 1 entries in X-server colormap.
\*--------------------------------------------------------------------------*/

static void
StoreCmap1(PLStream *pls)
{
    XwDev *dev = (XwDev *) pls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;

    PLColor cmap1color;
    int i;

    if ( ! xwd->color)
	return;

    for (i = 0; i < xwd->ncol1; i++) {
	plcol_interp(pls, &cmap1color, i, xwd->ncol1);
	PLColor_to_XColor(&cmap1color, &xwd->cmap1[i]);
	if (xwd->rw_cmap)
	  XStoreColor(xwd->display, xwd->map, &xwd->cmap1[i]);
	else
	  XAllocColor(xwd->display, xwd->map, &xwd->cmap1[i]);
    }
}

/*--------------------------------------------------------------------------*\
 * PLColor_to_XColor()
 *
 * Copies the supplied PLColor to an XColor, padding with bits as necessary
 * (a PLColor uses 8 bits for color storage, while an XColor uses 16 bits).
 * The argument types follow the same order as in the function name.
\*--------------------------------------------------------------------------*/

#define ToXColor(a) (((0xFF & (a)) << 8) | (a))
#define ToPLColor(a) (((U_LONG) a) >> 8)

static void
PLColor_to_XColor(PLColor *plcolor, XColor *xcolor)
{
    xcolor->red   = ToXColor(plcolor->r);
    xcolor->green = ToXColor(plcolor->g);
    xcolor->blue  = ToXColor(plcolor->b);
    xcolor->flags = DoRed | DoGreen | DoBlue;
}

/*--------------------------------------------------------------------------*\
 * PLColor_from_XColor()
 *
 * Copies the supplied XColor to a PLColor, stripping off bits as
 * necessary.  See the previous routine for more info.
\*--------------------------------------------------------------------------*/

static void
PLColor_from_XColor(PLColor *plcolor, XColor *xcolor)
{
    plcolor->r = ToPLColor(xcolor->red);
    plcolor->g = ToPLColor(xcolor->green);
    plcolor->b = ToPLColor(xcolor->blue);
}

/*--------------------------------------------------------------------------*\
 * AreWeGrayscale(Display *display)
 *
 * Determines if we're using a monochrome or grayscale device.
 * gmf 11-8-91; Courtesy of Paul Martz of Evans and Sutherland.
 * Altered Andrew Ross 26-01-2004 to fix memory leak.
\*--------------------------------------------------------------------------*/

static int
AreWeGrayscale(Display *display)
{
#if defined(__cplusplus) || defined(c_plusplus)
#define THING c_class
#else
#define THING class
#endif

    XVisualInfo *visuals;
    int nitems, i, igray;

    /* get a list of info on the visuals available */
    visuals = XGetVisualInfo(display, 0, NULL, &nitems);

    igray = 1;
    /* check the list looking for non-monochrome visual classes */
    for (i = 0; i < nitems; i++)
	if ((visuals[i].THING != GrayScale) &&
	    (visuals[i].THING != StaticGray)) {
		igray = 0;
		break;
	}

    XFree(visuals);
    /* if igray = 1 only StaticGray and GrayScale classes available */
    return igray;
}

#ifdef DUMMY
/*--------------------------------------------------------------------------*\
 * SaveColormap()  **** DUMMY, NOT USED ANYMORE ***
 *
 * Saves RGB components of given colormap.
 * Used in an ugly hack to get past some X11R5 and TK limitations.
 * This isn't guaranteed to work under all circumstances, but hopefully
 * in the future there will be a nicer way to accomplish the same thing.
 *
 * Note: I tried using XCopyColormapAndFree to do the same thing, but under
 * HPUX 9.01/VUE/X11R5 at least it doesn't preserve the previous read-only
 * color cell allocations made by Tk.  Is this a bug?  Have to look at the
 * source to find out.
\*--------------------------------------------------------------------------*/

static void
SaveColormap(Display *display, Colormap colormap)
{
    int i;

    if ( ! plplot_ccmap)
	return;

    sxwm_colors_set = 1;
    for (i = 0; i < RWMAP_MAX_COLORS; i++) {
	sxwm_colors[i].pixel = i;
    }
    XQueryColors(display, colormap, sxwm_colors, RWMAP_MAX_COLORS);
/*
    printf("\nAt startup, default colors are: \n\n");
    for (i = 0; i < RWMAP_MAX_COLORS; i++) {
	printf(" i: %d,  pixel: %d,  r: %d,  g: %d,  b: %d\n",
	       i, sxwm_colors[i].pixel,
	       sxwm_colors[i].red, sxwm_colors[i].green, sxwm_colors[i].blue);
    }
 */
}
#endif

/*--------------------------------------------------------------------------*\
 * GetImageErrorHandler()
 *
 * Error handler used in XGetImage() to catch errors when pixmap or window
 * are not completely viewable.
\*--------------------------------------------------------------------------*/

static int
GetImageErrorHandler(Display *display, XErrorEvent *error)
{
    if (error->error_code != BadMatch) {
	char buffer[256];
	XGetErrorText(display, error->error_code, buffer, 256);
	fprintf(stderr, "xwin: Error in XGetImage: %s.\n", buffer);
    }
    return 1;
}

/*--------------------------------------------------------------------------*\
 * DrawImage()
 *
 * Fill polygon described in points pls->dev_x[] and pls->dev_y[].
 * Only solid color fill supported.
\*--------------------------------------------------------------------------*/

static void
DrawImage(PLStream *pls)
{
    XwDev *dev = (XwDev *) pls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;
    XImage *ximg = NULL;
    XColor curcolor;
    PLINT xmin, xmax, ymin, ymax, icol1;

    int (*oldErrorHandler)(Display*, XErrorEvent*);

    float mlr, mtb;
    float blt, brt, brb, blb;
    float left, right;
    int kx, ky;
    int nx, ny, ix, iy;
    int i, corners[4], r[4];

    struct {
	float x, y;
    } Ppts[4];

    CheckForEvents(pls);

    xmin = dev->xscale * pls->imclxmin;
    xmax = dev->xscale * pls->imclxmax;
    ymin = dev->yscale * pls->imclymin;
    ymax = dev->yscale * pls->imclymax;

    nx = pls->dev_nptsX;
    ny = pls->dev_nptsY;

/* XGetImage() call fails if either the pixmap or window is not fully viewable! */
    oldErrorHandler = XSetErrorHandler(GetImageErrorHandler);

    XFlush(xwd->display);
    if (dev->write_to_pixmap)
	ximg = XGetImage( xwd->display, dev->pixmap, 0, 0, dev->width, dev->height,
			  AllPlanes, ZPixmap);

    if (dev->write_to_window)
	ximg = XGetImage( xwd->display, dev->window, 0, 0, dev->width, dev->height,
			  AllPlanes, ZPixmap);

    XSetErrorHandler(oldErrorHandler);

    if (ximg == NULL) {
	plabort("Can't get image, the window must be partly off-screen, move it to fit screen");
	return;
    }

    if (xwd->ncol1 == 0)
	AllocCmap1(pls);
    if (xwd->ncol1 < 2)
	return;

/* translate array for rotation */
    switch ((int)(pls->diorot - 4.*floor(pls->diorot/4.))) {
    case 0:
	r[0]=0; r[1]=1; r[2]=2; r[3]=3; break;
    case 1:
	r[0]=1; r[1]=2; r[2]=3; r[3]=0; break;
    case 2:
	r[0]=2; r[1]=3; r[2]=0; r[3]=1; break;
    case 3:
	r[0]=3; r[1]=0; r[2]=1; r[3]=2;
    }

  /* after rotation and coordinate translation, each fill
     lozangue will have coordinates (Ppts), slopes (m...)
     and y intercepts (b...):

           Ppts[3]
             /\
    mlr,blt /  \ mtb,brt
           /    \
   Ppts[0]<      > Ppts[2]
           \    /
    mtb,blt \  / mlr,brb
             \/
           Ppts[1]
  */

/* slope of left/right and top/bottom edges */
    mlr = (dev->yscale * (pls->dev_iy[1] - pls->dev_iy[0])) /
	(dev->xscale * (pls->dev_ix[1] - pls->dev_ix[0]));

    mtb = (dev->yscale * (pls->dev_iy[ny] - pls->dev_iy[0])) /
	(dev->xscale * (pls->dev_ix[ny] - pls->dev_ix[0]));

    for(ix = 0; ix < nx-1; ix++) {
	for(iy = 0; iy < ny-1; iy++) {
	    corners[0] = ix*ny+iy; /* [ix][iy] */
	    corners[1] = (ix+1)*ny+iy; /* [ix+1][iy] */
	    corners[2] = (ix+1)*ny+iy+1; /* [ix+1][iy+1] */
	    corners[3] = ix*ny+iy+1; /* [ix][iy+1] */

	    for (i=0; i<4; i++) {
		Ppts[i].x = dev->xscale * (pls->dev_ix[corners[r[i]]]);
		Ppts[i].y = dev->yscale * (pls->dev_iy[corners[r[i]]]);
	    }

	/* if any corner is inside the draw area */
	    if (Ppts[0].x >= xmin || Ppts[2].x <= xmax ||
		Ppts[1].y >= ymin || Ppts[3].y <= ymax) {

		Ppts[0].x = MAX(Ppts[0].x, xmin);
		Ppts[2].x = MIN(Ppts[2].x, xmax);
		Ppts[1].y = MAX(Ppts[1].y, ymin);
		Ppts[3].y = MIN(Ppts[3].y, ymax);

	    /* the Z array has size (nx-1)*(ny-1) */
		icol1 = pls->dev_z[ix*(ny-1)+iy];

	    /* only plot points within zmin/zmax range */
		if (icol1 < pls->dev_zmin || icol1 > pls->dev_zmax)
		    continue;

		icol1 = icol1/(float)USHRT_MAX * (xwd->ncol1-1);
		if (xwd->color)
		    curcolor = xwd->cmap1[icol1];
		else
		    curcolor = xwd->fgcolor;

	    /* Fill square between current and next points. */

	    /* If the fill area is a single dot, accelerate the fill. */
		if ( (fabs(Ppts[2].x - Ppts[0].x) == 1) &&
		     (fabs(Ppts[3].y - Ppts[1].y) == 1)) {
		    XPutPixel(ximg, Ppts[0].x, dev->height-1 - Ppts[0].y, curcolor.pixel);

		/* integer rotate, accelerate */
		} else if (pls->diorot == floor(pls->diorot)) {
		    for( ky = Ppts[1].y; ky < Ppts[3].y; ky++)
			for( kx = Ppts[0].x; kx < Ppts[2].x; kx++)
			    XPutPixel(ximg, kx, dev->height-1 - ky, curcolor.pixel);

		/* lozangue, scanline fill it */
		} else {

		/* y interception point of left/right top/bottom edges */
		    blt = Ppts[0].y - mlr * Ppts[0].x;
		    brb = Ppts[2].y - mlr * Ppts[2].x;

		    brt = Ppts[2].y - mtb * Ppts[2].x;
		    blb = Ppts[0].y - mtb * Ppts[0].x;

		    for( ky = Ppts[1].y; ky < Ppts[3].y; ky++) {
			left = MAX(((ky-blt)/mlr), ((ky-blb)/mtb));
			right = MIN(((ky-brt)/mtb), ((ky-brb)/mlr));
			for( kx = Ppts[0].x; kx < Ppts[2].x; kx++) {
			    if (kx >= rint(left) && kx <= rint(right)) {
				XPutPixel(ximg, kx, dev->height-1 - ky, curcolor.pixel);
			    }
			}
		    }
		}
	    }
	}
    }

    if (dev->write_to_pixmap)
	XPutImage( xwd->display, dev->pixmap, dev->gc, ximg, 0, 0, 0, 0, dev->width, dev->height);

    if (dev->write_to_window)
	XPutImage( xwd->display, dev->window, dev->gc, ximg, 0, 0,
		   0, 0, dev->width, dev->height);

    XDestroyImage(ximg);
}

static void
imageops(PLStream *pls, PLINT *ptr)
{
    XwDev *dev = (XwDev *) pls->dev;
    XwDisplay *xwd = (XwDisplay *) dev->xwd;

/* TODO: store/revert to/from previous state */

    switch (*ptr) {
    case ZEROW2D:
	dev->write_to_window = 0;
	break;

    case ONEW2D:
	dev->write_to_window = 1;
	break;

    case ZEROW2B:
	dev->write_to_pixmap = 0;
	break;

    case ONEW2B:
	XFlush(xwd->display);
	dev->write_to_pixmap = 1;
	break;
    }
}

#else
int
pldummy_xwin(void)
{
    return 0;
}

#endif				/* PLD_xwin */