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
|
/* $XTermId: misc.c,v 1.482 2010/01/21 09:34:58 tom Exp $ */
/*
*
* Copyright 1999-2009,2010 by Thomas E. Dickey
*
* All Rights Reserved
*
* 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 THE ABOVE LISTED COPYRIGHT HOLDER(S) 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.
*
* Except as contained in this notice, the name(s) of the above copyright
* holders shall not be used in advertising or otherwise to promote the
* sale, use or other dealings in this Software without prior written
* authorization.
*
*
* Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts.
*
* All Rights Reserved
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose and without fee is hereby granted,
* provided that the above copyright notice appear in all copies and that
* both that copyright notice and this permission notice appear in
* supporting documentation, and that the name of Digital Equipment
* Corporation not be used in advertising or publicity pertaining to
* distribution of the software without specific, written prior permission.
*
*
* DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
* ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
* DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
* ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
* ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
* SOFTWARE.
*/
#include <version.h>
#include <main.h>
#include <xterm.h>
#include <sys/stat.h>
#include <stdio.h>
#include <signal.h>
#include <ctype.h>
#include <pwd.h>
#include <sys/wait.h>
#include <X11/keysym.h>
#include <X11/Xatom.h>
#include <X11/cursorfont.h>
#include <X11/Xlocale.h>
#include <X11/Xmu/Error.h>
#include <X11/Xmu/SysUtil.h>
#include <X11/Xmu/WinUtil.h>
#include <X11/Xmu/Xmu.h>
#if HAVE_X11_SUNKEYSYM_H
#include <X11/Sunkeysym.h>
#endif
#ifdef HAVE_LANGINFO_CODESET
#include <langinfo.h>
#endif
#include <xutf8.h>
#include <data.h>
#include <error.h>
#include <menu.h>
#include <fontutils.h>
#include <xcharmouse.h>
#include <xstrings.h>
#include <xtermcap.h>
#include <VTparse.h>
#include <assert.h>
#if (XtSpecificationRelease < 6)
#ifndef X_GETTIMEOFDAY
#define X_GETTIMEOFDAY(t) gettimeofday(t,(struct timezone *)0)
#endif
#endif
#ifdef VMS
#define XTERM_VMS_LOGFILE "SYS$SCRATCH:XTERM_LOG.TXT"
#ifdef ALLOWLOGFILEEXEC
#undef ALLOWLOGFILEEXEC
#endif
#endif /* VMS */
#if OPT_TEK4014
#define OUR_EVENT(event,Type) \
(event.type == Type && \
(event.xcrossing.window == XtWindow(XtParent(xw)) || \
(tekWidget && \
event.xcrossing.window == XtWindow(XtParent(tekWidget)))))
#else
#define OUR_EVENT(event,Type) \
(event.type == Type && \
(event.xcrossing.window == XtWindow(XtParent(xw))))
#endif
static Cursor make_hidden_cursor(XtermWidget);
#if OPT_EXEC_XTERM
/* Like readlink(2), but returns a malloc()ed buffer, or NULL on
error; adapted from libc docs */
static char *
Readlink(const char *filename)
{
char *buf = NULL;
unsigned size = 100;
int n;
for (;;) {
buf = TypeRealloc(char, size, buf);
memset(buf, 0, size);
n = readlink(filename, buf, size);
if (n < 0) {
free(buf);
return NULL;
}
if ((unsigned) n < size) {
return buf;
}
size *= 2;
}
}
#endif /* OPT_EXEC_XTERM */
static void
Sleep(int msec)
{
static struct timeval select_timeout;
select_timeout.tv_sec = 0;
select_timeout.tv_usec = msec * 1000;
select(0, 0, 0, 0, &select_timeout);
}
static void
selectwindow(TScreen * screen, int flag)
{
TRACE(("selectwindow(%d) flag=%d\n", screen->select, flag));
#if OPT_TEK4014
if (TEK4014_ACTIVE(term)) {
if (!Ttoggled)
TCursorToggle(tekWidget, TOGGLE);
screen->select |= flag;
if (!Ttoggled)
TCursorToggle(tekWidget, TOGGLE);
} else
#endif
{
if (screen->xic)
XSetICFocus(screen->xic);
if (screen->cursor_state && CursorMoved(screen))
HideCursor();
screen->select |= flag;
if (screen->cursor_state)
ShowCursor();
}
}
static void
unselectwindow(TScreen * screen, int flag)
{
TRACE(("unselectwindow(%d) flag=%d\n", screen->select, flag));
if (screen->hide_pointer) {
screen->hide_pointer = False;
xtermDisplayCursor(term);
}
if (!screen->always_highlight) {
#if OPT_TEK4014
if (TEK4014_ACTIVE(term)) {
if (!Ttoggled)
TCursorToggle(tekWidget, TOGGLE);
screen->select &= ~flag;
if (!Ttoggled)
TCursorToggle(tekWidget, TOGGLE);
} else
#endif
{
if (screen->xic)
XUnsetICFocus(screen->xic);
screen->select &= ~flag;
if (screen->cursor_state && CursorMoved(screen))
HideCursor();
if (screen->cursor_state)
ShowCursor();
}
}
}
static void
DoSpecialEnterNotify(XtermWidget xw, XEnterWindowEvent * ev)
{
TScreen *screen = TScreenOf(xw);
TRACE(("DoSpecialEnterNotify(%d)\n", screen->select));
TRACE_FOCUS(xw, ev);
if (((ev->detail) != NotifyInferior) &&
ev->focus &&
!(screen->select & FOCUS))
selectwindow(screen, INWINDOW);
}
static void
DoSpecialLeaveNotify(XtermWidget xw, XEnterWindowEvent * ev)
{
TScreen *screen = TScreenOf(xw);
TRACE(("DoSpecialLeaveNotify(%d)\n", screen->select));
TRACE_FOCUS(xw, ev);
if (((ev->detail) != NotifyInferior) &&
ev->focus &&
!(screen->select & FOCUS))
unselectwindow(screen, INWINDOW);
}
#ifndef XUrgencyHint
#define XUrgencyHint (1L << 8) /* X11R5 does not define */
#endif
static void
setXUrgency(TScreen * screen, Bool enable)
{
if (screen->bellIsUrgent) {
XWMHints *h = XGetWMHints(screen->display, VShellWindow);
if (h != 0) {
if (enable) {
h->flags |= XUrgencyHint;
} else {
h->flags &= ~XUrgencyHint;
}
XSetWMHints(screen->display, VShellWindow, h);
}
}
}
void
do_xevents(void)
{
TScreen *screen = TScreenOf(term);
if (XtAppPending(app_con)
||
#if defined(VMS) || defined(__VMS)
screen->display->qlen > 0
#else
GetBytesAvailable(ConnectionNumber(screen->display)) > 0
#endif
)
xevents();
}
void
xtermDisplayCursor(XtermWidget xw)
{
TScreen *screen = TScreenOf(xw);
if (screen->Vshow) {
if (screen->hide_pointer) {
TRACE(("Display hidden_cursor\n"));
XDefineCursor(screen->display, VWindow(screen), screen->hidden_cursor);
} else {
TRACE(("Display pointer_cursor\n"));
recolor_cursor(screen,
screen->pointer_cursor,
T_COLOR(screen, MOUSE_FG),
T_COLOR(screen, MOUSE_BG));
XDefineCursor(screen->display, VWindow(screen), screen->pointer_cursor);
}
}
}
void
xtermShowPointer(XtermWidget xw, Bool enable)
{
static int tried = -1;
TScreen *screen = TScreenOf(xw);
#if OPT_TEK4014
if (TEK4014_SHOWN(xw))
enable = True;
#endif
/*
* Whether we actually hide the pointer depends on the pointer-mode and
* the mouse-mode:
*/
if (!enable) {
switch (screen->pointer_mode) {
case pNever:
enable = True;
break;
case pNoMouse:
if (screen->send_mouse_pos != MOUSE_OFF)
enable = True;
break;
case pAlways:
break;
}
}
if (enable) {
if (screen->hide_pointer) {
screen->hide_pointer = False;
xtermDisplayCursor(xw);
switch (screen->send_mouse_pos) {
case ANY_EVENT_MOUSE:
break;
default:
MotionOff(screen, xw);
break;
}
}
} else if (!(screen->hide_pointer) && (tried <= 0)) {
if (screen->hidden_cursor == 0) {
screen->hidden_cursor = make_hidden_cursor(xw);
}
if (screen->hidden_cursor == 0) {
tried = 1;
} else {
tried = 0;
screen->hide_pointer = True;
xtermDisplayCursor(xw);
MotionOn(screen, xw);
}
}
}
void
xevents(void)
{
XtermWidget xw = term;
TScreen *screen = TScreenOf(xw);
XEvent event;
XtInputMask input_mask;
if (need_cleanup)
Cleanup(0);
if (screen->scroll_amt)
FlushScroll(xw);
/*
* process timeouts, relying on the fact that XtAppProcessEvent
* will process the timeout and return without blockng on the
* XEvent queue. Other sources i.e. the pty are handled elsewhere
* with select().
*/
while ((input_mask = XtAppPending(app_con)) & XtIMTimer)
XtAppProcessEvent(app_con, XtIMTimer);
#if OPT_SESSION_MGT
/*
* Session management events are alternative input events. Deal with
* them in the same way.
*/
while ((input_mask = XtAppPending(app_con)) & XtIMAlternateInput)
XtAppProcessEvent(app_con, XtIMAlternateInput);
#endif
/*
* If there's no XEvents, don't wait around...
*/
if ((input_mask & XtIMXEvent) != XtIMXEvent)
return;
do {
/*
* This check makes xterm hang when in mouse hilite tracking mode.
* We simply ignore all events except for those not passed down to
* this function, e.g., those handled in in_put().
*/
if (screen->waitingForTrackInfo) {
Sleep(10);
return;
}
XtAppNextEvent(app_con, &event);
/*
* Hack to get around problems with the toolkit throwing away
* eventing during the exclusive grab of the menu popup. By
* looking at the event ourselves we make sure that we can
* do the right thing.
*/
if (OUR_EVENT(event, EnterNotify)) {
DoSpecialEnterNotify(xw, &event.xcrossing);
} else if (OUR_EVENT(event, LeaveNotify)) {
DoSpecialLeaveNotify(xw, &event.xcrossing);
} else if ((screen->send_mouse_pos == ANY_EVENT_MOUSE
#if OPT_DEC_LOCATOR
|| screen->send_mouse_pos == DEC_LOCATOR
#endif /* OPT_DEC_LOCATOR */
)
&& event.xany.type == MotionNotify
&& event.xcrossing.window == XtWindow(xw)) {
SendMousePosition(xw, &event);
continue;
}
if (!event.xany.send_event ||
screen->allowSendEvents ||
((event.xany.type != KeyPress) &&
(event.xany.type != KeyRelease) &&
(event.xany.type != ButtonPress) &&
(event.xany.type != ButtonRelease))) {
/*
* If the event is interesting (and not a keyboard event), turn the
* mouse pointer back on.
*/
if (screen->hide_pointer) {
switch (event.xany.type) {
case KeyPress:
case KeyRelease:
case ButtonPress:
case ButtonRelease:
/* also these... */
case Expose:
case NoExpose:
case PropertyNotify:
break;
default:
xtermShowPointer(xw, True);
break;
}
}
XtDispatchEvent(&event);
}
} while ((input_mask = XtAppPending(app_con)) & XtIMXEvent);
}
static Cursor
make_hidden_cursor(XtermWidget xw)
{
TScreen *screen = TScreenOf(xw);
Cursor c;
Display *dpy = screen->display;
XFontStruct *fn;
static XColor dummy;
/*
* Prefer nil2 (which is normally available) to "fixed" (which is supposed
* to be "always" available), since it's a smaller glyph in case the
* server insists on drawing _something_.
*/
TRACE(("Ask for nil2 font\n"));
if ((fn = XLoadQueryFont(dpy, "nil2")) == 0) {
TRACE(("...Ask for fixed font\n"));
fn = XLoadQueryFont(dpy, DEFFONT);
}
if (fn != 0) {
/* a space character seems to work as a cursor (dots are not needed) */
c = XCreateGlyphCursor(dpy, fn->fid, fn->fid, 'X', ' ', &dummy, &dummy);
XFreeFont(dpy, fn);
} else {
c = 0;
}
TRACE(("XCreateGlyphCursor ->%#lx\n", c));
return (c);
}
Cursor
make_colored_cursor(unsigned cursorindex, /* index into font */
unsigned long fg, /* pixel value */
unsigned long bg) /* pixel value */
{
TScreen *screen = TScreenOf(term);
Cursor c;
Display *dpy = screen->display;
c = XCreateFontCursor(dpy, cursorindex);
if (c != None) {
recolor_cursor(screen, c, fg, bg);
}
return (c);
}
/* ARGSUSED */
void
HandleKeyPressed(Widget w GCC_UNUSED,
XEvent * event,
String * params GCC_UNUSED,
Cardinal *nparams GCC_UNUSED)
{
TRACE(("Handle insert-seven-bit for %p\n", (void *) w));
Input(term, &event->xkey, False);
}
/* ARGSUSED */
void
HandleEightBitKeyPressed(Widget w GCC_UNUSED,
XEvent * event,
String * params GCC_UNUSED,
Cardinal *nparams GCC_UNUSED)
{
TRACE(("Handle insert-eight-bit for %p\n", (void *) w));
Input(term, &event->xkey, True);
}
/* ARGSUSED */
void
HandleStringEvent(Widget w GCC_UNUSED,
XEvent * event GCC_UNUSED,
String * params,
Cardinal *nparams)
{
if (*nparams != 1)
return;
if ((*params)[0] == '0' && (*params)[1] == 'x' && (*params)[2] != '\0') {
const char *abcdef = "ABCDEF";
const char *xxxxxx;
Char c;
UString p;
unsigned value = 0;
for (p = (UString) (*params + 2); (c = CharOf(x_toupper(*p))) !=
'\0'; p++) {
value *= 16;
if (c >= '0' && c <= '9')
value += (unsigned) (c - '0');
else if ((xxxxxx = strchr(abcdef, c)) != 0)
value += (unsigned) (xxxxxx - abcdef) + 10;
else
break;
}
if (c == '\0') {
Char hexval[2];
hexval[0] = (Char) value;
hexval[1] = 0;
StringInput(term, hexval, (size_t) 1);
}
} else {
StringInput(term, (Char *) * params, strlen(*params));
}
}
#if OPT_EXEC_XTERM
#ifndef PROCFS_ROOT
#define PROCFS_ROOT "/proc"
#endif
/* ARGSUSED */
void
HandleSpawnTerminal(Widget w GCC_UNUSED,
XEvent * event GCC_UNUSED,
String * params,
Cardinal *nparams)
{
TScreen *screen = TScreenOf(term);
char *child_cwd = NULL;
char *child_exe;
pid_t pid;
/*
* Try to find the actual program which is running in the child process.
* This works for Linux. If we cannot find the program, fall back to the
* xterm program (which is usually adequate). Give up if we are given only
* a relative path to xterm, since that would not always match $PATH.
*/
child_exe = Readlink(PROCFS_ROOT "/self/exe");
if (!child_exe) {
if (strncmp(ProgramName, "./", 2)
&& strncmp(ProgramName, "../", 3)) {
child_exe = xtermFindShell(ProgramName, True);
} else {
fprintf(stderr, "Cannot exec-xterm given %s\n", ProgramName);
}
if (child_exe == 0)
return;
}
/*
* Determine the current working directory of the child so that we can
* spawn a new terminal in the same directory.
*
* If we cannot get the CWD of the child, just use our own.
*/
if (screen->pid) {
char child_cwd_link[sizeof(PROCFS_ROOT) + 80];
sprintf(child_cwd_link, PROCFS_ROOT "/%lu/cwd", (unsigned long) screen->pid);
child_cwd = Readlink(child_cwd_link);
}
/* The reaper will take care of cleaning up the child */
pid = fork();
if (pid == -1) {
fprintf(stderr, "Could not fork: %s\n", SysErrorMsg(errno));
} else if (!pid) {
/* We are the child */
if (child_cwd) {
IGNORE_RC(chdir(child_cwd)); /* We don't care if this fails */
}
if (setuid(screen->uid) == -1
|| setgid(screen->gid) == -1) {
fprintf(stderr, "Cannot reset uid/gid\n");
} else {
unsigned myargc = *nparams + 1;
char **myargv = TypeMallocN(char *, myargc + 1);
unsigned n = 0;
myargv[n++] = child_exe;
while (n < myargc) {
myargv[n++] = *params++;
}
myargv[n] = 0;
execv(child_exe, myargv);
/* If we get here, we've failed */
fprintf(stderr, "exec of '%s': %s\n", child_exe, SysErrorMsg(errno));
}
_exit(0);
} else {
/* We are the parent; clean up */
if (child_cwd)
free(child_cwd);
if (child_exe)
free(child_exe);
}
}
#endif /* OPT_EXEC_XTERM */
/*
* Rather than sending characters to the host, put them directly into our
* input queue. That lets a user have access to any of the control sequences
* for a key binding. This is the equivalent of local function key support.
*
* NOTE: This code does not support the hexadecimal kludge used in
* HandleStringEvent because it prevents us from sending an arbitrary string
* (but it appears in a lot of examples - so we are stuck with it). The
* standard string converter does recognize "\" for newline ("\n") and for
* octal constants (e.g., "\007" for BEL). So we assume the user can make do
* without a specialized converter. (Don't try to use \000, though).
*/
/* ARGSUSED */
void
HandleInterpret(Widget w GCC_UNUSED,
XEvent * event GCC_UNUSED,
String * params,
Cardinal *param_count)
{
if (*param_count == 1) {
char *value = params[0];
int need = (int) strlen(value);
int used = VTbuffer->next - VTbuffer->buffer;
int have = VTbuffer->last - VTbuffer->buffer;
if (have - used + need < BUF_SIZE) {
fillPtyData(TScreenOf(term), VTbuffer, value, (int) strlen(value));
TRACE(("Interpret %s\n", value));
VTbuffer->update++;
}
}
}
/*ARGSUSED*/
void
HandleEnterWindow(Widget w GCC_UNUSED,
XtPointer eventdata GCC_UNUSED,
XEvent * event GCC_UNUSED,
Boolean * cont GCC_UNUSED)
{
/* NOP since we handled it above */
TRACE(("HandleEnterWindow ignored\n"));
TRACE_FOCUS(w, event);
}
/*ARGSUSED*/
void
HandleLeaveWindow(Widget w GCC_UNUSED,
XtPointer eventdata GCC_UNUSED,
XEvent * event GCC_UNUSED,
Boolean * cont GCC_UNUSED)
{
/* NOP since we handled it above */
TRACE(("HandleLeaveWindow ignored\n"));
TRACE_FOCUS(w, event);
}
/*ARGSUSED*/
void
HandleFocusChange(Widget w GCC_UNUSED,
XtPointer eventdata GCC_UNUSED,
XEvent * ev,
Boolean * cont GCC_UNUSED)
{
XFocusChangeEvent *event = (XFocusChangeEvent *) ev;
XtermWidget xw = term;
TScreen *screen = TScreenOf(xw);
TRACE(("HandleFocusChange type=%s, mode=%d, detail=%d\n",
visibleEventType(event->type),
event->mode,
event->detail));
TRACE_FOCUS(xw, event);
if (screen->quiet_grab
&& (event->mode == NotifyGrab || event->mode == NotifyUngrab)) {
;
} else if (event->type == FocusIn) {
setXUrgency(screen, False);
/*
* NotifyNonlinear only happens (on FocusIn) if the pointer was not in
* one of our windows. Use this to reset a case where one xterm is
* partly obscuring another, and X gets (us) confused about whether the
* pointer was in the window. In particular, this can happen if the
* user is resizing the obscuring window, causing some events to not be
* delivered to the obscured window.
*/
if (event->detail == NotifyNonlinear
&& (screen->select & INWINDOW) != 0) {
unselectwindow(screen, INWINDOW);
}
selectwindow(screen,
((event->detail == NotifyPointer)
? INWINDOW
: FOCUS));
SendFocusButton(xw, event);
} else {
#if OPT_FOCUS_EVENT
if (event->type == FocusOut) {
SendFocusButton(xw, event);
}
#endif
/*
* XGrabKeyboard() will generate NotifyGrab event that we want to
* ignore.
*/
if (event->mode != NotifyGrab) {
unselectwindow(screen,
((event->detail == NotifyPointer)
? INWINDOW
: FOCUS));
}
if (screen->grabbedKbd && (event->mode == NotifyUngrab)) {
Bell(XkbBI_Info, 100);
ReverseVideo(xw);
screen->grabbedKbd = False;
update_securekbd();
}
}
}
static long lastBellTime; /* in milliseconds */
#if defined(HAVE_XKB_BELL_EXT)
static Atom
AtomBell(XtermWidget xw, int which)
{
#define DATA(name) { XkbBI_##name, XkbBN_##name }
static struct {
int value;
const char *name;
} table[] = {
DATA(Info),
DATA(MarginBell),
DATA(MinorError),
DATA(TerminalBell)
};
Cardinal n;
Atom result = None;
for (n = 0; n < XtNumber(table); ++n) {
if (table[n].value == which) {
result = XInternAtom(XtDisplay(xw), table[n].name, True);
break;
}
}
return result;
}
#endif
void
xtermBell(XtermWidget xw, int which, int percent)
{
TScreen *screen = TScreenOf(xw);
#if defined(HAVE_XKB_BELL_EXT)
Atom tony = AtomBell(xw, which);
#endif
switch (which) {
case XkbBI_Info:
case XkbBI_MinorError:
case XkbBI_MajorError:
case XkbBI_TerminalBell:
switch (screen->warningVolume) {
case bvOff:
percent = -100;
break;
case bvLow:
break;
case bvHigh:
percent = 100;
break;
}
break;
case XkbBI_MarginBell:
switch (screen->marginVolume) {
case bvOff:
percent = -100;
break;
case bvLow:
break;
case bvHigh:
percent = 100;
break;
}
break;
default:
break;
}
#if defined(HAVE_XKB_BELL_EXT)
if (tony != None) {
XkbBell(screen->display, VShellWindow, percent, tony);
} else
#endif
XBell(screen->display, percent);
}
void
Bell(int which, int percent)
{
XtermWidget xw = term;
TScreen *screen = TScreenOf(xw);
struct timeval curtime;
long now_msecs;
TRACE(("BELL %d %d%%\n", which, percent));
if (!XtIsRealized((Widget) xw)) {
return;
}
setXUrgency(screen, True);
/* has enough time gone by that we are allowed to ring
the bell again? */
if (screen->bellSuppressTime) {
if (screen->bellInProgress) {
do_xevents();
if (screen->bellInProgress) { /* even after new events? */
return;
}
}
X_GETTIMEOFDAY(&curtime);
now_msecs = 1000 * curtime.tv_sec + curtime.tv_usec / 1000;
if (lastBellTime != 0 && now_msecs - lastBellTime >= 0 &&
now_msecs - lastBellTime < screen->bellSuppressTime) {
return;
}
lastBellTime = now_msecs;
}
if (screen->visualbell) {
VisualBell();
} else {
xtermBell(xw, which, percent);
}
if (screen->poponbell)
XRaiseWindow(screen->display, VShellWindow);
if (screen->bellSuppressTime) {
/* now we change a property and wait for the notify event to come
back. If the server is suspending operations while the bell
is being emitted (problematic for audio bell), this lets us
know when the previous bell has finished */
Widget w = CURRENT_EMU();
XChangeProperty(XtDisplay(w), XtWindow(w),
XA_NOTICE, XA_NOTICE, 8, PropModeAppend, NULL, 0);
screen->bellInProgress = True;
}
}
#define VB_DELAY screen->visualBellDelay
static void
flashWindow(TScreen * screen, Window window, GC visualGC, unsigned width, unsigned height)
{
XFillRectangle(screen->display, window, visualGC, 0, 0, width, height);
XFlush(screen->display);
Sleep(VB_DELAY);
XFillRectangle(screen->display, window, visualGC, 0, 0, width, height);
}
void
VisualBell(void)
{
TScreen *screen = TScreenOf(term);
if (VB_DELAY > 0) {
Pixel xorPixel = (T_COLOR(screen, TEXT_FG) ^
T_COLOR(screen, TEXT_BG));
XGCValues gcval;
GC visualGC;
gcval.function = GXxor;
gcval.foreground = xorPixel;
visualGC = XtGetGC((Widget) term, GCFunction + GCForeground, &gcval);
#if OPT_TEK4014
if (TEK4014_ACTIVE(term)) {
TekScreen *tekscr = TekScreenOf(tekWidget);
flashWindow(screen, TWindow(tekscr), visualGC,
TFullWidth(tekscr),
TFullHeight(tekscr));
} else
#endif
{
flashWindow(screen, VWindow(screen), visualGC,
FullWidth(screen),
FullHeight(screen));
}
XtReleaseGC((Widget) term, visualGC);
}
}
/* ARGSUSED */
void
HandleBellPropertyChange(Widget w GCC_UNUSED,
XtPointer data GCC_UNUSED,
XEvent * ev,
Boolean * more GCC_UNUSED)
{
TScreen *screen = TScreenOf(term);
if (ev->xproperty.atom == XA_NOTICE) {
screen->bellInProgress = False;
}
}
Window
WMFrameWindow(XtermWidget termw)
{
Window win_root, win_current, *children;
Window win_parent = 0;
unsigned int nchildren;
win_current = XtWindow(termw);
/* find the parent which is child of root */
do {
if (win_parent)
win_current = win_parent;
XQueryTree(TScreenOf(termw)->display,
win_current,
&win_root,
&win_parent,
&children,
&nchildren);
XFree(children);
} while (win_root != win_parent);
return win_current;
}
#if OPT_DABBREV
/*
* The following code implements `dynamic abbreviation' expansion a la
* Emacs. It looks in the preceding visible screen and its scrollback
* to find expansions of a typed word. It compares consecutive
* expansions and ignores one of them if they are identical.
* (Tomasz J. Cholewo, t.cholewo@ieee.org)
*/
#define IS_WORD_CONSTITUENT(x) ((x) != ' ' && (x) != '\0')
#define MAXWLEN 1024 /* maximum word length as in tcsh */
static int
dabbrev_prev_char(TScreen * screen, CELL * cell, LineData ** ld)
{
int result = -1;
int firstLine = -(screen->savedlines);
*ld = getLineData(screen, cell->row);
while (cell->row >= firstLine) {
if (--(cell->col) >= 0) {
result = (int) (*ld)->charData[cell->col];
break;
}
if (--(cell->row) < firstLine)
break; /* ...there is no previous line */
*ld = getLineData(screen, cell->row);
cell->col = MaxCols(screen);
if (!LineTstWrapped(*ld)) {
result = ' '; /* treat lines as separate */
break;
}
}
return result;
}
static char *
dabbrev_prev_word(TScreen * screen, CELL * cell, LineData ** ld)
{
static char ab[MAXWLEN];
char *abword;
int c;
char *ab_end = (ab + MAXWLEN - 1);
char *result = 0;
abword = ab_end;
*abword = '\0'; /* end of string marker */
while ((c = dabbrev_prev_char(screen, cell, ld)) >= 0 &&
IS_WORD_CONSTITUENT(c)) {
if (abword > ab) /* store only |MAXWLEN| last chars */
*(--abword) = (char) c;
}
if (c >= 0) {
result = abword;
} else if (abword != ab_end) {
result = abword;
}
if (result != 0) {
while ((c = dabbrev_prev_char(screen, cell, ld)) >= 0 &&
!IS_WORD_CONSTITUENT(c)) {
; /* skip preceding spaces */
}
(cell->col)++; /* can be | > screen->max_col| */
}
return result;
}
static int
dabbrev_expand(TScreen * screen)
{
int pty = screen->respond; /* file descriptor of pty */
static CELL cell;
static char *dabbrev_hint = 0, *lastexpansion = 0;
static unsigned int expansions;
char *expansion;
Char *copybuffer;
size_t hint_len;
unsigned del_cnt;
unsigned buf_cnt;
int result = 0;
LineData *ld;
if (!screen->dabbrev_working) { /* initialize */
expansions = 0;
cell.col = screen->cur_col;
cell.row = screen->cur_row;
if (dabbrev_hint != 0)
free(dabbrev_hint);
if ((dabbrev_hint = dabbrev_prev_word(screen, &cell, &ld)) != 0) {
if (lastexpansion != 0)
free(lastexpansion);
if ((lastexpansion = strdup(dabbrev_hint)) != 0) {
/* make own copy */
if ((dabbrev_hint = strdup(dabbrev_hint)) != 0) {
screen->dabbrev_working = True;
/* we are in the middle of dabbrev process */
}
}
}
if (!screen->dabbrev_working) {
if (lastexpansion != 0) {
free(lastexpansion);
lastexpansion = 0;
}
return result;
}
} else {
}
hint_len = strlen(dabbrev_hint);
for (;;) {
if ((expansion = dabbrev_prev_word(screen, &cell, &ld)) == 0) {
if (expansions >= 2) {
expansions = 0;
cell.col = screen->cur_col;
cell.row = screen->cur_row;
continue;
}
break;
}
if (!strncmp(dabbrev_hint, expansion, hint_len) && /* empty hint matches everything */
strlen(expansion) > hint_len && /* trivial expansion disallowed */
strcmp(expansion, lastexpansion)) /* different from previous */
break;
}
if (expansion != 0) {
del_cnt = strlen(lastexpansion) - hint_len;
buf_cnt = del_cnt + strlen(expansion) - hint_len;
if ((copybuffer = TypeMallocN(Char, buf_cnt)) != 0) {
/* delete previous expansion */
memset(copybuffer, screen->dabbrev_erase_char, del_cnt);
memmove(copybuffer + del_cnt,
expansion + hint_len,
strlen(expansion) - hint_len);
v_write(pty, copybuffer, buf_cnt);
/* v_write() just reset our flag */
screen->dabbrev_working = True;
free(copybuffer);
free(lastexpansion);
if ((lastexpansion = strdup(expansion)) != 0) {
result = 1;
expansions++;
}
}
}
return result;
}
/*ARGSUSED*/
void
HandleDabbrevExpand(Widget w,
XEvent * event GCC_UNUSED,
String * params GCC_UNUSED,
Cardinal *nparams GCC_UNUSED)
{
XtermWidget xw;
TRACE(("Handle dabbrev-expand for %p\n", (void *) w));
if ((xw = getXtermWidget(w)) != 0) {
TScreen *screen = TScreenOf(xw);
if (!dabbrev_expand(screen))
Bell(XkbBI_TerminalBell, 0);
}
}
#endif /* OPT_DABBREV */
#if OPT_MAXIMIZE
/*ARGSUSED*/
void
HandleDeIconify(Widget w,
XEvent * event GCC_UNUSED,
String * params GCC_UNUSED,
Cardinal *nparams GCC_UNUSED)
{
XtermWidget xw;
if ((xw = getXtermWidget(w)) != 0) {
TScreen *screen = TScreenOf(xw);
XMapWindow(screen->display, VShellWindow);
}
}
/*ARGSUSED*/
void
HandleIconify(Widget w,
XEvent * event GCC_UNUSED,
String * params GCC_UNUSED,
Cardinal *nparams GCC_UNUSED)
{
XtermWidget xw;
if ((xw = getXtermWidget(w)) != 0) {
TScreen *screen = TScreenOf(xw);
XIconifyWindow(screen->display,
VShellWindow,
DefaultScreen(screen->display));
}
}
int
QueryMaximize(XtermWidget termw, unsigned *width, unsigned *height)
{
TScreen *screen = TScreenOf(termw);
XSizeHints hints;
long supp = 0;
Window root_win;
int root_x = -1; /* saved co-ordinates */
int root_y = -1;
unsigned root_border;
unsigned root_depth;
if (XGetGeometry(screen->display,
RootWindowOfScreen(XtScreen(termw)),
&root_win,
&root_x,
&root_y,
width,
height,
&root_border,
&root_depth)) {
TRACE(("QueryMaximize: XGetGeometry position %d,%d size %d,%d border %d\n",
root_x,
root_y,
*width,
*height,
root_border));
*width -= (root_border * 2);
*height -= (root_border * 2);
hints.flags = PMaxSize;
if (XGetWMNormalHints(screen->display,
VShellWindow,
&hints,
&supp)
&& (hints.flags & PMaxSize) != 0) {
TRACE(("QueryMaximize: WM hints max_w %#x max_h %#x\n",
hints.max_width,
hints.max_height));
if ((unsigned) hints.max_width < *width)
*width = (unsigned) hints.max_width;
if ((unsigned) hints.max_height < *height)
*height = (unsigned) hints.max_height;
}
return 1;
}
return 0;
}
void
RequestMaximize(XtermWidget termw, int maximize)
{
TScreen *screen = TScreenOf(termw);
XWindowAttributes wm_attrs, vshell_attrs;
unsigned root_width, root_height;
TRACE(("RequestMaximize %s\n", maximize ? "maximize" : "restore"));
if (maximize) {
if (QueryMaximize(termw, &root_width, &root_height)) {
if (XGetWindowAttributes(screen->display,
WMFrameWindow(termw),
&wm_attrs)) {
if (XGetWindowAttributes(screen->display,
VShellWindow,
&vshell_attrs)) {
if (screen->restore_data != True
|| screen->restore_width != root_width
|| screen->restore_height != root_height) {
screen->restore_data = True;
screen->restore_x = wm_attrs.x + wm_attrs.border_width;
screen->restore_y = wm_attrs.y + wm_attrs.border_width;
screen->restore_width = (unsigned) vshell_attrs.width;
screen->restore_height = (unsigned) vshell_attrs.height;
TRACE(("HandleMaximize: save window position %d,%d size %d,%d\n",
screen->restore_x,
screen->restore_y,
screen->restore_width,
screen->restore_height));
}
/* subtract wm decoration dimensions */
root_width -=
(unsigned) ((wm_attrs.width - vshell_attrs.width)
+ (wm_attrs.border_width * 2));
root_height -=
(unsigned) ((wm_attrs.height - vshell_attrs.height)
+ (wm_attrs.border_width * 2));
XMoveResizeWindow(screen->display, VShellWindow,
0 + wm_attrs.border_width, /* x */
0 + wm_attrs.border_width, /* y */
root_width,
root_height);
}
}
}
} else {
if (screen->restore_data) {
TRACE(("HandleRestoreSize: position %d,%d size %d,%d\n",
screen->restore_x,
screen->restore_y,
screen->restore_width,
screen->restore_height));
screen->restore_data = False;
XMoveResizeWindow(screen->display,
VShellWindow,
screen->restore_x,
screen->restore_y,
screen->restore_width,
screen->restore_height);
}
}
}
/*ARGSUSED*/
void
HandleMaximize(Widget w,
XEvent * event GCC_UNUSED,
String * params GCC_UNUSED,
Cardinal *nparams GCC_UNUSED)
{
XtermWidget xw;
if ((xw = getXtermWidget(w)) != 0) {
RequestMaximize(xw, 1);
}
}
/*ARGSUSED*/
void
HandleRestoreSize(Widget w,
XEvent * event GCC_UNUSED,
String * params GCC_UNUSED,
Cardinal *nparams GCC_UNUSED)
{
XtermWidget xw;
if ((xw = getXtermWidget(w)) != 0) {
RequestMaximize(xw, 0);
}
}
#endif /* OPT_MAXIMIZE */
void
Redraw(void)
{
TScreen *screen = TScreenOf(term);
XExposeEvent event;
TRACE(("Redraw\n"));
event.type = Expose;
event.display = screen->display;
event.x = 0;
event.y = 0;
event.count = 0;
if (VWindow(screen)) {
event.window = VWindow(screen);
event.width = term->core.width;
event.height = term->core.height;
(*term->core.widget_class->core_class.expose) ((Widget) term,
(XEvent *) & event,
NULL);
if (ScrollbarWidth(screen)) {
(screen->scrollWidget->core.widget_class->core_class.expose)
(screen->scrollWidget, (XEvent *) & event, NULL);
}
}
#if OPT_TEK4014
if (TEK4014_SHOWN(term)) {
TekScreen *tekscr = TekScreenOf(tekWidget);
event.window = TWindow(tekscr);
event.width = tekWidget->core.width;
event.height = tekWidget->core.height;
TekExpose((Widget) tekWidget, (XEvent *) & event, NULL);
}
#endif
}
#ifdef VMS
#define TIMESTAMP_FMT "%s%d-%02d-%02d-%02d-%02d-%02d"
#else
#define TIMESTAMP_FMT "%s%d-%02d-%02d.%02d:%02d:%02d"
#endif
void
timestamp_filename(char *dst, const char *src)
{
time_t tstamp;
struct tm *tstruct;
tstamp = time((time_t *) 0);
tstruct = localtime(&tstamp);
sprintf(dst, TIMESTAMP_FMT,
src,
tstruct->tm_year + 1900,
tstruct->tm_mon + 1,
tstruct->tm_mday,
tstruct->tm_hour,
tstruct->tm_min,
tstruct->tm_sec);
}
int
open_userfile(uid_t uid, gid_t gid, char *path, Bool append)
{
int fd;
struct stat sb;
#ifdef VMS
if ((fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644)) < 0) {
int the_error = errno;
fprintf(stderr, "%s: cannot open %s: %d:%s\n",
xterm_name,
path,
the_error,
SysErrorMsg(the_error));
return -1;
}
chown(path, uid, gid);
#else
if ((access(path, F_OK) != 0 && (errno != ENOENT))
|| (creat_as(uid, gid, append, path, 0644) <= 0)
|| ((fd = open(path, O_WRONLY | O_APPEND)) < 0)) {
int the_error = errno;
fprintf(stderr, "%s: cannot open %s: %d:%s\n",
xterm_name,
path,
the_error,
SysErrorMsg(the_error));
return -1;
}
#endif
/*
* Doublecheck that the user really owns the file that we've opened before
* we do any damage, and that it is not world-writable.
*/
if (fstat(fd, &sb) < 0
|| sb.st_uid != uid
|| (sb.st_mode & 022) != 0) {
fprintf(stderr, "%s: you do not own %s\n", xterm_name, path);
close(fd);
return -1;
}
return fd;
}
#ifndef VMS
/*
* Create a file only if we could with the permissions of the real user id.
* We could emulate this with careful use of access() and following
* symbolic links, but that is messy and has race conditions.
* Forking is messy, too, but we can't count on setreuid() or saved set-uids
* being available.
*
* Note: When called for user logging, we have ensured that the real and
* effective user ids are the same, so this remains as a convenience function
* for the debug logs.
*
* Returns
* 1 if we can proceed to open the file in relative safety,
* -1 on error, e.g., cannot fork
* 0 otherwise.
*/
int
creat_as(uid_t uid, gid_t gid, Bool append, char *pathname, int mode)
{
int fd;
pid_t pid;
int retval = 0;
int childstat = 0;
#ifndef HAVE_WAITPID
int waited;
SIGNAL_T(*chldfunc) (int);
chldfunc = signal(SIGCHLD, SIG_DFL);
#endif /* HAVE_WAITPID */
TRACE(("creat_as(uid=%d/%d, gid=%d/%d, append=%d, pathname=%s, mode=%#o)\n",
(int) uid, (int) geteuid(),
(int) gid, (int) getegid(),
append,
pathname,
mode));
if (uid == geteuid() && gid == getegid()) {
fd = open(pathname,
O_WRONLY | O_CREAT | (append ? O_APPEND : O_EXCL),
mode);
if (fd >= 0)
close(fd);
return (fd >= 0);
}
pid = fork();
switch (pid) {
case 0: /* child */
if (setgid(gid) == -1
|| setuid(uid) == -1) {
/* we cannot report an error here via stderr, just quit */
retval = 1;
} else {
fd = open(pathname,
O_WRONLY | O_CREAT | (append ? O_APPEND : O_EXCL),
mode);
if (fd >= 0) {
close(fd);
retval = 0;
} else {
retval = 1;
}
}
_exit(retval);
/* NOTREACHED */
case -1: /* error */
return retval;
default: /* parent */
#ifdef HAVE_WAITPID
while (waitpid(pid, &childstat, 0) < 0) {
#ifdef EINTR
if (errno == EINTR)
continue;
#endif /* EINTR */
#ifdef ERESTARTSYS
if (errno == ERESTARTSYS)
continue;
#endif /* ERESTARTSYS */
break;
}
#else /* HAVE_WAITPID */
waited = wait(&childstat);
signal(SIGCHLD, chldfunc);
/*
Since we had the signal handler uninstalled for a while,
we might have missed the termination of our screen child.
If we can check for this possibility without hanging, do so.
*/
do
if (waited == TScreenOf(term)->pid)
Cleanup(0);
while ((waited = nonblocking_wait()) > 0) ;
#endif /* HAVE_WAITPID */
#ifndef WIFEXITED
#define WIFEXITED(status) ((status & 0xff) != 0)
#endif
if (WIFEXITED(childstat))
retval = 1;
return retval;
}
}
#endif /* !VMS */
int
xtermResetIds(TScreen * screen)
{
int result = 0;
if (setgid(screen->gid) == -1) {
fprintf(stderr, "%s: unable to reset group-id\n", ProgramName);
result = -1;
}
if (setuid(screen->uid) == -1) {
fprintf(stderr, "%s: unable to reset user-id\n", ProgramName);
result = -1;
}
return result;
}
#ifdef ALLOWLOGGING
/*
* Logging is a security hole, since it allows a setuid program to write
* arbitrary data to an arbitrary file. So it is disabled by default.
*/
#ifdef ALLOWLOGFILEEXEC
static SIGNAL_T
logpipe(int sig GCC_UNUSED)
{
TScreen *screen = TScreenOf(term);
#ifdef SYSV
(void) signal(SIGPIPE, SIG_IGN);
#endif /* SYSV */
if (screen->logging)
CloseLog(screen);
}
#endif /* ALLOWLOGFILEEXEC */
void
StartLog(TScreen * screen)
{
static char *log_default;
#ifdef ALLOWLOGFILEEXEC
char *cp;
#endif /* ALLOWLOGFILEEXEC */
if (screen->logging || (screen->inhibit & I_LOG))
return;
#ifdef VMS /* file name is fixed in VMS variant */
screen->logfd = open(XTERM_VMS_LOGFILE,
O_CREAT | O_TRUNC | O_APPEND | O_RDWR,
0640);
if (screen->logfd < 0)
return; /* open failed */
#else /*VMS */
if (screen->logfile == NULL || *screen->logfile == 0) {
if (screen->logfile)
free(screen->logfile);
if (log_default == NULL) {
#if defined(HAVE_GETHOSTNAME) && defined(HAVE_STRFTIME)
char log_def_name[512]; /* see sprintf below */
char hostname[255 + 1]; /* Internet standard limit (RFC 1035):
``To simplify implementations, the
total length of a domain name (i.e.,
label octets and label length
octets) is restricted to 255 octets
or less.'' */
char yyyy_mm_dd_hh_mm_ss[4 + 5 * (1 + 2) + 1];
time_t now;
struct tm *ltm;
now = time((time_t *) 0);
ltm = (struct tm *) localtime(&now);
if ((gethostname(hostname, sizeof(hostname)) == 0) &&
(strftime(yyyy_mm_dd_hh_mm_ss,
sizeof(yyyy_mm_dd_hh_mm_ss),
"%Y.%m.%d.%H.%M.%S", ltm) > 0)) {
(void) sprintf(log_def_name, "Xterm.log.%.255s.%.20s.%d",
hostname, yyyy_mm_dd_hh_mm_ss, (int) getpid());
}
if ((log_default = x_strdup(log_def_name)) == NULL)
return;
#else
const char *log_def_name = "XtermLog.XXXXXX";
if ((log_default = x_strdup(log_def_name)) == NULL)
return;
mktemp(log_default);
#endif
}
if ((screen->logfile = x_strdup(log_default)) == 0)
return;
}
if (*screen->logfile == '|') { /* exec command */
#ifdef ALLOWLOGFILEEXEC
/*
* Warning, enabling this "feature" allows arbitrary programs
* to be run. If ALLOWLOGFILECHANGES is enabled, this can be
* done through escape sequences.... You have been warned.
*/
int pid;
int p[2];
static char *shell;
struct passwd *pw;
if (pipe(p) < 0 || (pid = fork()) < 0)
return;
if (pid == 0) { /* child */
/*
* Close our output (we won't be talking back to the
* parent), and redirect our child's output to the
* original stderr.
*/
close(p[1]);
dup2(p[0], 0);
close(p[0]);
dup2(fileno(stderr), 1);
dup2(fileno(stderr), 2);
close(fileno(stderr));
close(ConnectionNumber(screen->display));
close(screen->respond);
if ((((cp = x_getenv("SHELL")) == NULL)
&& ((pw = getpwuid(screen->uid)) == NULL
|| *(cp = pw->pw_shell) == 0))
|| (shell = CastMallocN(char, strlen(cp))) == 0) {
static char dummy[] = "/bin/sh";
shell = dummy;
} else {
strcpy(shell, cp);
}
signal(SIGHUP, SIG_DFL);
signal(SIGCHLD, SIG_DFL);
/* (this is redundant) */
if (xtermResetIds(screen) < 0)
exit(ERROR_SETUID);
execl(shell, shell, "-c", &screen->logfile[1], (void *) 0);
fprintf(stderr, "%s: Can't exec `%s'\n", xterm_name,
&screen->logfile[1]);
exit(ERROR_LOGEXEC);
}
close(p[0]);
screen->logfd = p[1];
signal(SIGPIPE, logpipe);
#else
Bell(XkbBI_Info, 0);
Bell(XkbBI_Info, 0);
return;
#endif
} else {
if ((screen->logfd = open_userfile(screen->uid,
screen->gid,
screen->logfile,
(log_default != 0))) < 0)
return;
}
#endif /*VMS */
screen->logstart = VTbuffer->next;
screen->logging = True;
update_logging();
}
void
CloseLog(TScreen * screen)
{
if (!screen->logging || (screen->inhibit & I_LOG))
return;
FlushLog(screen);
close(screen->logfd);
screen->logging = False;
update_logging();
}
void
FlushLog(TScreen * screen)
{
if (screen->logging && !(screen->inhibit & I_LOG)) {
Char *cp;
int i;
#ifdef VMS /* avoid logging output loops which otherwise occur sometimes
when there is no output and cp/screen->logstart are 1 apart */
if (!tt_new_output)
return;
tt_new_output = False;
#endif /* VMS */
cp = VTbuffer->next;
if (screen->logstart != 0
&& (i = cp - screen->logstart) > 0) {
IGNORE_RC(write(screen->logfd, screen->logstart, (unsigned) i));
}
screen->logstart = VTbuffer->next;
}
}
#endif /* ALLOWLOGGING */
/***====================================================================***/
#if OPT_ISO_COLORS
static void
ReportAnsiColorRequest(XtermWidget xw, int colornum, int final)
{
if (AllowColorOps(xw, ecGetAnsiColor)) {
XColor color;
Colormap cmap = xw->core.colormap;
char buffer[80];
TRACE(("ReportAnsiColorRequest %d\n", colornum));
color.pixel = GET_COLOR_RES(xw, TScreenOf(xw)->Acolors[colornum]);
XQueryColor(TScreenOf(xw)->display, cmap, &color);
sprintf(buffer, "4;%d;rgb:%04x/%04x/%04x",
colornum,
color.red,
color.green,
color.blue);
unparseputc1(xw, ANSI_OSC);
unparseputs(xw, buffer);
unparseputc1(xw, final);
unparse_end(xw);
}
}
static unsigned
getColormapSize(Display * display)
{
unsigned result;
int numFound;
XVisualInfo myTemplate, *visInfoPtr;
myTemplate.visualid = XVisualIDFromVisual(DefaultVisual(display,
XDefaultScreen(display)));
visInfoPtr = XGetVisualInfo(display, (long) VisualIDMask,
&myTemplate, &numFound);
result = (numFound >= 1) ? (unsigned) visInfoPtr->colormap_size : 0;
XFree((char *) visInfoPtr);
return result;
}
/*
* Find closest color for "def" in "cmap".
* Set "def" to the resulting color.
*
* Based on Monish Shah's "find_closest_color()" for Vim 6.0,
* modified with ideas from David Tong's "noflash" library.
* The code from Vim in turn was derived from FindClosestColor() in Tcl/Tk.
*
* These provide some introduction:
* http://en.wikipedia.org/wiki/YIQ
* for an introduction to YIQ weights.
* http://en.wikipedia.org/wiki/Luminance_(video)
* for a discussion of luma.
* http://en.wikipedia.org/wiki/YUV
*
* Return False if not able to find or allocate a color.
*/
static Boolean
find_closest_color(Display * dpy, Colormap cmap, XColor * def)
{
Boolean result = False;
XColor *colortable;
char *tried;
double diff, thisRGB, bestRGB;
unsigned attempts;
unsigned bestInx;
unsigned cmap_size;
unsigned i;
cmap_size = getColormapSize(dpy);
if (cmap_size != 0) {
colortable = TypeMallocN(XColor, (size_t) cmap_size);
if (colortable != 0) {
tried = TypeCallocN(char, (size_t) cmap_size);
if (tried != 0) {
for (i = 0; i < cmap_size; i++) {
colortable[i].pixel = (unsigned long) i;
}
XQueryColors(dpy, cmap, colortable, (int) cmap_size);
/*
* Try (possibly each entry in the color map) to find the best
* approximation to the requested color.
*/
for (attempts = 0; attempts < cmap_size; attempts++) {
Boolean first = True;
bestRGB = 0.0;
bestInx = 0;
for (i = 0; i < cmap_size; i++) {
if (!tried[bestInx]) {
/*
* Look for the best match based on luminance.
* Measure this by the least-squares difference of
* the weighted R/G/B components from the color map
* versus the requested color. Use the Y (luma)
* component of the YIQ color space model for
* weights that correspond to the luminance.
*/
#define AddColorWeight(weight, color) \
diff = weight * (int) ((def->color) - colortable[i].color); \
thisRGB = diff * diff
AddColorWeight(0.30, red);
AddColorWeight(0.61, green);
AddColorWeight(0.11, blue);
if (first || (thisRGB < bestRGB)) {
first = False;
bestInx = i;
bestRGB = thisRGB;
}
}
}
if (XAllocColor(dpy, cmap, &colortable[bestInx]) != 0) {
*def = colortable[bestInx];
result = True;
break;
}
/*
* It failed - either the color map entry was readonly, or
* another client has allocated the entry. Mark the entry
* so we will ignore it
*/
tried[bestInx] = True;
}
free(tried);
}
free(colortable);
}
}
return result;
}
/*
* Allocate a color for the "ANSI" colors. That actually includes colors up
* to 256.
*
* Returns
* -1 on error
* 0 on no change
* 1 if a new color was allocated.
*/
static int
AllocateAnsiColor(XtermWidget xw,
ColorRes * res,
char *spec)
{
int result;
XColor def;
TScreen *screen = TScreenOf(xw);
Colormap cmap = xw->core.colormap;
if (XParseColor(screen->display, cmap, spec, &def)
&& (XAllocColor(screen->display, cmap, &def)
|| find_closest_color(screen->display, cmap, &def))) {
if (
#if OPT_COLOR_RES
res->mode == True &&
#endif
EQL_COLOR_RES(res, def.pixel)) {
result = 0;
} else {
result = 1;
SET_COLOR_RES(res, def.pixel);
TRACE(("AllocateAnsiColor[%d] %s (pixel %#lx)\n",
(res - screen->Acolors), spec, def.pixel));
#if OPT_COLOR_RES
if (!res->mode)
result = 0;
res->mode = True;
#endif
}
} else {
TRACE(("AllocateAnsiColor %s (failed)\n", spec));
result = -1;
}
return (result);
}
#if OPT_COLOR_RES
Pixel
xtermGetColorRes(XtermWidget xw, ColorRes * res)
{
Pixel result = 0;
if (res->mode) {
result = res->value;
} else {
TRACE(("xtermGetColorRes for Acolors[%d]\n",
res - TScreenOf(xw)->Acolors));
if (res >= TScreenOf(xw)->Acolors) {
assert(res - TScreenOf(xw)->Acolors < MAXCOLORS);
if (AllocateAnsiColor(xw, res, res->resource) < 0) {
res->value = TScreenOf(xw)->Tcolors[TEXT_FG].value;
res->mode = -True;
fprintf(stderr,
"%s: Cannot allocate color %s\n",
xterm_name,
NonNull(res->resource));
}
result = res->value;
} else {
result = 0;
}
}
return result;
}
#endif
static int
ChangeOneAnsiColor(XtermWidget xw, int color, char *name)
{
int code;
if (color < 0 || color >= MAXCOLORS) {
code = -1;
} else {
ColorRes *res = &(TScreenOf(xw)->Acolors[color]);
TRACE(("ChangeAnsiColor for Acolors[%d]\n", color));
code = AllocateAnsiColor(xw, res, name);
}
return code;
}
/*
* Set or query entries in the Acolors[] array by parsing pairs of color/name
* values from the given buffer.
*
* The color can be any legal index into Acolors[], which consists of the
* 16/88/256 "ANSI" colors, followed by special color values for the various
* colorXX resources. The indices for the special color values are not
* simple to work with, so an alternative is to use the calls which pass in
* 'first' set to the beginning of those indices.
*
* If the name is "?", report to the host the current value for the color.
*/
static Bool
ChangeAnsiColorRequest(XtermWidget xw,
char *buf,
int first,
int final)
{
char *name;
int color;
int repaint = False;
int code;
int last = (MAXCOLORS - first);
TRACE(("ChangeAnsiColorRequest string='%s'\n", buf));
while (buf && *buf) {
name = strchr(buf, ';');
if (name == NULL)
break;
*name = '\0';
name++;
color = atoi(buf);
if (color < 0 || color >= last)
break; /* quit on any error */
buf = strchr(name, ';');
if (buf) {
*buf = '\0';
buf++;
}
if (!strcmp(name, "?")) {
ReportAnsiColorRequest(xw, color + first, final);
} else {
code = ChangeOneAnsiColor(xw, color + first, name);
if (code < 0) {
/* stop on any error */
break;
} else if (code > 0) {
repaint = True;
}
/* FIXME: free old color somehow? We aren't for the other color
* change style (dynamic colors).
*/
}
}
return (repaint);
}
static Bool
ResetOneAnsiColor(XtermWidget xw, int color, int start)
{
Bool repaint = False;
int last = MAXCOLORS - start;
if (color >= 0 && color < last) {
ColorRes *res = &(TScreenOf(xw)->Acolors[color + start]);
if (res->mode) {
/* a color has been allocated for this slot - test further... */
if (ChangeOneAnsiColor(xw, color + start, res->resource) > 0) {
repaint = True;
}
}
}
return repaint;
}
int
ResetAnsiColorRequest(XtermWidget xw, char *buf, int start)
{
int repaint = 0;
int color;
TRACE(("ResetAnsiColorRequest(%s)\n", buf));
if (*buf != '\0') {
/* reset specific colors */
while (!IsEmpty(buf)) {
char *next;
color = strtol(buf, &next, 10);
if (next == buf)
break; /* no number at all */
if (next != 0) {
if (strchr(";", *next) == 0)
break; /* unexpected delimiter */
++next;
}
if (ResetOneAnsiColor(xw, color, start)) {
++repaint;
}
buf = next;
}
} else {
TRACE(("...resetting all %d colors\n", MAXCOLORS));
for (color = 0; color < MAXCOLORS; ++color) {
if (ResetOneAnsiColor(xw, color, start)) {
++repaint;
}
}
}
TRACE(("...ResetAnsiColorRequest ->%d\n", repaint));
return repaint;
}
#else
#define find_closest_color(display, cmap, def) 0
#endif /* OPT_ISO_COLORS */
#if OPT_PASTE64
static void
ManipulateSelectionData(XtermWidget xw, TScreen * screen, char *buf, int final)
{
#define PDATA(a,b) { a, #b }
static struct {
char given;
String result;
} table[] = {
PDATA('s', SELECT),
PDATA('p', PRIMARY),
PDATA('c', CLIPBOARD),
PDATA('0', CUT_BUFFER0),
PDATA('1', CUT_BUFFER1),
PDATA('2', CUT_BUFFER2),
PDATA('3', CUT_BUFFER3),
PDATA('4', CUT_BUFFER4),
PDATA('5', CUT_BUFFER5),
PDATA('6', CUT_BUFFER6),
PDATA('7', CUT_BUFFER7),
};
const char *base = buf;
char *used = x_strdup(base);
Cardinal j, n = 0;
String *select_args = 0;
TRACE(("Manipulate selection data\n"));
while (*buf != ';' && *buf != '\0') {
++buf;
}
if (*buf == ';') {
*buf++ = '\0';
if (*base == '\0')
base = "s0";
if ((select_args = TypeCallocN(String, 1 + strlen(base))) == 0)
return;
while (*base != '\0') {
for (j = 0; j < XtNumber(table); ++j) {
if (*base == table[j].given) {
used[n] = *base;
select_args[n++] = table[j].result;
TRACE(("atom[%d] %s\n", n, table[j].result));
break;
}
}
++base;
}
used[n] = 0;
if (!strcmp(buf, "?")) {
if (AllowWindowOps(xw, ewGetSelection)) {
TRACE(("Getting selection\n"));
unparseputc1(xw, ANSI_OSC);
unparseputs(xw, "52");
unparseputc(xw, ';');
unparseputs(xw, used);
unparseputc(xw, ';');
/* Tell xtermGetSelection data is base64 encoded */
screen->base64_paste = n;
screen->base64_final = final;
/* terminator will be written in this call */
xtermGetSelection((Widget) xw, 0, select_args, n, NULL);
}
} else {
if (AllowWindowOps(xw, ewSetSelection)) {
TRACE(("Setting selection with %s\n", buf));
ClearSelectionBuffer(screen);
while (*buf != '\0')
AppendToSelectionBuffer(screen, CharOf(*buf++));
CompleteSelection(xw, select_args, n);
}
}
}
}
#endif /* OPT_PASTE64 */
/***====================================================================***/
#define IsSetUtf8Title(xw) (IsTitleMode(xw, tmSetUtf8) || (xw->screen.utf8_title))
static Bool
xtermIsPrintable(XtermWidget xw, Char ** bufp, Char * last)
{
TScreen *screen = TScreenOf(xw);
Bool result = False;
Char *cp = *bufp;
Char *next = cp;
(void) screen;
(void) last;
#if OPT_WIDE_CHARS
if (xtermEnvUTF8() && IsSetUtf8Title(xw)) {
PtyData data;
if (decodeUtf8(fakePtyData(&data, cp, last))) {
if (data.utf_data != UCS_REPL
&& (data.utf_data >= 128 ||
ansi_table[data.utf_data] == CASE_PRINT)) {
next += (data.utf_size - 1);
result = True;
} else {
result = False;
}
} else {
result = False;
}
} else
#endif
#if OPT_C1_PRINT
if (screen->c1_printable
&& (*cp >= 128 && *cp < 160)) {
result = True;
} else
#endif
if (ansi_table[*cp] == CASE_PRINT) {
result = True;
}
*bufp = next;
return result;
}
/***====================================================================***/
/*
* Enum corresponding to the actual OSC codes rather than the internal
* array indices. Compare with TermColors.
*/
typedef enum {
OSC_TEXT_FG = 10
,OSC_TEXT_BG
,OSC_TEXT_CURSOR
,OSC_MOUSE_FG
,OSC_MOUSE_BG
#if OPT_TEK4014
,OSC_TEK_FG = 15
,OSC_TEK_BG
#endif
#if OPT_HIGHLIGHT_COLOR
,OSC_HIGHLIGHT_BG = 17
#endif
#if OPT_TEK4014
,OSC_TEK_CURSOR = 18
#endif
#if OPT_HIGHLIGHT_COLOR
,OSC_HIGHLIGHT_FG = 19
#endif
,OSC_NCOLORS
} OscTextColors;
/*
* Map codes to OSC controls that can reset colors.
*/
#define OSC_RESET 100
#define OSC_Reset(code) (code) + OSC_RESET
static ScrnColors *pOldColors = NULL;
static Bool
GetOldColors(XtermWidget xw)
{
int i;
if (pOldColors == NULL) {
pOldColors = (ScrnColors *) XtMalloc(sizeof(ScrnColors));
if (pOldColors == NULL) {
fprintf(stderr, "allocation failure in GetOldColors\n");
return (False);
}
pOldColors->which = 0;
for (i = 0; i < NCOLORS; i++) {
pOldColors->colors[i] = 0;
pOldColors->names[i] = NULL;
}
GetColors(xw, pOldColors);
}
return (True);
}
static int
oppositeColor(int n)
{
switch (n) {
case TEXT_FG:
n = TEXT_BG;
break;
case TEXT_BG:
n = TEXT_FG;
break;
case MOUSE_FG:
n = MOUSE_BG;
break;
case MOUSE_BG:
n = MOUSE_FG;
break;
#if OPT_TEK4014
case TEK_FG:
n = TEK_BG;
break;
case TEK_BG:
n = TEK_FG;
break;
#endif
#if OPT_HIGHLIGHT_COLOR
case HIGHLIGHT_FG:
n = HIGHLIGHT_BG;
break;
case HIGHLIGHT_BG:
n = HIGHLIGHT_FG;
break;
#endif
default:
break;
}
return n;
}
static void
ReportColorRequest(XtermWidget xw, int ndx, int final)
{
if (AllowColorOps(xw, ecGetColor)) {
XColor color;
Colormap cmap = xw->core.colormap;
char buffer[80];
/*
* ChangeColorsRequest() has "always" chosen the opposite color when
* reverse-video is set. Report this as the original color index, but
* reporting the opposite color which would be used.
*/
int i = (xw->misc.re_verse) ? oppositeColor(ndx) : ndx;
GetOldColors(xw);
color.pixel = pOldColors->colors[ndx];
XQueryColor(TScreenOf(xw)->display, cmap, &color);
sprintf(buffer, "%d;rgb:%04x/%04x/%04x", i + 10,
color.red,
color.green,
color.blue);
TRACE(("ReportColors %d: %#lx as %s\n",
ndx, pOldColors->colors[ndx], buffer));
unparseputc1(xw, ANSI_OSC);
unparseputs(xw, buffer);
unparseputc1(xw, final);
unparse_end(xw);
}
}
static Bool
UpdateOldColors(XtermWidget xw GCC_UNUSED, ScrnColors * pNew)
{
int i;
/* if we were going to free old colors, this would be the place to
* do it. I've decided not to (for now), because it seems likely
* that we'd have a small set of colors we use over and over, and that
* we could save some overhead this way. The only case in which this
* (clearly) fails is if someone is trying a boatload of colors, in
* which case they can restart xterm
*/
for (i = 0; i < NCOLORS; i++) {
if (COLOR_DEFINED(pNew, i)) {
if (pOldColors->names[i] != NULL) {
XtFree(pOldColors->names[i]);
pOldColors->names[i] = NULL;
}
if (pNew->names[i]) {
pOldColors->names[i] = pNew->names[i];
}
pOldColors->colors[i] = pNew->colors[i];
}
}
return (True);
}
/*
* OSC codes are constant, but the indices for the color arrays depend on how
* xterm is compiled.
*/
static int
OscToColorIndex(OscTextColors mode)
{
int result = 0;
#define CASE(name) case OSC_##name: result = name; break
switch (mode) {
CASE(TEXT_FG);
CASE(TEXT_BG);
CASE(TEXT_CURSOR);
CASE(MOUSE_FG);
CASE(MOUSE_BG);
#if OPT_TEK4014
CASE(TEK_FG);
CASE(TEK_BG);
#endif
#if OPT_HIGHLIGHT_COLOR
CASE(HIGHLIGHT_BG);
CASE(HIGHLIGHT_FG);
#endif
#if OPT_TEK4014
CASE(TEK_CURSOR);
#endif
case OSC_NCOLORS:
break;
}
return result;
}
static Bool
ChangeColorsRequest(XtermWidget xw,
int start,
char *names,
int final)
{
Bool result = False;
char *thisName;
ScrnColors newColors;
int i, ndx;
TRACE(("ChangeColorsRequest start=%d, names='%s'\n", start, names));
if (GetOldColors(xw)) {
newColors.which = 0;
for (i = 0; i < NCOLORS; i++) {
newColors.names[i] = NULL;
}
for (i = start; i < OSC_NCOLORS; i++) {
ndx = OscToColorIndex((OscTextColors) i);
if (xw->misc.re_verse)
ndx = oppositeColor(ndx);
if (IsEmpty(names)) {
newColors.names[ndx] = NULL;
} else {
if (names[0] == ';')
thisName = NULL;
else
thisName = names;
names = strchr(names, ';');
if (names != NULL) {
*names++ = '\0';
}
if (thisName != 0 && !strcmp(thisName, "?")) {
ReportColorRequest(xw, ndx, final);
} else if (!pOldColors->names[ndx]
|| (thisName
&& strcmp(thisName, pOldColors->names[ndx]))) {
AllocateTermColor(xw, &newColors, ndx, thisName);
}
}
}
if (newColors.which != 0) {
ChangeColors(xw, &newColors);
UpdateOldColors(xw, &newColors);
}
result = True;
}
return result;
}
static Bool
ResetColorsRequest(XtermWidget xw,
int code)
{
Bool result = False;
char *thisName;
ScrnColors newColors;
int ndx;
TRACE(("ResetColorsRequest code=%d\n", code));
#if OPT_COLOR_RES
if (GetOldColors(xw)) {
ndx = OscToColorIndex((OscTextColors) (code - OSC_RESET));
if (xw->misc.re_verse)
ndx = oppositeColor(ndx);
thisName = xw->screen.Tcolors[ndx].resource;
newColors.which = 0;
newColors.names[ndx] = NULL;
if (thisName != 0
&& pOldColors->names[ndx] != 0
&& strcmp(thisName, pOldColors->names[ndx])) {
AllocateTermColor(xw, &newColors, ndx, thisName);
if (newColors.which != 0) {
ChangeColors(xw, &newColors);
UpdateOldColors(xw, &newColors);
}
}
result = True;
}
#endif
return result;
}
#if OPT_SHIFT_FONTS
/*
* Initially, 'source' points to '#' or '?'.
*
* Look for an optional sign and optional number. If those are found, lookup
* the corresponding menu font entry.
*/
static int
ParseShiftedFont(XtermWidget xw, char *source, char **target)
{
TScreen *screen = TScreenOf(xw);
int num = screen->menu_font_number;
int rel = 0;
if (*++source == '+') {
rel = 1;
source++;
} else if (*source == '-') {
rel = -1;
source++;
}
if (isdigit(CharOf(*source))) {
int val = atoi(source);
if (rel > 0)
rel = val;
else if (rel < 0)
rel = -val;
else
num = val;
}
if (rel != 0) {
num = lookupRelativeFontSize(xw,
screen->menu_font_number, rel);
}
TRACE(("ParseShiftedFont(%s) ->%d (%s)\n", *target, num, source));
*target = source;
return num;
}
static void
QueryFontRequest(XtermWidget xw, char *buf, int final)
{
if (AllowFontOps(xw, efGetFont)) {
TScreen *screen = TScreenOf(xw);
Bool success = True;
int num;
char *base = buf + 1;
char *name = 0;
char temp[10];
num = ParseShiftedFont(xw, buf, &buf);
if (num < 0
|| num > fontMenu_lastBuiltin) {
Bell(XkbBI_MinorError, 0);
success = False;
} else {
#if OPT_RENDERFONT
if (UsingRenderFont(xw)) {
name = getFaceName(xw, False);
} else
#endif
if ((name = screen->MenuFontName(num)) == 0) {
success = False;
}
}
unparseputc1(xw, ANSI_OSC);
unparseputs(xw, "50");
if (success) {
unparseputc(xw, ';');
if (buf >= base) {
/* identify the font-entry, unless it is the current one */
if (*buf != '\0') {
unparseputc(xw, '#');
sprintf(temp, "%d", num);
unparseputs(xw, temp);
if (*name != '\0')
unparseputc(xw, ' ');
}
}
unparseputs(xw, name);
}
unparseputc1(xw, final);
unparse_end(xw);
}
}
static void
ChangeFontRequest(XtermWidget xw, char *buf)
{
if (AllowFontOps(xw, efSetFont)) {
TScreen *screen = TScreenOf(xw);
Bool success = True;
int num;
VTFontNames fonts;
char *name;
/*
* If the font specification is a "#", followed by an optional sign and
* optional number, lookup the corresponding menu font entry.
*
* Further, if the "#", etc., is followed by a font name, use that
* to load the font entry.
*/
if (*buf == '#') {
num = ParseShiftedFont(xw, buf, &buf);
if (num < 0
|| num > fontMenu_lastBuiltin) {
Bell(XkbBI_MinorError, 0);
success = False;
} else {
/*
* Skip past the optional number, and any whitespace to look
* for a font specification within the control.
*/
while (isdigit(CharOf(*buf))) {
++buf;
}
while (isspace(CharOf(*buf))) {
++buf;
}
#if OPT_RENDERFONT
if (UsingRenderFont(xw)) {
; /* there is only one font entry to load */
} else
#endif
{
/*
* Normally there is no font specified in the control.
* But if there is, simply overwrite the font entry.
*/
if (*buf == '\0') {
if ((buf = screen->MenuFontName(num)) == 0) {
success = False;
}
}
}
}
} else {
num = screen->menu_font_number;
}
name = x_strtrim(buf);
if (success && !IsEmpty(name)) {
#if OPT_RENDERFONT
if (UsingRenderFont(xw)) {
setFaceName(xw, name);
xtermUpdateFontInfo(xw, True);
} else
#endif
{
memset(&fonts, 0, sizeof(fonts));
fonts.f_n = name;
SetVTFont(xw, num, True, &fonts);
}
} else {
Bell(XkbBI_MinorError, 0);
}
free(name);
}
}
#endif /* OPT_SHIFT_FONTS */
/***====================================================================***/
void
do_osc(XtermWidget xw, Char * oscbuf, unsigned len GCC_UNUSED, int final)
{
TScreen *screen = TScreenOf(xw);
int mode;
Char *cp;
int state = 0;
char *buf = 0;
char temp[2];
#if OPT_ISO_COLORS
int ansi_colors = 0;
#endif
Bool need_data = True;
TRACE(("do_osc %s\n", oscbuf));
/*
* Lines should be of the form <OSC> number ; string <ST>, however
* older xterms can accept <BEL> as a final character. We will respond
* with the same final character as the application sends to make this
* work better with shell scripts, which may have trouble reading an
* <ESC><backslash>, which is the 7-bit equivalent to <ST>.
*/
mode = 0;
for (cp = oscbuf; *cp != '\0'; cp++) {
switch (state) {
case 0:
if (isdigit(*cp)) {
mode = 10 * mode + (*cp - '0');
if (mode > 65535) {
TRACE(("do_osc found unknown mode %d\n", mode));
return;
}
break;
}
/* FALLTHRU */
case 1:
if (*cp != ';') {
TRACE(("do_osc did not find semicolon offset %d\n", cp - oscbuf));
return;
}
state = 2;
break;
case 2:
buf = (char *) cp;
state = 3;
/* FALLTHRU */
default:
if (!xtermIsPrintable(xw, &cp, oscbuf + len)) {
switch (mode) {
case 0:
case 1:
case 2:
break;
default:
TRACE(("do_osc found nonprinting char %02X offset %d\n",
CharOf(*cp),
cp - oscbuf));
return;
}
}
}
}
/*
* Most OSC controls other than resets require data. Handle the others as
* a special case.
*/
switch (mode) {
#if OPT_ISO_COLORS
case OSC_Reset(4):
case OSC_Reset(5):
case OSC_Reset(OSC_TEXT_FG):
case OSC_Reset(OSC_TEXT_BG):
case OSC_Reset(OSC_TEXT_CURSOR):
case OSC_Reset(OSC_MOUSE_FG):
case OSC_Reset(OSC_MOUSE_BG):
#if OPT_HIGHLIGHT_COLOR
case OSC_Reset(OSC_HIGHLIGHT_BG):
case OSC_Reset(OSC_HIGHLIGHT_FG):
#endif
#if OPT_TEK4014
case OSC_Reset(OSC_TEK_FG):
case OSC_Reset(OSC_TEK_BG):
case OSC_Reset(OSC_TEK_CURSOR):
#endif
need_data = False;
break;
#endif
default:
break;
}
/*
* Check if we have data when we want, and not when we do not want it.
* Either way, that is a malformed control sequence, and will be ignored.
*/
if (IsEmpty(buf)) {
if (need_data) {
TRACE(("do_osc found no data\n"));
return;
}
temp[0] = '\0';
buf = temp;
} else if (!need_data) {
TRACE(("do_osc found found unwanted data\n"));
return;
}
switch (mode) {
case 0: /* new icon name and title */
ChangeIconName(xw, buf);
ChangeTitle(xw, buf);
break;
case 1: /* new icon name only */
ChangeIconName(xw, buf);
break;
case 2: /* new title only */
ChangeTitle(xw, buf);
break;
case 3: /* change X property */
if (AllowWindowOps(xw, ewSetXprop))
ChangeXprop(buf);
break;
#if OPT_ISO_COLORS
case 5:
ansi_colors = NUM_ANSI_COLORS;
/* FALLTHRU */
case 4:
if (ChangeAnsiColorRequest(xw, buf, ansi_colors, final))
xtermRepaint(xw);
break;
case OSC_Reset(5):
ansi_colors = NUM_ANSI_COLORS;
/* FALLTHRU */
case OSC_Reset(4):
if (ResetAnsiColorRequest(xw, buf, ansi_colors))
xtermRepaint(xw);
break;
#endif
case OSC_TEXT_FG:
case OSC_TEXT_BG:
case OSC_TEXT_CURSOR:
case OSC_MOUSE_FG:
case OSC_MOUSE_BG:
#if OPT_HIGHLIGHT_COLOR
case OSC_HIGHLIGHT_BG:
case OSC_HIGHLIGHT_FG:
#endif
#if OPT_TEK4014
case OSC_TEK_FG:
case OSC_TEK_BG:
case OSC_TEK_CURSOR:
#endif
if (xw->misc.dynamicColors) {
ChangeColorsRequest(xw, mode, buf, final);
}
break;
case OSC_Reset(OSC_TEXT_FG):
case OSC_Reset(OSC_TEXT_BG):
case OSC_Reset(OSC_TEXT_CURSOR):
case OSC_Reset(OSC_MOUSE_FG):
case OSC_Reset(OSC_MOUSE_BG):
#if OPT_HIGHLIGHT_COLOR
case OSC_Reset(OSC_HIGHLIGHT_BG):
case OSC_Reset(OSC_HIGHLIGHT_FG):
#endif
#if OPT_TEK4014
case OSC_Reset(OSC_TEK_FG):
case OSC_Reset(OSC_TEK_BG):
case OSC_Reset(OSC_TEK_CURSOR):
#endif
if (xw->misc.dynamicColors) {
ResetColorsRequest(xw, mode);
}
break;
case 30:
case 31:
/* reserved for Konsole (Stephan Binner <Stephan.Binner@gmx.de>) */
break;
#ifdef ALLOWLOGGING
case 46: /* new log file */
#ifdef ALLOWLOGFILECHANGES
/*
* Warning, enabling this feature allows people to overwrite
* arbitrary files accessible to the person running xterm.
*/
if (strcmp(buf, "?")
&& (cp = CastMallocN(char, strlen(buf)) != NULL)) {
strcpy(cp, buf);
if (screen->logfile)
free(screen->logfile);
screen->logfile = cp;
break;
}
#endif
Bell(XkbBI_Info, 0);
Bell(XkbBI_Info, 0);
break;
#endif /* ALLOWLOGGING */
case 50:
#if OPT_SHIFT_FONTS
if (*buf == '?') {
QueryFontRequest(xw, buf, final);
} else if (xw->misc.shift_fonts) {
ChangeFontRequest(xw, buf);
}
#endif /* OPT_SHIFT_FONTS */
break;
case 51:
/* reserved for Emacs shell (Rob Mayoff <mayoff@dqd.com>) */
break;
#if OPT_PASTE64
case 52:
ManipulateSelectionData(xw, screen, buf, final);
break;
#endif
/*
* One could write code to send back the display and host names,
* but that could potentially open a fairly nasty security hole.
*/
default:
TRACE(("do_osc - unrecognized code\n"));
break;
}
unparse_end(xw);
}
#ifdef SunXK_F36
#define MAX_UDK 37
#else
#define MAX_UDK 35
#endif
static struct {
char *str;
int len;
} user_keys[MAX_UDK];
/*
* Parse one nibble of a hex byte from the OSC string. We have removed the
* string-terminator (replacing it with a null), so the only other delimiter
* that is expected is semicolon. Ignore other characters (Ray Neuman says
* "real" terminals accept commas in the string definitions).
*/
static int
udk_value(const char **cp)
{
int result = -1;
int c;
for (;;) {
if ((c = **cp) != '\0')
*cp = *cp + 1;
if (c == ';' || c == '\0')
break;
if ((result = x_hex2int(c)) >= 0)
break;
}
return result;
}
void
reset_decudk(void)
{
int n;
for (n = 0; n < MAX_UDK; n++) {
if (user_keys[n].str != 0) {
free(user_keys[n].str);
user_keys[n].str = 0;
user_keys[n].len = 0;
}
}
}
/*
* Parse the data for DECUDK (user-defined keys).
*/
static void
parse_decudk(const char *cp)
{
while (*cp) {
const char *base = cp;
char *str = CastMallocN(char, strlen(cp) + 1);
unsigned key = 0;
int lo, hi;
int len = 0;
while (isdigit(CharOf(*cp)))
key = (key * 10) + (unsigned) (*cp++ - '0');
if (*cp == '/') {
cp++;
while ((hi = udk_value(&cp)) >= 0
&& (lo = udk_value(&cp)) >= 0) {
str[len++] = (char) ((hi << 4) | lo);
}
}
if (len > 0 && key < MAX_UDK) {
if (user_keys[key].str != 0)
free(user_keys[key].str);
user_keys[key].str = str;
user_keys[key].len = len;
} else {
free(str);
}
if (*cp == ';')
cp++;
if (cp == base) /* badly-formed sequence - bail out */
break;
}
}
#if OPT_TRACE
#define SOFT_WIDE 10
#define SOFT_HIGH 20
static void
parse_decdld(ANSI * params, const char *string)
{
char DscsName[8];
int len;
int Pfn = params->a_param[0];
int Pcn = params->a_param[1];
int Pe = params->a_param[2];
int Pcmw = params->a_param[3];
int Pw = params->a_param[4];
int Pt = params->a_param[5];
int Pcmh = params->a_param[6];
int Pcss = params->a_param[7];
int start_char = Pcn + 0x20;
int char_wide = ((Pcmw == 0)
? (Pcss ? 6 : 10)
: (Pcmw > 4
? Pcmw
: (Pcmw + 3)));
int char_high = ((Pcmh == 0)
? ((Pcmw >= 2 || Pcmw <= 4)
? 10
: 20)
: Pcmh);
Char ch;
Char bits[SOFT_HIGH][SOFT_WIDE];
Bool first = True;
Bool prior = False;
int row = 0, col = 0;
TRACE(("Parsing DECDLD\n"));
TRACE((" font number %d\n", Pfn));
TRACE((" starting char %d\n", Pcn));
TRACE((" erase control %d\n", Pe));
TRACE((" char-width %d\n", Pcmw));
TRACE((" font-width %d\n", Pw));
TRACE((" text/full %d\n", Pt));
TRACE((" char-height %d\n", Pcmh));
TRACE((" charset-size %d\n", Pcss));
if (Pfn > 1
|| Pcn > 95
|| Pe > 2
|| Pcmw > 10
|| Pcmw == 1
|| Pt > 2
|| Pcmh > 20
|| Pcss > 1
|| char_wide > SOFT_WIDE
|| char_high > SOFT_HIGH) {
TRACE(("DECDLD illegal parameter\n"));
return;
}
len = 0;
while (*string != '\0') {
ch = CharOf(*string++);
if (ch >= ANSI_SPA && ch <= 0x2f) {
if (len < 2)
DscsName[len++] = (char) ch;
} else if (ch >= 0x30 && ch <= 0x7e) {
DscsName[len++] = (char) ch;
break;
}
}
DscsName[len] = 0;
TRACE((" Dscs name '%s'\n", DscsName));
TRACE((" character matrix %dx%d\n", char_high, char_wide));
while (*string != '\0') {
if (first) {
TRACE(("Char %d:\n", start_char));
if (prior) {
for (row = 0; row < char_high; ++row) {
TRACE(("%.*s\n", char_wide, bits[row]));
}
}
prior = False;
first = False;
for (row = 0; row < char_high; ++row) {
for (col = 0; col < char_wide; ++col) {
bits[row][col] = '.';
}
}
row = col = 0;
}
ch = CharOf(*string++);
if (ch >= 0x3f && ch <= 0x7e) {
int n;
ch = CharOf(ch - 0x3f);
for (n = 0; n < 6; ++n) {
bits[row + n][col] = CharOf((ch & (1 << n)) ? '*' : '.');
}
col += 1;
prior = True;
} else if (ch == '/') {
row += 6;
col = 0;
} else if (ch == ';') {
first = True;
++start_char;
}
}
}
#else
#define parse_decdld(p,q) /* nothing */
#endif
/*
* Parse numeric parameters. Normally we use a state machine to simplify
* interspersing with control characters, but have the string already.
*/
static void
parse_ansi_params(ANSI * params, const char **string)
{
const char *cp = *string;
ParmType nparam = 0;
memset(params, 0, sizeof(*params));
while (*cp != '\0') {
Char ch = CharOf(*cp++);
if (isdigit(ch)) {
if (nparam < NPARAM) {
params->a_param[nparam] =
(ParmType) ((params->a_param[nparam] * 10)
+ (ch - '0'));
}
} else if (ch == ';') {
if (++nparam < NPARAM)
params->a_nparam = nparam;
} else if (ch < 32) {
;
} else {
/* should be 0x30 to 0x7e */
params->a_final = ch;
break;
}
}
*string = cp;
}
void
do_dcs(XtermWidget xw, Char * dcsbuf, size_t dcslen)
{
TScreen *screen = TScreenOf(xw);
char reply[BUFSIZ];
const char *cp = (const char *) dcsbuf;
Bool okay;
ANSI params;
TRACE(("do_dcs(%s:%d)\n", (char *) dcsbuf, dcslen));
if (dcslen != strlen(cp))
/* shouldn't have nulls in the string */
return;
switch (*cp) { /* intermediate character, or parameter */
case '$': /* DECRQSS */
okay = True;
cp++;
if (*cp++ == 'q') {
if (!strcmp(cp, "\"q")) { /* DECSCA */
sprintf(reply, "%d%s",
(screen->protected_mode == DEC_PROTECT)
&& (xw->flags & PROTECTED) ? 1 : 0,
cp);
} else if (!strcmp(cp, "\"p")) { /* DECSCL */
sprintf(reply, "%d%s%s",
(screen->vtXX_level ?
screen->vtXX_level : 1) + 60,
(screen->vtXX_level >= 2)
? (screen->control_eight_bits
? ";0" : ";1")
: "",
cp);
} else if (!strcmp(cp, "r")) { /* DECSTBM */
sprintf(reply, "%d;%dr",
screen->top_marg + 1,
screen->bot_marg + 1);
} else if (!strcmp(cp, "m")) { /* SGR */
strcpy(reply, "0");
if (xw->flags & BOLD)
strcat(reply, ";1");
if (xw->flags & UNDERLINE)
strcat(reply, ";4");
if (xw->flags & BLINK)
strcat(reply, ";5");
if (xw->flags & INVERSE)
strcat(reply, ";7");
if (xw->flags & INVISIBLE)
strcat(reply, ";8");
#if OPT_256_COLORS || OPT_88_COLORS
if_OPT_ISO_COLORS(screen, {
if (xw->flags & FG_COLOR) {
if (xw->cur_foreground >= 16)
sprintf(reply + strlen(reply),
";38;5;%d", xw->cur_foreground);
else
sprintf(reply + strlen(reply),
";%d%d",
xw->cur_foreground >= 8 ? 9 : 3,
xw->cur_foreground >= 8 ?
xw->cur_foreground - 8 :
xw->cur_foreground);
}
if (xw->flags & BG_COLOR) {
if (xw->cur_background >= 16)
sprintf(reply + strlen(reply),
";48;5;%d", xw->cur_foreground);
else
sprintf(reply + strlen(reply),
";%d%d",
xw->cur_background >= 8 ? 10 : 4,
xw->cur_background >= 8 ?
xw->cur_background - 8 :
xw->cur_background);
}
});
#elif OPT_ISO_COLORS
if_OPT_ISO_COLORS(screen, {
if (xw->flags & FG_COLOR)
sprintf(reply + strlen(reply),
";%d%d",
xw->cur_foreground >= 8 ? 9 : 3,
xw->cur_foreground >= 8 ?
xw->cur_foreground - 8 :
xw->cur_foreground);
if (xw->flags & BG_COLOR)
sprintf(reply + strlen(reply),
";%d%d",
xw->cur_background >= 8 ? 10 : 4,
xw->cur_background >= 8 ?
xw->cur_background - 8 :
xw->cur_background);
});
#endif
strcat(reply, "m");
} else
okay = False;
if (okay) {
unparseputc1(xw, ANSI_DCS);
unparseputc(xw, okay ? '1' : '0');
unparseputc(xw, '$');
unparseputc(xw, 'r');
cp = reply;
unparseputs(xw, cp);
unparseputc1(xw, ANSI_ST);
} else {
unparseputc(xw, ANSI_CAN);
}
} else {
unparseputc(xw, ANSI_CAN);
}
break;
#if OPT_TCAP_QUERY
case '+':
cp++;
switch (*cp) {
case 'p':
if (AllowTcapOps(xw, etSetTcap)) {
set_termcap(xw, cp + 1);
}
break;
case 'q':
if (AllowTcapOps(xw, etGetTcap)) {
Bool fkey;
unsigned state;
int code;
const char *tmp;
const char *parsed = ++cp;
code = xtermcapKeycode(xw, &parsed, &state, &fkey);
unparseputc1(xw, ANSI_DCS);
unparseputc(xw, code >= 0 ? '1' : '0');
unparseputc(xw, '+');
unparseputc(xw, 'r');
while (*cp != 0 && (code >= -1)) {
if (cp == parsed)
break; /* no data found, error */
for (tmp = cp; tmp != parsed; ++tmp)
unparseputc(xw, *tmp);
if (code >= 0) {
unparseputc(xw, '=');
screen->tc_query_code = code;
screen->tc_query_fkey = fkey;
#if OPT_ISO_COLORS
/* XK_COLORS is a fake code for the "Co" entry (maximum
* number of colors) */
if (code == XK_COLORS) {
unparseputn(xw, NUM_ANSI_COLORS);
} else
#endif
if (code == XK_TCAPNAME) {
unparseputs(xw, xterm_name);
} else {
XKeyEvent event;
event.state = state;
Input(xw, &event, False);
}
screen->tc_query_code = -1;
} else {
break; /* no match found, error */
}
cp = parsed;
if (*parsed == ';') {
unparseputc(xw, *parsed++);
cp = parsed;
code = xtermcapKeycode(xw, &parsed, &state, &fkey);
}
}
unparseputc1(xw, ANSI_ST);
}
break;
}
break;
#endif
default:
if (screen->terminal_id >= 200) { /* VT220 */
parse_ansi_params(¶ms, &cp);
switch (params.a_final) {
case '|': /* DECUDK */
if (params.a_param[0] == 0)
reset_decudk();
parse_decudk(cp);
break;
case '{': /* DECDLD (no '}' case though) */
parse_decdld(¶ms, cp);
break;
}
}
break;
}
unparse_end(xw);
}
char *
udk_lookup(int keycode, int *len)
{
if (keycode >= 0 && keycode < MAX_UDK) {
*len = user_keys[keycode].len;
return user_keys[keycode].str;
}
return 0;
}
static void
ChangeGroup(XtermWidget xw, const char *attribute, char *value)
{
#if OPT_WIDE_CHARS
static Char *converted; /* NO_LEAKS */
#endif
static char empty[1];
Arg args[1];
Boolean changed = True;
Widget w = CURRENT_EMU();
Widget top = SHELL_OF(w);
char *my_attr;
char *name;
unsigned limit;
Char *c1;
Char *cp;
if (!AllowTitleOps(xw))
return;
if (value == 0)
value = empty;
if (IsTitleMode(xw, tmSetBase16)) {
const char *temp;
char *test;
value = x_decode_hex(value, &temp);
if (*temp != '\0')
return;
for (test = value; *test != '\0'; ++test) {
if (CharOf(*test) < 32) {
*test = '\0';
break;
}
}
}
c1 = (Char *) value;
name = value;
limit = strlen(name);
my_attr = x_strdup(attribute);
TRACE(("ChangeGroup(attribute=%s, value=%s)\n", my_attr, name));
/*
* Ignore titles that are too long to be plausible requests.
*/
if (limit > 0 && limit < 1024) {
/*
* After all decoding, overwrite nonprintable characters with '?'.
*/
for (cp = c1; *cp != 0; ++cp) {
Char *c2 = cp;
if (!xtermIsPrintable(xw, &cp, c1 + limit)) {
memset(c2, '?', (size_t) (cp + 1 - c2));
}
}
#if OPT_WIDE_CHARS
/*
* If we're running in UTF-8 mode, and have not been told that the
* title string is in UTF-8, it is likely that non-ASCII text in the
* string will be rejected because it is not printable in the current
* locale. So we convert it to UTF-8, allowing the X library to
* convert it back.
*/
if (xtermEnvUTF8() && !IsSetUtf8Title(xw)) {
int n;
for (n = 0; name[n] != '\0'; ++n) {
if (CharOf(name[n]) > 127) {
if (converted != 0)
free(converted);
if ((converted = TypeMallocN(Char, 1 + (6 * limit))) != 0) {
Char *temp = converted;
while (*name != 0) {
temp = convertToUTF8(temp, CharOf(*name));
++name;
}
*temp = 0;
name = (char *) converted;
TRACE(("...converted{%s}\n", name));
}
break;
}
}
}
#endif
#if OPT_SAME_NAME
/* If the attribute isn't going to change, then don't bother... */
if (resource.sameName) {
char *buf;
XtSetArg(args[0], my_attr, &buf);
XtGetValues(top, args, 1);
TRACE(("...comparing{%s}\n", buf));
if (strcmp(name, buf) == 0)
changed = False;
}
#endif /* OPT_SAME_NAME */
if (changed) {
TRACE(("...updating %s\n", my_attr));
TRACE(("...value is %s\n", name));
XtSetArg(args[0], my_attr, name);
XtSetValues(top, args, 1);
#if OPT_WIDE_CHARS
if (xtermEnvUTF8()) {
Display *dpy = XtDisplay(xw);
Atom my_atom;
const char *propname = (!strcmp(my_attr, XtNtitle)
? "_NET_WM_NAME"
: "_NET_WM_ICON_NAME");
if ((my_atom = XInternAtom(dpy, propname, False)) != None) {
if (IsSetUtf8Title(xw)) {
TRACE(("...updating %s\n", propname));
TRACE(("...value is %s\n", value));
XChangeProperty(dpy, VShellWindow, my_atom,
XA_UTF8_STRING(dpy), 8,
PropModeReplace,
(Char *) value,
(int) strlen(value));
} else {
TRACE(("...deleting %s\n", propname));
XDeleteProperty(dpy, VShellWindow, my_atom);
}
}
}
#endif
}
free(my_attr);
if (IsTitleMode(xw, tmSetBase16))
free(value);
}
return;
}
void
ChangeIconName(XtermWidget xw, char *name)
{
if (name == 0) {
static char dummy[] = "";
name = dummy;
}
#if OPT_ZICONBEEP /* If warning should be given then give it */
if (resource.zIconBeep && TScreenOf(xw)->zIconBeep_flagged) {
char *newname = CastMallocN(char, strlen(name) + 4);
if (!newname) {
fprintf(stderr, "malloc failed in ChangeIconName\n");
return;
}
strcpy(newname, "*** ");
strcat(newname, name);
ChangeGroup(xw, XtNiconName, newname);
free(newname);
} else
#endif /* OPT_ZICONBEEP */
ChangeGroup(xw, XtNiconName, name);
}
void
ChangeTitle(XtermWidget xw, char *name)
{
ChangeGroup(xw, XtNtitle, name);
}
#define Strlen(s) strlen((char *)(s))
void
ChangeXprop(char *buf)
{
Display *dpy = XtDisplay(toplevel);
Window w = XtWindow(toplevel);
XTextProperty text_prop;
Atom aprop;
Char *pchEndPropName = (Char *) strchr(buf, '=');
if (pchEndPropName)
*pchEndPropName = '\0';
aprop = XInternAtom(dpy, buf, False);
if (pchEndPropName == NULL) {
/* no "=value" given, so delete the property */
XDeleteProperty(dpy, w, aprop);
} else {
text_prop.value = pchEndPropName + 1;
text_prop.encoding = XA_STRING;
text_prop.format = 8;
text_prop.nitems = Strlen(text_prop.value);
XSetTextProperty(dpy, w, &text_prop, aprop);
}
}
/***====================================================================***/
/*
* This is part of ReverseVideo(). It reverses the data stored for the old
* "dynamic" colors that might have been retrieved using OSC 10-18.
*/
void
ReverseOldColors(void)
{
ScrnColors *pOld = pOldColors;
Pixel tmpPix;
char *tmpName;
if (pOld) {
/* change text cursor, if necesary */
if (pOld->colors[TEXT_CURSOR] == pOld->colors[TEXT_FG]) {
pOld->colors[TEXT_CURSOR] = pOld->colors[TEXT_BG];
if (pOld->names[TEXT_CURSOR]) {
XtFree(pOldColors->names[TEXT_CURSOR]);
pOld->names[TEXT_CURSOR] = NULL;
}
if (pOld->names[TEXT_BG]) {
if ((tmpName = x_strdup(pOld->names[TEXT_BG])) != 0) {
pOld->names[TEXT_CURSOR] = tmpName;
}
}
}
EXCHANGE(pOld->colors[TEXT_FG], pOld->colors[TEXT_BG], tmpPix);
EXCHANGE(pOld->names[TEXT_FG], pOld->names[TEXT_BG], tmpName);
EXCHANGE(pOld->colors[MOUSE_FG], pOld->colors[MOUSE_BG], tmpPix);
EXCHANGE(pOld->names[MOUSE_FG], pOld->names[MOUSE_BG], tmpName);
#if OPT_TEK4014
EXCHANGE(pOld->colors[TEK_FG], pOld->colors[TEK_BG], tmpPix);
EXCHANGE(pOld->names[TEK_FG], pOld->names[TEK_BG], tmpName);
#endif
}
return;
}
Bool
AllocateTermColor(XtermWidget xw,
ScrnColors * pNew,
int ndx,
const char *name)
{
Bool result = False;
if (AllowColorOps(xw, ecSetColor)) {
XColor def;
TScreen *screen = TScreenOf(xw);
Colormap cmap = xw->core.colormap;
char *newName;
if (XParseColor(screen->display, cmap, name, &def)
&& (XAllocColor(screen->display, cmap, &def)
|| find_closest_color(screen->display, cmap, &def))
&& (newName = x_strdup(name)) != 0) {
if (COLOR_DEFINED(pNew, ndx))
free(pNew->names[ndx]);
SET_COLOR_VALUE(pNew, ndx, def.pixel);
SET_COLOR_NAME(pNew, ndx, newName);
TRACE(("AllocateTermColor #%d: %s (pixel %#lx)\n", ndx, newName, def.pixel));
result = True;
} else {
TRACE(("AllocateTermColor #%d: %s (failed)\n", ndx, name));
}
}
return result;
}
/***====================================================================***/
/* ARGSUSED */
void
Panic(const char *s GCC_UNUSED, int a GCC_UNUSED)
{
#ifdef DEBUG
if (debug) {
fprintf(stderr, "%s: PANIC!\t", xterm_name);
fprintf(stderr, s, a);
fputs("\r\n", stderr);
fflush(stderr);
}
#endif /* DEBUG */
}
const char *
SysErrorMsg(int code)
{
static char unknown[] = "unknown error";
char *s = strerror(code);
return s ? s : unknown;
}
const char *
SysReasonMsg(int code)
{
/* *INDENT-OFF* */
static const struct {
int code;
const char *name;
} table[] = {
{ ERROR_FIONBIO, "main: ioctl() failed on FIONBIO" },
{ ERROR_F_GETFL, "main: ioctl() failed on F_GETFL" },
{ ERROR_F_SETFL, "main: ioctl() failed on F_SETFL", },
{ ERROR_OPDEVTTY, "spawn: open() failed on /dev/tty", },
{ ERROR_TIOCGETP, "spawn: ioctl() failed on TIOCGETP", },
{ ERROR_PTSNAME, "spawn: ptsname() failed", },
{ ERROR_OPPTSNAME, "spawn: open() failed on ptsname", },
{ ERROR_PTEM, "spawn: ioctl() failed on I_PUSH/\"ptem\"" },
{ ERROR_CONSEM, "spawn: ioctl() failed on I_PUSH/\"consem\"" },
{ ERROR_LDTERM, "spawn: ioctl() failed on I_PUSH/\"ldterm\"" },
{ ERROR_TTCOMPAT, "spawn: ioctl() failed on I_PUSH/\"ttcompat\"" },
{ ERROR_TIOCSETP, "spawn: ioctl() failed on TIOCSETP" },
{ ERROR_TIOCSETC, "spawn: ioctl() failed on TIOCSETC" },
{ ERROR_TIOCSETD, "spawn: ioctl() failed on TIOCSETD" },
{ ERROR_TIOCSLTC, "spawn: ioctl() failed on TIOCSLTC" },
{ ERROR_TIOCLSET, "spawn: ioctl() failed on TIOCLSET" },
{ ERROR_INIGROUPS, "spawn: initgroups() failed" },
{ ERROR_FORK, "spawn: fork() failed" },
{ ERROR_EXEC, "spawn: exec() failed" },
{ ERROR_PTYS, "get_pty: not enough ptys" },
{ ERROR_PTY_EXEC, "waiting for initial map" },
{ ERROR_SETUID, "spawn: setuid() failed" },
{ ERROR_INIT, "spawn: can't initialize window" },
{ ERROR_TIOCKSET, "spawn: ioctl() failed on TIOCKSET" },
{ ERROR_TIOCKSETC, "spawn: ioctl() failed on TIOCKSETC" },
{ ERROR_SPREALLOC, "spawn: realloc of ttydev failed" },
{ ERROR_LUMALLOC, "luit: command-line malloc failed" },
{ ERROR_SELECT, "in_put: select() failed" },
{ ERROR_VINIT, "VTInit: can't initialize window" },
{ ERROR_KMMALLOC1, "HandleKeymapChange: malloc failed" },
{ ERROR_TSELECT, "Tinput: select() failed" },
{ ERROR_TINIT, "TekInit: can't initialize window" },
{ ERROR_BMALLOC2, "SaltTextAway: malloc() failed" },
{ ERROR_LOGEXEC, "StartLog: exec() failed" },
{ ERROR_XERROR, "xerror: XError event" },
{ ERROR_XIOERROR, "xioerror: X I/O error" },
{ ERROR_SCALLOC, "Alloc: calloc() failed on base" },
{ ERROR_SCALLOC2, "Alloc: calloc() failed on rows" },
{ ERROR_SAVE_PTR, "ScrnPointers: malloc/realloc() failed" },
{ ERROR_MMALLOC, "my_memmove: malloc/realloc failed" },
};
/* *INDENT-ON* */
Cardinal n;
const char *result = "?";
for (n = 0; n < XtNumber(table); ++n) {
if (code == table[n].code) {
result = table[n].name;
break;
}
}
return result;
}
void
SysError(int code)
{
int oerrno = errno;
fprintf(stderr, "%s: Error %d, errno %d: ", xterm_name, code, oerrno);
fprintf(stderr, "%s\n", SysErrorMsg(oerrno));
fprintf(stderr, "Reason: %s\n", SysReasonMsg(code));
Cleanup(code);
}
/*
* cleanup by sending SIGHUP to client processes
*/
void
Cleanup(int code)
{
static Bool cleaning;
TScreen *screen = TScreenOf(term);
/*
* Process "-hold" and session cleanup only for a normal exit.
*/
if (code == 0) {
if (cleaning) {
hold_screen = 0;
return;
}
cleaning = True;
need_cleanup = False;
TRACE(("Cleanup %d\n", code));
if (hold_screen) {
hold_screen = 2;
while (hold_screen) {
xevents();
Sleep(10);
}
}
#if OPT_SESSION_MGT
if (resource.sessionMgt) {
XtVaSetValues(toplevel,
XtNjoinSession, False,
(XtPointer *) 0);
}
#endif
}
if (screen->pid > 1) {
(void) kill_process_group(screen->pid, SIGHUP);
}
Exit(code);
}
#ifndef VMS
char *
xtermFindShell(char *leaf, Bool warning)
{
char *s;
char *d;
char *tmp;
char *result = leaf;
TRACE(("xtermFindShell(%s)\n", leaf));
if (*result != '\0' && strchr("+/-", *result) == 0) {
/* find it in $PATH */
if ((s = x_getenv("PATH")) != 0) {
if ((tmp = TypeMallocN(char, strlen(leaf) + strlen(s) + 2)) != 0) {
Bool found = False;
while (*s != '\0') {
strcpy(tmp, s);
for (d = tmp;; ++d) {
if (*d == ':' || *d == '\0') {
int skip = (*d != '\0');
*d = '/';
strcpy(d + 1, leaf);
if (skip)
++d;
s += (d - tmp);
if (*tmp == '/'
&& strstr(tmp, "..") == 0
&& access(tmp, X_OK) == 0) {
result = x_strdup(tmp);
found = True;
}
break;
}
if (found)
break;
}
if (found)
break;
}
free(tmp);
}
}
}
TRACE(("...xtermFindShell(%s)\n", result));
if (*result != '/'
|| strstr(result, "..") != 0
|| access(result, X_OK) != 0) {
if (warning)
fprintf(stderr, "No absolute path found for shell: %s\n", result);
result = 0;
}
return result;
}
#endif /* VMS */
#define ENV_HUNK(n) (unsigned) ((((n) + 1) | 31) + 1)
/*
* copy the environment before Setenv'ing.
*/
void
xtermCopyEnv(char **oldenv)
{
unsigned size;
char **newenv;
for (size = 0; oldenv[size] != NULL; size++) {
;
}
newenv = TypeCallocN(char *, ENV_HUNK(size));
memmove(newenv, oldenv, size * sizeof(char *));
environ = newenv;
}
/*
* sets the value of var to be arg in the Unix 4.2 BSD environment env.
* Var should end with '=' (bindings are of the form "var=value").
* This procedure assumes the memory for the first level of environ
* was allocated using calloc, with enough extra room at the end so not
* to have to do a realloc().
*/
void
xtermSetenv(const char *var, const char *value)
{
if (value != 0) {
char *test;
int envindex = 0;
size_t len = strlen(var);
int found = -1;
TRACE(("xtermSetenv(%s=%s)\n", var, value));
while ((test = environ[envindex]) != NULL) {
if (strncmp(test, var, len) == 0 && test[len] == '=') {
found = envindex;
break;
}
envindex++;
}
if (found < 0) {
unsigned need = ENV_HUNK(envindex + 1);
unsigned have = ENV_HUNK(envindex);
if (need > have) {
char **newenv;
newenv = TypeMallocN(char *, need);
if (newenv == 0) {
fprintf(stderr, "Cannot increase environment\n");
return;
}
memmove(newenv, environ, have * sizeof(*newenv));
free(environ);
environ = newenv;
}
found = envindex;
environ[found + 1] = NULL;
environ = environ;
}
environ[found] = CastMallocN(char, 1 + len + strlen(value));
if (environ[found] == 0) {
fprintf(stderr, "Cannot allocate environment %s\n", var);
return;
}
sprintf(environ[found], "%s=%s", var, value);
}
}
/*ARGSUSED*/
int
xerror(Display * d, XErrorEvent * ev)
{
fprintf(stderr, "%s: warning, error event received:\n", xterm_name);
(void) XmuPrintDefaultErrorMessage(d, ev, stderr);
Exit(ERROR_XERROR);
return 0; /* appease the compiler */
}
/*ARGSUSED*/
int
xioerror(Display * dpy)
{
int the_error = errno;
(void) fprintf(stderr,
"%s: fatal IO error %d (%s) or KillClient on X server \"%s\"\r\n",
xterm_name, the_error, SysErrorMsg(the_error),
DisplayString(dpy));
Exit(ERROR_XIOERROR);
return 0; /* appease the compiler */
}
void
xt_error(String message)
{
(void) fprintf(stderr, "%s Xt error: %s\n", ProgramName, message);
/*
* Check for the obvious - Xt does a poor job of reporting this.
*/
if (x_getenv("DISPLAY") == 0) {
fprintf(stderr, "%s: DISPLAY is not set\n", ProgramName);
}
exit(1);
}
int
XStrCmp(char *s1, char *s2)
{
if (s1 && s2)
return (strcmp(s1, s2));
if (s1 && *s1)
return (1);
if (s2 && *s2)
return (-1);
return (0);
}
#if OPT_TEK4014
static void
withdraw_window(Display * dpy, Window w, int scr)
{
TRACE(("withdraw_window %#lx\n", (long) w));
(void) XmuUpdateMapHints(dpy, w, NULL);
XWithdrawWindow(dpy, w, scr);
return;
}
#endif
void
set_vt_visibility(Bool on)
{
TScreen *screen = TScreenOf(term);
TRACE(("set_vt_visibility(%d)\n", on));
if (on) {
if (!screen->Vshow && term) {
VTInit(term);
XtMapWidget(XtParent(term));
#if OPT_TOOLBAR
/* we need both of these during initialization */
XtMapWidget(SHELL_OF(term));
ShowToolbar(resource.toolBar);
#endif
screen->Vshow = True;
}
}
#if OPT_TEK4014
else {
if (screen->Vshow && term) {
withdraw_window(XtDisplay(term),
VShellWindow,
XScreenNumberOfScreen(XtScreen(term)));
screen->Vshow = False;
}
}
set_vthide_sensitivity();
set_tekhide_sensitivity();
update_vttekmode();
update_tekshow();
update_vtshow();
#endif
return;
}
#if OPT_TEK4014
void
set_tek_visibility(Bool on)
{
TRACE(("set_tek_visibility(%d)\n", on));
if (on) {
if (!TEK4014_SHOWN(term) && (tekWidget || TekInit())) {
Widget tekParent = SHELL_OF(tekWidget);
XtRealizeWidget(tekParent);
XtMapWidget(XtParent(tekWidget));
#if OPT_TOOLBAR
/* we need both of these during initialization */
XtMapWidget(tekParent);
XtMapWidget(tekWidget);
#endif
XtOverrideTranslations(tekParent,
XtParseTranslationTable
("<Message>WM_PROTOCOLS: DeleteWindow()"));
(void) XSetWMProtocols(XtDisplay(tekParent),
XtWindow(tekParent),
&wm_delete_window, 1);
TEK4014_SHOWN(term) = True;
}
} else {
if (TEK4014_SHOWN(term) && tekWidget) {
withdraw_window(XtDisplay(tekWidget),
TShellWindow,
XScreenNumberOfScreen(XtScreen(tekWidget)));
TEK4014_SHOWN(term) = False;
}
}
set_tekhide_sensitivity();
set_vthide_sensitivity();
update_vtshow();
update_tekshow();
update_vttekmode();
return;
}
void
end_tek_mode(void)
{
if (TEK4014_ACTIVE(term)) {
FlushLog(TScreenOf(term));
longjmp(Tekend, 1);
}
return;
}
void
end_vt_mode(void)
{
if (!TEK4014_ACTIVE(term)) {
FlushLog(TScreenOf(term));
TEK4014_ACTIVE(term) = True;
longjmp(VTend, 1);
}
return;
}
void
switch_modes(Bool tovt) /* if true, then become vt mode */
{
if (tovt) {
if (tekRefreshList)
TekRefresh(tekWidget);
end_tek_mode(); /* WARNING: this does a longjmp... */
} else {
end_vt_mode(); /* WARNING: this does a longjmp... */
}
}
void
hide_vt_window(void)
{
set_vt_visibility(False);
if (!TEK4014_ACTIVE(term))
switch_modes(False); /* switch to tek mode */
}
void
hide_tek_window(void)
{
set_tek_visibility(False);
tekRefreshList = (TekLink *) 0;
if (TEK4014_ACTIVE(term))
switch_modes(True); /* does longjmp to vt mode */
}
#endif /* OPT_TEK4014 */
static const char *
skip_punct(const char *s)
{
while (*s == '-' || *s == '/' || *s == '+' || *s == '#' || *s == '%') {
++s;
}
return s;
}
static int
cmp_options(const void *a, const void *b)
{
const char *s1 = skip_punct(((const OptionHelp *) a)->opt);
const char *s2 = skip_punct(((const OptionHelp *) b)->opt);
return strcmp(s1, s2);
}
static int
cmp_resources(const void *a, const void *b)
{
return strcmp(((const XrmOptionDescRec *) a)->option,
((const XrmOptionDescRec *) b)->option);
}
XrmOptionDescRec *
sortedOptDescs(XrmOptionDescRec * descs, Cardinal res_count)
{
static XrmOptionDescRec *res_array = 0;
#ifdef NO_LEAKS
if (descs == 0 && res_array != 0) {
free(res_array);
res_array = 0;
} else
#endif
if (res_array == 0) {
Cardinal j;
/* make a sorted index to 'resources' */
res_array = TypeCallocN(XrmOptionDescRec, res_count);
for (j = 0; j < res_count; j++)
res_array[j] = descs[j];
qsort(res_array, res_count, sizeof(*res_array), cmp_resources);
}
return res_array;
}
/*
* The first time this is called, construct sorted index to the main program's
* list of options, taking into account the on/off options which will be
* compressed into one token. It's a lot simpler to do it this way than
* maintain the list in sorted form with lots of ifdef's.
*/
OptionHelp *
sortedOpts(OptionHelp * options, XrmOptionDescRec * descs, Cardinal numDescs)
{
static OptionHelp *opt_array = 0;
#ifdef NO_LEAKS
if (descs == 0 && opt_array != 0) {
sortedOptDescs(descs, numDescs);
free(opt_array);
opt_array = 0;
return 0;
} else if (options == 0 || descs == 0) {
return 0;
}
#endif
if (opt_array == 0) {
Cardinal opt_count, j;
#if OPT_TRACE
Cardinal k;
XrmOptionDescRec *res_array = sortedOptDescs(descs, numDescs);
int code;
const char *mesg;
#else
(void) descs;
(void) numDescs;
#endif
/* count 'options' and make a sorted index to it */
for (opt_count = 0; options[opt_count].opt != 0; ++opt_count) {
;
}
opt_array = TypeCallocN(OptionHelp, opt_count + 1);
for (j = 0; j < opt_count; j++)
opt_array[j] = options[j];
qsort(opt_array, opt_count, sizeof(OptionHelp), cmp_options);
/* supply the "turn on/off" strings if needed */
#if OPT_TRACE
for (j = 0; j < opt_count; j++) {
if (!strncmp(opt_array[j].opt, "-/+", 3)) {
char *name = opt_array[j].opt + 3;
for (k = 0; k < numDescs; ++k) {
char *value = res_array[k].value;
if (res_array[k].option[0] == '-') {
code = -1;
} else if (res_array[k].option[0] == '+') {
code = 1;
} else {
code = 0;
}
if (x_strindex(opt_array[j].desc, "inhibit") != 0)
code = -code;
if (code != 0
&& res_array[k].value != 0
&& !strcmp(name, res_array[k].option + 1)) {
if (((code < 0) && !strcmp(value, "on"))
|| ((code > 0) && !strcmp(value, "off"))
|| ((code > 0) && !strcmp(value, "0"))) {
mesg = "turn on/off";
} else {
mesg = "turn off/on";
}
if (strncmp(mesg, opt_array[j].desc, strlen(mesg))) {
if (strncmp(opt_array[j].desc, "turn ", 5)) {
char *s = CastMallocN(char,
strlen(mesg)
+ 1
+ strlen(opt_array[j].desc));
if (s != 0) {
sprintf(s, "%s %s", mesg, opt_array[j].desc);
opt_array[j].desc = s;
}
} else {
TRACE(("OOPS "));
}
}
TRACE(("%s: %s %s: %s (%s)\n",
mesg,
res_array[k].option,
res_array[k].value,
opt_array[j].opt,
opt_array[j].desc));
break;
}
}
}
}
#endif
}
return opt_array;
}
/*
* Report the character-type locale that xterm was started in.
*/
char *
xtermEnvLocale(void)
{
static char *result;
if (result == 0) {
if ((result = x_nonempty(setlocale(LC_CTYPE, 0))) == 0) {
result = x_strdup("C");
} else {
result = x_strdup(result);
}
TRACE(("xtermEnvLocale ->%s\n", result));
}
return result;
}
char *
xtermEnvEncoding(void)
{
static char *result;
if (result == 0) {
#ifdef HAVE_LANGINFO_CODESET
result = nl_langinfo(CODESET);
#else
char *locale = xtermEnvLocale();
if (!strcmp(locale, "C") || !strcmp(locale, "POSIX")) {
result = "ASCII";
} else {
result = "ISO-8859-1";
}
#endif
TRACE(("xtermEnvEncoding ->%s\n", result));
}
return result;
}
#if OPT_WIDE_CHARS
/*
* Tell whether xterm was started in a locale that uses UTF-8 encoding for
* characters. That environment is inherited by subprocesses and used in
* various library calls.
*/
Bool
xtermEnvUTF8(void)
{
static Bool init = False;
static Bool result = False;
if (!init) {
init = True;
#ifdef HAVE_LANGINFO_CODESET
result = (strcmp(xtermEnvEncoding(), "UTF-8") == 0);
#else
result = (strstr(xtermEnvLocale(), "UTF-8") != NULL);
#endif
TRACE(("xtermEnvUTF8 ->%s\n", BtoS(result)));
}
return result;
}
#endif /* OPT_WIDE_CHARS */
/*
* Returns the version-string used in the "-v' message as well as a few other
* places. It is derived (when possible) from the __vendorversion__ symbol
* that some newer imake configurations define.
*/
char *
xtermVersion(void)
{
static char *result;
if (result == 0) {
char *vendor = __vendorversion__;
char first[BUFSIZ];
char second[BUFSIZ];
result = CastMallocN(char, strlen(vendor) + 9);
if (result == 0)
result = vendor;
else {
/* some vendors leave trash in this string */
for (;;) {
if (!strncmp(vendor, "Version ", 8))
vendor += 8;
else if (isspace(CharOf(*vendor)))
++vendor;
else
break;
}
if (strlen(vendor) < BUFSIZ &&
sscanf(vendor, "%[0-9.] %[A-Za-z_0-9.]", first, second) == 2)
sprintf(result, "%s %s(%d)", second, first, XTERM_PATCH);
else
sprintf(result, "%s(%d)", vendor, XTERM_PATCH);
}
}
return result;
}
/*
* Check if the current widget, or any parent, is the VT100 "xterm" widget.
*/
XtermWidget
getXtermWidget(Widget w)
{
XtermWidget xw;
if (w == 0) {
xw = (XtermWidget) CURRENT_EMU();
if (!IsXtermWidget(xw)) {
xw = 0;
}
} else if (IsXtermWidget(w)) {
xw = (XtermWidget) w;
} else {
xw = getXtermWidget(XtParent(w));
}
TRACE2(("getXtermWidget %p -> %p\n", w, xw));
return xw;
}
|