summaryrefslogtreecommitdiff
path: root/Build/source/texk/xdvik/events.c
blob: 417e09d4b185dfc3ec7601542962d1040366ce3c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
/*======================================================================*\

Copyright (c) 1990-2004  Paul Vojta and others

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
PAUL VOJTA OR ANY OTHER AUTHOR OF THIS SOFTWARE BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

NOTE:
	xdvi is based on prior work, as noted in the modification history
	in xdvi.c.

\*========================================================================*/

#include "xdvi-config.h"

#ifdef STDC_HEADERS
# include <unistd.h>
# include <fcntl.h>
#endif
#include <signal.h>
#include <sys/file.h>	/* this defines FASYNC */
#ifdef HAVE_SYS_FCNTL_H
# include <sys/fcntl.h>  /* Or this might define FASYNC */
#endif
#include <sys/ioctl.h>	/* this defines SIOCSPGRP and FIOASYNC */
#include <sys/wait.h>	/* ignore HAVE_SYS_WAIT_H -- we always need WNOHANG */

#include "xdvi.h" /* this includes Xlib and Xutil are already included */
#include "xdvi-debug.h"


#ifndef MOTIF
#include <X11/Xaw/Form.h> /* for XtNresizable */
#endif

#include <setjmp.h>
#include <sys/time.h>	/* for gettimeofday */

#include <X11/IntrinsicP.h>

#include <X11/Xatom.h>
#include <X11/StringDefs.h>
#include <X11/Shell.h>	/* needed for def. of XtNiconX(??) */

#include "pagesel.h"
#include "filehist.h"
#include "special.h"
#include "psgs.h"


#include <errno.h>

#include <ctype.h>

#include "util.h"
#include "x_util.h"
#include "string-utils.h"
#include "print-dialog.h"
#include "search-dialog.h"
#include "sfSelFile.h"
#include "mag.h"
#include "help-window.h"
#include "message-window.h"
#include "dvi-draw.h"
#include "statusline.h"
#include "hypertex.h"
#include "dvi-init.h"
#include "Tip.h"
#include "browser.h"
#include "search-internal.h"
#include "my-snprintf.h"

#include "events.h"
#include "selection.h"
#include "encodings.h"
#include "pagehist.h"
#include "xm_colorsel.h"
#include "xm_toolbar.h"
#include "xaw_menu.h"
#include "xm_menu.h"
#include "xm_prefs.h"

#include "xm_prefs_appearance.h" /* for update_preferences_expert() */
#include "xm_prefs_fonts.h"	 /* for update_preferences_color() */
#include "xm_prefs_page.h"	 /* for update_preferences_shrink() */

#ifdef	X_NOT_STDC_ENV
extern int errno;
#endif /* X_NOT_STDC_ENV */

/* Linux prefers O_ASYNC over FASYNC; SGI IRIX does the opposite.  */
#if !defined(FASYNC) && defined(O_ASYNC)
# define FASYNC	O_ASYNC
#endif

#if !defined(FLAKY_SIGPOLL) && !HAVE_STREAMS && !defined(FASYNC)
# if !defined(SIOCSPGRP) || !defined(FIOASYNC)
#  define FLAKY_SIGPOLL	1
# endif
#endif

#ifndef FLAKY_SIGPOLL

# ifndef SIGPOLL
#  define SIGPOLL	SIGIO
# endif

# ifndef SA_RESTART
#  define SA_RESTART 0
# endif

# if HAVE_STREAMS
#  include <stropts.h>

#  ifndef S_RDNORM
#   define S_RDNORM S_INPUT
#  endif

#  ifndef S_RDBAND
#   define S_RDBAND  0
#  endif

#  ifndef S_HANGUP
#   define S_HANGUP  0
#  endif

#  ifndef S_WRNORM
#   define S_WRNORM  S_OUTPUT
#  endif
# endif /* HAVE_STREAMS */

#endif /* not FLAKY_SIGPOLL */

#if HAVE_SIGACTION && !defined SA_RESETHAND
# ifdef SA_ONESHOT
#  define SA_RESETHAND SA_ONESHOT
# else
#  undef HAVE_SIGACTION         /* Needed for Mac OS X < 10.2 (9/2002) */
# endif
#endif

#if HAVE_POLL
# include <poll.h>
#else
# if HAVE_SYS_SELECT_H
#  include <sys/select.h>
# else
#  if HAVE_SELECT_H
#   include <select.h>
#  endif
# endif
# define XIO_IN 1
# define XIO_OUT 2
#endif /* HAVE_POLL */

static sigset_t all_signals;

/*
 *	Interrupt system for receiving events.  The program sets a flag
 *	whenever an event comes in, so that at the proper time (i.e., when
 *	reading a new dvi item), we can check incoming events to see if we
 *	still want to go on printing this page.  This way, one can stop
 *	displaying a page if it is about to be erased anyway.  We try to read
 *	as many events as possible before doing anything and base the next
 *	action on all events read.
 *	Note that the Xlib and Xt routines are not reentrant, so the most we
 *	can do is set a flag in the interrupt routine and check it later.
 *	Also, sometimes the interrupts are not generated (some systems only
 *	guarantee that SIGIO is generated for terminal files, and on the system
 *	I use, the interrupts are not generated if I use "(xdvi foo &)" instead
 *	of "xdvi foo").  Therefore, there is also a mechanism to check the
 *	event queue every 70 drawing operations or so.  This mechanism is
 *	disabled if it turns out that the interrupts do work.
 *	For a fuller discussion of some of the above, see xlife in
 *	comp.sources.x.
 */

/*
 *	Signal flags
 */

/* This could be static volatile, but we want to avoid any optimizer bugs.  */
VOLATILE unsigned int sig_flags	= 0;

#define	SF_USR	1
#define	SF_ALRM	2
#define	SF_POLL	4
#define	SF_CHLD	8
#define	SF_TERM	16
#define	SF_SEGV	32

static void do_sigusr(void);
static void do_sigalrm(void);
static void do_sigpoll(void);
static void do_sigchld(void);
static void do_sigterm(void);
static void do_sigsegv(void);

/* these must be in the same order as SF_*.
   The higher flags have higher priority, since these are
   checked first when resolving flags_to_sigproc[sig_flags].

   Example: flag := SF_TERM | SF_CHLD = 24
   
   flags_to_sigproc[24] =>
       do_sigterm, which sets flag to 24 & ~SF_TERM == 8
   then, in next check:       
   flags_to_sigproc[8] =>
       do_sigchld, which sets flag 8 & ~SF_CHLD == 0.
 */
#define	SP0	do_sigusr
#define	SP1	do_sigalrm
#define	SP2	do_sigpoll
#define	SP3	do_sigchld
#define	SP4	do_sigterm
#define	SP5	do_sigsegv

typedef	void	(*signalproc)(void);

static const signalproc flags_to_sigproc[64] = {
    NULL,
    /* 1 */
    SP0,
    /* 2 - 3 */
    SP1, SP1,
    /* 4 - 7 */
    SP2, SP2, SP2, SP2,
    /* 8 - 15 */
    SP3, SP3, SP3, SP3, SP3, SP3, SP3, SP3,
    /* 16 - 31 */
    SP4, SP4, SP4, SP4, SP4, SP4, SP4, SP4,
    SP4, SP4, SP4, SP4, SP4, SP4, SP4, SP4,
    /* 32 - 63 */
    SP5, SP5, SP5, SP5, SP5, SP5, SP5, SP5,
    SP5, SP5, SP5, SP5, SP5, SP5, SP5, SP5,
    SP5, SP5, SP5, SP5, SP5, SP5, SP5, SP5,
    SP5, SP5, SP5, SP5, SP5, SP5, SP5, SP5
};

#undef	SP0
#undef	SP2
#undef	SP3
#undef	SP4
#undef	SP5

/* file-static variables for prefix argument mechanism */
static Boolean m_have_arg = False; /* flag whether we have a possible prefix arg */
static int m_number = 0;        /* prefix arg value, without the sign */
static int m_sign = 1;          /* is prefix arg negative? */


/* to remember the scrollbar positions so that we can restore them
   when `keep position' is active and window is resized to full size
   (removing scrollbars) and then back (#810501) */
static int m_x_scroll = 0, m_y_scroll = 0;

static int source_reverse_x, source_reverse_y;
static int source_show_all;

/* globals for color stuff */
Pixel plane_masks[4];
XColor color_data[2];
struct pagecolor_info page_colors = { 0, NULL };

struct rgb *color_bottom;
unsigned int color_bot_size;		/* number of entries */
struct colorframe *rcs_top;
struct rgb fg_initial;			/* Initial fg (from command line) */
struct rgb bg_initial;			/* Initial bg */
struct bgrec *bg_head = NULL;		/* head of list */
struct bgrec *bg_current = NULL;	/* current bg value */
struct fgrec *fg_current;		/* current fg value */
struct fgrec *fg_active = NULL;		/* where the GCs are */
Pixel *color_list;			/* list of colors */
unsigned int color_list_len = 0;	/* current len of list*/
unsigned int color_list_max = 0;	/* allocated size */
Boolean color_warned = False;
/*
  FIXME: the following file-static flag is used to control whether
  a mouse-related Act_* should block further actions that have
  been registered for the same event.
  
  It is used for the Act_href_* routines.
  
  This used to be a
     longjmp(somewehre_in_the_event_loop);
  but that was pretty dreadful as well. Surely there must
  be some other (X(t)-specific?) way to do this?? (Apart from
  de-registering the action and re-registering it again.)
*/
static Boolean m_block_mouse_event = False; 

/* for calling it from mag.c */
void
block_next_mouse_event(void) {
    m_block_mouse_event = True;
}

Boolean
block_this_mouse_event(void) {
    if (m_block_mouse_event == True) {
	m_block_mouse_event = False;
	return True;
    }
    return False;
}


void null_mouse(XEvent *event)
{
    UNUSED(event);
}

mouse_proc mouse_motion = null_mouse;
mouse_proc mouse_release = null_mouse;

static void Act_digit(Widget, XEvent *, String *, Cardinal *);
static void Act_find(Widget, XEvent *, String *, Cardinal *);
static void Act_find_next(Widget, XEvent *, String *, Cardinal *);
static void Act_minus(Widget, XEvent *, String *, Cardinal *);
static void Act_quit(Widget, XEvent *, String *, Cardinal *);
static void Act_quit_confirm(Widget, XEvent *, String *, Cardinal *);
static void Act_print(Widget, XEvent *, String *, Cardinal *);
static void Act_save(Widget, XEvent *, String *, Cardinal *);
static void Act_help(Widget, XEvent *, String *, Cardinal *);
static void Act_goto_page(Widget, XEvent *, String *, Cardinal *);
static void Act_declare_page_number(Widget, XEvent *, String *, Cardinal *);
static void Act_toggle_mark(Widget, XEvent *, String *, Cardinal *);
static void Act_home(Widget, XEvent *, String *, Cardinal *);
static void Act_home_or_top(Widget, XEvent *, String *, Cardinal *);
static void Act_end_or_bottom(Widget, XEvent *, String *, Cardinal *);
static void Act_center(Widget, XEvent *, String *, Cardinal *);
static void Act_left(Widget, XEvent *, String *, Cardinal *);
static void Act_right(Widget, XEvent *, String *, Cardinal *);
static void Act_up(Widget, XEvent *, String *, Cardinal *);
static void Act_down(Widget, XEvent *, String *, Cardinal *);
static void Act_up_or_previous(Widget, XEvent *, String *, Cardinal *);
static void Act_down_or_next(Widget, XEvent *, String *, Cardinal *);
static void Act_set_margins(Widget, XEvent *, String *, Cardinal *);
static void Act_show_display_attributes(Widget, XEvent *, String *, Cardinal *);
static void Act_set_density(Widget, XEvent *, String *, Cardinal *);
static void Act_change_density(Widget, XEvent *, String *, Cardinal *);
static void Act_fullscreen(Widget, XEvent *, String *, Cardinal *);
#ifdef GREY
static void Act_set_greyscaling(Widget, XEvent *, String *, Cardinal *);
#endif
#if COLOR
static void Act_set_color(Widget, XEvent *, String *, Cardinal *);
#endif

static void Act_htex_anchorinfo(Widget, XEvent *, String *, Cardinal *);

static void Act_reread_dvi_file(Widget, XEvent *, String *, Cardinal *);
static void Act_select_dvi_file(Widget, XEvent *, String *, Cardinal *);
static void Act_discard_number(Widget, XEvent *, String *, Cardinal *);
static void Act_drag(Widget, XEvent *, String *, Cardinal *);
static void Act_wheel(Widget, XEvent *, String *, Cardinal *);
static void Act_motion(Widget, XEvent *, String *, Cardinal *);
static void Act_release(Widget, XEvent *, String *, Cardinal *);
static void Act_source_special(Widget, XEvent *, String *, Cardinal *);
static void Act_show_source_specials(Widget, XEvent *, String *, Cardinal *);
static void Act_source_what_special(Widget, XEvent *, String *, Cardinal *);
static void Act_unpause_or_next(Widget, XEvent *, String *, Cardinal *);
static void Act_ruler_snap_origin(Widget w, XEvent *event, String *params, Cardinal *num_params);
static void Act_text_mode(Widget w, XEvent *event, String *params, Cardinal *num_params);
static void Act_load_url(Widget w, XEvent *event, String *params, Cardinal *num_params);
#ifdef MOTIF
static void Act_prefs_dialog(Widget w, XEvent *event, String *params, Cardinal *num_params);
#endif

static XtActionsRec m_actions[] = {
    {"digit", Act_digit},
    {"switch-mode", Act_switch_mode},
    {"ruler-mode", Act_ruler_mode},
    {"text-mode", Act_text_mode},
    {"minus", Act_minus},
    {"recent-files", Act_recent_files},
    {"quit", Act_quit},
    {"quit-confirm", Act_quit_confirm},
    {"print", Act_print},
    {"save", Act_save},
    {"find", Act_find},
    {"find-next", Act_find_next},
    {"help", Act_help},
    {"goto-page", Act_goto_page},
    {"use-tex-pages", Act_use_tex_pages},
    {"forward-page", Act_forward_page},
    {"back-page", Act_back_page},
    {"toggle-mark", Act_toggle_mark},
    {"declare-page-number", Act_declare_page_number},
    {"home", Act_home},
    {"home-or-top", Act_home_or_top},
    {"end-or-bottom", Act_end_or_bottom},
    {"center", Act_center},
    {"set-keep-flag", Act_set_keep_flag},
    {"ruler-snap-origin", Act_ruler_snap_origin},
    {"left", Act_left},
    {"right", Act_right},
    {"up", Act_up},
    {"down", Act_down},
    {"up-or-previous", Act_up_or_previous},
    {"down-or-next", Act_down_or_next},
    {"set-margins", Act_set_margins},
    {"show-display-attributes", Act_show_display_attributes},
    {"set-shrink-factor", Act_set_shrink_factor},
    {"shrink-to-dpi", Act_shrink_to_dpi},
    {"set-density", Act_set_density},
    {"change-density", Act_change_density},
    {"fullscreen", Act_fullscreen},
#ifdef GREY
    {"set-greyscaling", Act_set_greyscaling},
#endif
#if COLOR
    {"set-color", Act_set_color},
#endif
#ifdef PS
    {"set-ps", Act_set_ps},
#endif
    {"htex-back", Act_htex_back},
    {"htex-forward", Act_htex_forward},
    {"htex-anchorinfo", Act_htex_anchorinfo},
#ifdef PS_GS
    {"set-gs-alpha", Act_set_gs_alpha},
#endif
    {"set-expert-mode", Act_set_expert_mode},
    {"reread-dvi-file", Act_reread_dvi_file},
    {"select-dvi-file", Act_select_dvi_file},
    {"discard-number", Act_discard_number},
    {"drag", Act_drag},
    {"wheel", Act_wheel},
    {"motion", Act_motion},
    {"release", Act_release},
    {"source-special", Act_source_special},
    {"show-source-specials", Act_show_source_specials},
    {"source-what-special", Act_source_what_special},
    {"unpause-or-next", Act_unpause_or_next},
#if defined(NEW_MENU_CREATION) || defined(MOTIF)
    {"set-papersize", Act_set_papersize},
    {"set-paper-landscape", Act_set_paper_landscape},
#endif /* NEW_MENU_CREATION */
    {"load-url", Act_load_url},
    {"pagehistory-clear", Act_pagehistory_clear},
    {"pagehistory-back", Act_pagehistory_back},
    {"pagehistory-forward", Act_pagehistory_forward},
    {"pagehistory-delete-backward", Act_pagehistory_delete_backward},
    {"pagehistory-delete-forward", Act_pagehistory_delete_forward},    
#ifdef MOTIF
    {"prefs-dialog", Act_prefs_dialog},    
#endif
};

/*
 * Access to m_actions
 */
int get_num_actions(void)
{
    return XtNumber(m_actions);
}

XtActionsRec *get_actions(void)
{
    return m_actions;
}

/*
 *	Data for buffered events.
 */

#ifndef FLAKY_SIGPOLL
static VOLATILE int event_freq = 70;
#else
#define	event_freq	70
#endif

static void can_exposures(struct WindowRec *windowrec);


/*
 *	Set the flag so that termination occurs, via the above routine.
 *	This should be used in place of xdvi_exit() when there may be a
 *	non-killable process running (e.g., anytime within read_events()).
 */

static void
xdvi_normal_exit(void)
{
    sig_flags |= SF_TERM;
}

static void
xdvi_normal_exit_cb(XtPointer arg)
{
    UNUSED(arg);
    sig_flags |= SF_TERM;
}

void
xdvi_exit_callback(Widget w, XtPointer client_data, XtPointer call_data)
{
    UNUSED(w);
    UNUSED(client_data);
    UNUSED(call_data);

    sig_flags |= SF_TERM;
}

/*
 * Event-handling routines.
 */


void
expose(struct WindowRec *windowrec,
       int x, int y,
       unsigned int w, unsigned int h)
{
    if (windowrec->min_x > x)
	windowrec->min_x = x;
    if (windowrec->max_x < (int)(x + w))
	windowrec->max_x = x + w;
    if (windowrec->min_y > y)
	windowrec->min_y = y;
    if (windowrec->max_y < (int)(y + h))
	windowrec->max_y = y + h;

    globals.ev.flags |= EV_EXPOSE;
}

void
clearexpose(struct WindowRec *windowrec,
	    int x, int y,
	    unsigned w, unsigned h)
{
    XClearArea(DISP, windowrec->win, x, y, w, h, False);
    expose(windowrec, x, y, w, h);
}

/*
 *	Routines for X11 toolkit.
 */

static Position window_x, window_y;
static Arg arg_xy[] = {
    {XtNx, (XtArgVal) &window_x},
    {XtNy, (XtArgVal) &window_y},
};

#define	get_xy() XtGetValues(globals.widgets.draw_widget, arg_xy, XtNumber(arg_xy))


static void
warn_num_params(const char *act_name, String *params, int num_params, int max_params)
{
    if (num_params > max_params) {
	XDVI_WARNING((stderr, "Too many parameters (%d) for action \"%s\", ignoring all after \"%s\"",
		      num_params, act_name, params[max_params - 1]));
    }
}


struct xdvi_action *
compile_action(const char *str)
{
    const char *p, *p1, *p2;
    XtActionsRec *actp;
    struct xdvi_action *ap;

    while (*str == ' ' || *str == '\t')
	++str;

    if (*str == '\0' || *str == '\n')
	return NULL;

    p = str;

    /* find end of command name */
    while (isalnum((int)*p) || *p == '-' || *p == '_')
	++p;

    for (actp = m_actions; ; ++actp) {
	if (actp >= m_actions + XtNumber(m_actions)) {
	    const char *tmp = strchr(str, '\0');
	    if (tmp == NULL) {
		tmp = p;
	    }
	    XDVI_WARNING((stderr, "Cannot compile action \"%.*s\".", (int)(tmp - str), str));

	    return NULL;
	}
	if (memcmp(str, actp->string, p - str) == 0 && actp->string[p - str] == '\0')
	    break;
    }

    while (*p == ' ' || *p == '\t')
	++p;
    if (*p != '(') {
	while (*p != '\0' && *p != '\n')
	    ++p;
	XDVI_WARNING((stderr, "Syntax error in action %.*s.", (int)(p - str), str));

	return NULL;
    }
    ++p;
    while (*p == ' ' || *p == '\t')
	++p;
    for (p1 = p;; ++p1) {
	if (*p1 == '\0' || *p1 == '\n') {
	    XDVI_WARNING((stderr, "Syntax error in action %.*s.", (int)(p1 - str), str));
	    return NULL;
	}
	if (*p1 == ')')
	    break;
    }

    ap = xmalloc(sizeof *ap);
    ap->proc = actp->proc;
    for (p2 = p1;; --p2) {
	if (p2 <= p) {	/* if no args */
	    ap->num_params = 0;
	    ap->param = NULL;
	    break;
	}
	else if (p2[-1] != ' ' && p2[-1] != '\t') {
	    char *arg;

	    arg = xmalloc(p2 - p + 1);
	    memcpy(arg, p, p2 - p);
	    arg[p2 - p] = '\0';
	    ap->num_params = 1;
	    ap->param = arg;
	    break;
	}
    }
    
    ap->next = compile_action(p1 + 1);

    return ap;
}

void
handle_command(Widget widget, XtPointer client_data, XtPointer call_data)
{
    struct xdvi_action *actp;

    UNUSED(call_data);

    /* call all actions registered for this event */
    for (actp = (struct xdvi_action *)client_data; actp != NULL; actp = actp->next) {
	if (globals.debug & DBG_EVENT)
	    fprintf(stderr, "calling action with param: %s\n", actp->param);
	(actp->proc) (widget, NULL, &actp->param, &actp->num_params);
    }
}

#ifdef MOTIF
int
set_bar_value(Widget bar, int value, int max)
{
    XmScrollBarCallbackStruct call_data;

#ifdef TEST_SCROLLING
    fprintf(stderr, "set_bar_value: val %d, max %d\n", value, max);
#endif
    if (value > max)
	value = max;
    if (value < 0)
	value = 0;
    call_data.value = value;
    XtVaSetValues(bar, XmNvalue, value, NULL);
    XtCallCallbacks(bar, XmNvalueChangedCallback, &call_data);
    return value;
}
#endif

void
home(wide_bool scrl)
{
    if (!scrl)
	XUnmapWindow(DISP, mane.win);
# ifdef MOTIF
    {
	int value;

	value = (globals.page.w - mane.width) / 2;
	if (value > resource.sidemargin_int / mane.shrinkfactor)
	    value = resource.sidemargin_int / mane.shrinkfactor;
	(void)set_bar_value(globals.widgets.x_bar, value, (int)(globals.page.w - mane.width));

	value = (globals.page.h - mane.height) / 2;
	if (value > resource.topmargin_int / mane.shrinkfactor)
	    value = resource.topmargin_int / mane.shrinkfactor;
	(void)set_bar_value(globals.widgets.y_bar, value, (int)(globals.page.h - mane.height));
    }
# else
    get_xy();
    if (globals.widgets.x_bar != NULL) {
	int coord = (globals.page.w - mane.width) / 2;

	if (coord > resource.sidemargin_int / mane.shrinkfactor)
	    coord = resource.sidemargin_int / mane.shrinkfactor;
	XtCallCallbacks(globals.widgets.x_bar, XtNscrollProc, (XtPointer) (window_x + coord));
    }
    if (globals.widgets.y_bar != NULL) {
	int coord = (globals.page.h - mane.height) / 2;

	if (coord > resource.topmargin_int / mane.shrinkfactor)
	    coord = resource.topmargin_int / mane.shrinkfactor;
	XtCallCallbacks(globals.widgets.y_bar, XtNscrollProc, (XtPointer) (window_y + coord));
    }
# endif /* MOTIF */
    if (!scrl) {
	XMapWindow(DISP, mane.win);
	/* Wait for the server to catch up---this eliminates flicker. */
	XSync(DISP, False);
    }
    handle_x_scroll(NULL, NULL, NULL, NULL);
    handle_y_scroll(NULL, NULL, NULL, NULL);
}

/*
 *	Same as home(), except move to the bottom of the page.
 */

static void
home_bottom(wide_bool scrl)
{
    UNUSED(scrl);
    XUnmapWindow(DISP, mane.win);
#ifdef MOTIF
    {
	int value;

	value = (globals.page.w - mane.width) / 2;
	if (value > resource.sidemargin_int / mane.shrinkfactor)
	    value = resource.sidemargin_int / mane.shrinkfactor;
	(void)set_bar_value(globals.widgets.x_bar, value, (int)(globals.page.w - mane.width));

	(void)set_bar_value(globals.widgets.y_bar, (int)(globals.page.h - mane.height), (int)(globals.page.h - mane.height));
    }
#else /* MOTIF */
    get_xy();
    if (globals.widgets.x_bar != NULL) {
	int coord = (globals.page.w - mane.width) / 2;

	if (coord > resource.sidemargin_int / mane.shrinkfactor)
	    coord = resource.sidemargin_int / mane.shrinkfactor;
	XtCallCallbacks(globals.widgets.x_bar, XtNscrollProc, (XtPointer) (window_x + coord));
    }
    if (globals.widgets.y_bar != NULL)
	XtCallCallbacks(globals.widgets.y_bar, XtNscrollProc, (XtPointer)(window_y + (globals.page.h - mane.height)));
#endif /* MOTIF */
    XMapWindow(DISP, mane.win);
    /* Wait for the server to catch up---this eliminates flicker. */
    XSync(DISP, False);

    handle_x_scroll(NULL, NULL, NULL, NULL);
    handle_y_scroll(NULL, NULL, NULL, NULL);
}


#ifndef MOTIF
static void
handle_destroy_bar(Widget w, XtPointer client_data, XtPointer call_data)
{
    UNUSED(w);
    UNUSED(call_data);
    *(Widget *) client_data = NULL;
}
#endif

static Boolean resized = False;

static void
get_geom(void)
{
    static Dimension new_clip_w, new_clip_h;
    
    static Arg arg_wh_clip[] = {
	{XtNwidth, (XtArgVal) &new_clip_w},
	{XtNheight, (XtArgVal) &new_clip_h},
    };

    static Dimension window_w, window_h;

    static Arg arg_wh[] = {
	{XtNwidth, (XtArgVal) &window_w},
	{XtNheight, (XtArgVal) &window_h},
    };

    
    int old_clip_w;

#ifdef MOTIF
    /* event handlers for Motif scrollbars have already been added
       in create_initialize_widgets(), xdvi.c */
    XtGetValues(globals.widgets.main_window, arg_wh, XtNumber(arg_wh));
#else
    XtGetValues(globals.widgets.vport_widget, arg_wh, XtNumber(arg_wh));
    /* Note:  widgets may be destroyed but not forgotten */
    if (globals.widgets.x_bar == NULL) {
	globals.widgets.x_bar = XtNameToWidget(globals.widgets.vport_widget, "horizontal");
	if (globals.widgets.x_bar != NULL) {
	    XtAddCallback(globals.widgets.x_bar, XtNdestroyCallback, handle_destroy_bar,
			  (XtPointer)&globals.widgets.x_bar);
	    XtAddEventHandler(globals.widgets.x_bar, ButtonMotionMask | ButtonPressMask | ButtonReleaseMask,
			      False, handle_x_scroll, NULL);
	}
    }
    if (globals.widgets.y_bar == NULL) {
	globals.widgets.y_bar = XtNameToWidget(globals.widgets.vport_widget, "vertical");
	if (globals.widgets.y_bar != NULL) {
	    XtAddCallback(globals.widgets.y_bar, XtNdestroyCallback, handle_destroy_bar,
			  (XtPointer)&globals.widgets.y_bar);
	    XtAddEventHandler(globals.widgets.y_bar, ButtonMotionMask | ButtonPressMask | ButtonReleaseMask,
			      False, handle_y_scroll, NULL);
	}
    }
#endif
    XtGetValues(globals.widgets.clip_widget, arg_wh_clip, XtNumber(arg_wh_clip));

    old_clip_w = mane.width;

    /* we need to do this because 
       sizeof(Dimension) != sizeof(int)
    */
    mane.width = new_clip_w;
    mane.height = new_clip_h;
    if (old_clip_w == 0) {
	globals.ev.flags |= EV_NEWPAGE;
    }

    if (resource.keep_flag) {
#ifndef MOTIF
	Dimension d;
	int curr_scroll;
	if ((globals.widgets.x_bar != NULL && m_x_scroll != 0) || (globals.widgets.y_bar != NULL && m_y_scroll != 0)) {
	    get_xy();
	}
#endif
	if (globals.widgets.x_bar != NULL && m_x_scroll != 0) {
#ifdef MOTIF
	    if (m_x_scroll > 0)
		(void)set_bar_value(globals.widgets.x_bar, m_x_scroll, (int)(globals.page.w - mane.width));
#else
	    XtVaGetValues(globals.widgets.clip_widget, XtNy, &d, NULL);
	    curr_scroll = d - window_x;
	    if (m_x_scroll > curr_scroll) {
		TRACE_GUI((stderr, "======== diff: %d", m_x_scroll - curr_scroll));
		XtCallCallbacks(globals.widgets.x_bar, XtNscrollProc, (XtPointer)(m_x_scroll - curr_scroll));
	    }
#endif
	}
	if (globals.widgets.y_bar != NULL && m_y_scroll != 0) {
#ifdef MOTIF
	    if (m_y_scroll > 0)
		(void)set_bar_value(globals.widgets.y_bar, m_y_scroll, (int)(globals.page.h - mane.height));
#else
	    XtVaGetValues(globals.widgets.clip_widget, XtNy, &d, NULL);
	    curr_scroll = d - window_y;
	    if (m_y_scroll > curr_scroll) {
		TRACE_GUI((stderr, "======== diff: %d", m_y_scroll - curr_scroll));
		XtCallCallbacks(globals.widgets.y_bar, XtNscrollProc, (XtPointer)(m_y_scroll - curr_scroll));
	    }
#endif
	}
    }
    /*     home(False); */
    resized = False;
}

/*
 * Callback routines
 */

void
handle_resize(Widget widget, XtPointer junk, XEvent *event, Boolean *cont)
{
    UNUSED(widget);
    UNUSED(junk);
    UNUSED(event);
    UNUSED(cont);
    
    resized = True;
#ifndef MOTIF
    handle_statusline_resize();
    handle_pagelist_resize();
#endif
}

void
reconfig(void)
{
/*      Dimension x, y; */

    if (globals.dvi_file.bak_fp == NULL)
	return;
    
#ifndef MOTIF
    XtVaSetValues(globals.widgets.vport_widget, XtNresizable, (XtArgVal)False, NULL);
#endif
    TRACE_GUI((stderr, "globals.widgets.draw_widget: w %d, h %d", globals.page.w, globals.page.h));
    XtVaSetValues(globals.widgets.draw_widget, XtNwidth, (XtArgVal)globals.page.w, XtNheight, (XtArgVal)globals.page.h, NULL);
    
#ifdef TEST_SCROLLING
/*     XtVaSetValues(globals.widgets.draw_background, XtNwidth, (XtArgVal)globals.page.w, XtNheight, (XtArgVal)globals.page.h, NULL); */
#endif
    
#ifndef MOTIF
    handle_statusline_resize(); /* without this, statusline will disappear */
    /* following not needed? */
    /*     handle_pagelist_resize(); */
#endif
    
    get_geom();

/*     set_windowsize(&x, &y */
/* #ifndef MOTIF */
/* 		   , get_panel_width() */
/* #endif */
/* 		   ); */
/*     XResizeWindow(DISP, XtWindow(globals.widgets.top_level), x, y); */
/*      reconfigure_window(False, x, y, True); */
/*      reconfig_window(); */
}


int
check_goto_page(int pageno)
{
    int retval;
    if (pageno < 0) {
	XBell(DISP, 0);
	statusline_print(STATUS_SHORT, "Can't go to page %d, going to first page instead", pageno + 1);
	retval = 0;
    }
    else if (pageno >= total_pages) {
	XBell(DISP, 0);
	statusline_print(STATUS_SHORT,
			 "Can't go to page %d, going to last page (%d) instead",
			 pageno + 1, total_pages);
	retval = total_pages - 1;
    }
    else
	retval = pageno;

    page_history_insert(retval);
    return retval;
}


static int
check_goto_tex_page(int pageno)
{
    /*
      Translate from TeX page number to `real' page number if
      needed. Note that pageno is a C-style 0-based number, hence we
      add 1 for the argument of pageinfo_get_index_of_number().
    */
    int retval;
    if (resource.use_tex_pages) {
	int res = pageinfo_get_index_of_number(pageno + 1);
	if (res >= 0)
	    retval = res;
	else {
	    XBell(DISP, 0);
	    if (pageno < 1) {
		statusline_print(STATUS_SHORT, "Can't go to page %d, going to first page instead", pageno + 1);
		retval = 0;
	    }
	    else {
		/* there is no quick way to determine the last page number in the TeX page index */
		statusline_print(STATUS_SHORT,
				 "Can't go to page %d, going to last page instead",
				 pageno + 1);
		retval = total_pages - 1;
	    }
	}
	page_history_insert(retval);
    }
    else {
	retval = check_goto_page(pageno);
    }
    return retval;
}

/* |||
 *	Currently the event handler does not coordinate XCopyArea requests
 *	with GraphicsExpose events.  This can lead to problems if the window
 *	is partially obscured and one, for example, drags a scrollbar.
 */

/*
 *	Actions for the translation mechanism.
 */

/* if there are global prefixes, return them in res and reset them to defaults */
static Boolean
get_prefix_arg(int *res)
{
    Boolean ret;

    *res = m_sign * m_number;
    ret = m_have_arg;
    /* reset global flags */
    m_have_arg = False;
    m_number = 0;
    m_sign = 1;
    return ret;
}

Boolean
get_int_arg(String *param, Cardinal *num_params, int *res)
{
    if (*num_params > 0) {
	*res = atoi(*param);
	return True;
    }
    else {
	if (get_prefix_arg(res)) { /* prefix argument? */
	    return True;
	}
    }
    return False;
}


Boolean
toggle_arg(int arg, String *param, Cardinal *num_params)
{
    if (*num_params > 0) {
	if (**param != 't' && (atoi(*param) != 0) == arg)
	    return False;
    }
    else {
	if (m_have_arg) {
	    int	tmparg = m_number;

	    m_have_arg = False;
	    m_number = 0;
	    m_sign = 1;

	    if ((tmparg != 0) == arg)
		return False;
	}
    }
    return True;
}

#if defined(NEW_MENU_CREATION) || defined(MOTIF)
Boolean
check_resource_expert(void *val, const char *param)
{
    int j = strtol(param, (char **)NULL, 10);
    /* check if the j-1th bit is set: */
    return (*(int *)val >> (j - 1)) & 1;
}

Boolean
check_papersize(void *val, const char *param)
{
    UNUSED(val);
    UNUSED(param);
    return False; /* TODO */
}

Boolean
check_paper_landscape(void *val, const char *param)
{
    UNUSED(val);
    UNUSED(param);
    return False; /* TODO */
}

/* comparison functions for the menu setting code */
Boolean
check_toggle(void *val, const char *param)
{
    Boolean *on = val;
    if (strcmp(param, "toggle") == 0) {
	return *on;
    }
    else {
	fprintf(stderr, "TODO: check_toggle: arg |%s|, curr: %d\n", param, *(int *)val);
	return *on;
    }
}

Boolean
check_int(void *val, const char *param)
{
    int i = strtol(param, (char **)NULL, 10);
    return i == *(int *)val;
}
#endif /* NEW_MENU_CREATION */


static void
Act_digit(Widget w, XEvent *event,
	  String *params, Cardinal *num_params)
{
    int digit;
    /* for overflow checks */
    static const int MAXINT_QUOT = INT_MAX / 10;
    static const int MAXINT_MOD = INT_MAX % 10;


    UNUSED(w);
    UNUSED(event);

    if (*num_params != 1 || (digit = **params - '0') > 9) {
	XBell(DISP, 0);
	return;
    }
    m_have_arg = True;

    /* don't increment m_number if it would overflow */
    if (m_number < MAXINT_QUOT || (m_number == MAXINT_QUOT && digit <= MAXINT_MOD)) {
	m_number = m_number * 10 + digit;
	if (resource.expert_mode & XPRT_SHOW_STATUSLINE) /* too distracting for stdout */
	    statusline_print(STATUS_SHORT, "numerical prefix: %s%d", m_sign < 0 ? "-" : "", m_number);
    }
    else {
	XBell(DISP, 0);
	statusline_print(STATUS_SHORT, "numerical prefix: %s%d: no larger value possible", m_sign < 0 ? "-" : "", m_number);
    }
}

static void
Act_minus(Widget w, XEvent *event,
	  String *params, Cardinal *num_params)
{
    UNUSED(w);
    UNUSED(event);
    UNUSED(params);
    UNUSED(num_params);
    
    m_have_arg = True;
    m_sign = -m_sign;
    if (m_number > 0) {
	if (resource.expert_mode & XPRT_SHOW_STATUSLINE) /* too distracting for stdout */
	    statusline_print(STATUS_SHORT, "numerical prefix: %s%d", m_sign < 0 ? "-" : "", m_number);
    }
    else {
	if (resource.expert_mode & XPRT_SHOW_STATUSLINE) /* too distracting for stdout */
	    statusline_print(STATUS_SHORT, "numerical prefix: %s", m_sign < 0 ? "-" : "");
    }
}

static void
Act_quit(Widget w, XEvent *event,
	 String *params, Cardinal *num_params)
{
    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(event);
    UNUSED(params);
    UNUSED(num_params);
    
#ifndef FLAKY_SIGPOLL
    if (globals.debug & DBG_EVENT)
	puts(event_freq < 0
	     ? "SIGPOLL is working"
	     : "no SIGPOLL signals received");
#endif
    xdvi_normal_exit();
}

static void
Act_quit_confirm(Widget w, XEvent *event,
		 String *params, Cardinal *num_params)
{
    static Widget dialog = 0;
    
    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(event);
    UNUSED(params);
    UNUSED(num_params);

#ifndef FLAKY_SIGPOLL
    if (globals.debug & DBG_EVENT)
	puts(event_freq < 0
	     ? "SIGPOLL is working"
	     : "no SIGPOLL signals received");
#endif

    /* already a quit dialog open? */
    if (dialog != 0) {
	/* HACK ALERT: use brute force, since tests for XtIsRealized()
	   or XtIsMapped() don't work?? Grabbing the server apparently
	   has problems with Xaw, and it's not a nice solution anyway ... */
	if (kill_message_window(dialog))
	    XBell(DISP, 0);
    }

    dialog = choice_dialog_sized(globals.widgets.top_level,
				 MSG_QUESTION,
				 SIZE_SMALL,
				 NULL,
#ifndef MOTIF
				 "quit",
#endif
				 NULL, NULL, /* no pre_callbacks */
				 "OK", xdvi_normal_exit_cb, NULL,
				 "Cancel", NULL, NULL,
				 "Really quit xdvi?");
}

static void
Act_load_url(Widget w, XEvent *event, String *params, Cardinal *num_params)
{
    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(event);
    UNUSED(num_params);
    launch_browser(*params);
}

static void
Act_print(Widget w, XEvent *event, String *params, Cardinal *num_params)
{
    static struct save_or_print_info info;

    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(event);
    UNUSED(params);
    UNUSED(num_params);
    
    info.act = FILE_PRINT;
    
    save_or_print_callback(&info);
}

static void
Act_save(Widget w, XEvent *event, String *params, Cardinal *num_params)
{
    static struct save_or_print_info info;

    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(event);
    UNUSED(params);
    UNUSED(num_params);
    
    info.act = FILE_SAVE;
    
    save_or_print_callback(&info);
}

static void
Act_find(Widget w, XEvent *event, String *params, Cardinal *num_params)
{
    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(event);
    UNUSED(params);
    UNUSED(num_params);
    dvi_find_string(NULL, False);
}

static void
Act_find_next(Widget w, XEvent *event, String *params, Cardinal *num_params)
{
    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(event);
    UNUSED(params);
    UNUSED(num_params);
    dvi_find_string(NULL, True);
}

static void
Act_help(Widget w, XEvent *event,
	 String *params, Cardinal *num_params)
{
    char *arg = NULL;

    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(event);
    
    if (*num_params > 0)
	arg = *params;
    
    show_help(globals.widgets.top_level, arg);
}

static home_proc home_action = NULL;

void
goto_page(int new_page, home_proc proc, Boolean force)
{
    /* SU: added clearing the window here, else old window content
       will survive switching pages as long as globals.pausing.flag is active
       (i.e. when inadvertedly changing page instead of unpausing)
    */
    if (globals.pausing.flag) {
	XClearWindow(DISP, mane.win);
    }
	    
    if (globals.dvi_file.bak_fp == NULL) {
	current_page = new_page; /* so that xdvi gets the page change */
	return;
    }

    ASSERT(new_page >= 0 && new_page < total_pages, "new_page in goto_page() out of range");   
    if (current_page != new_page || force) {
	globals.cursor.flags &= ~CURSOR_LINK; /* disable link cursor if needed */

	current_page = new_page;
	home_action = proc;
	globals.warn_spec_now = resource.warn_spec;
    /* this seems unneccessary */
/* 	if (!resource.keep_flag) */
/* 	    home(False); */
#if defined(MOTIF) && HAVE_XPM
	tb_check_navigation_sensitivity(current_page);
/*  	page_history_update_toolbar_navigation(); */
#endif
	maybe_scroll_pagelist(current_page, False);

	if (globals.pausing.num_save)
	    globals.pausing.num = globals.pausing.num_save[new_page];
	else
	    globals.pausing.num = 0;
	/* Control-L (and changing the page) clears this box */
	globals.src.fwd_box_page = -1;

	globals.ev.flags |= EV_NEWPAGE;
	XFlush(DISP);       
    }
}


static void
Act_goto_page(Widget w, XEvent *event,
	      String *params, Cardinal *num_params)
{
    int arg;
    Boolean clear_statusline = False;

    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(event);

    warn_num_params("goto-page()", params, *num_params, 1);
    
    if (*num_params > 0) {
	if (**params == 'e') {
	    arg = total_pages - 1;
	}
	else
	    arg = atoi(*params) - globals.pageno_correct;
    }
    else {
	if (get_prefix_arg(&arg)) {
	    clear_statusline = True;
	    arg -= globals.pageno_correct;
	}
	else {
	    arg = total_pages - 1;
	}
    }
    if (arg == total_pages - 1) {
	/* with TeX numbers, total_pages - 1 might not be found in the page list,
	   so don't use check_goto_tex_page() in this case */
	goto_page(check_goto_page(arg), resource.keep_flag ? NULL : home, False);
    }
    else {
	goto_page(check_goto_tex_page(arg), resource.keep_flag ? NULL : home, False);
    }
    search_signal_page_changed();
    if (clear_statusline)
	statusline_clear();
}

void
Act_recent_files(Widget w, XEvent *event,
		 String *params, Cardinal *num_params)
{
    UNUSED(w);
    UNUSED(event);
    UNUSED(params);
    UNUSED(num_params);
}

void
Act_use_tex_pages(Widget w, XEvent *event,
		  String *params, Cardinal *num_params)
{
    UNUSED(w);
    UNUSED(event);

    if (block_this_mouse_event())
	return;
    
    if (*num_params == 0) {
	if (m_have_arg) {
	    resource.use_tex_pages = (m_number != 0);
	    m_have_arg = False;
	    m_number = 0;
	    m_sign = 1;
	}
	else {
	    resource.use_tex_pages = !resource.use_tex_pages;
	}
    }
    else
	resource.use_tex_pages = (**params == 't' ? !resource.use_tex_pages : atoi(*params));
    
    if (resource.use_tex_pages) {
	statusline_print(STATUS_SHORT, "Using TeX page numbers for \"g\", goto-page()");
    }
    else {
	statusline_print(STATUS_SHORT, "Using physical page numbers for \"g\", goto-page()");
    }

    store_preference(NULL, "useTeXPages", "%s", resource.use_tex_pages ? "True" : "False");
    
#if defined(NEW_MENU_CREATION) || defined(MOTIF)
    set_menu(&resource.use_tex_pages, Act_use_tex_pages, check_toggle);
#else
#ifdef MOTIF
   set_use_tex_option();
#else
    toggle_menu(resource.use_tex_pages,  Act_use_tex_pages);
#endif
#endif /* NEW_MENU_CREATION */
    refresh_pagelist(total_pages, current_page);
}

void
Act_forward_page(Widget w, XEvent *event,
		 String *params, Cardinal *num_params)
{
    int arg;
    Boolean clear_statusline = False;

    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(event);

    if (!get_int_arg(params, num_params, &arg))
	arg = 1;
    else
	clear_statusline = True;
    
    arg += current_page;

    if (arg == current_page) { /* zero argument -> redraw page */
	globals.src.fwd_box_page = -1;
	search_reset_info();
	globals.ev.flags |= EV_NEWPAGE;
	XFlush(DISP);
	statusline_print(STATUS_SHORT, "Page redrawn.");
	return;
    }
    else if (current_page >= total_pages - 1) {
	XBell(DISP, 0);
	statusline_print(STATUS_SHORT, "Last page of DVI file");
	return;
    }
    
    goto_page(check_goto_page(arg), resource.keep_flag ? NULL : home, False);
    if (clear_statusline)
	statusline_clear();
    search_signal_page_changed();
}

void
Act_back_page(Widget w, XEvent *event,
	      String *params, Cardinal *num_params)
{
    int arg;
    Boolean clear_statusline = False;
    
    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(event);

    if (!get_int_arg(params, num_params, &arg))
	arg = 1;
    else
	clear_statusline = True;
    
    arg = current_page - arg;

    if (current_page == 0) {
	XBell(DISP, 0);
	statusline_print(STATUS_SHORT, "First page of DVI file");
	return;
    }

    goto_page(check_goto_page(arg), resource.keep_flag ? NULL : home, False);
    if (clear_statusline)
	statusline_clear();
    search_signal_page_changed();
}

static void
Act_declare_page_number(Widget w, XEvent *event,
			String *params, Cardinal *num_params)
{
    int arg;

    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(event);

    if (resource.mouse_mode == MOUSE_RULER_MODE) {
	show_distance_from_ruler(event, True);
	return;
    }
    
    if (!get_int_arg(params, num_params, &arg)) {
	arg = 0;
    }
    globals.pageno_correct = arg - current_page;
    statusline_print(STATUS_SHORT, "Current page number set to %d", arg);
}

static void
Act_toggle_mark(Widget w, XEvent *event,
		String *params, Cardinal *num_params)
{
    int arg;

    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(event);

    if (globals.dvi_file.bak_fp == NULL)
	return;
    
    if (
#ifdef MOTIF
	(resource.expert_mode & XPRT_SHOW_PAGELIST) == 0
#else
	(resource.expert_mode & XPRT_SHOW_BUTTONS) == 0
#endif
	)
	return;
    
    if (*num_params > 0) {
	arg = atoi(*params);
	if (arg < -1 || arg > 2) {
	    XBell(DISP, 0);
	    statusline_print(STATUS_SHORT,
			     "Possible arguments: none (toggle current), "
			     "-1 (mark all), 0 (unmark all), 1 (toggle odd), 2 (toggle even)");
	}
	list_toggle_marks(arg);
    }
    else if (get_prefix_arg(&arg)) {
	list_toggle_marks(arg);
	statusline_clear();
    }
    else {
	arg = current_page;
	list_toggle_current(arg);
    }
}

static void
Act_home(Widget w, XEvent *event,
	 String *params, Cardinal *num_params)
{
    UNUSED(w);
    UNUSED(event);
    UNUSED(params);
    UNUSED(num_params);

    if (block_this_mouse_event())
	return;
    
    home(True);
}

static void
Act_home_or_top(Widget w, XEvent *event,
		String *params, Cardinal *num_params)
{
    UNUSED(w);
    UNUSED(event);
    UNUSED(params);
    UNUSED(num_params);
    
    if (block_this_mouse_event())
	return;
    
    if (resource.keep_flag) {
	String args[1];
	args[0] = "10"; /* should be large enough ... */
	XtCallActionProc(globals.widgets.top_level, "up", NULL, args, 1);
    }
    else {
	home(True);
    }
}

static void
Act_end_or_bottom(Widget w, XEvent *event,
		String *params, Cardinal *num_params)
{
    String args[1];

    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(event);
    UNUSED(params);
    UNUSED(num_params);

    args[0] = "10"; /* should be large enough ... */
    XtCallActionProc(globals.widgets.top_level, "down", NULL, args, 1);
    
    if (!resource.keep_flag
#ifndef MOTIF
	&& globals.widgets.x_bar != NULL
#endif
	) {
	XtCallActionProc(globals.widgets.top_level, "right", NULL, args, 1);
    }
}

static void
Act_center(Widget w, XEvent *event,
	   String *params, Cardinal *num_params)
{
    int x, y;

    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(params);
    UNUSED(num_params);

#ifdef MOTIF
    /* The clip widget gives a more exact value. */
    x = event->xkey.x - mane.width / 2;
    y = event->xkey.y - mane.height / 2;

    x = set_bar_value(globals.widgets.x_bar, x, (int)(globals.page.w - mane.width));
    y = set_bar_value(globals.widgets.y_bar, y, (int)(globals.page.h - mane.height));
    get_xy();
    XWarpPointer(DISP, None, None, 0, 0, 0, 0, -x - window_x, -y - window_y);
#else

    if (event == NULL)
	return;	/* button actions do not provide events */

    x = event->xkey.x - mane.width / 2;
    y = event->xkey.y - mane.height / 2;
    /* The clip widget gives a more exact value. */
    if (globals.widgets.x_bar != NULL)
	XtCallCallbacks(globals.widgets.x_bar, XtNscrollProc, (XtPointer) x);
    if (globals.widgets.y_bar != NULL)
	XtCallCallbacks(globals.widgets.y_bar, XtNscrollProc, (XtPointer) y);
    XWarpPointer(DISP, None, None, 0, 0, 0, 0, -x, -y);
#endif
    handle_x_scroll(NULL, NULL, NULL, NULL);
    handle_y_scroll(NULL, NULL, NULL, NULL);
}

void
Act_ruler_snap_origin(Widget w, XEvent *event,
		      String *params, Cardinal *num_params)
{
    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(params);
    UNUSED(num_params);

    if (resource.mouse_mode == MOUSE_RULER_MODE)
	ruler_snap_origin(event);
}

#if defined(NEW_MENU_CREATION) || defined(MOTIF)
void
Act_set_papersize(Widget w, XEvent *event,
		  String *params, Cardinal *num_params)
{
    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(event);
    UNUSED(num_params);

    fprintf(stderr, "set_paperformat: %s\n", *params);
    resource.paper = *params;
    set_menu((void *)resource.paper, Act_set_papersize, check_papersize);
}

void
Act_set_paper_landscape(Widget w, XEvent *event,
			String *params, Cardinal *num_params)
{
    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(event);
    UNUSED(num_params);

    resource.paper_landscape = !resource.paper_landscape;
    fprintf(stderr, "set_paper_landscape: %s\n", *params);

    set_menu((char *)resource.paper,  Act_set_paper_landscape, check_paper_landscape);
}
#endif /* NEW_MENU_CREATION */

void
Act_set_keep_flag(Widget w, XEvent *event,
		  String *params, Cardinal *num_params)
{
    if (block_this_mouse_event())
	return;
    
    UNUSED(event);
    UNUSED(w);
    
    if (*num_params == 0) {
	if (m_have_arg) {
	    resource.keep_flag = (m_number != 0);
	    m_have_arg = False;
	    m_number = 0;
	    m_sign = 1;
	}
	else {
	    resource.keep_flag = !resource.keep_flag;
	}
    }
    else
	resource.keep_flag = (**params == 't'
			      ? !resource.keep_flag : atoi(*params));
    if (resource.keep_flag) {
	statusline_print(STATUS_SHORT, "Keeping position when switching pages");
    }
    else {
	statusline_print(STATUS_SHORT,
			 "Not keeping position when switching pages");
    }

    store_preference(NULL, "keepPosition", "%s", resource.keep_flag ? "True" : "False");
    
#if defined(NEW_MENU_CREATION) || defined(MOTIF)
    set_menu(&resource.keep_flag, Act_set_keep_flag, check_toggle);
#else
    toggle_menu(resource.keep_flag,  Act_set_keep_flag);
#endif /* NEW_MENU_CREATION */
}

static void
Act_left(Widget w, XEvent *event,
	 String *params, Cardinal *num_params)
{
    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(event);

    do_autoscroll = False;
    
    warn_num_params("left()", params, *num_params, 1);

#ifdef MOTIF
    get_xy();
#ifdef TEST_SCROLLING
    fprintf(stderr, "left for %p\n", (void *)w);
    fprintf(stderr, "window x: %d, y: %d\n", window_x, window_y);
#endif

    (void)set_bar_value(globals.widgets.x_bar, (*num_params == 0 ? (-2 * (int)mane.width / 3)
				: (int)(-my_atof(*params) * mane.width)) - window_x,
			(int)(globals.page.w - mane.width));
#else
    if (globals.widgets.x_bar != NULL)
	XtCallCallbacks(globals.widgets.x_bar, XtNscrollProc,
			(XtPointer) (*num_params == 0 ? (-2 * (int)mane.width / 3)
				     : (int)(-my_atof(*params) * mane.width)));
    else {
	XBell(DISP, 0);
	statusline_print(STATUS_SHORT, "Horizontal scrolling not possible");
    }
#endif
    handle_x_scroll(NULL, NULL, NULL, NULL);
}

static void
Act_right(Widget w, XEvent *event,
	  String *params, Cardinal *num_params)
{
    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(event);

    do_autoscroll = False;
    
    warn_num_params("right()", params, *num_params, 1);

#ifdef MOTIF
    get_xy();
#ifdef TEST_SCROLLING
    fprintf(stderr, "right for %p\n", (void *)w);
    fprintf(stderr, "window x: %d, y: %d\n", window_x, window_y);
#endif

    (void)set_bar_value(globals.widgets.x_bar, (*num_params == 0 ? (2 * (int)mane.width / 3)
				: (int)(my_atof(*params) * mane.width)) - window_x,
			(int)(globals.page.w - mane.width));
#else
    if (globals.widgets.x_bar != NULL)
	XtCallCallbacks(globals.widgets.x_bar, XtNscrollProc,
			(XtPointer) (*num_params == 0 ? (2 * (int)mane.width / 3)
				     : (int)(my_atof(*params) * mane.width)));
    else {
	XBell(DISP, 0);
	statusline_print(STATUS_SHORT, "Horizontal scrolling not possible");
    }
#endif
    handle_x_scroll(NULL, NULL, NULL, NULL);
}

static void
Act_up(Widget w, XEvent *event,
       String *params, Cardinal *num_params)
{
    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(event);

    do_autoscroll = False;
    
    warn_num_params("up()", params, *num_params, 1);
    
#ifdef MOTIF
#ifdef TEST_SCROLLING
    fprintf(stderr, "up for %p\n", (void *)w);
#endif
    get_xy();
    (void)set_bar_value(globals.widgets.y_bar, (*num_params == 0 ? (-2 * (int)mane.height / 3)
				: (int)(-my_atof(*params) * mane.height)) - window_y,
			(int)(globals.page.h - mane.height));
#else
    if (globals.widgets.y_bar != NULL)
	XtCallCallbacks(globals.widgets.y_bar, XtNscrollProc,
			(XtPointer) (*num_params == 0 ? (-2 * (int)mane.height / 3)
				     : (int)(-my_atof(*params) * mane.height)));
    else {
	XBell(DISP, 0);
	statusline_print(STATUS_SHORT, "Vertical scrolling not possible");
    }
#endif
    handle_y_scroll(NULL, NULL, NULL, NULL);
}

static void
Act_down(Widget w, XEvent *event,
	 String *params, Cardinal *num_params)
{
    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(event);

    do_autoscroll = False;

    warn_num_params("down()", params, *num_params, 1);

#ifdef MOTIF
#ifdef TEST_SCROLLING
    fprintf(stderr, "down for %p\n", (void *)w);
#endif
    get_xy();
    (void)set_bar_value(globals.widgets.y_bar, (*num_params == 0 ? (2 * (int)mane.height / 3)
				: (int)(my_atof(*params) * mane.height)) - window_y,
			(int)(globals.page.h - mane.height));
#else
    if (globals.widgets.y_bar != NULL)
	XtCallCallbacks(globals.widgets.y_bar, XtNscrollProc,
			(XtPointer) (*num_params == 0 ? (2 * (int)mane.height / 3)
				     : (int)(my_atof(*params) * mane.height)));
    else {
	XBell(DISP, 0);
	statusline_print(STATUS_SHORT, "Vertical scrolling not possible");
    }
#endif
    handle_y_scroll(NULL, NULL, NULL, NULL);
}

static void
Act_down_or_next(Widget w, XEvent *event,
		 String *params, Cardinal *num_params)
{
    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(event);

    do_autoscroll = False;

    warn_num_params("down-or-next()", params, *num_params, 1);

#ifdef TEST_SCROLLING
    fprintf(stderr, "down-or-next for %p\n", (void *)w);
#endif

#ifdef MOTIF
    get_xy();
    if (window_y > (int)mane.height - (int)globals.page.h) {
	(void)set_bar_value(globals.widgets.y_bar, (*num_params == 0 ? (2 * (int)mane.height / 3)
				    : (int)(my_atof(*params) * mane.height)) -
			    window_y, (int)(globals.page.h - mane.height));
	return;
    }
#else
    if (globals.widgets.y_bar != NULL) {
	get_xy();
	if (window_y > (int)mane.height - (int)globals.page.h) {
	    XtCallCallbacks(globals.widgets.y_bar, XtNscrollProc,
			    (XtPointer) (*num_params ==
					 0 ? (2 * (int)mane.height / 3)
					 : (int)(my_atof(*params) * mane.height)));
	    return;
	}
    }
#endif

    if (current_page < total_pages - 1) {
	goto_page(current_page + 1, home, False);
	search_signal_page_changed();
    }
    else {
	XBell(DISP, 0);
	statusline_print(STATUS_SHORT, "At bottom of last page");
    }
    handle_y_scroll(NULL, NULL, NULL, NULL);
}


static void
Act_up_or_previous(Widget w, XEvent *event,
		   String *params, Cardinal *num_params)
{
    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(event);

    do_autoscroll = False;

    warn_num_params("up-or-previous()", params, *num_params, 1);

#ifdef TEST_SCROLLING
    fprintf(stderr, "up-or-previous for %p\n", (void *)w);
#endif
#ifdef MOTIF
    get_xy();
    if (window_y < 0) {
	(void)set_bar_value(globals.widgets.y_bar,
			    (*num_params == 0 ? (-2 * (int)mane.height / 3)
			     : (int)(-my_atof(*params) * mane.height)) - window_y,
			    (int)(globals.page.h - mane.height));
	return;
    }
#else
    if (globals.widgets.y_bar != NULL) {
	get_xy();
	if (window_y < 0) {
	    XtCallCallbacks(globals.widgets.y_bar, XtNscrollProc,
			    (XtPointer) (*num_params ==
					 0 ? (-2 * (int)mane.height / 3)
					 : (int)(-my_atof(*params) * mane.height)));
	    return;
	}
    }
#endif

    if (current_page > 0) {
	goto_page(current_page - 1, home_bottom, False);
	search_signal_page_changed();
    }
    else {
	XBell(DISP, 0);
	statusline_print(STATUS_SHORT, "At top of first page");
    }
    handle_y_scroll(NULL, NULL, NULL, NULL);
}


static void
Act_set_margins(Widget w, XEvent *event,
		String *params, Cardinal *num_params)
{
    Window dummy;

    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(params);
    UNUSED(num_params);

#ifndef MOTIF
    if (event == NULL)
	return;	/* button actions do not provide events */
#endif

    (void)XTranslateCoordinates(DISP, event->xkey.window, mane.win,
				event->xkey.x, event->xkey.y, &resource.sidemargin_int, &resource.topmargin_int, &dummy);	/* throw away last argument */
    statusline_print(STATUS_SHORT, "Margins set to cursor position (%d, %d)", resource.sidemargin_int, resource.topmargin_int);
    resource.sidemargin_int *= mane.shrinkfactor;
    resource.topmargin_int *= mane.shrinkfactor;
}

static void
Act_show_display_attributes(Widget w, XEvent *event,
			    String *params, Cardinal *num_params)
{
    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(event);
    UNUSED(params);
    UNUSED(num_params);

    statusline_print(STATUS_SHORT, "Unit = %d, bitord = %d, byteord = %d",
		     BitmapUnit(DISP), BitmapBitOrder(DISP),
		     ImageByteOrder(DISP));
}

int
shrink_to_fit(void)
{
    int value1;
    int value2;
    static Dimension window_w;
#ifndef MOTIF
    static Dimension window_h;
#endif
    
    static Arg arg_wh[] = {
	{XtNwidth, (XtArgVal) &window_w}
#ifndef MOTIF
	, {XtNheight, (XtArgVal) &window_h}
#endif
    };

    
#ifdef MOTIF
    XtGetValues(globals.widgets.main_window, arg_wh, XtNumber(arg_wh));
#else
    XtGetValues(globals.widgets.vport_widget, arg_wh, XtNumber(arg_wh));
#endif
    
    value1 = ROUNDUP(globals.page.unshrunk_w, window_w - 2);

#ifdef  MOTIF
    {	/* account for menubar */
	static Dimension new_h;

	/* get rid of scrollbar */
	XtVaSetValues(globals.widgets.draw_widget, XtNwidth, (XtArgVal)1, XtNheight, (XtArgVal)1, NULL);
	XtVaGetValues(globals.widgets.clip_widget, XtNheight, &new_h, NULL);
	value2 = ROUNDUP(globals.page.unshrunk_h, new_h - 2);
    }
#else
    /* FIXME: value seems too small here! */
    value2 = ROUNDUP(globals.page.unshrunk_h, window_h - 2);
#endif

    return value1 > value2 ? value1 : value2;
}

void
do_set_shrinkfactor(int arg, Boolean set_resource)
{
    static int shrink_bak = -1;
    
    /* We don't store this as preference since it may affect initial window geometry. */
    /*  store_preference(NULL, "shrinkFactor", "%d", arg); */
    
    if (resource.mouse_mode == MOUSE_TEXT_MODE) {
	text_change_region(TEXT_SEL_CLEAR, NULL);
    }
    
    mane.shrinkfactor = arg;
    if (set_resource)
	resource.shrinkfactor = mane.shrinkfactor;
    
#if defined(NEW_MENU_CREATION) || defined(MOTIF)
    set_menu(&arg, Act_set_shrink_factor, check_int);
#if HAVE_XMP
    tb_set_zoom_sensitivity(arg != 1);
#endif
#else
    toggle_menu(arg, Act_set_shrink_factor);
#endif /* NEW_MENU_CREATION */
    if (arg != 1 && arg != shrink_bak) {
	shrink_bak = arg;
#if GREY
#if COLOR
	if (resource.use_grey)
	    fg_active = NULL;
#else 
	if (resource.use_grey)
	    init_pix();
#endif
#endif /* GREY */
	reset_fonts();
    }
    init_page();
    reconfig();

    htex_resize_page();

    /* this seems unneccessary */
/*     if (!resource.keep_flag) */
/* 	home(False); */

    globals.ev.flags |= EV_NEWPAGE;
    XFlush(DISP);
}

void
Act_set_shrink_factor(Widget w, XEvent *event,
		      String *params, Cardinal *num_params)
{
    int arg;
    /* Set a limit to the shrink factors allowed; otherwise xdvi may
       consume a lot of memory (even run out of memory in malloc) in
       the allocation for the subpixel lookup table pixeltbl,
       dvi-draw.c. The `correct' solution would be to recognize that at a
       certain shrink, the only pixel for a character will be always
       set to `on' anyway, so that we could do without the lookup table for
       very large shrink factors ... */
    static const int SHRINK_MAX = 999;
     
    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(event);

    warn_num_params("set-shrink-factor()", params, *num_params, 1);

    if (*num_params > 0) {
	if (**params == 'a')
	    arg = shrink_to_fit();
	else if (**params == '-')
	    arg = mane.shrinkfactor + 1;
	else if (**params == '+')
	    arg = mane.shrinkfactor - 1;
	else
	    arg = atoi(*params);
    }
    else if (!get_prefix_arg(&arg)) {
	arg = shrink_to_fit();
    }

    if (arg <= 0) {
	XBell(DISP, 0);
	statusline_print(STATUS_SHORT,
			 "No more enlarging possible");
	return;
    }
    
    if (arg > SHRINK_MAX) {
	XBell(DISP, 0);
	statusline_print(STATUS_SHORT,
			 "Shrink factor %d too large (maximum: %d)", arg, SHRINK_MAX);
	return;
    }
    
    /* SU: added clearing the window here, else old window content
       will survive changing shrink
    */
    if (globals.pausing.flag) {
	XClearWindow(DISP, mane.win);
    }
    
    statusline_print(STATUS_SHORT, "shrink factor: %d", arg);
#if 0
    /* Uncommented this, otherwise selecting `shrink to fit' with same value as
       current mane.shrinkfactor will clear the canvas (only fixed by changing shrink
       factor again). That bug is also present in xdvik-22.48-alpha3. */
    if (arg == mane.shrinkfactor) {
	return;
    }
#endif

    do_set_shrinkfactor(arg, True);

#if MOTIF    
    /* note: mustn't do that inside do_set_shrinkfactor(),
       or we get into an endless loop! */
    update_preferences_shrink();
#endif
}

void
Act_shrink_to_dpi(Widget w, XEvent *event,
		  String *params, Cardinal *num_params)
{
    int arg, arg_bak;
    Boolean clear_statusline = False;
    
    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(event);

    warn_num_params("shrink-to-dpi()", params, *num_params, 1);
    
    if (!get_int_arg(params, num_params, &arg))
	arg = 0;
    else
	clear_statusline = True;
    
    arg_bak = arg;
    
    if (arg > 0)
	arg = (double)resource.pixels_per_inch / arg + 0.5;

    if (arg <= 0) {
	XBell(DISP, 0);
	statusline_print(STATUS_SHORT,
			 "shrink-to-dpi requires a positive argument");
	return;
    }

    /* like elsewhere */
    if (globals.pausing.flag) {
	XClearWindow(DISP, mane.win);
    }
#if 0
    /* Uncommented this, otherwise selecting `shrink to fit' with same value as
       current mane.shrinkfactor will clear the canvas (only fixed by changing shrink
       factor again). That bug is also present in xdvik-22.48-alpha3. */
    if (arg == mane.shrinkfactor)
	return;
#endif
    do_set_shrinkfactor(arg, True);

#if MOTIF    
    /* note: mustn't do that inside do_set_shrinkfactor(),
       or we get into an endless loop! */
    update_preferences_shrink();
#endif
}

void
do_set_density(double newgamma, Boolean force, Boolean update_resource)
{
    
    /* like elsewhere */
    if (globals.pausing.flag) {
	XClearWindow(DISP, mane.win);
    }

#ifdef GREY
    if (resource.use_grey) {
	if (newgamma == resource.gamma && !force) {
	    statusline_print(STATUS_SHORT, "density value: %.3f", newgamma);
	    return;
	}
	resource.gamma = newgamma;
	if (update_resource)
	    globals.curr_gamma = resource.gamma;
	
#if COLOR
	fg_active = NULL;
	reset_colors();
#else
	init_pix();
	if (G_visual->class != TrueColor) {
	    return;
	}
	reset_fonts();
#endif /* COLOR */
	statusline_print(STATUS_SHORT, "density value: %.3f", newgamma);
    } else
#endif /* GREY */
    {
	reset_fonts();
	if (mane.shrinkfactor == 1) {
	    statusline_print(STATUS_SHORT,
		    "set-density ignored at magnification 1");
	    return;
	}
	statusline_print(STATUS_SHORT, "density value: %.3f", newgamma);
    }

    store_preference(NULL, "gamma", "%f", resource.gamma);

    globals.ev.flags |= EV_NEWPAGE;
    XFlush(DISP);
}

static void
Act_set_density(Widget w, XEvent *event,
		String *params, Cardinal *num_params)
{
    int arg;

    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(event);

    warn_num_params("set-density()", params, *num_params, 1);
    
    if (!get_int_arg(params, num_params, &arg)) {
	XBell(DISP, 0);
	return;
    }
/*     if (arg < 0) { */
/* 	XBell(DISP, 0); */
/* 	statusline_print(STATUS_SHORT, */
/* 			 "set-density requires a positive value"); */
/* 	return; */
/*     } */
    do_set_density(arg != 0 ? arg / 100.0 : 1.0, False, True);
#if MOTIF
    update_preferences_darkness();
#else
    store_preference(NULL, "gamma", "%f", resource.gamma);
#endif
}


static void
Act_change_density(Widget w, XEvent *event,
		   String *params, Cardinal *num_params)
{
    int arg;
    double diff;
    double oldgamma = resource.gamma;
    UNUSED(w);
    UNUSED(event);

    if (block_this_mouse_event())
	return;
    
    warn_num_params("change-density()", params, *num_params, 1);
    
    if (!get_int_arg(params, num_params, &arg)) {
	XBell(DISP, 0);
	return;
    }
    diff = oldgamma / arg;
    if (oldgamma + diff <= 0.0)
	oldgamma = 0.0;
    else
	oldgamma += diff;
    do_set_density(oldgamma, False, True);
#if MOTIF
    update_preferences_darkness();
#endif
}

static void
Act_fullscreen(Widget w, XEvent *event,
	       String *params, Cardinal *num_params)
{
    Dimension main_win_w, main_win_h;
    static int orig_x = 0, orig_y = 0;
#ifndef MOTIF
    static Dimension get_x, get_y;
#endif
    static Dimension old_w = 0, old_h = 0;
    Dimension panel_width = 0;
#if 0
    static Dimension w_old = 0, h_old = 0;
#endif

    if (block_this_mouse_event())
	return;

    UNUSED(w);
    UNUSED(event);
    
    if (!toggle_arg(resource.fullscreen, params, num_params)) {
	return;
    }
    
    resource.fullscreen = !resource.fullscreen;
    
#ifndef MOTIF
    panel_width = get_panel_width();
#endif
    
    if (resource.fullscreen) {
	/* when toggling to fullscreen, save current scrollbar values
	   and window geometry */
	XtVaGetValues(globals.widgets.top_level, XtNwidth, &old_w, XtNheight, &old_h, NULL);
	/*  	fprintf(stderr, "saved geometry: %dx%d\n", old_w, old_h); */
#ifdef MOTIF
	if (globals.widgets.x_bar != NULL)
	    XtVaGetValues(globals.widgets.x_bar, XmNvalue, &orig_x, NULL);
	if (globals.widgets.y_bar != NULL)
	    XtVaGetValues(globals.widgets.y_bar, XmNvalue, &orig_y, NULL);
#else
	get_xy();
	if (globals.widgets.x_bar != NULL)
	    XtVaGetValues(globals.widgets.clip_widget, XtNx, &get_x, NULL);
	if (globals.widgets.y_bar != NULL)
	    XtVaGetValues(globals.widgets.clip_widget, XtNy, &get_y, NULL);
	orig_x = -(get_x - window_x);
	orig_y = -(get_y - window_y);
#endif /* MOTIF */
	/*  	fprintf(stderr, "Current offsets: %d, %d, %d, %d\n", orig_x, window_x, orig_y, window_y); */
    }
#if 0 /* TODO: don't hardcode w/h values -
	 what's wrong with the set_windowsize() call below? */    
    if (resource.fullscreen) {
	XWindowAttributes attr;
	if (XGetWindowAttributes(DISP, XtWindow(globals.widgets.top_level), &attr)) {
	    w_old = attr.width;
	    h_old = attr.height;
	}
	main_win_w = WidthOfScreen(SCRN);
	main_win_h = HeightOfScreen(SCRN);
    }
    else if (w_old > 0 && h_old > 0) {
	main_win_w = w_old;
	main_win_h = h_old;
    }
    else {
	main_win_w = 800;
	main_win_h = 600;
    }
#else
    if (resource.fullscreen) {
	set_windowsize(&main_win_w, &main_win_h, panel_width, 0, False);
    }
    else { /* re-use old window sizes, or initialize them if started in fullscreen mode */
	if (old_w == 0 || old_h == 0) /* started in fullscreen mode */
	    set_windowsize(&old_w, &old_h, panel_width, 0, False);
	else
	    set_windowsize(&old_w, &old_h, panel_width, 0, True);
    }
#endif

/*      fprintf(stderr, "reconfigure window!\n"); */
    if (resource.fullscreen)
	reconfigure_window(resource.fullscreen, main_win_w, main_win_h, True);
    else {
	reconfigure_window(resource.fullscreen, old_w, old_h, True);
    }

    /*      fprintf(stderr, "orig values: %d, %d\n", orig_x, orig_y); */
    /* restore horizontal scroll position */
    if (resource.keep_flag && orig_x != 0 && globals.widgets.x_bar != NULL) {
#ifdef MOTIF
	if (!resource.fullscreen) {
	    /* only scroll back in non-fullscreen mode. This was:
	       if (resource.fullscreen)
	           (void)set_bar_value(globals.widgets.y_bar, orig_y, (int)(globals.page.h - mane.height));
	       else ...
	       but that was broken (bogus values in globals.page.h - mane.height).
	    */
	    (void)set_bar_value(globals.widgets.x_bar, orig_x, INT_MAX);
	}
#else
	int curr_x;
	get_xy();
	XtVaGetValues(globals.widgets.clip_widget, XtNx, &get_x, NULL);
	curr_x = -(get_x - window_x);
	if (curr_x - orig_x > 0)
	    XtCallCallbacks(globals.widgets.x_bar, XtNscrollProc, (XtPointer)(curr_x - orig_x));
#endif /* MOTIF */
    }

    /* restore vertical scroll position */
    if (resource.keep_flag && orig_y != 0 && globals.widgets.y_bar != NULL) {
#ifdef MOTIF
	if (!resource.fullscreen) {
	    /* only scroll back in non-fullscreen mode. This was:
	       if (resource.fullscreen)
	           (void)set_bar_value(globals.widgets.y_bar, orig_y, (int)(globals.page.h - mane.height));
	       else ...
	       but that was broken (bogus values in globals.page.h - mane.height).
	    */
	    (void)set_bar_value(globals.widgets.y_bar, orig_y, INT_MAX);
	}
#else
	int curr_y;
	get_xy();
	XtVaGetValues(globals.widgets.clip_widget, XtNy, &get_y, NULL);
	curr_y = -(get_y - window_y);
	if (curr_y - orig_y > 0)
	    XtCallCallbacks(globals.widgets.x_bar, XtNscrollProc, (XtPointer)(curr_y - orig_y));
#endif /* MOTIF */
    }
    handle_x_scroll(NULL, NULL, NULL, NULL);
    handle_y_scroll(NULL, NULL, NULL, NULL);
}

#ifdef GREY

static void
Act_set_greyscaling(Widget w, XEvent *event,
		    String *params, Cardinal *num_params)
{
    int arg;

    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(event);

    warn_num_params("set-greyscaling()", params, *num_params, 1);
    
    if (!get_int_arg(params, num_params, &arg)) { /* no arg, toggle */
	if (!toggle_arg(resource.use_grey, params, num_params)) {
	    return;
	}
	resource.use_grey = !resource.use_grey;
	if (resource.use_grey) {
	    statusline_print(STATUS_SHORT, "greyscaling on");
	}
	else {
	    statusline_print(STATUS_SHORT, "greyscaling off");
	}
	globals.ev.flags |= EV_NEWPAGE;
	XFlush(DISP);
	return;
    }

    switch (arg) {
    case 0:
	resource.use_grey = False;
	statusline_print(STATUS_SHORT, "greyscaling off");
	break;
    case 1:
	resource.use_grey = True;
	statusline_print(STATUS_SHORT, "greyscaling on");
	break;
    default:
	{
	    float newgamma = arg != 0 ? arg / 100.0 : 1.0;
	    resource.use_grey = newgamma;
	    statusline_print(STATUS_SHORT, "greyscale value: %.1f", newgamma);
	}
    }

    /* like elsewhere */
    if (globals.pausing.flag) {
	XClearWindow(DISP, mane.win);
    }
    
    if (resource.use_grey) {
	if (G_visual->class != TrueColor)
	    init_plane_masks();
#if COLOR
	fg_active = NULL;
#else
	init_pix();
#endif
    }
    reset_fonts();
    globals.ev.flags |= EV_NEWPAGE;
    XFlush(DISP);
}

#endif

#if COLOR

void
do_toggle_color(Boolean update_resource)
{
    if (resource.use_color) {
	resource.use_color = False;
	full_reset_colors();
	scanned_page_color = total_pages;
#if PS
	if (ignore_papersize_specials || scanned_page_ps <= total_pages) {
	    scanned_page = scanned_page_ps;
	}
#endif
	statusline_print(STATUS_SHORT, "color specials off");
    }
    else {
	resource.use_color = True;
	scanned_page = scanned_page_color = scanned_page_reset;
	statusline_print(STATUS_SHORT, "color specials on");
    }
    if (update_resource)
	globals.curr_use_color = resource.use_color;
    
#ifdef MOTIF
    update_preferences_color();
#endif
    globals.ev.flags |= EV_NEWPAGE;
}

static void
Act_set_color(Widget w, XEvent *event,
	      String *params, Cardinal *num_params)
{
    UNUSED(w);
    UNUSED(event);

    if (block_this_mouse_event())
	return;
    
    if (!toggle_arg(resource.use_color, params, num_params)) {
	return;
    };
	
    /* like elsewhere */
    if (globals.pausing.flag) {
	XClearWindow(DISP, mane.win);
    }

    do_toggle_color(True);
}

#endif /* COLOR */

#if PS

void
Act_set_ps(Widget w, XEvent *event,
	   String *params, Cardinal *num_params)
{
    int arg;

    if (block_this_mouse_event())
	return;
    
    UNUSED(event);
    UNUSED(w);
    
    if (!get_int_arg(params, num_params, &arg))
	resource.postscript++;
    else
	resource.postscript = arg;

    if (resource.postscript > 2)
	resource.postscript = 0;

#ifdef PS_GS
    if (!resource.useGS) {
	if (resource.postscript > 0) {
	    popup_message(globals.widgets.top_level,
			  MSG_WARN,
			  "This version of xdvi depends on ghostscript for rendering Postscript images. "
			  "Postscript rendering cannot be activated if the option ``-noghostscript'' is used "
			  "or if the resource ``Ghostscript'' is set to false.",
			  /* message */
			  "Option ``-noghostscript'' is active; "
			  "cannot enable Postscript rendering without ghostscript.");
	}
	resource.postscript = 0;
    }
#endif
    if (resource.postscript > 0) {
	scanned_page_ps = scanned_page_ps_bak;
	if (scanned_page > scanned_page_ps)
	    scanned_page = scanned_page_ps;
	if (resource.postscript == 1) {
	    statusline_print(STATUS_SHORT, "Postscript rendering on");
	}
	else {
	    statusline_print(STATUS_SHORT, "Postscript rendering on (with bounding box)");
	}
    }
    else {
	scanned_page_ps_bak = scanned_page_ps;
	scanned_page_ps = total_pages;
#if COLOR
	if (ignore_papersize_specials || scanned_page_color <= total_pages) {
	    scanned_page = scanned_page_color;
	}
#endif
	statusline_print(STATUS_SHORT, "Postscript rendering off; displaying bounding box instead");
    }

    store_preference(NULL, "postscript", "%d", resource.postscript);
    
    psp.toggle(resource.postscript);
#if defined(NEW_MENU_CREATION) || defined(MOTIF)
    set_menu(&resource.postscript, Act_set_ps, check_int);
#else
    toggle_menu(resource.postscript, Act_set_ps);
#endif /* NEW_MENU_CREATION */
    /* like elsewhere */
    if (globals.pausing.flag) {
	XClearWindow(DISP, mane.win);
    }
    
    globals.ev.flags |= EV_PS_TOGGLE;
    XFlush(DISP);
}

#endif /* PS */

void
Act_htex_back(Widget w, XEvent *event,
	      String *params, Cardinal *num_params)
{
    UNUSED(w);
    UNUSED(event);
    UNUSED(params);
    UNUSED(num_params);

    if (block_this_mouse_event())
	return;
    
    htex_back();
}

void
Act_htex_forward(Widget w, XEvent *event,
		 String *params, Cardinal *num_params)
{
    UNUSED(w);
    UNUSED(event);
    UNUSED(params);
    UNUSED(num_params);

    if (block_this_mouse_event())
	return;
    
    htex_forward();
}

static void
Act_htex_anchorinfo(Widget w, XEvent *event,
		    String *params, Cardinal *num_params)
{
    int x, y;
    Window dummy;

    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(params);
    UNUSED(num_params);

    (void)XTranslateCoordinates(DISP, event->xkey.window, mane.win,
				event->xkey.x, event->xkey.y, &x, &y, &dummy);
    htex_displayanchor(x, y);
}

#ifdef PS_GS
void
Act_set_gs_alpha(Widget w, XEvent *event,
		 String *params, Cardinal *num_params)
{
    UNUSED(w);
    UNUSED(event);

    if (block_this_mouse_event())
	return;
    
    if (!toggle_arg(resource.gs_alpha, params, num_params)) {
	return;
    }
    resource.gs_alpha = !resource.gs_alpha;

    if (resource.gs_alpha) {
	statusline_print(STATUS_SHORT, "ghostscript alpha active");
    }
    else {
	statusline_print(STATUS_SHORT, "ghostscript alpha inactive");
    }

    store_preference(NULL, "gsAlpha", "%s", resource.gs_alpha ? "True" : "False");
    
#if defined(NEW_MENU_CREATION) || defined(MOTIF)
    set_menu(&resource.gs_alpha, Act_set_gs_alpha, check_toggle);
#else
    toggle_menu(resource.gs_alpha, Act_set_gs_alpha);
#endif /* NEW_MENU_CREATION */
#if GS_PIXMAP_CLEARING_HACK
    had_ps_specials = False; /* else infinite loop and/or crash in redraw! */
#endif
    /* like elsewhere */
    if (globals.pausing.flag) {
	XClearWindow(DISP, mane.win);
    }
    
    globals.ev.flags |= EV_PS_TOGGLE;
    XFlush(DISP);
}
#endif

static void
Act_reread_dvi_file(Widget w, XEvent *event,
		    String *params, Cardinal *num_params)
{
    UNUSED(w);
    UNUSED(event);
    UNUSED(params);
    UNUSED(num_params);

    if (block_this_mouse_event())
	return;
    
/*      fprintf(stderr, "reread file!\n"); */
    globals.ev.flags |= EV_RELOAD;
}

static void
Act_discard_number(Widget w, XEvent *event,
		   String *params, Cardinal *num_params)
{
    UNUSED(w);
    UNUSED(event);
    UNUSED(params);
    UNUSED(num_params);

    if (block_this_mouse_event())
	return;
    
    m_have_arg = False;
    m_number = 0;
    m_sign = 1;
    if (resource.expert_mode & XPRT_SHOW_STATUSLINE) /* too distracting for stdout */
	statusline_print(STATUS_SHORT, "numerical prefix discarded");
}

/*
 * Actions to support dragging the image.
 */

static int drag_last_x, drag_last_y;	/* last position of cursor */

static int text_last_x = -1;
static int text_last_y = -1;
static int text_last_page = -1;

static void drag_motion(XEvent *);
static void drag_release(XEvent *);

/* access for hyperref.c */
Boolean dragging_text_selection(void)
{
    MYTRACE((stderr, "dragging selection? %d", mouse_motion == text_motion));
    return mouse_motion == text_motion;
}

static void
text_release(XEvent * event)
{
    int ulx, uly, w, h;
    static char *text;
    int text_len = 0;
    
    UNUSED(event);

    MYTRACE((stderr, "text_release!"));
    
    if (mouse_motion == null_mouse)
	return;
    mouse_motion = mouse_release = null_mouse;

    w = text_last_x - drag_last_x;
    h = text_last_y - drag_last_y;

    if (w == 0 || h == 0) {
	text_last_x = text_last_y = -1;
	drag_last_x = drag_last_y = -1;
	text_last_page = -1;
	return;
    }

    if (w < 0) {
	ulx = drag_last_x + w;
	w = -w;
    }
    else
	ulx = drag_last_x;

    if (h < 0) {
	uly = drag_last_y + h;
	h = -h;
    }
    else
	uly = drag_last_y;

    free(text);
    /* this allocates text */
    text = get_text_selection(&text_len,
			      ulx * currwin.shrinkfactor,
			      uly * currwin.shrinkfactor,
			      (ulx + w) * currwin.shrinkfactor,
			      (uly + h) * currwin.shrinkfactor);
    if (text[0] == '\0') {
	/* fprintf(stdout, "Text selection empty.\n"); */
	return;
    }

    TRACE_GUI((stderr, "Selected `%s'", text));

    if (text_len > 4 * XMaxRequestSize(DISP) - 32) {
	MYTRACE((stderr, "selection too large: %d bytes", text_len));
	XBell(DISP, 10);
	statusline_print(STATUS_MEDIUM, "Selection too large (%d bytes, maximum %d bytes)",
			 text_len, 4 * XMaxRequestSize(DISP) - 32);
	MYTRACE((stderr, "after statusline_print1"));
	return;
    }
    
    if (!set_selection(text, globals.widgets.top_level)) {
	MYTRACE((stderr, "setting selection failed"));
	XBell(DISP, 10);
	statusline_print(STATUS_MEDIUM, "Could not set primary selection!");
	MYTRACE((stderr, "after statusline_print2"));
	text_change_region(TEXT_SEL_CLEAR, NULL);
	MYTRACE((stderr, "after text_change_region"));
    }
    MYTRACE((stderr, "End of text_release"));
}

void
text_motion(XEvent *event)
{
    text_change_region(TEXT_SEL_MOVE, event);
}

static void
get_rectangle(XRectangle *rect, int x, int y, int last_x, int last_y)
{
    rect->width = ABS(x - last_x);
    rect->height = ABS(y - last_y);
    rect->x = (x < last_x) ? x : last_x;
    rect->y = (y < last_y) ? y : last_y;
}

static void
crop_to_window(int *x, int *y)
{
    if (*x < -currwin.base_x + 1)
	*x = -currwin.base_x + 1;
    else if (*x > -currwin.base_x + (int)ROUNDUP(pageinfo_get_page_width(current_page), currwin.shrinkfactor) + 1)
	*x = -currwin.base_x + ROUNDUP(pageinfo_get_page_width(current_page), currwin.shrinkfactor) + 1;
    
    if (*y < -currwin.base_y + 1)
	*y = -currwin.base_y + 1;
    else if (*y > -currwin.base_y + (int)ROUNDUP(pageinfo_get_page_height(current_page), currwin.shrinkfactor) + 1)
	*y = -currwin.base_y + (int)ROUNDUP(pageinfo_get_page_height(current_page), currwin.shrinkfactor) + 1;
}

void
text_change_region(textSelectionT mode, XEvent *event)
{
    static GC bboxGC = 0;
    static GC redrawGC = 0; /* needed since bboxGC is clipped to diff of old and new region */

    MYTRACE((stderr, "text_change_region: %d", mode));
    
    if (bboxGC == 0) {
	XGCValues values;
	unsigned long valuemask;

	values.function = GXinvert; /* as in search code */
	if (values.function == GXinvert) {
	    valuemask = GCFunction;
	}
	else {
	    values.foreground = WhitePixelOfScreen(SCRN) ^ BlackPixelOfScreen(SCRN);
	    /* 		fprintf(stderr, "foreground: 0x%lx, white pixel: 0x%lx, black pixel: 0x%lx\n", */
	    /* 			values.foreground, WhitePixelOfScreen(SCRN), BlackPixelOfScreen(SCRN)); */
	    valuemask = GCFunction | GCForeground;
	}
	values.line_width = 1;
	valuemask |= GCLineWidth;
	bboxGC = XCreateGC(DISP, XtWindow(globals.widgets.top_level), valuemask, &values);
	redrawGC = XCreateGC(DISP, XtWindow(globals.widgets.top_level), valuemask, &values);
    }

    MYTRACE((stderr, "text_change_region: after bboxGC"));
    switch (mode) {
    case TEXT_SEL_MOVE:
	{
	    int x, y;
	    
	    Window dummy;

	    XRectangle redraw = { -1, -1, 0, 0 };

	    ASSERT(event != NULL, "event in text_change_region() musn't be NULL for TEXT_SEL_MOVE");

	    (void)XTranslateCoordinates(DISP, event->xkey.window, mane.win,
					event->xkey.x, event->xkey.y,
					&x, &y,
					&dummy);

	    crop_to_window(&x, &y);

	    get_rectangle(&redraw, x, y, drag_last_x, drag_last_y);

	    /*
	     * If we have an old region, we want to clip the GC to the area:
	     *
	     * (clip \cup redraw) - (clip \cap redraw)
	     *
	     * and redraw both rectangle areas; otherwise, just draw the redraw area.
	     */

	    if (text_last_x != -1 && text_last_y != -1) {

		XRectangle clip = { -1, -1, 0, 0 };
		
		Region clip_region = XCreateRegion();
		Region redraw_region = XCreateRegion();
		Region union_region = XCreateRegion();
		Region intersect_region = XCreateRegion();

		get_rectangle(&clip, text_last_x, text_last_y, drag_last_x, drag_last_y);

		XUnionRectWithRegion(&clip, clip_region, clip_region);
		XUnionRectWithRegion(&redraw, redraw_region, redraw_region);

		XUnionRegion(clip_region, redraw_region, union_region);
		XIntersectRegion(clip_region, redraw_region, intersect_region);
		
		XSubtractRegion(union_region, intersect_region, redraw_region);

		XSetRegion(DISP, bboxGC, redraw_region);

		XDestroyRegion(clip_region);
		XDestroyRegion(redraw_region); 
		XDestroyRegion(union_region); 
		XDestroyRegion(intersect_region); 
		
		XFillRectangle(DISP, mane.win, bboxGC, clip.x, clip.y, clip.width, clip.height);
	    }
	    
	    XFillRectangle(DISP, mane.win, bboxGC, redraw.x, redraw.y, redraw.width, redraw.height);

	    text_last_x = x;
	    text_last_y = y;
	    text_last_page = current_page;
	}
	break;
    case TEXT_SEL_CLEAR:
	unset_selection(globals.widgets.top_level);
    case TEXT_SEL_ERASE:
    case TEXT_SEL_REDRAW:
	if (text_last_page == current_page
	    && text_last_x != -1 && text_last_y != -1
	    && drag_last_x != -1 && drag_last_y != -1) {

	    XRectangle clear = { -1, -1, 0, 0 };

	    get_rectangle(&clear, text_last_x, text_last_y, drag_last_x, drag_last_y);
	    
	    if (mode == TEXT_SEL_CLEAR) {
		text_last_x = text_last_y = drag_last_x = drag_last_y = -1;
		text_last_page = -1;
		/* Note ZLB: the region is erased instead of inverted to avoid
		 * multiple inverting problem. An exposure is generated to
		 * make the region redrawn */
 		clearexpose(&mane, clear.x, clear.y, clear.width, clear.height);
	    }
	    else if (clip_region_to_rect(&clear)) {
		if (mode == TEXT_SEL_ERASE) {
		    /* If width or height are 0, XClearArea will clear entire window
		     * from coordinates x, y, so check for that: */
		    if (clear.width > 0 && clear.height > 0)
		    	XClearArea(DISP, mane.win, clear.x, clear.y, clear.width, clear.height, False);
		}
		else
		    XFillRectangle(DISP, mane.win, redrawGC, clear.x, clear.y, clear.width, clear.height);
	    }
	}
	break;
    }
    MYTRACE((stderr, "text_change_region: done"));
}

void
text_selection_start(XEvent *event)
{
    int x, y;
    Window dummy;

    /* erase existing region */
    text_change_region(TEXT_SEL_CLEAR, NULL);

    (void)XTranslateCoordinates(DISP, event->xkey.window, mane.win,
				event->xkey.x, event->xkey.y,
				&x, &y,
				&dummy);	/* throw away last argument */

    crop_to_window(&x, &y);
    
    drag_last_x = x;
    drag_last_y = y;

    text_last_x = text_last_y = -1;

    MYTRACE((stderr, "selection start; mouse_release: %p; null: %p!",
	     (void *)mouse_release, (void *)null_mouse));
    if (mouse_release == null_mouse) {
	MYTRACE((stderr, "init text_motion!"));
	mouse_motion = text_motion;
	mouse_release = text_release;
    }
}

/*
 * If action list for <Btn1Down> does NOT contain a magnifier() binding,
 * return that action list; else return NULL.
 */
static char *
btn1_no_magnifier_binding(void)
{
    static Boolean initialized = False;
    static char *btn1_binding = NULL;

    if (!initialized) { /* cache value of previous calls */
	if (resource.main_translations != NULL) {
	    if ((btn1_binding = strstr(resource.main_translations, "<Btn1Down>")) != NULL) {
		char *eol, *test;
		btn1_binding = strchr(btn1_binding, ':');
		if (btn1_binding != NULL)
		    btn1_binding++;
		while (isspace((int)*btn1_binding))
		    btn1_binding++;
		eol = strchr(btn1_binding, '\n');
		if (eol == NULL)
		    eol = btn1_binding + strlen(btn1_binding);
		if ((test = strstr(btn1_binding, "magnifier(")) == NULL || test > eol) {
		    /* binding not found */
		    return btn1_binding;
		}
	    }
	}
/* 	fprintf(stderr, "MAG: %d\n", btn1_has_magnifier); */
	initialized = True;
    }
    return btn1_binding;
}

void
Act_switch_mode(Widget w, XEvent *event,
		String *params, Cardinal *num_params)
{
    mouseModeT prev_mode = resource.mouse_mode;
    int arg = -1;
    char *ptr;
    
    if (block_this_mouse_event())
	return;
    
    UNUSED(w);

    if ((ptr = btn1_no_magnifier_binding()) != NULL) {
	XBell(DISP, 0);
	statusline_print(STATUS_MEDIUM,
			 "Cannot switch modes: Action list for Btn1Down (%s) "
			 "does not contain magnifier() action.", ptr);
	return;
    }
    
/*      fprintf(stderr, "prev mode: %d\n", prev_mode); */
    
    if (get_int_arg(params, num_params, &arg)) {
	if (arg < MOUSE_MAGNIFIER_MODE || arg >= MOUSE_MAX_MODE) {
	    statusline_print(STATUS_SHORT, "Argument for Act_switch_mode outside of range from %d to %d",
			     MOUSE_MAGNIFIER_MODE, MOUSE_MAX_MODE - 1);
	    resource.mouse_mode++;
	}
	else
	    resource.mouse_mode = (mouseModeT)arg;
    }
    else
	resource.mouse_mode++;

    /* check if wrapped */
    if (resource.mouse_mode >= MOUSE_MAX_MODE)
	resource.mouse_mode = MOUSE_MAGNIFIER_MODE;

    /* undo effects of previous mode */
    switch (prev_mode) {
    case MOUSE_RULER_MODE:
	clear_ruler();
	mouse_motion = mouse_release = null_mouse;
	break;
    case MOUSE_TEXT_MODE:
	text_change_region(TEXT_SEL_CLEAR, NULL);
	mouse_motion = mouse_release = null_mouse;
	break;
    default: /* magnifier, nothing to do */
	    break;
    }
    
    if (resource.mouse_mode == MOUSE_RULER_MODE) {
	XDefineCursor(DISP, CURSORWIN, globals.cursor.rule);
	statusline_print(STATUS_SHORT, "Ruler mode; click Mouse-1 to set ruler");
	show_ruler(event);
	show_distance_from_ruler(event, False);
    }
    else if (resource.mouse_mode == MOUSE_TEXT_MODE) {
	statusline_print(STATUS_SHORT, "Text selection mode; click and drag Mouse-1 to select a region");
    }
    else { /* default: MOUSE_MAGNIFIER_MODE */
	statusline_print(STATUS_SHORT, "Magnifier mode; click Mouse-1 to magnify text");
	mouse_motion = mouse_release = null_mouse;
    }
    
    globals.ev.flags |= EV_CURSOR;
    XFlush(DISP);
    
#if defined(NEW_MENU_CREATION) || defined(MOTIF)
    set_menu(&resource.mouse_mode, Act_switch_mode, check_int);
#else
    toggle_menu(resource.mouse_mode, Act_switch_mode);
#endif /* NEW_MENU_CREATION */
    store_preference(NULL, "mouseMode", "%d", resource.mouse_mode);
}

static void
Act_text_mode(Widget w, XEvent *event,
	      String *params, Cardinal *num_params)
{
    char *ptr;
    
    UNUSED(w);
    UNUSED(event);
    UNUSED(params);
    UNUSED(num_params);

    if (block_this_mouse_event())
	return;

    if ((ptr = btn1_no_magnifier_binding()) != NULL) {
	XBell(DISP, 0);
	statusline_print(STATUS_MEDIUM,
			 "Cannot switch modes: Action list for Btn1Down (%s) "
			 "does not contain magnifier() action.", ptr);
	return;
    }
    
    if (resource.mouse_mode == MOUSE_TEXT_MODE) {
	resource.mouse_mode++;
	if (resource.mouse_mode >= MOUSE_MAX_MODE)
	    resource.mouse_mode = MOUSE_MAGNIFIER_MODE;
    }
    else
	resource.mouse_mode = MOUSE_TEXT_MODE;

    if (resource.mouse_mode == MOUSE_TEXT_MODE) {
	if (mouse_release != null_mouse && mouse_release != text_release)
	    return;
	
	globals.ev.flags |= EV_CURSOR;
	
        XFlush(DISP);
    }
    else {
	mouse_motion = mouse_release = null_mouse;
	globals.ev.flags |= EV_CURSOR;

	text_change_region(TEXT_SEL_CLEAR, NULL);
	
	XFlush(DISP);
    }
#if defined(NEW_MENU_CREATION) || defined(MOTIF)
    set_menu(&resource.mouse_mode, Act_switch_mode, check_int);
#else
    toggle_menu(resource.mouse_mode, Act_switch_mode);
#endif /* NEW_MENU_CREATION || MOTIF */
}

static void
Act_drag(Widget w, XEvent *event,
	 String *params, Cardinal *num_params)
{
    UNUSED(w);

    if (block_this_mouse_event())
	return;
    
    if (mouse_release != null_mouse && mouse_release != drag_release)
	return;

    if (resource.mouse_mode == MOUSE_TEXT_MODE && text_last_page != -1
	/* this was:
	   && (text_last_x != drag_last_x || text_last_y != drag_last_y)
	   but that isn't restrictive enough */
	) { /* dragging would mess up region drawing */
	XBell(DISP, 0);
	statusline_print(STATUS_SHORT, "Dragging page not possible while selection is active");
	return;
    }
    
    if (*num_params != 1) {
	XDVI_WARNING((stderr, "drag() requires 1 argument (got %d)", *num_params));
	return;
    }
    switch (**params) {
    case '|':
	globals.cursor.flags |= CURSOR_DRAG_V;
	break;
    case '-':
	globals.cursor.flags |= CURSOR_DRAG_H;
	break;
    case '+':
	globals.cursor.flags |= CURSOR_DRAG_A;
	break;
    default:
	XDVI_WARNING((stderr, "drag(): Valid arguments are `+', `|' or `-'"));
    }
    
    globals.ev.flags |= EV_CURSOR;
    
    if (mouse_release == null_mouse) {
	mouse_motion = drag_motion;
	mouse_release = drag_release;
	drag_last_x = event->xbutton.x_root;
	drag_last_y = event->xbutton.y_root;
    }
    else
	drag_motion(event);

    XFlush(DISP);
}


static void
drag_motion(XEvent * event)
{
#ifdef MOTIF
    get_xy();
#endif

    if (globals.cursor.flags & (CURSOR_DRAG_H | CURSOR_DRAG_A)) { /* horizontal motion */
#ifdef MOTIF
	(void)set_bar_value(globals.widgets.x_bar,
			    drag_last_x - event->xbutton.x_root - window_x,
			    (int)(globals.page.w - mane.width));
#else
	if (globals.widgets.x_bar != NULL) {
	    XtCallCallbacks(globals.widgets.x_bar, XtNscrollProc,
			    (XtPointer) (drag_last_x - event->xbutton.x_root));
	}
#endif
	drag_last_x = event->xbutton.x_root;
    }

    if (globals.cursor.flags & (CURSOR_DRAG_V | CURSOR_DRAG_A)) { /* vertical motion */
#ifdef MOTIF
	(void)set_bar_value(globals.widgets.y_bar,
			    drag_last_y - event->xbutton.y_root - window_y,
			    (int)(globals.page.h - mane.height));
#else
	if (globals.widgets.y_bar != NULL) {
	    XtCallCallbacks(globals.widgets.y_bar, XtNscrollProc,
			    (XtPointer) (drag_last_y - event->xbutton.y_root));
	}
#endif
	drag_last_y = event->xbutton.y_root;
    }
    handle_x_scroll(NULL, NULL, NULL, NULL);
    handle_y_scroll(NULL, NULL, NULL, NULL);
}


static void
drag_release(XEvent * event)
{
    drag_motion(event);
    mouse_motion = mouse_release = null_mouse;

    globals.cursor.flags &= ~(CURSOR_DRAG_H | CURSOR_DRAG_V | CURSOR_DRAG_A);
    globals.ev.flags |= EV_CURSOR;
    XFlush(DISP);
}



/* Wheel mouse support.  */

static int wheel_button = -1;

static void
Act_wheel(Widget w, XEvent *event,
	  String *params, Cardinal *num_params)
{
    int dist;

    UNUSED(w);

    if (block_this_mouse_event())
	return;

    if (*num_params != 1) {
	XDVI_WARNING((stderr, "wheel() requires 1 argument (got %d)", *num_params));
	return;
    }
    dist = (strchr(*params, '.') == NULL) ? atoi(*params)
	: (int)(my_atof(*params) * resource.wheel_unit);
#ifdef MOTIF
    get_xy();
    set_bar_value(globals.widgets.y_bar, dist - window_y, (int)(globals.page.h - mane.height));
#else
    if (globals.widgets.y_bar != NULL)
	XtCallCallbacks(globals.widgets.y_bar, XtNscrollProc, (XtPointer) dist);
#endif

    wheel_button = event->xbutton.button;

    handle_y_scroll(NULL, NULL, NULL, NULL);
}


/* Internal mouse actions.  */

static void
Act_motion(Widget w, XEvent *event,
	   String *params, Cardinal *num_params)
{
    /* remember last position, to do this only when pointer is actually moved */
    static int old_x = -1, old_y = -1;
    int x, y;

    UNUSED(w);
    UNUSED(params);
    UNUSED(num_params);

    if (block_this_mouse_event()) {
	MYTRACE((stderr, "returning!"));
	return;
    }

    if (resource.mouse_mode == MOUSE_RULER_MODE) {
	show_distance_from_ruler(event, False);
    }
    /* This used to be:
          (abs(x - old_x) > x_threshold || abs(y - old_y) > y_threshold))
       but that didn't work too well either. Just change it whenever user
       moves the mouse. */       
    if (!MAGNIFIER_ACTIVE && resource.mouse_mode != MOUSE_RULER_MODE
	&& pointerlocate(&x, &y) && (x != old_x || y != old_y)) {
	htex_displayanchor(x, y);
	old_x = x;
	old_y = y;
    }

    if ((int)(event->xbutton.button) != wheel_button) {
	mouse_motion(event);
    }
}


static void
Act_release(Widget w, XEvent *event,
	    String *params, Cardinal *num_params)
{
    UNUSED(w);
    UNUSED(params);
    UNUSED(num_params);

    if (block_this_mouse_event())
	return;
    
    if ((int)(event->xbutton.button) == wheel_button) {
	wheel_button = -1;
	return;
    }

    mouse_release(event);
}

void
Act_ruler_mode(Widget w, XEvent *event,
	       String *params, Cardinal *num_params)
{
    char *ptr;
    
    UNUSED(w);
    UNUSED(params);
    UNUSED(num_params);

    if (block_this_mouse_event())
	return;

    if ((ptr = btn1_no_magnifier_binding()) != NULL) {
	XBell(DISP, 0);
	statusline_print(STATUS_MEDIUM,
			 "Cannot switch modes: Action list for Btn1Down (%s) "
			 "does not contain magnifier() action.", ptr);
	return;
    }
    
    if (resource.mouse_mode == MOUSE_RULER_MODE) {
	resource.mouse_mode++;
	if (resource.mouse_mode >= MOUSE_MAX_MODE)
	    resource.mouse_mode = MOUSE_MAGNIFIER_MODE;
    }
    else
	resource.mouse_mode = MOUSE_RULER_MODE;
    
    if (resource.mouse_mode == MOUSE_RULER_MODE) {
	XDefineCursor(DISP, CURSORWIN, globals.cursor.rule);
	statusline_print(STATUS_SHORT, "Ruler mode on; use Mouse-1 to set/drag ruler");
	show_ruler(event);
	show_distance_from_ruler(event, False);
    }
    else {
	if (globals.cursor.flags & CURSOR_LINK) {
	    XDefineCursor(DISP, CURSORWIN, globals.cursor.link);
	}
	else {
	    XDefineCursor(DISP, CURSORWIN, globals.cursor.ready);
	}
	statusline_print(STATUS_SHORT, "Ruler mode off");
	clear_ruler();
	mouse_motion = mouse_release = null_mouse;
    }
#if defined(NEW_MENU_CREATION) || defined(MOTIF)
    set_menu(&resource.mouse_mode, Act_switch_mode, check_int);
#else
    toggle_menu(resource.mouse_mode, Act_switch_mode);
#endif /* NEW_MENU_CREATION || MOTIF */
}


/* Actions for source specials.  */

void
Act_source_special(Widget w, XEvent *event,
		   String *params, Cardinal *num_params)
{
    Window dummy;

    UNUSED(w);
    UNUSED(params);
    UNUSED(num_params);

    if (block_this_mouse_event())
	return;
    
    if ((event->type == ButtonPress && mouse_release != null_mouse)
	|| MAGNIFIER_ACTIVE) {
	XBell(DISP, 0);
	return;
    }

    source_reverse_x = event->xbutton.x;
    source_reverse_y = event->xbutton.y;
    if (event->xbutton.window != mane.win)
	(void)XTranslateCoordinates(DISP,
				    RootWindowOfScreen(SCRN), mane.win,
				    event->xbutton.x_root,
				    event->xbutton.y_root,
				    &source_reverse_x,
				    &source_reverse_y,
				    &dummy);	/* throw away last argument */

    source_reverse_x = (source_reverse_x + mane_base_x) * mane.shrinkfactor;
    source_reverse_y = (source_reverse_y + mane_base_y) * mane.shrinkfactor;

    globals.ev.flags |= EV_SRC;
}

void
Act_show_source_specials(Widget w, XEvent *event,
			 String *params, Cardinal *num_params)
{
    int arg;
    Boolean clear_statusline = False;
    
    if (block_this_mouse_event())
	return;
    
    UNUSED(w);

    if (!get_int_arg(params, num_params, &arg))
	arg = -1;
    else
	clear_statusline = True;

    if ((event->type == ButtonPress && mouse_release != null_mouse)
	|| magnifier.win != (Window) 0) {
	XBell(DISP, 0);
	return;
    }

    if (!(globals.ev.flags & EV_SRC)) {
	source_reverse_x = -1;
	source_show_all = (arg == 1 ? True : False);

	globals.ev.flags |= EV_SRC;
    }
    if (clear_statusline)
	statusline_clear();
}

void
Act_source_what_special(Widget w, XEvent *event,
			String *params, Cardinal *num_params)
{
    int my_x, my_y;
    Window dummy;

    UNUSED(w);
    UNUSED(params);
    UNUSED(num_params);

    if (block_this_mouse_event())
	return;
    
    (void)XTranslateCoordinates(DISP, event->xkey.window, mane.win,
				event->xkey.x, event->xkey.y, &my_x, &my_y, &dummy);	/* throw away last argument */
    my_x = (my_x + mane_base_x) * mane.shrinkfactor;
    my_y = (my_y + mane_base_y) * mane.shrinkfactor;
    source_reverse_search(my_x, my_y, False);
}

static void
select_cb(const char *filename, void *data)
{
    UNUSED(data);
    if (filename != NULL) {
	TRACE_FILES((stderr, "new filename: |%s|", filename));
		
	set_dvi_name_expand(filename);
	current_page = 0; /* switch to first page */
	close_old_filep();
	globals.ev.flags |= EV_NEWDOC;
	globals.ev.flags |= EV_PAGEHIST_INSERT;
    }
}

static void
Act_select_dvi_file(Widget w, XEvent *event,
		    String *params, Cardinal *num_params)
{
    static struct filesel_callback cb; /* static so that we can pass its address */
    int arg = -1;
    
    UNUSED(w);
    UNUSED(event);

    if (block_this_mouse_event())
	return;

    if (get_int_arg(params, num_params, &arg)) { /* try item from file history */
	char *fname;
	int dummy_page;

	if (arg < 1) {
	    XBell(DISP, 0);
	    statusline_print(STATUS_MEDIUM, "Error: File history number must be >= 1");
	}
	else if ((fname = file_history_get_elem(arg - 1, &dummy_page)) == NULL) {
	    statusline_print(STATUS_MEDIUM, "No file number %d in history (history size: %lu)",
			     arg, (unsigned long)file_history_size());
	}
	else {
	    file_history_open(fname);
	}
	return;
    }
    
    cb.title = "Xdvi: Open file";
    cb.prompt = "Open file:";
    cb.ok = "OK";
    cb.cancel = "Cancel";
    cb.init_path = NULL;
    cb.filemask = "*.dvi";
    cb.must_exist = True;
    cb.exit_on_cancel = False;
    cb.func_ptr = select_cb;
    cb.data = NULL;

    file_history_set_page(current_page);
    
    XsraSelFile(globals.widgets.top_level, &cb);
}

/*
 * If all GUI elements have been turned on/off, make this synonymous
 * with expert mode off/on, so that next `x' keystroke does something
 * reasonable.
 */
void
update_expert_mode(void)
{
    if ((resource.expert_mode & (XPRT_SHOW_STATUSLINE | XPRT_SHOW_SCROLLBARS
#ifdef MOTIF
				 | XPRT_SHOW_PAGELIST | XPRT_SHOW_TOOLBAR | XPRT_SHOW_MENUBAR
#else
				 | XPRT_SHOW_BUTTONS
#endif
				 )) == XPRT_SHOW_ALL) {
	resource.expert = False;
    }
    else if ((resource.expert_mode & (XPRT_SHOW_STATUSLINE
#ifdef MOTIF
				      | XPRT_SHOW_SCROLLBARS | XPRT_SHOW_PAGELIST
				      | XPRT_SHOW_TOOLBAR | XPRT_SHOW_MENUBAR
#else
				      | BROKEN_RECONFIG ? 0 : XPRT_SHOW_SCROLLBARS | XPRT_SHOW_BUTTONS
#endif
				      )) == XPRT_SHOW_NONE) {
	resource.expert = True;
    }
}

void
Act_set_expert_mode(Widget w, XEvent *event,
		    String *params, Cardinal *num_params)
{
    int arg;
    Boolean clear_statusline = False;

    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(event);

    if (!get_int_arg(params, num_params, &arg))
	arg = -1;
    else
	clear_statusline = True;
    
    switch(arg) {
    case 1:
	resource.expert_mode ^= XPRT_SHOW_STATUSLINE;
	toggle_statusline();
	update_expert_mode();
	break;
    case 2:
#ifndef MOTIF
	/* show this warning only when not toggling global expert mode
	   (that's why it can't be inside toggle_scrollbars) */
	if (BROKEN_RECONFIG) {
	    popup_message(globals.widgets.top_level,
			  MSG_WARN,
			  NULL,
			  "Sorry - cannot toggle scrollbars with this X Version.\n"
			  "This version of XFree has a broken implementation of the viewportWidget, "
			  "which would break the layout if the scrollbars are toggled. "
			  "Versions that are known to work have a VendorRelease version below 4000 or above 4002. "
			  "You will need to update your XFree server to fix this.");
	    return;
	}
#endif
	resource.expert_mode ^= XPRT_SHOW_SCROLLBARS;
	toggle_scrollbars();
	update_expert_mode();
	break;
	
#ifdef MOTIF
    case 3:
	resource.expert_mode ^= XPRT_SHOW_PAGELIST;
	toggle_pagelist();
	update_expert_mode();
	break;
	
    case 4: /* toolbar */
	resource.expert_mode ^= XPRT_SHOW_TOOLBAR;
	toggle_toolbar();
	update_expert_mode();
	break;
	
    case 5:
	resource.expert_mode ^= XPRT_SHOW_MENUBAR;
	toggle_menubar();
	update_expert_mode();
	break;
#else
    case 3:
/*  	fprintf(stderr, "sidebar\n"); */
	resource.expert_mode ^= XPRT_SHOW_BUTTONS;
	toggle_buttons();
	update_expert_mode();
	break;
#endif
    default:
	/* warn 'em */
	if (
#ifdef MOTIF
	    arg > 5
#else
	    arg > 3
#endif
	    ) {
	    statusline_print(STATUS_SHORT, "Number %d too large for `set-expert-mode', using 0 (= toggle) instead.",
			     arg);
	}
	/* toggle all items */
	resource.expert = !resource.expert;
	if (resource.expert)
	    resource.expert_mode = XPRT_SHOW_NONE;
	else
	    resource.expert_mode = XPRT_SHOW_ALL;
	
	toggle_statusline();
#ifndef MOTIF
	if (!BROKEN_RECONFIG)
	    toggle_scrollbars();
#else
	toggle_scrollbars();
#endif
	
#ifdef MOTIF
	toggle_pagelist();
	toggle_toolbar();
	toggle_menubar();
#else
	toggle_buttons();
#endif
    }

#ifdef MOTIF
    update_preferences_expert();
#endif

    store_preference(NULL, "expertMode", "%d", resource.expert_mode);
    
    if (clear_statusline)
	statusline_clear();
}

Boolean have_src_specials = False;
static Boolean do_update_property = False;

void
handle_x_scroll(Widget w, XtPointer closure, XEvent *ev, Boolean *cont)
{
#ifndef MOTIF
    Dimension get_x = 0;
#endif

    UNUSED(w);
    UNUSED(closure);
    UNUSED(ev);
    UNUSED(cont);

    if (/* !resource.keep_flag || */ globals.widgets.x_bar == NULL)
	return;

#ifdef MOTIF
    XtVaGetValues(globals.widgets.x_bar, XmNvalue, &m_x_scroll, NULL);
#else
    get_xy();
    XtVaGetValues(globals.widgets.clip_widget, XtNx, &get_x, NULL);
    m_x_scroll = get_x - window_x;
    scroll_x_panner(m_x_scroll);
#endif
}

void
handle_y_scroll(Widget w, XtPointer closure, XEvent *ev, Boolean *cont)
{
#ifndef MOTIF
    Dimension get_y = 0;
#endif
    
    UNUSED(w);
    UNUSED(closure);
    UNUSED(ev);
    UNUSED(cont);
    
    if (/* !resource.keep_flag || */ globals.widgets.y_bar == NULL)
	return;
    
#ifdef MOTIF
    XtVaGetValues(globals.widgets.y_bar, XmNvalue, &m_y_scroll, NULL);
#else
    get_xy();
    XtVaGetValues(globals.widgets.clip_widget, XtNy, &get_y, NULL);
    m_y_scroll = get_y - window_y;
    scroll_y_panner(m_y_scroll);
#endif
}

void
handle_expose(Widget w, XtPointer closure, XEvent *ev, Boolean *cont)
{
    struct WindowRec *windowrec = (struct WindowRec *)closure;

    UNUSED(w);
    UNUSED(cont);

    if (windowrec == &magnifier) {
	if (magnifier_stat < 0) { /* destroy upon exposure */
	    magnifier_stat = 0;
	    mag_release(ev);
	    return;
	}
	else
	    magnifier_stat = 0;
    }

    do_update_property = False;

    if (have_src_specials && !MAGNIFIER_ACTIVE) {
	do_update_property = True;
    }

    MYTRACE((stderr, "Expose!"));
    expose(windowrec, (&(ev->xexpose))->x, (&(ev->xexpose))->y,
	   (unsigned int)(&(ev->xexpose))->width, (unsigned int)(&(ev->xexpose))->height);
}


void
handle_property_change(Widget w, XtPointer junk,
		       XEvent *ev, Boolean *cont)
{
    char *prop_ret;
    size_t prop_len;

    UNUSED(w);
    UNUSED(junk);
    UNUSED(cont);

    if ((&(ev->xproperty))->window != XtWindow(globals.widgets.top_level)) /* if spurious event */
	return;
    
    if ((&(ev->xproperty))->atom == atom_src_goto()) {
	/* forward search requested */
	if ((prop_len = property_get_data(XtWindow(globals.widgets.top_level), atom_src_goto(),
					  &prop_ret,
					  XGetWindowProperty)) == 0) {
	    TRACE_CLIENT((stderr, "property_get_data() failed for atom_src_goto()!"));
	    return;
	}
	TRACE_CLIENT((stderr, "got back atom_src_goto: |%s|", prop_ret));
	globals.src.fwd_string = prop_ret;
	globals.ev.flags |= EV_SRC;
    }
    else if ((&(ev->xproperty))->atom == atom_find_string()) {
	/* string search requested */
	if ((prop_len = property_get_data(XtWindow(globals.widgets.top_level), atom_find_string(),
					  &prop_ret,
					  XGetWindowProperty)) == 0) {
	    TRACE_CLIENT((stderr, "property_get_data() failed for atom_find_string()!"));
	    return;
	}
	TRACE_FIND((stderr, "got back atom_find_string: |%s|", prop_ret));
	resource.find_string = prop_ret;
	globals.ev.flags |= EV_FIND;
    }
    else if ((&(ev->xproperty))->atom == atom_reload()) {
	/* like do_sigusr(); there's no data in this case. */
	TRACE_CLIENT((stderr, "atom_reload()"));
	globals.ev.flags |= EV_RELOAD;
    }
    else if ((&(ev->xproperty))->atom == atom_newdoc()) {
	/* loading a new file */
	FILE *new_fp;
	if ((prop_len = property_get_data(XtWindow(globals.widgets.top_level), atom_newdoc(),
					  &prop_ret,
					  XGetWindowProperty)) == 0) {
	    TRACE_CLIENT((stderr, "property_get_data() returned zero length for atom_newdoc()"));
	    /* just raise it in this case */
	    XMapRaised(XtDisplay(globals.widgets.top_level), XtWindow(globals.widgets.top_level));
	    raise_message_windows();
	    return;
	}
	TRACE_CLIENT((stderr, "got back atom_newdoc: |%s|", prop_ret));
	if ((new_fp = XFOPEN(prop_ret, "r")) == NULL) {
	    popup_message(globals.widgets.top_level,
			  MSG_ERR, NULL, "Loading %s failed: %s",
			  prop_ret, strerror(errno));
	    return;
	}
	set_dvi_name_expand(prop_ret);
	/*FIXME: Here we would like to insert the first page of the new file
	  into the page history:
	  
	  page_history_insert(0);
	  
	  However, if the commandline had been:
	  xdvi -unique +5 file.dvi
	  then the following property change will change to page 5 and insert
	  page 5, so in this case two pages will be inserted by the xdvi invocation.
	  I guess to fix this we'd need a bitmask instead of 2 atoms to set both
	  features at the same time ...
	*/
	globals.ev.flags |= EV_NEWDOC;
    }
    else if ((&(ev->xproperty))->atom == atom_newpage()) {
	/* jumping to a different page */
	int newpage;
	char *testptr;
	if ((prop_len = property_get_data(XtWindow(globals.widgets.top_level), atom_newpage(),
					  &prop_ret,
					  XGetWindowProperty)) == 0) {
	    TRACE_CLIENT((stderr, "property_get_data() failed for atom_newpage(): |%s|", prop_ret));
	    return;
	}
	TRACE_CLIENT((stderr, "got back atom_newpage: |%s|", prop_ret));
	if (strcmp(prop_ret, "+") == 0) { /* special case: treat `+' as last page */
	    newpage = total_pages - 1;
	}
	else {
	    newpage = strtol(prop_ret, &testptr, 10) - 1;
	    if (*testptr != '\0') {
		XDVI_FATAL((stderr, "Invalid page number: `%s'.", prop_ret));
	    }
	}

	if (newpage == total_pages - 1) { /* as in Act_goto_page() */
	    goto_page(check_goto_page(newpage), resource.keep_flag ? NULL : home, False);
	    search_signal_page_changed();
	}
	else {
	    goto_page(check_goto_tex_page(newpage), resource.keep_flag ? NULL : home, False);
	    search_signal_page_changed();
	}
    }
    else if ((&(ev->xproperty))->atom == atom_raise()) {
	XMapRaised(XtDisplay(globals.widgets.top_level), XtWindow(globals.widgets.top_level));
	raise_message_windows();
    }
    else if ((&(ev->xproperty))->atom == atom_reread_prefs()) {
	read_user_preferences(globals.widgets.top_level, ".xdvirc.tmp");
    }
}


/*
 *	Signal routines.  At the signal level, all we do is set flags.
 */

#ifndef FLAKY_SIGPOLL
static RETSIGTYPE
handle_sigpoll(int signo)
{
    UNUSED(signo);
    
    globals.ev.ctr = 1;
    event_freq = -1;	/* forget Plan B */
    sig_flags |= SF_POLL;
# ifndef HAVE_SIGACTION
    (void) signal(SIGPOLL, handle_sigpoll);	/* reset the signal */
# endif
}
#endif

static RETSIGTYPE
handle_sigterm(int signo)
{
    UNUSED(signo);
    
    sig_flags |= SF_TERM;
}

static RETSIGTYPE
handle_sigchld(int signo)
{
    UNUSED(signo);

    sig_flags |= SF_CHLD;
}

static RETSIGTYPE
handle_sigalrm(int signo)
{
    UNUSED(signo);

    sig_flags |= SF_ALRM;
}

static RETSIGTYPE
handle_sigusr(int signo)
{
    UNUSED(signo);
    
    globals.ev.ctr = 1;
    sig_flags |= SF_USR;
}

static RETSIGTYPE
handle_sigsegv(int signo)
{
    UNUSED(signo);
    
    XDVI_ABORT((stderr, "Segmentation fault - trying to clean up and aborting ..."));
}

static Boolean sigalarm_initialized = False;

void
setup_sigalarm(void)
{
#if HAVE_SIGACTION
    struct sigaction a;

    a.sa_handler = handle_sigalrm;
    (void) sigemptyset(&a.sa_mask);
    (void) sigaddset(&a.sa_mask, SIGALRM);
    a.sa_flags = 0;
    sigaction(SIGALRM, &a, NULL);
#else /* not HAVE_SIGACTION */
    (void) signal(SIGALRM, handle_sigalrm);
#endif /* not HAVE_SIGACTION */

    sigalarm_initialized = True;
}

/*
 * Called from main to set up the signal handlers.
 */
void
setup_signal_handlers(void)
{
#ifndef FLAKY_SIGPOLL
    int	sock_fd	= ConnectionNumber(DISP);
#endif
#if HAVE_SIGACTION
    struct sigaction a;
#endif

#ifndef FLAKY_SIGPOLL
#if HAVE_SIGACTION
    /* Subprocess handling, e.g., MakeTeXPK, fails on the Alpha without
       this, because SIGPOLL interrupts the call of system(3), since OSF/1
       doesn't retry interrupted wait calls by default.  From code by
       maj@cl.cam.ac.uk.  */
    a.sa_handler = handle_sigpoll;
    (void) sigemptyset(&a.sa_mask);
    (void) sigaddset(&a.sa_mask, SIGPOLL);
    a.sa_flags = SA_RESTART;
    sigaction(SIGPOLL, &a, NULL);
#else /* not HAVE_SIGACTION */
    (void) signal(SIGPOLL, handle_sigpoll);
#endif /* not HAVE_SIGACTION */

    prep_fd(sock_fd, False);
#endif	/* not FLAKY_SIGPOLL */

#if HAVE_SIGACTION
    a.sa_handler = handle_sigterm;
    (void) sigemptyset(&a.sa_mask);
    (void) sigaddset(&a.sa_mask, SIGINT);
    (void) sigaddset(&a.sa_mask, SIGQUIT);
    (void) sigaddset(&a.sa_mask, SIGTERM);
    (void) sigaddset(&a.sa_mask, SIGHUP);
    a.sa_flags = SA_RESETHAND;
    sigaction(SIGINT, &a, NULL);
    sigaction(SIGQUIT, &a, NULL);
    sigaction(SIGTERM, &a, NULL);
    sigaction(SIGHUP, &a, NULL);
    a.sa_handler = handle_sigsegv;
    (void)sigemptyset(&a.sa_mask);
    (void)sigaddset(&a.sa_mask, SIGSEGV);
    a.sa_flags = 0;
    sigaction(SIGSEGV, &a, NULL);
#else /* not HAVE_SIGACTION */
    (void) signal(SIGINT, handle_sigterm);
    (void) signal(SIGQUIT, handle_sigterm);
    (void) signal(SIGTERM, handle_sigterm);
    (void) signal(SIGHUP, handle_sigterm);
    (void)signal(SIGSEGV, handle_sigsegv);
#endif /* not HAVE_SIGACTION */

#if HAVE_SIGACTION
    a.sa_handler = handle_sigchld;
    (void) sigemptyset(&a.sa_mask);
    (void) sigaddset(&a.sa_mask, SIGCHLD);
    a.sa_flags = 0;
    sigaction(SIGCHLD, &a, NULL);
#else /* not HAVE_SIGACTION */
    (void) signal(SIGCHLD, handle_sigchld);
#endif /* not HAVE_SIGACTION */

#if HAVE_SIGACTION
    a.sa_handler = handle_sigusr;
    (void) sigemptyset(&a.sa_mask);
    (void) sigaddset(&a.sa_mask, SIGUSR1);
    a.sa_flags = 0;
    sigaction(SIGUSR1, &a, NULL);
#else /* not HAVE_SIGACTION */
    (void) signal(SIGUSR1, handle_sigusr);
#endif /* not HAVE_SIGACTION */

    (void)sigemptyset(&all_signals);
    (void)sigaddset(&all_signals, SIGPOLL);
    (void)sigaddset(&all_signals, SIGINT);
    (void)sigaddset(&all_signals, SIGQUIT);
    (void)sigaddset(&all_signals, SIGTERM);
    (void)sigaddset(&all_signals, SIGHUP);
    (void)sigaddset(&all_signals, SIGCHLD);
    (void)sigaddset(&all_signals, SIGALRM);
    (void)sigaddset(&all_signals, SIGUSR1);
    (void)sigaddset(&all_signals, SIGSEGV);

}


/*
 *	Mid-level signal handlers.  These are called from within read_events(),
 *	and do the actual work appropriate for the given signal.
 */

/*
 *	Process-related routines.  Call set_chld(xchild *) to indicate
 *	that a given child process should be watched for when it
 *	terminates.  Call clear_chld() to remove the process from the
 *	list.  When the child terminates, the record is removed from
 *	the list and xchild->proc is called.
 *	The caller can set the `io' member in xchild to a pointer to
 *	an xio structure for reading from the file descriptor; see
 *	psgs.c and util.c for examples.
 */

static struct xchild *child_recs = NULL;	/* head of child process list */

void
set_chld(struct xchild *cp)
{
    cp->next = child_recs;
    child_recs = cp;
}

void
clear_chld(struct xchild *cp)
{
    struct xchild	**cpp;
    struct xchild	*cp2;

    if (child_recs == NULL) {
	if (globals.debug & DBG_EVENT)
	    fprintf(stderr, "child_recs: %p\n", (void *)child_recs);
	return;
    }
    for (cpp = &child_recs;;) {
	cp2 = *cpp;
	if (cp2 == cp)
	    break;
	cpp = &cp2->next;
    }
    *cpp = cp->next;
}

static void
do_sigchld(void)
{
    pid_t	pid;
    int	status;

    sig_flags &= ~SF_CHLD;

#if ! HAVE_SIGACTION
    (void) signal(SIGCHLD, handle_sigchld);	/* reset the signal */
#endif
    for (;;) {
#if HAVE_WAITPID
	pid = waitpid(-1, &status, WNOHANG);
#else
	pid = wait3(&status, WNOHANG, NULL);
#endif
	if (pid == 0) break;

	if (pid != -1) {
	    struct xchild	**cpp;
	    struct xchild	*cp;

	    for (cpp = &child_recs;;) {
		cp = *cpp;
		if (cp == NULL)
		    break;
		if (cp->pid == pid) {
		    *cpp = cp->next;	/* unlink it */
		    /* call exit reporting procedure for this child */
		    (cp->proc)(status, cp);
		    break;
		}
		cpp = &cp->next;
	    }
	    break;
	}

	if (errno == EINTR) continue;
	if (errno == ECHILD) break;
#if HAVE_WAITPID
	perror("xdvi: waitpid");
#else
	perror("xdvi: wait3");
#endif
	break;
    }
}


/*
 *	File-related routines.  Call set_io() to indicate that a given fd
 *	should be watched for ability to input or output data.  Call clear_io()
 *	to remove it from the list.  When poll()/select() indicates that the fd
 *	is available for the indicated type of i/o, the corresponding routine
 *	is called.  Call clear_io() to remove an fd from the list.
 *	Both set_io() and clear_io() can be called from within read_proc or
 *	write_proc (although turning an io descriptor on or off is better
 *	accomplished by setting the events flag in the xio structure, and
 *	in the corresponding pollfd structure if the pfd pointer is not NULL
 *	(it is always non-NULL when read_proc and write_proc are called)).
 *	We allocate space for one additional record in the pollfd array, to
 *	accommodate the fd for the X connection; this is done by initializing
 *	num_fds to 1 instead of zero.
 */

static	struct xio	*iorecs	= NULL;	/* head of xio list */

#if HAVE_POLL
static	struct pollfd	*fds	= NULL;
static	int		num_fds	= 1;	/* current number of fds */
static	int		max_fds	= 0;	/* max allocated number of fds */
static	Boolean		io_dirty= True;	/* need to recompute fds[] array */
#else
static	int		numfds	= 0;
static	fd_set		readfds;
static	fd_set		writefds;
#endif

void
set_io(struct xio *ip)
{
    ip->next = iorecs;
    iorecs = ip;

#if HAVE_POLL
    ++num_fds;
    if (!io_dirty && num_fds <= max_fds) {
	fds[num_fds - 1].fd = ip->fd;
	fds[num_fds - 1].events = ip->xio_events;
	ip->pfd = &fds[num_fds - 1];
    }
    else {
	ip->pfd = NULL;
	io_dirty = True;
    }
#else
    if (numfds <= ip->fd) numfds = ip->fd + 1;
#endif
}

void
clear_io(struct xio *ip)
{
    struct xio	**ipp;

    for (ipp = &iorecs;;) {
	struct xio *ip2;

	ip2 = *ipp;
	if (ip2 == ip) break;
	ipp = &ip2->next;
    }
    *ipp = ip->next;

#if HAVE_POLL
    --num_fds;
    io_dirty = True;
#else
# if FLAKY_SIGPOLL
    numfds = ConnectionNumber(DISP);
# else
    numfds = (event_freq < 0 ? -1 : ConnectionNumber(DISP));
# endif
    for (ip = iorecs; ip != NULL; ip = ip->next)
	if (ip->fd > numfds)
	    numfds = ip->fd;
    ++numfds;
#endif /* !HAVE_POLL */
}

static void
do_sigpoll(void)
{
#if FLAKY_SIGPOLL
    sig_flags &= ~SF_POLL;
#else
    struct xio	*ip;

    sig_flags &= ~SF_POLL;

# if HAVE_POLL

    if (io_dirty) {
	struct pollfd *fp;

	if (num_fds > max_fds) {
	    if (fds != NULL) free(fds);
	    fds = xmalloc(num_fds * sizeof *fds);
	    max_fds = num_fds;
	    fds->fd = ConnectionNumber(DISP);
	    fds->events = POLLIN;
	}
	fp = fds + 1;
	for (ip = iorecs; ip != NULL; ip = ip->next) {
	    fp->fd = ip->fd;
	    fp->events = ip->xio_events;
	    ip->pfd = fp;
	    ++fp;
	}
	io_dirty = False;
    }

    for (;;) {
	if (poll(fds + 1, num_fds - 1, 0) >= 0)
	    break;

	if (errno != EAGAIN && errno != EINTR) {
	    perror("xdvi: poll");
	    return;
	}
    }

    for (ip = iorecs; ip != NULL; ip = ip->next) {
	int revents = ip->pfd->revents;
	if (revents & POLLIN && ip->read_proc != NULL)
	    (void)(ip->read_proc)(ip->fd);
	if (revents & POLLOUT && ip->write_proc != NULL)
	    (ip->write_proc)(ip->fd);
    }

# else

    FD_ZERO(&readfds);
    FD_ZERO(&writefds);
    for (ip = iorecs; ip != NULL; ip = ip->next) {
	if (ip->xio_events & XIO_IN)
	    FD_SET(ip->fd, &readfds);
	if (ip->xio_events & XIO_OUT)
	    FD_SET(ip->fd, &writefds);
    }

    for (;;) {
	struct timeval tv;

	tv.tv_sec = tv.tv_usec = 0;
	if (select(numfds, &readfds, &writefds, (fd_set *) NULL, &tv) >= 0)
	    break;

	if (errno != EAGAIN && errno != EINTR) {
	    perror("select (xdvi read_events)");
	    return;
	}
    }

    for (ip = iorecs; ip != NULL; ip = ip->next) {
	if (FD_ISSET(ip->fd, &readfds) && ip->read_proc != NULL)
	    (void)(ip->read_proc)(ip->fd);
	if (FD_ISSET(ip->fd, &writefds) && ip->write_proc != NULL)
	    (ip->write_proc)(ip->fd);
    }

# endif
#endif /* not FLAKY_SIGPOLL */
}


/*
 *	Timer-related routines.  Call set_timer() to set a timer a given number
 *	of milliseconds in the future.  At that time, the timer will be cleared
 *	and the given procedure will be called with argument set to the struct
 *	passed to set_timer().  The timer routine may call set_timer() or
 *	cancel_timer().
 */


static	struct xtimer		*timers	= NULL;	/* head of timer list */

static	struct itimerval	itv	= {{0, 0}, {0, 0}};

#ifndef	timercmp
#define	timercmp(a, b, OP)	(((a)->tv_sec OP (b)->tv_sec || \
	((a)->tv_sec == (b)->tv_sec && (a)->tv_usec OP (b)->tv_usec)))
#endif	/* timercmp */


static void
show_timers(char *what)
{
    struct xtimer *tp;
    fprintf(stderr, "=======%s; timers:\n", what);
    for (tp = timers; tp != NULL; tp = tp->next) {
	fprintf(stderr, "timer %p: %lu\n", (void *)tp, (unsigned long)tp->when.tv_sec);
    }
    fprintf(stderr, "=======\n");
}

void
set_timer(struct xtimer *tp, int ms)
{
    struct xtimer	**tpp;
    struct xtimer	*tp2;

    if (globals.debug & DBG_EVENT)
	fprintf(stderr, "%s:%d: set_timer\n", __FILE__, __LINE__);

    gettimeofday(&tp->when, NULL);
    itv.it_value.tv_sec = ms / 1000;
    itv.it_value.tv_usec = (ms % 1000) * 1000;
    tp->when.tv_sec += itv.it_value.tv_sec;
    tp->when.tv_usec += itv.it_value.tv_usec;
    if (tp->when.tv_usec >= 1000000) {
	tp->when.tv_usec -= 1000000;
	++tp->when.tv_sec;
    }

    for (tpp = &timers;;) {		/* add timer to list */
	tp2 = *tpp;
	if (tp2 == NULL || timercmp(&tp->when, &tp2->when, <))
	    break;
	tpp = &tp2->next;
    }
    tp->next = tp2;
    *tpp = tp;

    if (tpp == &timers) {
	setitimer(ITIMER_REAL, &itv, NULL);
	if (ms == 0)
	    sig_flags |= SF_ALRM;
    }
    if (globals.debug & DBG_EVENT)
	show_timers("after set_timer");
}

void
cancel_timer(struct xtimer *tp)
{
    struct xtimer	**tpp;

    if (globals.debug & DBG_EVENT)
	show_timers("beginning of cancel_timer");
    
    if (timers == NULL) {
	fprintf(stderr, "%s:%d: BUG? timers == NULL!\n", __FILE__, __LINE__);
	return;
    }

    if (globals.debug & DBG_EVENT)
	fprintf(stderr, "%s:%d: cancel_timer %p from %p\n", __FILE__, __LINE__, (void *)&timers, (void *)tp);

    ASSERT(timers != NULL, "timers in cancel_timer() mustn't be NULL");
    for (tpp = &timers; ; ) {		/* remove from list */
	
	if (*tpp == tp)
	    break;
	tpp = &(*tpp)->next;
    }

    *tpp = (*tpp)->next;	/* unlink it */

    if (timers == NULL) {	/* cancel SIGALRM */
	itv.it_value.tv_sec = itv.it_value.tv_usec = 0;
	setitimer(ITIMER_REAL, &itv, NULL);
    }
}

#if XDVI_XT_TIMER_HACK
/*
 * Original comment by Paul:
 *	Newer versions of the Motif toolkit use the timer facility
 *	(XtAppAddTimeOut(), etc.) in the X Toolkit.  Proper functioning of
 *	this mechanism, however, requires that the X Toolkit be in charge of
 *	blocking.  Since xdvi does its own blocking, this means that we need
 *	to provide working alternatives to these X Toolkit routines (by
 *	redefining them ...).
 *	One symptom of the above-mentioned bug is that the printlog window
 *	eventually stops showing dvips progress until you move the mouse.
 *
 * Comment SU:
 *	Xdvik also uses XtAppAddTimeOut() in other places (hyperref/statusline/...),
 *	so we also need these redefinitions also in the Xaw version.
 *
 */

static void xt_alarm (struct xtimer *);

static struct xtimer *xt_free_timers = NULL;

XtIntervalId
XtAddTimeOut(unsigned long interval, XtTimerCallbackProc proc, XtPointer closure)
{
    return XtAppAddTimeOut(NULL, interval, proc, closure);
}

XtIntervalId
XtAppAddTimeOut(XtAppContext app, unsigned long interval, XtTimerCallbackProc proc, XtPointer closure)
{
    struct xtimer *tp;
    
    UNUSED(app);

    /* FIXME: better way of checking this instead of static boolean sigalarm_initialized?
       The following doesn't work, even after
       sigaddset(&all_signals, SIGALRM);
       
          static sigset_t sig_set;
          (void)sigprocmask(0, NULL, &sig_set);
	  if (sigismember(&sig_set, SIGALRM))
	      ... OK ...
	  else
	      ... NOT OK ...
    */
    ASSERT(sigalarm_initialized, "Shouldn't invoke XtAppAddTimeOut() before setup_sigalarm()");
    
    if (globals.debug & DBG_EVENT)
	fprintf(stderr, "XtAppAddTimeOut: %lu msecs\n", interval);
    
    if (xt_free_timers == NULL)
	tp = xmalloc(sizeof *tp);
    else {
	tp = xt_free_timers;
	xt_free_timers = xt_free_timers->next;
    }

    tp->proc = xt_alarm;
    tp->xt_proc = proc;
    tp->closure = closure;
    
    set_timer(tp, interval);

    if (globals.debug & DBG_EVENT)
	show_timers("XtAppAddTimeOut");

    return (XtIntervalId)tp;
}

void
XtRemoveTimeOut(XtIntervalId id)
{
    struct xtimer *tp;

    ASSERT(id != 0, "XtIntervalId argument in XtRemoveTimeOut() mustn't be NULL");
    tp = (struct xtimer *)id;

    /* Motif (2.1 on Solaris 9, 2003) sometimes calls XtRemoveTimeOut() after
       the timer event has occurred, so we need to be sure not to remove
       the timer record twice.  */
    if (tp->proc == NULL)
	return;
    
    cancel_timer(tp);
    
    tp->next = xt_free_timers;
    xt_free_timers = tp;

    if (globals.debug & DBG_EVENT)
	show_timers("XtRemoveTimeOut");
}

void
xt_alarm(struct xtimer *tp)
{
    XtIntervalId id;

    tp->proc = NULL;	/* flag timer as used-up */
    id = (XtIntervalId) tp;
    (tp->xt_proc)(tp->closure, &id);
    
    tp->next = xt_free_timers;
    xt_free_timers = tp;

    if (globals.debug & DBG_EVENT)
	show_timers("xt_alarm");
}
#endif /* XDVI_XT_TIMER_HACK */

static	void
do_sigalrm(void)
{
    struct timeval	now;

    sig_flags &= ~SF_ALRM;
#ifndef HAVE_SIGACTION
    (void) signal(SIGALRM, handle_sigalrm);	/* reset the signal */
#endif

    gettimeofday(&now, NULL);

    while (timers != NULL && timercmp(&timers->when, &now, <=)) {
	struct xtimer *tp = timers;
	timers = timers->next;	/* unlink it _first_ */
	(tp->proc)(tp);
    }

    if (timers != NULL) {		/* set next timer */
	int i;
	itv.it_value.tv_sec = timers->when.tv_sec - now.tv_sec;
	i = timers->when.tv_usec - now.tv_usec;
	if (i < 0) {
	    --itv.it_value.tv_sec;
	    i += 1000000;
	}
	itv.it_value.tv_usec = i;

	setitimer(ITIMER_REAL, &itv, NULL);
    }
}



/*
 *	Handle SIGUSR1 signal.  Pretty straightforward.
 */

static void
do_sigusr(void)
{
    sig_flags &= ~SF_USR;
#ifndef HAVE_SIGACTION
    (void) signal(SIGUSR1, handle_sigusr);	/* reset the signal */
#endif
    globals.ev.flags |= EV_RELOAD;
}


static void
do_sigsegv(void)
{
    sig_flags &= ~SF_SEGV;
#ifndef HAVE_SIGACTION
    (void) signal(SIGSEGV, handle_sigsegv);	/* reset the signal */
#endif
    handle_sigsegv(SIGSEGV);
}


/*
 *	Handle termination signals.  Kill child processes, if permitted.
 *	Otherwise, leave it up to the caller.  This is the only place where
 *	the EV_TERM event flag is set, and it can only happen if there's an
 *	active non-killable process.  This should only happen if read_events()
 *	is called from one of a very few select locations.
 */

static void
do_sigterm(void)
{
    struct xchild   *cp;

    sig_flags &= ~SF_TERM;

    /* loop through child processes */
    for (cp = child_recs; cp != NULL; cp = cp->next) {
	if (cp->killable)
	    kill(cp->pid, SIGKILL);
    }

     /* SU: Unlike non-k xdvi, we don't care about whether all children have been
	killed, since processes forked via fork_process() (e.g. the web browser)
	may still continue running. So we just exit here.
     */
    xdvi_exit(EXIT_SUCCESS);

    /* since xdvi_exit() may return, we mustn't do the following which
       is in non-k xdvi, else we'll end up in a busy loop! I don't know
       what's meant by `caller' here anyway ...

       globals.ev.flags |= EV_TERM; /\* otherwise, let the caller handle it *\/
    */
}

/*
 *	Since redrawing the screen is (potentially) a slow task, xdvi checks
 *	for incoming events while this is occurring.  It does not register
 *	a work proc that draws and returns every so often, as the toolkit
 *	documentation suggests.  Instead, it checks for events periodically
 *	(or not, if SIGPOLL can be used instead) and processes them in
 *	a subroutine called by the page drawing routine.  This routine (below)
 *	checks to see if anything has happened and processes those events and
 *	signals.  (Or, if it is called when there is no redrawing that needs
 *	to be done, it blocks until something happens.)
 *
 *	Ultimately, the goal is to have this be the only place in xdvi where
 *	blocking occurs.
 *
 *	The argument to this function should be a mask of event types (EV_*)
 *	indicating which event types should cause read_events to return instead
 *	of waiting for more events.  This function will always process all
 *	pending events and signals before returning.
 *	The return value is the value of globals.ev.flags.
 */

unsigned int
read_events(unsigned int ret_mask)
{
    XEvent event;

#if !HAVE_POLL
    if (numfds == 0)
	numfds = ConnectionNumber(DISP) + 1;
#endif

    if (globals.debug & DBG_EVENT)
	fprintf(stderr, "%s:%d: read_events %u\n", __FILE__, __LINE__, ret_mask);
    for (;;) {
	globals.ev.ctr = event_freq;
	/*
	 * The above line clears the flag indicating that an event is
	 * pending.  So if an event comes in right now, the flag will be
	 * set again needlessly, but we just end up making an extra call.
	 * Also, be careful about destroying the magnifying glass while
	 * drawing on it.
	 */

#if !FLAKY_SIGPOLL

	if (event_freq < 0) {	/* if SIGPOLL works */
	    if (!XtPending()) {
		sigset_t oldsig;

		(void) sigprocmask(SIG_BLOCK, &all_signals, &oldsig);
		for (;;) {
#ifdef SHOW_SIG_FLAGS
		    /* this gives HUGE output ... */
		    if (globals.debug & DBG_EVENT)
			fprintf(stderr, "%s:%d: sig_flags = %d\n",
				__FILE__, __LINE__, sig_flags);
#endif
		    while (sig_flags) {
			flags_to_sigproc[sig_flags]();
		    }

		    if (XtPending())
			break;

		    if (globals.ev.flags & ret_mask) {
			(void) sigprocmask(SIG_SETMASK, &oldsig, (sigset_t *) NULL);
			return globals.ev.flags;
		    }
		    (void) sigsuspend(&oldsig);
		}
		(void) sigprocmask(SIG_SETMASK, &oldsig, (sigset_t *) NULL);
	    }
	}
	else

#endif /* not FLAKY_SIGPOLL */

	    {
		for (;;) {
		    struct xio	*ip;

		    if (globals.debug & DBG_EVENT)
			fprintf(stderr, "%s:%d: (flaky) sig_flags = %d\n",
				__FILE__, __LINE__, sig_flags);
		    while (sig_flags) {
			sigset_t oldsig;

			(void) sigprocmask(SIG_BLOCK, &all_signals, &oldsig);

			while (sig_flags) {
			    flags_to_sigproc[sig_flags]();
			}

			(void) sigprocmask(SIG_SETMASK, &oldsig,
					   (sigset_t *) NULL);
		    }

		    if (XtPending())
			break;

		    if (globals.ev.flags & ret_mask)
			return globals.ev.flags;

		    /* If a SIGUSR1 signal comes right now, then it will wait
		       until an X event or another SIGUSR1 signal arrives. */

#if HAVE_POLL
		    if (globals.debug & DBG_EVENT)
			fprintf(stderr, "%s:%d: have_poll!\n",
				__FILE__, __LINE__);
		    if (io_dirty) {
			struct pollfd *fp;

			if (num_fds > max_fds) {
			    if (fds != NULL) free(fds);
			    fds = xmalloc(num_fds * sizeof *fds);
			    max_fds = num_fds;
			    fds->fd = ConnectionNumber(DISP);
			    fds->events = POLLIN;
			}
			fp = fds + 1;
			for (ip = iorecs; ip != NULL; ip = ip->next) {
			    fp->fd = ip->fd;
			    fp->events = ip->xio_events;
			    ip->pfd = fp;
			    ++fp;
			}
			io_dirty = False;
		    }

		    for (;;) {
			if (poll(fds, num_fds, -1) >= 0) {
			    for (ip = iorecs; ip != NULL; ip = ip->next) {
				int revents = ip->pfd->revents;

				if (revents & POLLIN && ip->read_proc != NULL)
				    (ip->read_proc)(ip->fd);
				if (revents & POLLOUT && ip->write_proc != NULL)
				    (ip->write_proc)(ip->fd);
			    }
			    break;
			}

			if (errno == EINTR)
			    break;

			if (errno != EAGAIN) {
			    perror("xdvi: poll");
			    break;
			}
		    }
#else /* HAVE_POLL */
		    if (globals.debug & DBG_EVENT)
			fprintf(stderr, "%s:%d: NOT have_poll!\n",
				__FILE__, __LINE__);
		    FD_ZERO(&readfds);
		    FD_ZERO(&writefds);
		    FD_SET(ConnectionNumber(DISP), &readfds);
		    for (ip = iorecs; ip != NULL; ip = ip->next) {
			if (ip->xio_events & XIO_IN)
			    FD_SET(ip->fd, &readfds);
			if (ip->xio_events & XIO_OUT)
			    FD_SET(ip->fd, &writefds);
		    }

		    for (;;) {
			if (select(numfds, &readfds, &writefds, (fd_set *) NULL,
				   (struct timeval *) NULL) >= 0) {
			    for (ip = iorecs; ip != NULL; ip = ip->next) {
				if (FD_ISSET(ip->fd, &readfds) && ip->read_proc != NULL) {
				    if (globals.debug & DBG_EVENT)
					fprintf(stderr, "%s:%d: reading from %d\n",
						__FILE__, __LINE__, ip->fd);
				    (ip->read_proc)(ip->fd);
				}
				if (FD_ISSET(ip->fd, &writefds) && ip->write_proc != NULL) {
				    if (globals.debug & DBG_EVENT)
					fprintf(stderr, "%s:%d: writing to %d\n",
						__FILE__, __LINE__, ip->fd);
				    (ip->write_proc)(ip->fd);
				}
			    }
			    break;
			}

			if (errno == EINTR)
			    break;

			if (errno != EAGAIN) {
			    perror("xdvi: select");
			    break;
			}
		    }
#endif /* HAVE_POLL */
		}
	    }
	XtAppNextEvent(app, &event);
#ifdef MOTIF
	if ((resource.expert_mode & XPRT_SHOW_TOOLBAR) != 0)
	    TipAppHandle(app, &event);
#endif

	if (resized)
	    get_geom();

	if (event.xany.window == magnifier.win && event.type == Expose) {
	    handle_expose((Widget) NULL, (XtPointer) &magnifier, &event,
			  (Boolean *) NULL);
	    continue;
	}
	else if (globals.broken_motif_event_handling &&
		 (resource.mouse_mode == MOUSE_RULER_MODE ||
		  resource.mouse_mode == MOUSE_TEXT_MODE)) {
	    /* In this case, Act_motion() and Act_release() are not called properly
	     * for updating the ruler/text selection (it works with the magnifier though),
	     * so we need to invoke them ourselves here: */
	    if (event.type == MotionNotify)
		Act_motion(NULL, &event, NULL, NULL);
	    else if (event.type == ButtonRelease)
		Act_release(NULL, &event, NULL, NULL);
	}

#ifdef MOTIF
	if (XtIsRealized(globals.widgets.top_level)
	    && event.xany.window == XtWindow(globals.widgets.clip_widget)
	    && event.type == KeyPress) { /* workaround for #610206 */
	    motif_translations_hack();
	}
#else
	if (resource.expert_mode & XPRT_SHOW_BUTTONS)
	    SubMenuHandleEvent(app, &event);
#endif
	XtDispatchEvent(&event);
    }
}


/*
 * Higher-level routines for managing events.
 */

static void
can_exposures(struct WindowRec *windowrec)
{
    windowrec->min_x = windowrec->min_y = MAXDIM;
    windowrec->max_x = windowrec->max_y = 0;
}

void
redraw(struct WindowRec *windowrec)
{
    currwin = *windowrec;
    globals.win_expose.min_x = currwin.min_x + currwin.base_x;
    globals.win_expose.min_y = currwin.min_y + currwin.base_y;
    globals.win_expose.max_x = currwin.max_x + currwin.base_x;
    globals.win_expose.max_y = currwin.max_y + currwin.base_y;
    can_exposures(windowrec);

    /* fix for bug #619070 - the complicated flags (and do_update_property)
       are needed to avoid too many updates at exposures, especially for
       a window of another xdvi instance when the magnifier intersects with
       that window.
    */
    if (have_src_specials && do_update_property
	&& globals.win_expose.min_x != 1 && globals.win_expose.max_y - globals.win_expose.min_y != 1
	&& currwin.base_x == 0 && currwin.base_y == 0) {
	update_window_property(XtWindow(globals.widgets.top_level), True);
    }

    TRACE_EVENTS((stderr, "Redraw %d x %d at (%d, %d) (base=%d,%d)",
		  globals.win_expose.max_x - globals.win_expose.min_x,
		  globals.win_expose.max_y - globals.win_expose.min_y,
		  globals.win_expose.min_x, globals.win_expose.min_y,
		  currwin.base_x, currwin.base_y));

    /* can't use ev_cursor here, since the event loop might not see this change quick enough */
    if (!(globals.ev.flags & EV_CURSOR)) {
	TRACE_EVENTS((stderr, "Cursor: %ld", globals.cursor.flags));
	if (!(globals.cursor.flags & (CURSOR_DRAG_H | CURSOR_DRAG_V | CURSOR_DRAG_A))) {
	    if (resource.mouse_mode == MOUSE_RULER_MODE)
		XDefineCursor(DISP, CURSORWIN, globals.cursor.rule);
	    else
		XDefineCursor(DISP, CURSORWIN, globals.cursor.wait);
	    XFlush(DISP);
	}
	globals.ev.flags |= EV_CURSOR;
    }

    /* No longer needed since windows are correctly transient now */
    /*      raise_message_windows(); */
    raise_file_selector();
    draw_page();
    globals.warn_spec_now = False;
}


void
redraw_page(void)
{
#if COLOR
    const struct rgb *rgbp;
#endif
    TRACE_FILES((stderr, "Redraw page on %p", (void *)globals.dvi_file.bak_fp));

    if (globals.dvi_file.bak_fp == NULL)
	return;

    if (scanned_page < current_page) {
	TRACE_FILES((stderr, "redraw_page: scanned_page = %d, current_page = %d, prescanning %p\n",
		     scanned_page, current_page, (void *)globals.dvi_file.bak_fp));

	prescan(globals.dvi_file.bak_fp);

	if (globals.ev.flags & EV_GE_NEWPAGE) {	/* if we need to re-prescan */
	    return;
	}
    }

    TRACE_FILES((stderr, "redraw_page: current_page = %d", current_page));
    if (pageinfo_get_window_width(current_page) != globals.page.unshrunk_w
	|| pageinfo_get_window_height(current_page) != globals.page.unshrunk_h) {
	TRACE_FILES((stderr, "NEW SIZE: %dx%d",
		     pageinfo_get_window_width(current_page), pageinfo_get_window_height(current_page)));
	init_page();
	reconfig();
    }
    
    /* We can't call home() without proper unshrunk_page_*, which requires
     * prescan(), which can't be done from within read_events() */

    /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! BUG ALERT !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
       There's some complicated interaction with Postscript specials
       here: if home_action check comes before the gs stuff, psp.drawfile
       might not get initialized correctly, resulting in empty PS figures
       (bounding box instead of figure). This is different in xdvi, due to
       different handling of the home_action stuff, but at the moment I can't
       remember the reason for this ...
       !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! BUG ALERT !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    */
#if PS_GS
    if (gs_postpone_prescan) {
	if (!setjmp(globals.ev.canit)) {
	    gs_resume_prescan();
	}
	else
	    return;
    }
#endif
    if (home_action != NULL) {
	home_action(False);
	home_action = NULL;
	/* This discards the expose event generated by home()
	   (1 for each page) */
	if (read_events(EV_NOWAIT) & EV_GE_NEWPAGE) {
	    return;
	}

	can_exposures(&mane);
    }

#if COLOR
    rgbp = &bg_initial;
    if (page_colors.stack != NULL) {
	ASSERT(current_page < (int)page_colors.size, "page_colors.size too small");
	rgbp = &page_colors.stack[current_page].bg;
    }

    /* Set background color */
    if (bg_current == NULL
	|| rgbp->r != bg_current->color.r
	|| rgbp->g != bg_current->color.g
	|| rgbp->b != bg_current->color.b) {
	struct bgrec **bgpp;

	for (bgpp = &bg_head;;) {
	    bg_current = *bgpp;
	    if (bg_current == NULL) {	/* if bg is not in list */
		bg_current = *bgpp = xmalloc(sizeof *bg_current);
		bg_current->next = NULL;
		bg_current->color = *rgbp;
		bg_current->fg_head = NULL;
		bg_current->pixel_good = False;
		break;
	    }
	    if (bg_current->color.r == rgbp->r
		&& bg_current->color.g == rgbp->g
		&& bg_current->color.b == rgbp->b)
		break;
	    bgpp = &bg_current->next;
	}
	fg_current = NULL;	/* force change of foreground color */
	/* globals.gc.high is only used in XDrawRectangle, so its background color
	   doesn't need to be changed.  */
	if (globals.debug & DBG_DVI)
	    printf("Changing background color to %5d %5d %5d\n",
		   bg_current->color.r, bg_current->color.g,
		   bg_current->color.b);

	if (!bg_current->pixel_good) {
	    bg_current->pixel = alloc_color(&bg_current->color,
					    color_data[1].pixel);
	    bg_current->pixel_good = True;
	}
	XSetWindowBackground(DISP, mane.win, bg_current->pixel);
#if MOTIF && !FIXED_FLUSHING_PAGING
	XtVaSetValues(XtParent(globals.widgets.draw_widget), XtNbackground, bg_current->pixel, NULL);
#endif
/* 	XSetWindowBackground(DISP, mane.win, bg_current->pixel); */
/*  	XClearWindow(DISP, mane.win); */
#if 0 /* don't recolor the cursor - gives too low contrast on color backgrounds,
	 and bad appearance when part of the background is white and cursor mask
	 is colored */
	{
	    XColor	bg_Color;
	    bg_Color.pixel = bg_current->pixel;
	    XQueryColor(DISP, G_colormap, &bg_Color);
	    XRecolorCursor(DISP, globals.cursor.ready, &globals.cr_color, &bg_Color);
	    XRecolorCursor(DISP, globals.cursor.wait, &globals.cr_color, &bg_Color);
	}
#endif
    }
#endif /* COLOR */
    
    if (!globals.pausing.flag) {
	XClearWindow(DISP, mane.win);
    }

    if (G_backing_store != NotUseful) {
	mane.min_x = mane.min_y = 0;
	mane.max_x = globals.page.w;
	mane.max_y = globals.page.h;
    }
    else {
	get_xy();
	mane.min_x = -window_x;
	mane.max_x = -window_x + mane.width;
	mane.min_y = -window_y;
	mane.max_y = -window_y + mane.height;
    }

/*      update_TOC(); */
    redraw(&mane);
}

void
do_pages(void)
{
    if (globals.debug & DBG_BATCH) {
	
	(void)read_events(EV_GT_IDLE);
	for (current_page = 0; current_page < total_pages; ++current_page) {
	    if (resource.keep_flag) {
		home_action = NULL;
	    }
	    else {
		home_action = home;
	    }
	    globals.warn_spec_now = resource.warn_spec;
#if PS_GS
	    for (;;) {
		redraw_page();
		(void) read_events(EV_NOWAIT);
		if (!(globals.ev.flags & (EV_NEWPAGE | EV_NEWDOC | EV_RELOAD)))
		    break;
		globals.ev.flags = EV_IDLE;
	    }
#else
	    redraw_page();
#endif
	}
	xdvi_exit(EXIT_SUCCESS);
    }
    else {
	for (;;) {	/* normal operation */
	    (void) read_events(EV_GT_IDLE);
 	    TRACE_EVENTS((stderr, "globals.ev.flags: %d; ev_newpage: %d, ev_newdoc: %d, ev_reload: %d\n",
			  globals.ev.flags, EV_NEWPAGE, EV_NEWDOC, EV_RELOAD));
	    /* NOTE: reloading must be checked first! */
	    if (globals.ev.flags & (EV_NEWPAGE | EV_NEWDOC | EV_RELOAD | EV_PS_TOGGLE)) {
		TRACE_EVENTS((stderr, "EV_NEWPAGE | ..."));
		globals.ev.flags &= ~(EV_NEWPAGE | EV_EXPOSE | EV_PS_TOGGLE);
		if (globals.ev.flags & EV_RELOAD) {
		    dviErrFlagT errflag;

		    globals.ev.flags &= ~EV_RELOAD;
		    if (load_dvi_file(True, &errflag)) {
#if PS
			ps_clear_cache();
#if PS_GS
			if (resource.gs_alpha) {
			    /* restart gs so that user has a method for fixing GS artifacts with gs_alpha
			       by using `reload' (see also GS_PIXMAP_CLEARING_HACK) */
			    ps_destroy();
			}
#endif
#endif
			statusline_print(STATUS_SHORT, "File reloaded.");
		    }
/* 		    else { */
/* 			statusline_print(STATUS_MEDIUM, "File corrupted, not reloading."); */
/* 		    } */
		}
		if (globals.ev.flags & EV_NEWDOC) {
		    dviErrFlagT errflag;
		    TRACE_EVENTS((stderr, "EV_NEWDOC!"));
/*  		    fprintf(stderr, "newdoc!\n"); */
		    TRACE_FILES((stderr, "current page: %d", current_page));
/*  		    file_history_set_page(current_page); */
		    globals.ev.flags &= ~EV_NEWDOC;
		    if (load_dvi_file(True, &errflag)) {
			statusline_append(STATUS_SHORT, "Opened ", "Opened \"%s\"", globals.dvi_name);
/* 			statusline_print(STATUS_SHORT, "Opened \"%s\"", globals.dvi_name); */
			TRACE_FILES((stderr, "Adding to history: |%s|\n", globals.dvi_name));
			if (file_history_push(globals.dvi_name)) { /* it's a new file, add to history */
			    TRACE_FILES((stderr, "New entry!"));
			    filehist_menu_add_entry(globals.dvi_name);
			}
			else { /* only need to move existing elements to new positions */
			    TRACE_FILES((stderr, "Existing entry!\n"));
			    filehist_menu_refresh();
			}
		    }
		}

		can_exposures(&mane);
		can_exposures(&magnifier);

#if PS && PS_GS && GS_PIXMAP_CLEARING_HACK
		if (had_ps_specials && !MAGNIFIER_ACTIVE) {
		    erasepage_gs();
		    had_ps_specials = False;
		}
#endif /* PS && PS_GS && GS_PIXMAP_CLEARING_HACK */

		if (globals.dvi_file.bak_fp != NULL) {
		    TRACE_EVENTS((stderr, "redraw_page()"));
		    redraw_page();
		}
		else {
		    TRACE_EVENTS((stderr, "dvi_file_changed()"));
		    (void)dvi_file_changed();
		}
	    }
	    else if (globals.ev.flags & EV_FILEHIST_GOTO_PAGE) {
		int pageno;
		globals.ev.flags &= ~EV_FILEHIST_GOTO_PAGE;
		pageno = check_goto_page(file_history_get_page());
		goto_page(pageno, resource.keep_flag ? NULL : home, False);
		TRACE_FILES((stderr, "got page: %d", pageno));
	    }
	    else if (globals.ev.flags & EV_PAGEHIST_INSERT) {
		globals.ev.flags &= ~EV_PAGEHIST_INSERT;
		page_history_insert(current_page);
	    }
	    else if (globals.ev.flags & EV_FIND_CANCEL) {
		/* NOTE: This must be done before checking for expose() */
		globals.ev.flags &= ~EV_FIND_CANCEL;
	    }
	    else if (globals.ev.flags & EV_ANCHOR) {
		/*
		 * Similar to forward search: search for a htex anchor.
		 * This needs to come before the next case which does the redraw_page(),
		 * otherwise anchors for the current page might not be drawn at all:
		 * anchor_search() sets the info later used by htex_draw_anchormarkers(),
		 * which is invoked by redraw_page().
		 */
		
		/* switch off the link cursor */
		globals.cursor.flags &= ~CURSOR_LINK;

		if (dvi_file_changed())
		    continue;
		
		anchor_search(g_anchor_pos);
		globals.ev.flags &= ~EV_ANCHOR;
	    }
	    else if (globals.ev.flags & EV_SRC) {
		/*
		 * Source special operations are deferred to here because
		 * they call geom_scan(), which may call define_font(),
		 * which may call makefont(), which may call read_events()
		 * recursively.
		 */
		if (globals.src.fwd_string != NULL) {
		    const char *s = globals.src.fwd_string;

		    if (dvi_file_changed())
			continue;
		    
		    source_forward_search(s);
		    globals.ev.flags &= ~EV_SRC;
		    globals.src.fwd_string = NULL;

		    /* de-iconify window if needed, and raise it */
		    XMapRaised(XtDisplay(globals.widgets.top_level), XtWindow(globals.widgets.top_level));
		    raise_message_windows();
		}
		else if (source_reverse_x != -1) {
		    if (dvi_file_changed())
			continue;
		    
		    source_reverse_search(source_reverse_x, source_reverse_y, True);
		    globals.ev.flags &= ~EV_SRC;
		}
		else {
		    source_special_show(source_show_all);
		    globals.ev.flags &= ~EV_SRC;
		}
	    }
	    /* support for `-findstring' */
	    else if (globals.ev.flags & EV_FIND) {
		if (dvi_file_changed())
		    continue;

		if (resource.find_string != NULL) { /* not first call */
		    dvi_find_string(resource.find_string, False);
		    resource.find_string = NULL;
		}
		else { /* actually should never arrive here?? */
		    dvi_find_string(NULL, True);
		}
		globals.ev.flags &= ~EV_FIND;
	    }
	    else if (globals.ev.flags & EV_MAG_MOVE) {
		MYTRACE((stderr, "moving mag!"));
		move_magnifier();
	    }
	    else if (globals.ev.flags & EV_EXPOSE) {
		if (magnifier.min_x < MAXDIM) {
/*  		    fprintf(stderr, "magnifier < maxdim!\n"); */
		    if (mane.min_x >= MAXDIM) {
/*  			fprintf(stderr, "mane >= maxdim!\n"); */
			globals.ev.flags &= ~EV_EXPOSE;
		    }
		    redraw(&magnifier);
		}
		else {
		    /* see comment in mag.c */
		    globals.ev.flags &= ~EV_EXPOSE;
		    if (mane.min_x < MAXDIM) {
			redraw(&mane);
		    }
		}
	    }
	    else if (globals.ev.flags & EV_CURSOR) {
		/*
		 * This code eliminates unnecessary calls to XDefineCursor,
		 * since this is a slow operation on some hardware (e.g., S3
		 * chips).
		 */
		XSync(DISP, False);
		if (!XtPending()) {
		    Cursor curr;
			
		    if (globals.cursor.flags & CURSOR_DRAG_V)
			curr = globals.cursor.drag_v;
		    else if (globals.cursor.flags & CURSOR_DRAG_H)
			curr = globals.cursor.drag_h;
		    else if (globals.cursor.flags & CURSOR_DRAG_A)
			curr = globals.cursor.drag_a;
		    else if (resource.mouse_mode == MOUSE_RULER_MODE)
			curr = globals.cursor.rule;
		    else if (resource.mouse_mode == MOUSE_TEXT_MODE && !(globals.cursor.flags & CURSOR_LINK))
			curr = globals.cursor.text;
		    else if (globals.cursor.flags & CURSOR_LINK)
			curr = globals.cursor.link;
		    else if (globals.cursor.flags & CURSOR_MAG)
			curr = globals.cursor.mag;
		    else if (globals.cursor.flags & CURSOR_CORRUPTED)
			curr = globals.cursor.corrupted;
		    else if (globals.pausing.flag)
			curr = globals.cursor.pause;
		    else
			curr = globals.cursor.ready;
		    XDefineCursor(DISP, CURSORWIN, curr);
		    globals.ev.flags &= ~EV_CURSOR;
		}
	    }
	    XFlush(DISP);
	}
    }
}

static void
Act_unpause_or_next(Widget w, XEvent *event,
		    String *params, Cardinal *num_params)
{
    if (block_this_mouse_event())
	return;
    
    if (globals.pausing.flag) {
        globals.pausing.num++;
	if (globals.pausing.num_save)
	    globals.pausing.num_save[current_page] = globals.pausing.num; 
	redraw_page();
    }
    else {
	Act_down_or_next(w, event, params, num_params);
    }
}

/*
 * timer callback for watching the DVI file.
 */
void
watch_file_cb(XtPointer client_data, XtIntervalId *id)
{
    static XtIntervalId timer = 0;
    
    UNUSED(client_data);
    UNUSED(id);

    if (resource.watch_file > 0.0) {
	unsigned long watch_time_ms;

	(void)dvi_file_changed();
    
	if (timer) {
	    XtRemoveTimeOut(timer);
	    timer = (XtIntervalId)(XtIntervalId)0;
	}

	watch_time_ms = (unsigned long)(resource.watch_file * 1000);
	timer = XtAppAddTimeOut(app, watch_time_ms, watch_file_cb, (XtPointer)NULL);
    }
}

void Act_pagehistory_back(Widget w, XEvent *event, String *params, Cardinal *num_params)
{
    int arg;

    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(event);

    if (!get_int_arg(params, num_params, &arg)) {
	arg = 1;
    }
    page_history_move(-arg);
}

void Act_pagehistory_forward(Widget w, XEvent *event, String *params, Cardinal *num_params)
{
    int arg;

    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(event);

    if (!get_int_arg(params, num_params, &arg)) {
	arg = 1;
    }
    page_history_move(arg);
}

void Act_pagehistory_clear(Widget w, XEvent *event, String *params, Cardinal *num_params)
{
    UNUSED(w);
    UNUSED(event);
    UNUSED(params);
    UNUSED(num_params);

    if (block_this_mouse_event())
	return;
    
    page_history_clear();
}

void Act_pagehistory_delete_backward(Widget w, XEvent *event, String *params, Cardinal *num_params)
{
    int arg;

    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(event);

    if (!get_int_arg(params, num_params, &arg)) {
	arg = 1;
    }
    page_history_delete(-arg);
}

void Act_pagehistory_delete_forward(Widget w, XEvent *event, String *params, Cardinal *num_params)
{
    int arg;

    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(event);

    if (!get_int_arg(params, num_params, &arg)) {
	arg = 1;
    }
    page_history_delete(arg);
}

#ifdef MOTIF
void Act_prefs_dialog(Widget w, XEvent *event, String *params, Cardinal *num_params)
{
    int arg;
    
    if (block_this_mouse_event())
	return;
    
    UNUSED(w);
    UNUSED(event);

    if (!get_int_arg(params, num_params, &arg)) {
	arg = -1;
    }
    
    popup_preferences_dialog(globals.widgets.top_level, arg);
}
#endif /* MOTIF */