summaryrefslogtreecommitdiff
path: root/src/Shell.c
blob: 12762d66df952d808880d69e4ffa9ef7a78d1e4d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
/* $Xorg: Shell.c,v 1.4 2001/02/09 02:03:58 xorgcvs Exp $ */

/***********************************************************
Copyright 1987, 1988 by Digital Equipment Corporation, Maynard, Massachusetts
Copyright 1993 by Sun Microsystems, Inc. Mountain View, CA.

                        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 names of Digital or Sun 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.

SUN DISCLAIMS ALL WARRANTIES WITH REGARD TO  THIS  SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FIT-
NESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SUN BE  LI-
ABLE  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.

******************************************************************/
/* $XFree86: xc/lib/Xt/Shell.c,v 3.16tsi Exp $ */

/*

Copyright 1987, 1988, 1994, 1998  The Open Group

Permission to use, copy, modify, distribute, and sell this software and its
documentation for any purpose is hereby granted without fee, provided that
the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation.

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
OPEN GROUP 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 of The Open Group shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from The Open Group.

*/

#define SHELL

#ifndef DEFAULT_WM_TIMEOUT
#define DEFAULT_WM_TIMEOUT 5000
#endif

#include "IntrinsicI.h"
#include "StringDefs.h"
#include "Shell.h"
#include "ShellP.h"
#include "ShellI.h"
#include "Vendor.h"
#include "VendorP.h"
#include <X11/Xatom.h>
#include <X11/Xlocale.h>
#include <X11/ICE/ICElib.h>
#include <stdio.h>
#include <stdlib.h>

#ifdef EDITRES
#include <X11/Xmu/Editres.h>
#endif

/***************************************************************************
 *
 * Note: per the Xt spec, the Shell geometry management assumes in
 * several places that there is only one managed child.  This is
 * *not* a bug.  Any subclass that assumes otherwise is broken.
 *
 ***************************************************************************/

#define BIGSIZE ((Dimension)32767)

/***************************************************************************
 *
 * Default values for resource lists
 *
 ***************************************************************************/

#ifdef CRAY
void _XtShellDepth(Widget, int, XrmValue *);
void _XtShellColormap(Widget, int, XrmValue *);
void _XtShellAncestorSensitive(Widget, int, XrmValue *);
void _XtTitleEncoding(Widget, int, XrmValue *);
#else
static void _XtShellDepth(Widget, int, XrmValue *);
static void _XtShellColormap(Widget, int, XrmValue *);
static void _XtShellAncestorSensitive(Widget, int, XrmValue *);
static void _XtTitleEncoding(Widget, int, XrmValue *);
#endif

/***************************************************************************
 *
 * Shell class record
 *
 ***************************************************************************/

#define Offset(x)	(XtOffsetOf(ShellRec, x))
static XtResource shellResources[]=
{
	{XtNx, XtCPosition, XtRPosition, sizeof(Position),
	    Offset(core.x), XtRImmediate, (XtPointer)BIGSIZE},
	{XtNy, XtCPosition, XtRPosition, sizeof(Position),
	    Offset(core.y), XtRImmediate, (XtPointer)BIGSIZE},
	{ XtNdepth, XtCDepth, XtRInt, sizeof(int),
	    Offset(core.depth), XtRCallProc, (XtPointer) _XtShellDepth},
	{ XtNcolormap, XtCColormap, XtRColormap, sizeof(Colormap),
	    Offset(core.colormap), XtRCallProc, (XtPointer) _XtShellColormap},
	{ XtNancestorSensitive, XtCSensitive, XtRBoolean, sizeof(Boolean),
	    Offset(core.ancestor_sensitive), XtRCallProc,
	    (XtPointer) _XtShellAncestorSensitive},
	{ XtNallowShellResize, XtCAllowShellResize, XtRBoolean,
	    sizeof(Boolean), Offset(shell.allow_shell_resize),
	    XtRImmediate, (XtPointer)False},
	{ XtNgeometry, XtCGeometry, XtRString, sizeof(String),
	    Offset(shell.geometry), XtRString, (XtPointer)NULL},
	{ XtNcreatePopupChildProc, XtCCreatePopupChildProc, XtRFunction,
	    sizeof(XtCreatePopupChildProc), Offset(shell.create_popup_child_proc),
	    XtRFunction, NULL},
	{ XtNsaveUnder, XtCSaveUnder, XtRBoolean, sizeof(Boolean),
	    Offset(shell.save_under), XtRImmediate, (XtPointer)False},
	{ XtNpopupCallback, XtCCallback, XtRCallback, sizeof(XtCallbackList),
	    Offset(shell.popup_callback), XtRCallback, (XtPointer) NULL},
	{ XtNpopdownCallback, XtCCallback, XtRCallback, sizeof(XtCallbackList),
	    Offset(shell.popdown_callback), XtRCallback, (XtPointer) NULL},
	{ XtNoverrideRedirect, XtCOverrideRedirect,
	    XtRBoolean, sizeof(Boolean), Offset(shell.override_redirect),
	    XtRImmediate, (XtPointer)False},
	{ XtNvisual, XtCVisual, XtRVisual, sizeof(Visual*),
	    Offset(shell.visual), XtRImmediate, CopyFromParent}
};

static void ClassPartInitialize(WidgetClass);
static void Initialize(Widget, Widget, ArgList, Cardinal *);
static void Realize(Widget, Mask *, XSetWindowAttributes *);
static void Resize(Widget);
static Boolean SetValues(Widget, Widget, Widget, ArgList , Cardinal *);
static void GetValuesHook(Widget, ArgList, Cardinal*);
static void ChangeManaged(Widget);
static XtGeometryResult GeometryManager(Widget, XtWidgetGeometry *, XtWidgetGeometry *);
static XtGeometryResult RootGeometryManager(Widget gw, XtWidgetGeometry *request, XtWidgetGeometry *reply);
static void Destroy(Widget);

static ShellClassExtensionRec shellClassExtRec = {
    NULL,
    NULLQUARK,
    XtShellExtensionVersion,
    sizeof(ShellClassExtensionRec),
    RootGeometryManager
};

externaldef(shellclassrec) ShellClassRec shellClassRec = {
  {   /* Core */
    /* superclass	  */	(WidgetClass) &compositeClassRec,
    /* class_name	  */	"Shell",
    /* size		  */	sizeof(ShellRec),
    /* Class Initializer  */	NULL,
    /* class_part_initialize*/	ClassPartInitialize,
    /* Class init'ed ?	  */	FALSE,
    /* initialize	  */	Initialize,
    /* initialize_notify  */	NULL,
    /* realize		  */	Realize,
    /* actions		  */	NULL,
    /* num_actions	  */	0,
    /* resources	  */	shellResources,
    /* resource_count	  */	XtNumber(shellResources),
    /* xrm_class	  */	NULLQUARK,
    /* compress_motion	  */	FALSE,
    /* compress_exposure  */	TRUE,
    /* compress_enterleave*/	FALSE,
    /* visible_interest	  */	FALSE,
    /* destroy		  */	Destroy,
    /* resize		  */	Resize,
    /* expose		  */	NULL,
    /* set_values	  */	SetValues,
    /* set_values_hook	  */	NULL,
    /* set_values_almost  */	XtInheritSetValuesAlmost,
    /* get_values_hook	  */	GetValuesHook,
    /* accept_focus	  */	NULL,
    /* intrinsics version */	XtVersion,
    /* callback offsets	  */	NULL,
    /* tm_table		  */	NULL,
    /* query_geometry	  */	NULL,
    /* display_accelerator*/	NULL,
    /* extension	  */	NULL
  },{ /* Composite */
    /* geometry_manager	  */	GeometryManager,
    /* change_managed	  */	ChangeManaged,
    /* insert_child	  */	XtInheritInsertChild,
    /* delete_child	  */	XtInheritDeleteChild,
    /* extension	  */	NULL
  },{ /* Shell */
    /* extension	  */	(XtPointer)&shellClassExtRec
  }
};

externaldef(shellwidgetclass) WidgetClass shellWidgetClass = (WidgetClass) (&shellClassRec);

/***************************************************************************
 *
 * OverrideShell class record
 *
 ***************************************************************************/

static XtResource overrideResources[]=
{
	{ XtNoverrideRedirect, XtCOverrideRedirect,
	    XtRBoolean, sizeof(Boolean), Offset(shell.override_redirect),
	    XtRImmediate, (XtPointer)True},
	{ XtNsaveUnder, XtCSaveUnder, XtRBoolean, sizeof(Boolean),
	    Offset(shell.save_under), XtRImmediate, (XtPointer)True},
};

externaldef(overrideshellclassrec) OverrideShellClassRec overrideShellClassRec = {
  {
    /* superclass         */    (WidgetClass) &shellClassRec,
    /* class_name         */    "OverrideShell",
    /* size               */    sizeof(OverrideShellRec),
    /* Class Initializer  */	NULL,
    /* class_part_initialize*/	NULL,
    /* Class init'ed ?    */	FALSE,
    /* initialize         */    NULL,
    /* initialize_notify    */	NULL,
    /* realize            */    XtInheritRealize,
    /* actions            */    NULL,
    /* num_actions        */    0,
    /* resources          */    overrideResources,
    /* resource_count     */	XtNumber(overrideResources),
    /* xrm_class          */    NULLQUARK,
    /* compress_motion    */    FALSE,
    /* compress_exposure  */    TRUE,
    /* compress_enterleave*/ 	FALSE,
    /* visible_interest   */    FALSE,
    /* destroy            */    NULL,
    /* resize             */    XtInheritResize,
    /* expose             */    NULL,
    /* set_values         */    NULL,
    /* set_values_hook      */	NULL,
    /* set_values_almost    */	XtInheritSetValuesAlmost,
    /* get_values_hook      */	NULL,
    /* accept_focus       */    NULL,
    /* intrinsics version */	XtVersion,
    /* callback offsets   */    NULL,
    /* tm_table		    */  NULL,
    /* query_geometry	    */  NULL,
    /* display_accelerator  */  NULL,
    /* extension	    */  NULL
  },{
    /* geometry_manager   */    XtInheritGeometryManager,
    /* change_managed     */    XtInheritChangeManaged,
    /* insert_child	  */	XtInheritInsertChild,
    /* delete_child	  */	XtInheritDeleteChild,
    /* extension	    */  NULL
  },{
    /* extension	    */  NULL
  },{
    /* extension	    */  NULL
  }
};

externaldef(overrideshellwidgetclass) WidgetClass overrideShellWidgetClass =
	(WidgetClass) (&overrideShellClassRec);

/***************************************************************************
 *
 * WMShell class record
 *
 ***************************************************************************/

#undef Offset
#define Offset(x)	(XtOffsetOf(WMShellRec, x))

static int default_unspecified_shell_int = XtUnspecifiedShellInt;
/*
 * Warning, casting XtUnspecifiedShellInt (which is -1) to an (XtPointer)
 * can result is loss of bits on some machines (i.e. crays)
 */

static XtResource wmResources[]=
{
	{ XtNtitle, XtCTitle, XtRString, sizeof(String),
	    Offset(wm.title), XtRString, NULL},
	{ XtNtitleEncoding, XtCTitleEncoding, XtRAtom, sizeof(Atom),
	    Offset(wm.title_encoding),
	    XtRCallProc, (XtPointer) _XtTitleEncoding},
	{ XtNwmTimeout, XtCWmTimeout, XtRInt, sizeof(int),
	    Offset(wm.wm_timeout), XtRImmediate,(XtPointer)DEFAULT_WM_TIMEOUT},
	{ XtNwaitForWm, XtCWaitForWm, XtRBoolean, sizeof(Boolean),
	    Offset(wm.wait_for_wm), XtRImmediate, (XtPointer)True},
	{ XtNtransient, XtCTransient, XtRBoolean, sizeof(Boolean),
	    Offset(wm.transient), XtRImmediate, (XtPointer)False},
/* size_hints minus things stored in core */
	{ XtNbaseWidth, XtCBaseWidth, XtRInt, sizeof(int),
	    Offset(wm.base_width),
	    XtRInt, (XtPointer) &default_unspecified_shell_int},
	{ XtNbaseHeight, XtCBaseHeight, XtRInt, sizeof(int),
	    Offset(wm.base_height),
	    XtRInt, (XtPointer) &default_unspecified_shell_int},
	{ XtNwinGravity, XtCWinGravity, XtRGravity, sizeof(int),
	    Offset(wm.win_gravity),
	    XtRGravity, (XtPointer) &default_unspecified_shell_int},
	{ XtNminWidth, XtCMinWidth, XtRInt, sizeof(int),
	    Offset(wm.size_hints.min_width),
	    XtRInt, (XtPointer) &default_unspecified_shell_int},
	{ XtNminHeight, XtCMinHeight, XtRInt, sizeof(int),
	    Offset(wm.size_hints.min_height),
	    XtRInt, (XtPointer) &default_unspecified_shell_int},
	{ XtNmaxWidth, XtCMaxWidth, XtRInt, sizeof(int),
	    Offset(wm.size_hints.max_width),
	    XtRInt, (XtPointer) &default_unspecified_shell_int},
	{ XtNmaxHeight, XtCMaxHeight, XtRInt, sizeof(int),
	    Offset(wm.size_hints.max_height),
	    XtRInt, (XtPointer) &default_unspecified_shell_int},
	{ XtNwidthInc, XtCWidthInc, XtRInt, sizeof(int),
	    Offset(wm.size_hints.width_inc),
	    XtRInt, (XtPointer) &default_unspecified_shell_int},
	{ XtNheightInc, XtCHeightInc, XtRInt, sizeof(int),
	    Offset(wm.size_hints.height_inc),
	    XtRInt, (XtPointer) &default_unspecified_shell_int},
	{ XtNminAspectX, XtCMinAspectX, XtRInt, sizeof(int),
	    Offset(wm.size_hints.min_aspect.x),
	    XtRInt, (XtPointer) &default_unspecified_shell_int},
	{ XtNminAspectY, XtCMinAspectY, XtRInt, sizeof(int),
	    Offset(wm.size_hints.min_aspect.y),
	    XtRInt, (XtPointer) &default_unspecified_shell_int},
	{ XtNmaxAspectX, XtCMaxAspectX, XtRInt, sizeof(int),
	    Offset(wm.size_hints.max_aspect.x),
	    XtRInt, (XtPointer) &default_unspecified_shell_int},
	{ XtNmaxAspectY, XtCMaxAspectY, XtRInt, sizeof(int),
	    Offset(wm.size_hints.max_aspect.y),
	    XtRInt, (XtPointer) &default_unspecified_shell_int},
/* wm_hints */
	{ XtNinput, XtCInput, XtRBool, sizeof(Bool),
	    Offset(wm.wm_hints.input), XtRImmediate, (XtPointer)False},
	{ XtNinitialState, XtCInitialState, XtRInitialState, sizeof(int),
	    Offset(wm.wm_hints.initial_state),
	    XtRImmediate, (XtPointer)NormalState},
	{ XtNiconPixmap, XtCIconPixmap, XtRBitmap, sizeof(Pixmap),
	    Offset(wm.wm_hints.icon_pixmap), XtRPixmap, NULL},
	{ XtNiconWindow, XtCIconWindow, XtRWindow, sizeof(Window),
	    Offset(wm.wm_hints.icon_window), XtRWindow,   (XtPointer) NULL},
	{ XtNiconX, XtCIconX, XtRInt, sizeof(int),
	    Offset(wm.wm_hints.icon_x),
	    XtRInt, (XtPointer) &default_unspecified_shell_int},
	{ XtNiconY, XtCIconY, XtRInt, sizeof(int),
	    Offset(wm.wm_hints.icon_y),
	    XtRInt, (XtPointer) &default_unspecified_shell_int},
	{ XtNiconMask, XtCIconMask, XtRBitmap, sizeof(Pixmap),
	    Offset(wm.wm_hints.icon_mask), XtRPixmap, NULL},
	{ XtNwindowGroup, XtCWindowGroup, XtRWindow, sizeof(Window),
	    Offset(wm.wm_hints.window_group),
	    XtRImmediate, (XtPointer)XtUnspecifiedWindow},
	{ XtNclientLeader, XtCClientLeader, XtRWidget, sizeof(Widget),
	    Offset(wm.client_leader), XtRWidget, NULL},
	{ XtNwindowRole, XtCWindowRole, XtRString, sizeof(String),
	    Offset(wm.window_role), XtRString, (XtPointer) NULL},
	{ XtNurgency, XtCUrgency, XtRBoolean, sizeof(Boolean),
	    Offset(wm.urgency), XtRImmediate, (XtPointer) False}
};

static void WMInitialize(Widget, Widget, ArgList, Cardinal *);
static Boolean WMSetValues(Widget, Widget, Widget, ArgList, Cardinal *);
static void WMDestroy(Widget);

externaldef(wmshellclassrec) WMShellClassRec wmShellClassRec = {
  {
    /* superclass         */    (WidgetClass) &shellClassRec,
    /* class_name         */    "WMShell",
    /* size               */    sizeof(WMShellRec),
    /* Class Initializer  */	NULL,
    /* class_part_initialize*/	NULL,
    /* Class init'ed ?    */	FALSE,
    /* initialize         */    WMInitialize,
    /* initialize_notify    */	NULL,
    /* realize            */    XtInheritRealize,
    /* actions            */    NULL,
    /* num_actions        */    0,
    /* resources          */    wmResources,
    /* resource_count     */	XtNumber(wmResources),
    /* xrm_class          */    NULLQUARK,
    /* compress_motion    */    FALSE,
    /* compress_exposure  */    TRUE,
    /* compress_enterleave*/	FALSE,
    /* visible_interest   */    FALSE,
    /* destroy            */    WMDestroy,
    /* resize             */    XtInheritResize,
    /* expose             */    NULL,
    /* set_values         */    WMSetValues,
    /* set_values_hook      */	NULL,
    /* set_values_almost    */	XtInheritSetValuesAlmost,
    /* get_values_hook      */	NULL,
    /* accept_focus       */    NULL,
    /* intrinsics version */	XtVersion,
    /* callback offsets   */    NULL,
    /* tm_table		    */  NULL,
    /* query_geometry	    */  NULL,
    /* display_accelerator  */  NULL,
    /* extension	    */  NULL
  },{
    /* geometry_manager   */    XtInheritGeometryManager,
    /* change_managed     */    XtInheritChangeManaged,
    /* insert_child	  */	XtInheritInsertChild,
    /* delete_child	  */	XtInheritDeleteChild,
    /* extension	    */  NULL
  },{
    /* extension	    */  NULL
  },{
    /* extension	    */  NULL
  }
};

externaldef(wmshellwidgetclass) WidgetClass wmShellWidgetClass = (WidgetClass) (&wmShellClassRec);

/***************************************************************************
 *
 * TransientShell class record
 *
 ***************************************************************************/

#undef Offset
#define Offset(x)	(XtOffsetOf(TransientShellRec, x))

static XtResource transientResources[]=
{
	{ XtNtransient, XtCTransient, XtRBoolean, sizeof(Boolean),
	    Offset(wm.transient), XtRImmediate, (XtPointer)True},
	{ XtNtransientFor, XtCTransientFor, XtRWidget, sizeof(Widget),
	    Offset(transient.transient_for), XtRWidget, NULL},
	{ XtNsaveUnder, XtCSaveUnder, XtRBoolean, sizeof(Boolean),
	    Offset(shell.save_under), XtRImmediate, (XtPointer)True},
};

static void TransientRealize(Widget, Mask *, XSetWindowAttributes *);
static Boolean TransientSetValues(Widget, Widget, Widget, ArgList, Cardinal *);

externaldef(transientshellclassrec) TransientShellClassRec transientShellClassRec = {
  {
    /* superclass	  */	(WidgetClass) &vendorShellClassRec,
    /* class_name	  */	"TransientShell",
    /* size		  */	sizeof(TransientShellRec),
    /* Class Initializer  */	NULL,
    /* class_part_initialize*/	NULL,
    /* Class init'ed ?	  */	FALSE,
    /* initialize	  */	NULL,
    /* initialize_notify  */	NULL,
    /* realize		  */	TransientRealize,
    /* actions		  */	NULL,
    /* num_actions	  */	0,
    /* resources	  */	transientResources,
    /* resource_count	  */	XtNumber(transientResources),
    /* xrm_class	  */	NULLQUARK,
    /* compress_motion	  */	FALSE,
    /* compress_exposure  */	TRUE,
    /* compress_enterleave*/	FALSE,
    /* visible_interest	  */	FALSE,
    /* destroy		  */	NULL,
    /* resize		  */	XtInheritResize,
    /* expose		  */	NULL,
    /* set_values	  */	TransientSetValues,
    /* set_values_hook	  */	NULL,
    /* set_values_almost  */	XtInheritSetValuesAlmost,
    /* get_values_hook	  */	NULL,
    /* accept_focus	  */	NULL,
    /* intrinsics version */	XtVersion,
    /* callback offsets	  */	NULL,
    /* tm_table		  */	XtInheritTranslations,
    /* query_geometry	  */	NULL,
    /* display_accelerator*/	NULL,
    /* extension	  */	NULL
  },{
    /* geometry_manager	  */	XtInheritGeometryManager,
    /* change_managed	  */	XtInheritChangeManaged,
    /* insert_child	  */	XtInheritInsertChild,
    /* delete_child	  */	XtInheritDeleteChild,
    /* extension	  */	NULL
  },{
    /* extension	  */	NULL
  },{
    /* extension	  */	NULL
  },{
    /* extension	  */	NULL
  },{
    /* extension	  */	NULL
  }
};

externaldef(transientshellwidgetclass) WidgetClass transientShellWidgetClass =
	(WidgetClass) (&transientShellClassRec);

/***************************************************************************
 *
 * TopLevelShell class record
 *
 ***************************************************************************/

#undef Offset
#define Offset(x)	(XtOffsetOf(TopLevelShellRec, x))

static XtResource topLevelResources[]=
{
	{ XtNiconName, XtCIconName, XtRString, sizeof(String),
	    Offset(topLevel.icon_name), XtRString, (XtPointer) NULL},
	{ XtNiconNameEncoding, XtCIconNameEncoding, XtRAtom, sizeof(Atom),
	    Offset(topLevel.icon_name_encoding),
	    XtRCallProc, (XtPointer) _XtTitleEncoding},
	{ XtNiconic, XtCIconic, XtRBoolean, sizeof(Boolean),
	    Offset(topLevel.iconic), XtRImmediate, (XtPointer)False}
};

static void TopLevelInitialize(Widget, Widget, ArgList, Cardinal *);
static Boolean TopLevelSetValues(Widget, Widget, Widget, ArgList, Cardinal *);
static void TopLevelDestroy(Widget);

externaldef(toplevelshellclassrec) TopLevelShellClassRec topLevelShellClassRec = {
  {
    /* superclass         */    (WidgetClass) &vendorShellClassRec,
    /* class_name         */    "TopLevelShell",
    /* size               */    sizeof(TopLevelShellRec),
    /* Class Initializer  */	NULL,
    /* class_part_initialize*/	NULL,
    /* Class init'ed ?    */	FALSE,
    /* initialize         */    TopLevelInitialize,
    /* initialize_notify    */	NULL,
    /* realize            */    XtInheritRealize,
    /* actions            */    NULL,
    /* num_actions        */    0,
    /* resources          */    topLevelResources,
    /* resource_count     */	XtNumber(topLevelResources),
    /* xrm_class          */    NULLQUARK,
    /* compress_motion    */    FALSE,
    /* compress_exposure  */    TRUE,
    /* compress_enterleave*/ 	FALSE,
    /* visible_interest   */    FALSE,
    /* destroy            */    TopLevelDestroy,
    /* resize             */    XtInheritResize,
    /* expose             */    NULL,
    /* set_values         */    TopLevelSetValues,
    /* set_values_hook      */	NULL,
    /* set_values_almost    */	XtInheritSetValuesAlmost,
    /* get_values_hook      */	NULL,
    /* accept_focus       */    NULL,
    /* intrinsics version */	XtVersion,
    /* callback offsets   */    NULL,
    /* tm_table		    */  XtInheritTranslations,
    /* query_geometry	    */  NULL,
    /* display_accelerator  */  NULL,
    /* extension	    */  NULL
  },{
    /* geometry_manager   */    XtInheritGeometryManager,
    /* change_managed     */    XtInheritChangeManaged,
    /* insert_child	  */	XtInheritInsertChild,
    /* delete_child	  */	XtInheritDeleteChild,
    /* extension	    */  NULL
  },{
    /* extension	    */  NULL
  },{
    /* extension	    */  NULL
  },{
    /* extension	    */  NULL
  },{
    /* extension	    */  NULL
  }
};

externaldef(toplevelshellwidgetclass) WidgetClass topLevelShellWidgetClass =
	(WidgetClass) (&topLevelShellClassRec);

/***************************************************************************
 *
 * ApplicationShell class record
 *
 ***************************************************************************/

#undef Offset
#define Offset(x)	(XtOffsetOf(ApplicationShellRec, x))

static XtResource applicationResources[]=
{
    {XtNargc, XtCArgc, XtRInt, sizeof(int),
	  Offset(application.argc), XtRImmediate, (XtPointer)0},
    {XtNargv, XtCArgv, XtRStringArray, sizeof(String*),
	  Offset(application.argv), XtRPointer, (XtPointer) NULL}
};
#undef Offset

static void ApplicationInitialize(Widget, Widget, ArgList, Cardinal *);
static void ApplicationDestroy(Widget);
static Boolean ApplicationSetValues(Widget, Widget, Widget, ArgList, Cardinal *);
static void ApplicationShellInsertChild(Widget);

static CompositeClassExtensionRec compositeClassExtension = {
    /* next_extension	*/	NULL,
    /* record_type	*/	NULLQUARK,
    /* version		*/	XtCompositeExtensionVersion,
    /* record_size	*/	sizeof(CompositeClassExtensionRec),
    /* accepts_objects	*/	TRUE,
    /* allows_change_managed_set */ FALSE
};


externaldef(applicationshellclassrec) ApplicationShellClassRec applicationShellClassRec = {
  {
    /* superclass         */    (WidgetClass) &topLevelShellClassRec,
    /* class_name         */    "ApplicationShell",
    /* size               */    sizeof(ApplicationShellRec),
    /* Class Initializer  */	NULL,
    /* class_part_initialize*/	NULL,
    /* Class init'ed ?    */	FALSE,
    /* initialize         */    ApplicationInitialize,
    /* initialize_notify  */	NULL,
    /* realize            */    XtInheritRealize,
    /* actions            */    NULL,
    /* num_actions        */    0,
    /* resources          */    applicationResources,
    /* resource_count     */	XtNumber(applicationResources),
    /* xrm_class          */    NULLQUARK,
    /* compress_motion    */    FALSE,
    /* compress_exposure  */    TRUE,
    /* compress_enterleave*/    FALSE,
    /* visible_interest   */    FALSE,
    /* destroy            */    ApplicationDestroy,
    /* resize             */    XtInheritResize,
    /* expose             */    NULL,
    /* set_values         */    ApplicationSetValues,
    /* set_values_hook    */	NULL,
    /* set_values_almost  */	XtInheritSetValuesAlmost,
    /* get_values_hook    */	NULL,
    /* accept_focus       */    NULL,
    /* intrinsics version */	XtVersion,
    /* callback offsets   */    NULL,
    /* tm_table		  */	XtInheritTranslations,
    /* query_geometry	  */	NULL,
    /* display_accelerator*/	NULL,
    /* extension	  */	NULL
  },{
    /* geometry_manager   */    XtInheritGeometryManager,
    /* change_managed     */    XtInheritChangeManaged,
    /* insert_child	  */	ApplicationShellInsertChild,
    /* delete_child	  */	XtInheritDeleteChild,
    /* extension	  */	(XtPointer)&compositeClassExtension
  },{
    /* extension	  */	NULL
  },{
    /* extension	  */	NULL
  },{
    /* extension	  */	NULL
  },{
    /* extension	  */	NULL
  },{
    /* extension	  */	NULL
  }
};

externaldef(applicationshellwidgetclass) WidgetClass applicationShellWidgetClass =
	(WidgetClass) (&applicationShellClassRec);

/***************************************************************************
 *
 * SessionShell class record
 *
 ***************************************************************************/

#undef Offset
#define Offset(x)	(XtOffsetOf(SessionShellRec, x))

static XtResource sessionResources[]=
{
#ifndef XT_NO_SM
 {XtNconnection, XtCConnection, XtRSmcConn, sizeof(SmcConn),
       Offset(session.connection), XtRSmcConn, (XtPointer) NULL},
#endif
 {XtNsessionID, XtCSessionID, XtRString, sizeof(String),
       Offset(session.session_id), XtRString, (XtPointer) NULL},
 {XtNrestartCommand, XtCRestartCommand, XtRCommandArgArray, sizeof(String*),
       Offset(session.restart_command), XtRPointer, (XtPointer) NULL},
 {XtNcloneCommand, XtCCloneCommand, XtRCommandArgArray, sizeof(String*),
       Offset(session.clone_command), XtRPointer, (XtPointer) NULL},
 {XtNdiscardCommand, XtCDiscardCommand, XtRCommandArgArray, sizeof(String*),
       Offset(session.discard_command), XtRPointer, (XtPointer) NULL},
 {XtNresignCommand, XtCResignCommand, XtRCommandArgArray, sizeof(String*),
       Offset(session.resign_command), XtRPointer, (XtPointer) NULL},
 {XtNshutdownCommand, XtCShutdownCommand, XtRCommandArgArray, sizeof(String*),
       Offset(session.shutdown_command), XtRPointer, (XtPointer) NULL},
 {XtNenvironment, XtCEnvironment, XtREnvironmentArray, sizeof(String*),
       Offset(session.environment), XtRPointer, (XtPointer) NULL},
 {XtNcurrentDirectory, XtCCurrentDirectory, XtRDirectoryString, sizeof(String),
       Offset(session.current_dir), XtRString, (XtPointer) NULL},
 {XtNprogramPath, XtCProgramPath, XtRString, sizeof(String),
      Offset(session.program_path), XtRString, (XtPointer) NULL},
 {XtNrestartStyle, XtCRestartStyle, XtRRestartStyle, sizeof(unsigned char),
      Offset(session.restart_style), XtRImmediate,
      (XtPointer) SmRestartIfRunning},
 {XtNjoinSession, XtCJoinSession, XtRBoolean, sizeof(Boolean),
       Offset(session.join_session), XtRImmediate, (XtPointer) True},
 {XtNsaveCallback, XtCCallback, XtRCallback, sizeof(XtPointer),
       Offset(session.save_callbacks), XtRCallback, (XtPointer) NULL},
 {XtNinteractCallback, XtCCallback, XtRCallback, sizeof(XtPointer),
       Offset(session.interact_callbacks), XtRCallback, (XtPointer)NULL},
 {XtNcancelCallback, XtCCallback, XtRCallback, sizeof(XtPointer),
       Offset(session.cancel_callbacks), XtRCallback, (XtPointer) NULL},
 {XtNsaveCompleteCallback, XtCCallback, XtRCallback, sizeof(XtPointer),
       Offset(session.save_complete_callbacks), XtRCallback, (XtPointer) NULL},
 {XtNdieCallback, XtCCallback, XtRCallback, sizeof(XtPointer),
       Offset(session.die_callbacks), XtRCallback, (XtPointer) NULL},
 {XtNerrorCallback, XtCCallback, XtRCallback, sizeof(XtPointer),
       Offset(session.error_callbacks), XtRCallback, (XtPointer) NULL}
};
#undef Offset

static void SessionInitialize(Widget, Widget, ArgList, Cardinal *);
static void SessionDestroy(Widget);
static Boolean SessionSetValues(Widget, Widget, Widget, ArgList, Cardinal *);

static CompositeClassExtensionRec sessionCompositeClassExtension = {
    /* next_extension	*/	NULL,
    /* record_type	*/	NULLQUARK,
    /* version		*/	XtCompositeExtensionVersion,
    /* record_size	*/	sizeof(CompositeClassExtensionRec),
    /* accepts_objects	*/	TRUE,
    /* allows_change_managed_set */ FALSE
};


externaldef(sessionshellclassrec) SessionShellClassRec sessionShellClassRec = {
  {
    /* superclass         */    (WidgetClass) &applicationShellClassRec,
    /* class_name         */    "SessionShell",
    /* size               */    sizeof(SessionShellRec),
    /* Class Initializer  */	NULL,
    /* class_part_initialize*/	NULL,
    /* Class init'ed ?    */	FALSE,
    /* initialize         */    SessionInitialize,
    /* initialize_notify  */	NULL,
    /* realize            */    XtInheritRealize,
    /* actions            */    NULL,
    /* num_actions        */    0,
    /* resources          */    sessionResources,
    /* resource_count     */	XtNumber(sessionResources),
    /* xrm_class          */    NULLQUARK,
    /* compress_motion    */    FALSE,
    /* compress_exposure  */    TRUE,
    /* compress_enterleave*/    FALSE,
    /* visible_interest   */    FALSE,
    /* destroy            */    SessionDestroy,
    /* resize             */    XtInheritResize,
    /* expose             */    NULL,
    /* set_values         */    SessionSetValues,
    /* set_values_hook    */	NULL,
    /* set_values_almost  */	XtInheritSetValuesAlmost,
    /* get_values_hook    */	NULL,
    /* accept_focus       */    NULL,
    /* intrinsics version */	XtVersion,
    /* callback offsets   */    NULL,
    /* tm_table		  */	XtInheritTranslations,
    /* query_geometry	  */	NULL,
    /* display_accelerator*/	NULL,
    /* extension	  */	NULL
  },{
    /* geometry_manager   */    XtInheritGeometryManager,
    /* change_managed     */    XtInheritChangeManaged,
    /* insert_child	  */	XtInheritInsertChild,
    /* delete_child	  */	XtInheritDeleteChild,
    /* extension	  */	(XtPointer)&sessionCompositeClassExtension
  },{
    /* extension	  */	NULL
  },{
    /* extension	  */	NULL
  },{
    /* extension	  */	NULL
  },{
    /* extension	  */	NULL
  },{
    /* extension	  */	NULL
  },{
    /* extension          */    NULL
  }
};

externaldef(sessionshellwidgetclass) WidgetClass sessionShellWidgetClass =
	(WidgetClass) (&sessionShellClassRec);

/****************************************************************************
 * Whew!
 ****************************************************************************/

static void ComputeWMSizeHints(
    WMShellWidget w,
    XSizeHints *hints)
{
    register long flags;
    hints->flags = flags = w->wm.size_hints.flags;
#define copy(field) hints->field = w->wm.size_hints.field
    if (flags & (USPosition | PPosition)) {
	copy(x);
	copy(y);
    }
    if (flags & (USSize | PSize)) {
	copy(width);
	copy(height);
    }
    if (flags & PMinSize) {
	copy(min_width);
	copy(min_height);
    }
    if (flags & PMaxSize) {
	copy(max_width);
	copy(max_height);
    }
    if (flags & PResizeInc) {
	copy(width_inc);
	copy(height_inc);
    }
    if (flags & PAspect) {
	copy(min_aspect.x);
	copy(min_aspect.y);
	copy(max_aspect.x);
	copy(max_aspect.y);
    }
#undef copy
#define copy(field) hints->field = w->wm.field
    if (flags & PBaseSize) {
	copy(base_width);
	copy(base_height);
    }
    if (flags & PWinGravity)
	copy(win_gravity);
#undef copy
}

static void _SetWMSizeHints(
    WMShellWidget w)
{
    XSizeHints *size_hints = XAllocSizeHints();

    if (size_hints == NULL) _XtAllocError("XAllocSizeHints");
    ComputeWMSizeHints(w, size_hints);
    XSetWMNormalHints(XtDisplay((Widget)w), XtWindow((Widget)w), size_hints);
    XFree((char*)size_hints);
}

static ShellClassExtension _FindClassExtension(
    WidgetClass widget_class)
{
    ShellClassExtension ext;
    for (ext = (ShellClassExtension)((ShellWidgetClass)widget_class)
	       ->shell_class.extension;
	 ext != NULL && ext->record_type != NULLQUARK;
	 ext = (ShellClassExtension)ext->next_extension);

    if (ext != NULL) {
	if (  ext->version == XtShellExtensionVersion
	      && ext->record_size == sizeof(ShellClassExtensionRec)) {
	    /* continue */
	} else {
	    String params[1];
	    Cardinal num_params = 1;
	    params[0] = widget_class->core_class.class_name;
	    XtErrorMsg( "invalidExtension", "shellClassPartInitialize",
		        XtCXtToolkitError,
		 "widget class %s has invalid ShellClassExtension record",
		 params, &num_params);
	}
    }
    return ext;
}

static void ClassPartInitialize(WidgetClass widget_class)
{
    ShellClassExtension ext = _FindClassExtension(widget_class);
    if (ext != NULL) {
	if (ext->root_geometry_manager == XtInheritRootGeometryManager) {
	    ext->root_geometry_manager =
		_FindClassExtension(widget_class->core_class.superclass)
		    ->root_geometry_manager;
	}
    } else {
	/* if not found, spec requires XtInheritRootGeometryManager */
	XtPointer *extP
	    = &((ShellWidgetClass)widget_class)->shell_class.extension;
	ext = XtNew(ShellClassExtensionRec);
	(void) memmove((char*)ext,
		       (char*)_FindClassExtension(widget_class->core_class.superclass),
		       sizeof(ShellClassExtensionRec));
	ext->next_extension = *extP;
	*extP = (XtPointer)ext;
    }
}


static void EventHandler(Widget wid, XtPointer closure, XEvent *event, Boolean *continue_to_dispatch);
static void _popup_set_prop(ShellWidget);


/*ARGSUSED*/
static void XtCopyDefaultDepth(
    Widget      widget,
    int		offset,
    XrmValue    *value)
{
    value->addr = (XPointer)(&DefaultDepthOfScreen(XtScreenOfObject(widget)));
}

#ifndef CRAY
static
#endif
void _XtShellDepth(
    Widget widget,
    int closure,
    XrmValue *value)
{
   if (widget->core.parent == NULL) XtCopyDefaultDepth(widget,closure,value);
   else _XtCopyFromParent (widget,closure,value);
}

/*ARGSUSED*/
static void XtCopyDefaultColormap(
    Widget      widget,
    int		offset,
    XrmValue    *value)
{
    value->addr = (XPointer)(&DefaultColormapOfScreen(XtScreenOfObject(widget)));
}

#ifndef CRAY
static
#endif
void _XtShellColormap(
    Widget widget,
    int closure,
    XrmValue *value)
{
   if (widget->core.parent == NULL)
	   XtCopyDefaultColormap(widget,closure,value);
   else _XtCopyFromParent (widget,closure,value);
}

#ifndef CRAY
static
#endif
void _XtShellAncestorSensitive(
    Widget widget,
    int closure,
    XrmValue *value)
{
   static Boolean true = True;
   if (widget->core.parent == NULL) value->addr = (XPointer)(&true);
   else _XtCopyFromParent (widget,closure,value);
}

/*ARGSUSED*/
#ifndef CRAY
static
#endif
void _XtTitleEncoding(
    Widget widget,
    int offset,
    XrmValue *value)
{
    static Atom atom;
    if (XtWidgetToApplicationContext(widget)->langProcRec.proc) atom = None;
    else atom = XA_STRING;
    value->addr = (XPointer) &atom;
}


/* ARGSUSED */
static void Initialize(
	Widget req,
	Widget new,
	ArgList args,		/* unused */
	Cardinal *num_args)	/* unused */
{
	ShellWidget w = (ShellWidget) new;

	w->shell.popped_up = FALSE;
	w->shell.client_specified =
	    _XtShellNotReparented | _XtShellPositionValid;

	if (w->core.x == BIGSIZE) {
	    w->core.x = 0;
	    if (w->core.y == BIGSIZE) w->core.y = 0;
	} else {
	    if (w->core.y == BIGSIZE) w->core.y = 0;
	    else w->shell.client_specified |= _XtShellPPositionOK;
	}

	XtAddEventHandler(new, (EventMask) StructureNotifyMask,
		TRUE, EventHandler, (XtPointer) NULL);

#ifdef EDITRES
	XtAddEventHandler(new, (EventMask) 0, TRUE,
			  _XEditResCheckMessages, NULL);
#endif
}

/* ARGSUSED */
static void WMInitialize(
	Widget req, Widget new,
	ArgList args,		/* unused */
	Cardinal *num_args)	/* unused */
{
	WMShellWidget w = (WMShellWidget) new;
	TopLevelShellWidget tls = (TopLevelShellWidget) new;	/* maybe */

	if(w->wm.title == NULL) {
	    if (XtIsTopLevelShell(new) &&
		    tls->topLevel.icon_name != NULL &&
		    strlen(tls->topLevel.icon_name) != 0) {
		w->wm.title = XtNewString(tls->topLevel.icon_name);
	    } else {
		w->wm.title = XtNewString(w->core.name);
	    }
	} else {
	    w->wm.title = XtNewString(w->wm.title);
	}
	w->wm.size_hints.flags = 0;
	w->wm.wm_hints.flags = 0;
	if (w->wm.window_role)
	    w->wm.window_role = XtNewString(w->wm.window_role);
}


/* ARGSUSED */
static void TopLevelInitialize(
	Widget req, Widget new,
	ArgList args,		/* unused */
	Cardinal *num_args)	/* unused */
{
	TopLevelShellWidget w = (TopLevelShellWidget) new;

	if (w->topLevel.icon_name == NULL) {
	    w->topLevel.icon_name = XtNewString(w->core.name);
	} else {
	    w->topLevel.icon_name = XtNewString(w->topLevel.icon_name);
	}

	if (w->topLevel.iconic)
	    w->wm.wm_hints.initial_state = IconicState;
}

static String *NewArgv(int, String *);
static String *NewStringArray(String *);
static void FreeStringArray(String *);

/* ARGSUSED */
static void ApplicationInitialize(
    Widget req, Widget new,
    ArgList args,		/* unused */
    Cardinal *num_args)		/* unused */
{
    ApplicationShellWidget w = (ApplicationShellWidget)new;

    if (w->application.argc > 0)
	w->application.argv = NewArgv(w->application.argc,
				      w->application.argv);
}

#define XtSaveInactive 0
#define XtSaveActive   1
#define XtInteractPending    2
#define XtInteractActive     3

#define XtCloneCommandMask	(1L<<0)
#define XtCurrentDirectoryMask	(1L<<1)
#define XtDiscardCommandMask	(1L<<2)
#define XtEnvironmentMask	(1L<<3)
#define XtProgramMask		(1L<<4)
#define XtResignCommandMask	(1L<<5)
#define XtRestartCommandMask	(1L<<6)
#define XtRestartStyleHintMask	(1L<<7)
#define XtShutdownCommandMask	(1L<<8)

static void JoinSession(SessionShellWidget);
static void SetSessionProperties(SessionShellWidget, Boolean, unsigned long, unsigned long);
static void StopManagingSession(SessionShellWidget, SmcConn);

typedef struct _XtSaveYourselfRec {
    XtSaveYourself next;
    int            save_type;
    int            interact_style;
    Boolean        shutdown;
    Boolean        fast;
    Boolean        cancel_shutdown;
    int		   phase;
    int            interact_dialog_type;
    Boolean	   request_cancel;
    Boolean	   request_next_phase;
    Boolean        save_success;
    int            save_tokens;
    int            interact_tokens;
} XtSaveYourselfRec;

/* ARGSUSED */
static void SessionInitialize(
    Widget req, Widget new,
    ArgList args,		/* unused */
    Cardinal *num_args)		/* unused */
{
#ifndef XT_NO_SM
    SessionShellWidget w = (SessionShellWidget)new;

    if (w->session.session_id) w->session.session_id =
	XtNewString(w->session.session_id);
    if (w->session.restart_command) w->session.restart_command =
	NewStringArray(w->session.restart_command);
    if (w->session.clone_command) w->session.clone_command =
	NewStringArray(w->session.clone_command);
    if (w->session.discard_command) w->session.discard_command =
	NewStringArray(w->session.discard_command);
    if (w->session.resign_command) w->session.resign_command =
	NewStringArray(w->session.resign_command);
    if (w->session.shutdown_command) w->session.shutdown_command =
	NewStringArray(w->session.shutdown_command);
    if (w->session.environment) w->session.environment =
	NewStringArray(w->session.environment);
    if (w->session.current_dir) w->session.current_dir =
	XtNewString(w->session.current_dir);
    if (w->session.program_path) w->session.program_path =
	XtNewString(w->session.program_path);

    w->session.checkpoint_state = XtSaveInactive;
    w->session.input_id = 0;
    w->session.save = NULL;

    if ((w->session.join_session) &&
	(w->application.argv || w->session.restart_command))
	JoinSession(w);

    if (w->session.connection)
	SetSessionProperties(w, True, 0L, 0L);
#endif /* !XT_NO_SM */
}

static void Resize(
    Widget w)
{
    register ShellWidget sw = (ShellWidget)w;
    Widget childwid;
    Cardinal i;
    for(i = 0; i < sw->composite.num_children; i++) {
        if (XtIsManaged(sw->composite.children[i])) {
             childwid = sw->composite.children[i];
             XtResizeWidget(childwid, sw->core.width, sw->core.height,
                           childwid->core.border_width);
	     break;		/* can only be one managed child */
        }
    }
}

static void GetGeometry(Widget, Widget);

static void Realize(
	Widget wid,
	Mask *vmask,
	XSetWindowAttributes *attr)
{
	ShellWidget w = (ShellWidget) wid;
        Mask mask = *vmask;

	if (! (w->shell.client_specified & _XtShellGeometryParsed)) {
	    /* we'll get here only if there was no child the first
	       time we were realized.  If the shell was Unrealized
	       and then re-Realized, we probably don't want to
	       re-evaluate the defaults anyway.
	     */
	    GetGeometry(wid, (Widget)NULL);
	}
	else if (w->core.background_pixmap == XtUnspecifiedPixmap) {
	    /* I attempt to inherit my child's background to avoid screen flash
	     * if there is latency between when I get resized and when my child
	     * is resized.  Background=None is not satisfactory, as I want the
	     * user to get immediate feedback on the new dimensions (most
	     * particularly in the case of a non-reparenting wm).  It is
	     * especially important to have the server clear any old cruft
	     * from the display when I am resized larger.
	     */
	    register Widget *childP = w->composite.children;
	    int i;
	    for (i = w->composite.num_children; i; i--, childP++) {
		if (XtIsWidget(*childP) && XtIsManaged(*childP)) {
		    if ((*childP)->core.background_pixmap
			    != XtUnspecifiedPixmap) {
			mask &= ~(CWBackPixel);
			mask |= CWBackPixmap;
			attr->background_pixmap =
			    w->core.background_pixmap =
				(*childP)->core.background_pixmap;
		    } else {
			attr->background_pixel =
			    w->core.background_pixel =
				(*childP)->core.background_pixel;
		    }
		    break;
		}
	    }
	}

	if(w->shell.save_under) {
		mask |= CWSaveUnder;
		attr->save_under = TRUE;
	}
	if(w->shell.override_redirect) {
		mask |= CWOverrideRedirect;
		attr->override_redirect = TRUE;
	}
	if (wid->core.width == 0 || wid->core.height == 0) {
	    Cardinal count = 1;
	    XtErrorMsg("invalidDimension", "shellRealize", XtCXtToolkitError,
		       "Shell widget %s has zero width and/or height",
		       &wid->core.name, &count);
	}
	wid->core.window = XCreateWindow(XtDisplay(wid),
		wid->core.screen->root, (int)wid->core.x, (int)wid->core.y,
		(unsigned int)wid->core.width, (unsigned int)wid->core.height,
		(unsigned int)wid->core.border_width, (int) wid->core.depth,
		(unsigned int) InputOutput, w->shell.visual,
		mask, attr);

	_popup_set_prop(w);
}


static void _SetTransientForHint(
     TransientShellWidget w,
     Boolean delete)
{
    Window window_group;

    if (w->wm.transient) {
	if (w->transient.transient_for != NULL
	    && XtIsRealized(w->transient.transient_for))
	    window_group = XtWindow(w->transient.transient_for);
	else if ((window_group = w->wm.wm_hints.window_group)
		 == XtUnspecifiedWindowGroup) {
	    if (delete)
		XDeleteProperty( XtDisplay((Widget)w),
				 XtWindow((Widget)w),
				 XA_WM_TRANSIENT_FOR
				);
	    return;
	}

	XSetTransientForHint( XtDisplay((Widget)w),
			      XtWindow((Widget)w),
			      window_group
			     );
    }
}


static void TransientRealize(
     Widget w,
     Mask *vmask,
     XSetWindowAttributes *attr)
{
    XtRealizeProc realize;

    LOCK_PROCESS;
    realize =
	transientShellWidgetClass->core_class.superclass->core_class.realize;
    UNLOCK_PROCESS;
    (*realize) (w, vmask, attr);

    _SetTransientForHint((TransientShellWidget)w, False);
}

static Widget GetClientLeader(
    Widget w)
{
    while ((! XtIsWMShell(w) || ! ((WMShellWidget)w)->wm.client_leader)
	   && w->core.parent)
	w = w->core.parent;

    /* ASSERT: w is a WMshell with client_leader set, or w has no parent */

    if (XtIsWMShell(w) && ((WMShellWidget)w)->wm.client_leader)
	w = ((WMShellWidget)w)->wm.client_leader;
    return w;
}

static void EvaluateWMHints(
    WMShellWidget w)
{
	XWMHints *hintp = &w->wm.wm_hints;

	hintp->flags = StateHint | InputHint;

	if (hintp->icon_x == XtUnspecifiedShellInt)
	    hintp->icon_x = -1;
	else
	    hintp->flags |= IconPositionHint;

	if (hintp->icon_y == XtUnspecifiedShellInt)
	    hintp->icon_y = -1;
	else
	    hintp->flags |= IconPositionHint;

	if (hintp->icon_pixmap != None) hintp->flags |= IconPixmapHint;
	if (hintp->icon_mask != None)   hintp->flags |= IconMaskHint;
	if (hintp->icon_window != None) hintp->flags |= IconWindowHint;

	if (hintp->window_group == XtUnspecifiedWindow) {
	    if(w->core.parent) {
		Widget p;
		for (p = w->core.parent; p->core.parent; p = p->core.parent);
		if (XtIsRealized(p)) {
		    hintp->window_group = XtWindow(p);
		    hintp->flags |=  WindowGroupHint;
		}
	    }
	} else if (hintp->window_group != XtUnspecifiedWindowGroup)
	    hintp->flags |=  WindowGroupHint;

	if (w->wm.urgency) hintp->flags |= XUrgencyHint;
}


static void EvaluateSizeHints(
    WMShellWidget w)
{
	struct _OldXSizeHints *sizep = &w->wm.size_hints;

	sizep->x = w->core.x;
	sizep->y = w->core.y;
	sizep->width = w->core.width;
	sizep->height = w->core.height;

	if (sizep->flags & USSize) {
	    if (sizep->flags & PSize) sizep->flags &= ~PSize;
	} else
	    sizep->flags |= PSize;

	if (sizep->flags & USPosition) {
	    if (sizep->flags & PPosition) sizep->flags &= ~PPosition;
	} else if (w->shell.client_specified & _XtShellPPositionOK)
	    sizep->flags |= PPosition;

	if (sizep->min_aspect.x != XtUnspecifiedShellInt
	    || sizep->min_aspect.y != XtUnspecifiedShellInt
	    || sizep->max_aspect.x != XtUnspecifiedShellInt
	    || sizep->max_aspect.y != XtUnspecifiedShellInt) {
	    sizep->flags |= PAspect;
	}
	if (sizep->flags & PBaseSize
	    || w->wm.base_width != XtUnspecifiedShellInt
	    || w->wm.base_height != XtUnspecifiedShellInt) {
	    sizep->flags |= PBaseSize;
	    if (w->wm.base_width == XtUnspecifiedShellInt)
		w->wm.base_width = 0;
	    if (w->wm.base_height == XtUnspecifiedShellInt)
		w->wm.base_height = 0;
	}
	if (sizep->flags & PResizeInc
	    || sizep->width_inc != XtUnspecifiedShellInt
	    || sizep->height_inc != XtUnspecifiedShellInt) {
	    if (sizep->width_inc < 1) sizep->width_inc = 1;
	    if (sizep->height_inc < 1) sizep->height_inc = 1;
	    sizep->flags |= PResizeInc;
	}
	if (sizep->flags & PMaxSize
	    || sizep->max_width != XtUnspecifiedShellInt
	    || sizep->max_height != XtUnspecifiedShellInt) {
	    sizep->flags |= PMaxSize;
	    if (sizep->max_width == XtUnspecifiedShellInt)
		sizep->max_width = BIGSIZE;
	    if (sizep->max_height == XtUnspecifiedShellInt)
		sizep->max_height = BIGSIZE;
	}
	if (sizep->flags & PMinSize
	    || sizep->min_width != XtUnspecifiedShellInt
	    || sizep->min_height != XtUnspecifiedShellInt) {
	    sizep->flags |= PMinSize;
	    if (sizep->min_width == XtUnspecifiedShellInt)
		sizep->min_width = 1;
	    if (sizep->min_height == XtUnspecifiedShellInt)
		sizep->min_height = 1;
	}
}

static void _popup_set_prop(
	ShellWidget w)
{
	Widget p;
	WMShellWidget wmshell = (WMShellWidget) w;
	TopLevelShellWidget tlshell = (TopLevelShellWidget) w;
	ApplicationShellWidget appshell = (ApplicationShellWidget) w;
	XTextProperty icon_name;
	XTextProperty window_name;
	char **argv;
	int argc;
	XSizeHints *size_hints;
	Window window_group;
	XClassHint classhint;
	Boolean copied_iname, copied_wname;

	if (!XtIsWMShell((Widget)w) || w->shell.override_redirect) return;

	if ((size_hints = XAllocSizeHints()) == NULL)
	    _XtAllocError("XAllocSizeHints");

	copied_iname = copied_wname = False;
        if (wmshell->wm.title_encoding == None &&
	    XmbTextListToTextProperty(XtDisplay((Widget)w),
				      (char**)&wmshell->wm.title,
				      1, XStdICCTextStyle,
				      &window_name) >= Success) {
	    copied_wname = True;
	} else {
	    window_name.value = (unsigned char*)wmshell->wm.title;
	    window_name.encoding = wmshell->wm.title_encoding ?
		wmshell->wm.title_encoding : XA_STRING;
	    window_name.format = 8;
	    window_name.nitems = strlen((char *)window_name.value);
	}

	if (XtIsTopLevelShell((Widget)w)) {
            if (tlshell->topLevel.icon_name_encoding == None &&
		XmbTextListToTextProperty(XtDisplay((Widget)w),
					  (char**)&tlshell->topLevel.icon_name,
					  1, XStdICCTextStyle,
					  &icon_name) >= Success) {
		copied_iname = True;
	    } else {
		icon_name.value = (unsigned char*)tlshell->topLevel.icon_name;
		icon_name.encoding = tlshell->topLevel.icon_name_encoding ?
		    tlshell->topLevel.icon_name_encoding : XA_STRING;
		icon_name.format = 8;
		icon_name.nitems = strlen((char *)icon_name.value);
	    }
	}

	EvaluateWMHints(wmshell);
	EvaluateSizeHints(wmshell);
	ComputeWMSizeHints(wmshell, size_hints);

	if (wmshell->wm.transient
	    && !XtIsTransientShell((Widget)w)
	    && (window_group = wmshell->wm.wm_hints.window_group)
	       != XtUnspecifiedWindowGroup) {

	    XSetTransientForHint(XtDisplay((Widget)w),
				 XtWindow((Widget)w),
				 window_group
				 );
	}

	classhint.res_name = w->core.name;
	/* For the class, look up to the top of the tree */
	for (p = (Widget)w; p->core.parent != NULL; p = p->core.parent);
	if (XtIsApplicationShell(p)) {
	    classhint.res_class =
		((ApplicationShellWidget)p)->application.class;
	} else {
	    LOCK_PROCESS;
	    classhint.res_class = XtClass(p)->core_class.class_name;
	    UNLOCK_PROCESS;
	}

	if (XtIsApplicationShell((Widget)w)
	    && (argc = appshell->application.argc) != -1)
	    argv = (char**)appshell->application.argv;
	else {
	    argv = NULL;
	    argc = 0;
	}

	XSetWMProperties(XtDisplay((Widget)w), XtWindow((Widget)w),
			 &window_name,
			 (XtIsTopLevelShell((Widget)w)) ? &icon_name : NULL,
			 argv, argc,
			 size_hints,
			 &wmshell->wm.wm_hints,
			 &classhint);
	XFree((char*)size_hints);
	if (copied_wname)
	    XFree((XPointer)window_name.value);
	if (copied_iname)
	    XFree((XPointer)icon_name.value);

	LOCK_PROCESS;
	if (XtWidgetToApplicationContext((Widget)w)->langProcRec.proc) {
	    char *locale = setlocale(LC_CTYPE, (char *)NULL);
	    if (locale)
		XChangeProperty(XtDisplay((Widget)w), XtWindow((Widget)w),
				XInternAtom(XtDisplay((Widget)w),
					    "WM_LOCALE_NAME", False),
				XA_STRING, 8, PropModeReplace,
				(unsigned char *)locale, strlen(locale));
	}
	UNLOCK_PROCESS;

	p = GetClientLeader((Widget)w);
	if (XtWindow(p))
	    XChangeProperty(XtDisplay((Widget)w), XtWindow((Widget)w),
			    XInternAtom(XtDisplay((Widget)w),
					"WM_CLIENT_LEADER", False),
			    XA_WINDOW, 32, PropModeReplace,
			    (unsigned char *)(&(p->core.window)), 1);
#ifndef XT_NO_SM
	if (p == (Widget) w) {
	    for ( ; p->core.parent != NULL; p = p->core.parent);
	    if (XtIsSubclass(p, sessionShellWidgetClass)) {
		String sm_client_id =
		    ((SessionShellWidget)p)->session.session_id;
		if (sm_client_id != NULL) {
		    XChangeProperty(XtDisplay((Widget)w), XtWindow((Widget)w),
				    XInternAtom(XtDisplay((Widget)w),
						"SM_CLIENT_ID", False),
				    XA_STRING, 8, PropModeReplace,
				    (unsigned char *) sm_client_id,
				    strlen(sm_client_id));
		}
	    }
	}
#endif /* !XT_NO_SM */

	if (wmshell->wm.window_role)
	    XChangeProperty(XtDisplay((Widget)w), XtWindow((Widget)w),
			    XInternAtom(XtDisplay((Widget)w),
					"WM_WINDOW_ROLE", False),
			    XA_STRING, 8, PropModeReplace,
			    (unsigned char *)wmshell->wm.window_role,
			    strlen(wmshell->wm.window_role));
}

/* ARGSUSED */
static void EventHandler(
	Widget wid,
	XtPointer closure,	/* unused */
	XEvent *event,
        Boolean *continue_to_dispatch) /* unused */
{
	register ShellWidget w = (ShellWidget) wid;
	WMShellWidget wmshell = (WMShellWidget) w;
	Boolean  sizechanged = FALSE;

	if(w->core.window != event->xany.window) {
		XtAppErrorMsg(XtWidgetToApplicationContext(wid),
			"invalidWindow","eventHandler",XtCXtToolkitError,
                        "Event with wrong window",
			(String *)NULL, (Cardinal *)NULL);
		return;
	}

	switch(event->type) {
	    case ConfigureNotify:
	        if (w->core.window != event->xconfigure.window)
		    return;  /* in case of SubstructureNotify */
#define NEQ(x)	( w->core.x != event->xconfigure.x )
		if( NEQ(width) || NEQ(height) || NEQ(border_width) ) {
			sizechanged = TRUE;
#undef NEQ
			w->core.width = event->xconfigure.width;
			w->core.height = event->xconfigure.height;
			w->core.border_width = event->xconfigure.border_width;
		}
		if (event->xany.send_event /* ICCCM compliant synthetic ev */
		    /* || w->shell.override_redirect */
		    || w->shell.client_specified & _XtShellNotReparented)
	        {
		    w->core.x = event->xconfigure.x;
		    w->core.y = event->xconfigure.y;
		    w->shell.client_specified |= _XtShellPositionValid;
		}
		else w->shell.client_specified &= ~_XtShellPositionValid;
		if (XtIsWMShell(wid) && !wmshell->wm.wait_for_wm) {
		    /* Consider trusting the wm again */
		    register struct _OldXSizeHints *hintp
			= &wmshell->wm.size_hints;
#define EQ(x) (hintp->x == w->core.x)
		    if (EQ(x) && EQ(y) && EQ(width) && EQ(height)) {
			wmshell->wm.wait_for_wm = TRUE;
		    }
#undef EQ
		}
		break;

	      case ReparentNotify:
		if (event->xreparent.window == XtWindow(w)) {
		   if (event->xreparent.parent !=
		       RootWindowOfScreen(XtScreen(w)))
		       w->shell.client_specified &=
			   ~(_XtShellNotReparented | _XtShellPositionValid);
		   else {
		       w->core.x = event->xreparent.x;
		       w->core.y = event->xreparent.y;
		       w->shell.client_specified |=
			   (_XtShellNotReparented | _XtShellPositionValid);
		   }
	        }
		return;

              case MapNotify:
                if (XtIsTopLevelShell(wid)) {
                    ((TopLevelShellWidget)wid)->topLevel.iconic = FALSE;
                }
                return;

	      case UnmapNotify:
		{
		    XtPerDisplayInput	pdi;
		    XtDevice		device;
		    Widget		p;

                    if (XtIsTopLevelShell(wid))
                        ((TopLevelShellWidget)wid)->topLevel.iconic = TRUE;

		    pdi = _XtGetPerDisplayInput(event->xunmap.display);

		    device = &pdi->pointer;
		    if (device->grabType == XtPassiveServerGrab) {
			p = device->grab.widget;
			while (p && !(XtIsShell(p)))
			    p = p->core.parent;
			if (p == wid)
			    device->grabType = XtNoServerGrab;
		    }

		    device = &pdi->keyboard;
		    if (IsEitherPassiveGrab(device->grabType)) {
			p = device->grab.widget;
			while (p && !(XtIsShell(p)))
			    p = p->core.parent;
			if (p == wid) {
			    device->grabType = XtNoServerGrab;
			    pdi->activatingKey = 0;
			}
		    }

		    return;
		}
	      default:
		 return;
	}
	{
	XtWidgetProc resize;

	LOCK_PROCESS;
	resize = XtClass(wid)->core_class.resize;
	UNLOCK_PROCESS;

	if (sizechanged && resize) {
	    CALLGEOTAT(_XtGeoTrace((Widget)w,
			   "Shell \"%s\" is being resized to %d %d.\n",
			   XtName(wid), wid->core.width, wid->core.height ));
	    (*resize)(wid);
	 }
	}
}

static void Destroy(
	Widget wid)
{
	if (XtIsRealized(wid))
	    XDestroyWindow( XtDisplay(wid), XtWindow(wid) );
}

static void WMDestroy(
	Widget wid)
{
	WMShellWidget w = (WMShellWidget) wid;

	XtFree((char *) w->wm.title);
	XtFree((char *) w->wm.window_role);
}

static void TopLevelDestroy(
	Widget wid)
{
	TopLevelShellWidget w = (TopLevelShellWidget) wid;

	XtFree((char *) w->topLevel.icon_name);
}

static void ApplicationDestroy(
    Widget wid)
{
    ApplicationShellWidget w = (ApplicationShellWidget) wid;
    if (w->application.argc > 0)
	FreeStringArray(w->application.argv);
}

static void SessionDestroy(
    Widget wid)
{
#ifndef XT_NO_SM
    SessionShellWidget w = (SessionShellWidget) wid;

    StopManagingSession(w, w->session.connection);
    XtFree(w->session.session_id);
    FreeStringArray(w->session.restart_command);
    FreeStringArray(w->session.clone_command);
    FreeStringArray(w->session.discard_command);
    FreeStringArray(w->session.resign_command);
    FreeStringArray(w->session.shutdown_command);
    FreeStringArray(w->session.environment);
    XtFree(w->session.current_dir);
    XtFree(w->session.program_path);
#endif /* !XT_NO_SM */
}

/*
 * If the Shell has a width and a height which are zero, and as such
 * suspect, and it has not yet been realized then it will grow to
 * match the child before parsing the geometry resource.
 *
 */
static void GetGeometry(
    Widget W, Widget child)
{
    register ShellWidget w = (ShellWidget)W;
    Boolean is_wmshell = XtIsWMShell(W);
    int x, y, width, height, win_gravity = -1, flag;
    XSizeHints hints;

    if (child != NULL) {
	/* we default to our child's size */
	if (is_wmshell && (w->core.width == 0 || w->core.height == 0))
	    ((WMShellWidget)W)->wm.size_hints.flags |= PSize;
	if (w->core.width == 0)	    w->core.width = child->core.width;
	if (w->core.height == 0)    w->core.height = child->core.height;
    }
    if(w->shell.geometry != NULL) {
	char def_geom[64];
	x = w->core.x;
	y = w->core.y;
	width = w->core.width;
	height = w->core.height;
	if (is_wmshell) {
	    WMShellPart* wm = &((WMShellWidget)w)->wm;
	    EvaluateSizeHints((WMShellWidget)w);
	    (void) memmove((char*)&hints, (char*)&wm->size_hints,
			   sizeof(struct _OldXSizeHints));
	    hints.win_gravity = wm->win_gravity;
	    if (wm->size_hints.flags & PBaseSize) {
		width -= wm->base_width;
		height -= wm->base_height;
		hints.base_width = wm->base_width;
		hints.base_height = wm->base_height;
	    }
	    else if (wm->size_hints.flags & PMinSize) {
		width -= wm->size_hints.min_width;
		height -= wm->size_hints.min_height;
	    }
	    if (wm->size_hints.flags & PResizeInc) {
		width /= wm->size_hints.width_inc;
		height /= wm->size_hints.height_inc;
	    }
	}
	else hints.flags = 0;

	sprintf( def_geom, "%dx%d+%d+%d", width, height, x, y );
	flag = XWMGeometry( XtDisplay(W),
			    XScreenNumberOfScreen(XtScreen(W)),
			    w->shell.geometry, def_geom,
			    (unsigned int)w->core.border_width,
			    &hints, &x, &y, &width, &height,
			    &win_gravity
			   );
	if (flag) {
	    if (flag & XValue) w->core.x = (Position)x;
	    if (flag & YValue) w->core.y = (Position)y;
	    if (flag & WidthValue) w->core.width = (Dimension)width;
	    if (flag & HeightValue) w->core.height = (Dimension)height;
	}
	else {
	    String params[2];
	    Cardinal num_params = 2;
	    params[0] = XtName(W);
	    params[1] = w->shell.geometry;
	    XtAppWarningMsg(XtWidgetToApplicationContext(W),
       "badGeometry", "shellRealize", XtCXtToolkitError,
       "Shell widget \"%s\" has an invalid geometry specification: \"%s\"",
			    params, &num_params);
	}
    }
    else
	flag = 0;

    if (is_wmshell) {
	WMShellWidget wmshell = (WMShellWidget) w;
	if (wmshell->wm.win_gravity == XtUnspecifiedShellInt) {
	    if (win_gravity != -1)
		wmshell->wm.win_gravity = win_gravity;
	    else
		wmshell->wm.win_gravity = NorthWestGravity;
	}
	wmshell->wm.size_hints.flags |= PWinGravity;
	if ((flag & (XValue|YValue)) == (XValue|YValue))
	    wmshell->wm.size_hints.flags |= USPosition;
	if ((flag & (WidthValue|HeightValue)) == (WidthValue|HeightValue))
	    wmshell->wm.size_hints.flags |= USSize;
    }
    w->shell.client_specified |= _XtShellGeometryParsed;
}


static void ChangeManaged(Widget wid)
{
    ShellWidget w = (ShellWidget) wid;
    Widget child = NULL;
    Cardinal i;

    for (i = 0; i < w->composite.num_children; i++) {
	if (XtIsManaged(w->composite.children[i])) {
	    child = w->composite.children[i];
	    break;		/* there can only be one of them! */
	}
    }

    if (!XtIsRealized (wid))	/* then we're about to be realized... */
	GetGeometry(wid, child);

    if (child != NULL)
	XtConfigureWidget (child, (Position)0, (Position)0,
			   w->core.width, w->core.height, (Dimension)0 );
}

/*
 * This is gross, I can't wait to see if the change happened so I will ask
 * the window manager to change my size and do the appropriate X work.
 * I will then tell the requester that he can.  Care must be taken because
 * it is possible that some time in the future the request will be
 * asynchronusly denied and the window reverted to it's old size/shape.
 */

/*ARGSUSED*/
static XtGeometryResult GeometryManager(
	Widget wid,
	XtWidgetGeometry *request,
	XtWidgetGeometry *reply)
{
	ShellWidget shell = (ShellWidget)(wid->core.parent);
	XtWidgetGeometry my_request;

	if(shell->shell.allow_shell_resize == FALSE && XtIsRealized(wid))
		return(XtGeometryNo);

	if (request->request_mode & (CWX | CWY))
	    return(XtGeometryNo);

	my_request.request_mode = (request->request_mode & XtCWQueryOnly);
	if (request->request_mode & CWWidth) {
	    my_request.width = request->width;
	    my_request.request_mode |= CWWidth;
	}
	if (request->request_mode & CWHeight) {
	    my_request.height = request->height;
	    my_request.request_mode |= CWHeight;
	}
	if (request->request_mode & CWBorderWidth) {
	    my_request.border_width = request->border_width;
	    my_request.request_mode |= CWBorderWidth;
	}
	if (XtMakeGeometryRequest((Widget)shell, &my_request, NULL)
		== XtGeometryYes) {
	    /* assert: if (request->request_mode & CWWidth) then
	     * 		  shell->core.width == request->width
	     * assert: if (request->request_mode & CWHeight) then
	     * 		  shell->core.height == request->height
	     *
	     * so, whatever the WM sized us to (if the Shell requested
	     * only one of the two) is now the correct child size
	     */

	    if (!(request->request_mode & XtCWQueryOnly)) {
		wid->core.width = shell->core.width;
		wid->core.height = shell->core.height;
		if (request->request_mode & CWBorderWidth) {
		    wid->core.x = wid->core.y = -request->border_width;
		}
	    }
	    return XtGeometryYes;
	} else return XtGeometryNo;
}

typedef struct {
	Widget  w;
	unsigned long request_num;
	Boolean done;
} QueryStruct;

static Bool isMine(
	Display *dpy,
	register XEvent  *event,
	char *arg)
{
	QueryStruct *q = (QueryStruct *) arg;
	register Widget w = q->w;

	if ( (dpy != XtDisplay(w)) || (event->xany.window != XtWindow(w)) ) {
	    return FALSE;
	}
	if (event->xany.serial >= q->request_num) {
	    if (event->type == ConfigureNotify) {
		q->done = TRUE;
		return TRUE;
	    }
	}
	else if (event->type == ConfigureNotify)
	    return TRUE;	/* flush old events */
	if (event->type == ReparentNotify
		 && event->xreparent.window == XtWindow(w)) {
	    /* we might get ahead of this event, so just in case someone
	     * asks for coordinates before this event is dispatched...
	     */
	    register ShellWidget s = (ShellWidget)w;
	    if (event->xreparent.parent != RootWindowOfScreen(XtScreen(w)))
		s->shell.client_specified &= ~_XtShellNotReparented;
	    else
		s->shell.client_specified |= _XtShellNotReparented;
	}
	return FALSE;
}

static Boolean _wait_for_response(
	ShellWidget	w,
	XEvent		*event,
        unsigned long	request_num)
{
	XtAppContext app = XtWidgetToApplicationContext((Widget) w);
	QueryStruct q;
	unsigned long timeout;

	if (XtIsWMShell((Widget)w))
	    timeout = ((WMShellWidget)w)->wm.wm_timeout;
	else
	    timeout = DEFAULT_WM_TIMEOUT;

	XFlush(XtDisplay(w));
	q.w = (Widget) w;
	q.request_num = request_num;
	q.done = FALSE;

	/*
	 * look for match event and discard all prior configures
	 */
	while (XCheckIfEvent(XtDisplay(w),event,isMine,(char*)&q)) {
	    if (q.done) return TRUE;
	}

	while (timeout > 0) {
	    if (_XtWaitForSomething (app,
				     FALSE, TRUE, TRUE, TRUE,
				     TRUE,
#ifdef XTHREADS
				     FALSE,
#endif
				     &timeout) != -1) {
		while (XCheckIfEvent(XtDisplay(w),event,isMine,(char*)&q)) {
		    if (q.done) return TRUE;
		}
	    }
	}
	return FALSE;
}

/*ARGSUSED*/
static XtGeometryResult RootGeometryManager(
    Widget gw,
    XtWidgetGeometry *request, XtWidgetGeometry *reply)
{
    register ShellWidget w = (ShellWidget)gw;
    XWindowChanges values;
    unsigned int mask = request->request_mode;
    XEvent event;
    Boolean wm;
    register struct _OldXSizeHints *hintp = NULL;
    int oldx, oldy, oldwidth, oldheight, oldborder_width;
    unsigned long request_num;

    CALLGEOTAT(_XtGeoTab(1));

    if (XtIsWMShell(gw)) {
	wm = True;
	hintp = &((WMShellWidget)w)->wm.size_hints;
	/* for draft-ICCCM wm's, need to make sure hints reflect
	   (current) reality so client can move and size separately. */
  	hintp->x = w->core.x;
  	hintp->y = w->core.y;
  	hintp->width = w->core.width;
   	hintp->height = w->core.height;
    } else
	wm = False;

    oldx = w->core.x;
    oldy = w->core.y;
    oldwidth = w->core.width;
    oldheight = w->core.height;
    oldborder_width = w->core.border_width;

#define PutBackGeometry() \
	{ w->core.x = oldx; \
	  w->core.y = oldy; \
	  w->core.width = oldwidth; \
	  w->core.height = oldheight; \
	  w->core.border_width = oldborder_width; }

    if (mask & CWX) {
	    if (w->core.x == request->x) mask &= ~CWX;
	    else {
		w->core.x = values.x = request->x;
		if (wm) {
		    hintp->flags &= ~USPosition;
		    hintp->flags |= PPosition;
		    hintp->x = values.x;
		}
	    }
    }
    if (mask & CWY) {
	    if (w->core.y == request->y) mask &= ~CWY;
	    else {
		w->core.y = values.y = request->y;
		if (wm) {
		    hintp->flags &= ~USPosition;
		    hintp->flags |= PPosition;
		    hintp->y = values.y;
		}
	    }
    }
    if (mask & CWBorderWidth) {
	    if (w->core.border_width == request->border_width) {
		    mask &= ~CWBorderWidth;
	    } else
		w->core.border_width =
		    values.border_width =
			request->border_width;
    }
    if (mask & CWWidth) {
	    if (w->core.width == request->width) mask &= ~CWWidth;
	    else {
		w->core.width = values.width = request->width;
		if (wm) {
		    hintp->flags &= ~USSize;
		    hintp->flags |= PSize;
		    hintp->width = values.width;
		}
	    }
    }
    if (mask & CWHeight) {
	    if (w->core.height == request->height) mask &= ~CWHeight;
	    else {
		w->core.height = values.height = request->height;
		if (wm) {
		    hintp->flags &= ~USSize;
		    hintp->flags |= PSize;
		    hintp->height = values.height;
		}
	    }
    }
    if (mask & CWStackMode) {
	values.stack_mode = request->stack_mode;
	if (mask & CWSibling)
	    values.sibling = XtWindow(request->sibling);
    }

    if (!XtIsRealized((Widget)w)) {
	CALLGEOTAT(_XtGeoTrace((Widget)w,
		      "Shell \"%s\" is not realized, return XtGeometryYes.\n",
		       XtName((Widget)w)));
    	CALLGEOTAT(_XtGeoTab(-1));
	return XtGeometryYes;
    }

    request_num = NextRequest(XtDisplay(w));

    CALLGEOTAT(_XtGeoTrace((Widget)w,"XConfiguring the Shell X window :\n"));
    CALLGEOTAT(_XtGeoTab(1));
#ifdef XT_GEO_TATTLER
    if (mask & CWX) { CALLGEOTAT(_XtGeoTrace((Widget)w,"x = %d\n",values.x));}
    if (mask & CWY) { CALLGEOTAT(_XtGeoTrace((Widget)w,"y = %d\n",values.y));}
    if (mask & CWWidth) { CALLGEOTAT(_XtGeoTrace((Widget)w,
					       "width = %d\n",values.width));}
    if (mask & CWHeight) { CALLGEOTAT(_XtGeoTrace((Widget)w,
					    "height = %d\n",values.height));}
    if (mask & CWBorderWidth) { CALLGEOTAT(_XtGeoTrace((Widget)w,
				  "border_width = %d\n",values.border_width));}
#endif
    CALLGEOTAT(_XtGeoTab(-1));

    XConfigureWindow(XtDisplay((Widget)w), XtWindow((Widget)w), mask,&values);

    if (wm && !w->shell.override_redirect
	&& mask & (CWX | CWY | CWWidth | CWHeight | CWBorderWidth)) {
	_SetWMSizeHints((WMShellWidget)w);
    }

    if (w->shell.override_redirect) {
	CALLGEOTAT(_XtGeoTrace((Widget)w,"Shell \"%s\" is override redirect, return XtGeometryYes.\n", XtName((Widget)w)));
    	CALLGEOTAT(_XtGeoTab(-1));
	return XtGeometryYes;
    }


    /* If no non-stacking bits are set, there's no way to tell whether
       or not this worked, so assume it did */

    if (!(mask & ~(CWStackMode | CWSibling))) return XtGeometryYes;

    if (wm && ((WMShellWidget)w)->wm.wait_for_wm == FALSE) {
	    /* the window manager is sick
	     * so I will do the work and
	     * say no so if a new WM starts up,
	     * or the current one recovers
	     * my size requests will be visible
	     */
	CALLGEOTAT(_XtGeoTrace((Widget)w,"Shell \"%s\" has wait_for_wm == FALSE, return XtGeometryNo.\n",
		       XtName((Widget)w)));
    	CALLGEOTAT(_XtGeoTab(-1));

	PutBackGeometry();
	return XtGeometryNo;
    }

    if (_wait_for_response(w, &event, request_num)) {
	/* got an event */
	if (event.type == ConfigureNotify) {

#define NEQ(x, msk) ((mask & msk) && (values.x != event.xconfigure.x))
	    if (NEQ(x, CWX) ||
		NEQ(y, CWY) ||
		NEQ(width, CWWidth) ||
		NEQ(height, CWHeight) ||
		NEQ(border_width, CWBorderWidth)) {
#ifdef XT_GEO_TATTLER
		if (NEQ(x, CWX)) {
		    CALLGEOTAT(_XtGeoTrace((Widget)w,
					   "received Configure X %d\n",
					   event.xconfigure.x));
		}
		if (NEQ(y, CWY)) {
		    CALLGEOTAT(_XtGeoTrace((Widget)w,
					   "received Configure Y %d\n",
					   event.xconfigure.y));
		}
		if (NEQ(width, CWWidth)) {
		    CALLGEOTAT(_XtGeoTrace((Widget)w,
					   "received Configure Width %d\n",
					   event.xconfigure.width));
		}
		if (NEQ(height, CWHeight)) {
		    CALLGEOTAT(_XtGeoTrace((Widget)w,
					   "received Configure Height %d\n",
					   event.xconfigure.height));
		}
		if (NEQ(border_width, CWBorderWidth)) {
		    CALLGEOTAT(_XtGeoTrace((Widget)w,
				        "received Configure BorderWidth %d\n",
					event.xconfigure.border_width));
		}
#endif
#undef NEQ
		XPutBackEvent(XtDisplay(w), &event);
		PutBackGeometry();
		/*
		 * We just potentially re-ordered the event queue
		 * w.r.t. ConfigureNotifies with some trepidation.
		 * But this is probably a Good Thing because we
		 * will know the new true state of the world sooner
		 * this way.
		 */
		CALLGEOTAT(_XtGeoTrace((Widget)w,
			   "ConfigureNotify failed, return XtGeometryNo.\n"));
		CALLGEOTAT(_XtGeoTab(-1));

		return XtGeometryNo;
	    }
	    else {
		w->core.width = event.xconfigure.width;
		w->core.height = event.xconfigure.height;
		w->core.border_width = event.xconfigure.border_width;
		if (event.xany.send_event || /* ICCCM compliant synth */
		    w->shell.client_specified & _XtShellNotReparented) {

		    w->core.x = event.xconfigure.x;
		    w->core.y = event.xconfigure.y;
		    w->shell.client_specified |= _XtShellPositionValid;
		}
		else w->shell.client_specified &= ~_XtShellPositionValid;
		CALLGEOTAT(_XtGeoTrace((Widget)w,
			 "ConfigureNotify succeed, return XtGeometryYes.\n"));
		CALLGEOTAT(_XtGeoTab(-1));
		return XtGeometryYes;
	    }
	} else if (!wm) {
	    PutBackGeometry();
	    CALLGEOTAT(_XtGeoTrace((Widget)w,
				   "Not wm, return XtGeometryNo.\n"));
	    CALLGEOTAT(_XtGeoTab(-1));
	    return XtGeometryNo;
	} else XtAppWarningMsg(XtWidgetToApplicationContext((Widget)w),
			       "internalError", "shell", XtCXtToolkitError,
			       "Shell's window manager interaction is broken",
			       (String *)NULL, (Cardinal *)NULL);
    } else if (wm) { /* no event */
	((WMShellWidget)w)->wm.wait_for_wm = FALSE; /* timed out; must be broken */
    }
    PutBackGeometry();
#undef PutBackGeometry
    CALLGEOTAT(_XtGeoTrace((Widget)w,
			   "Timeout passed?, return XtGeometryNo.\n"));
    CALLGEOTAT(_XtGeoTab(-1));
    return XtGeometryNo;
		}

/* ARGSUSED */
static Boolean SetValues(
	Widget old, Widget ref, Widget new,
	ArgList args,
	Cardinal *num_args)
{
	ShellWidget nw = (ShellWidget) new;
	ShellWidget ow = (ShellWidget) old;
	Mask mask = 0;
	XSetWindowAttributes attr;

	if (!XtIsRealized(new))
	    return False;

	if (ow->shell.save_under != nw->shell.save_under) {
	    mask = CWSaveUnder;
	    attr.save_under = nw->shell.save_under;
	}

	if (ow->shell.override_redirect != nw->shell.override_redirect) {
	    mask |= CWOverrideRedirect;
	    attr.override_redirect = nw->shell.override_redirect;
	}

	if (mask) {
	    XChangeWindowAttributes(XtDisplay(new),XtWindow(new), mask, &attr);
	    if ((mask & CWOverrideRedirect) && !nw->shell.override_redirect)
		_popup_set_prop(nw);
	}

	if (! (ow->shell.client_specified & _XtShellPositionValid)) {
	    Cardinal n;

	    for (n = *num_args; n; n--, args++) {
		if (strcmp(XtNx, args->name) == 0) {
		    _XtShellGetCoordinates((Widget)ow, &ow->core.x,
							&ow->core.y);
		} else if (strcmp(XtNy, args->name) == 0) {
		    _XtShellGetCoordinates((Widget)ow, &ow->core.x,
							&ow->core.y);
		}
	    }
	}
	return FALSE;
}

/* ARGSUSED */
static Boolean WMSetValues(
	Widget old, Widget ref, Widget new,
	ArgList args,		/* unused */
	Cardinal *num_args)	/* unused */
{
	WMShellWidget nwmshell = (WMShellWidget) new;
	WMShellWidget owmshell = (WMShellWidget) old;
	Boolean set_prop
	    = XtIsRealized(new) && !nwmshell->shell.override_redirect;
	Boolean title_changed;

	EvaluateSizeHints(nwmshell);

#define NEQ(f) (nwmshell->wm.size_hints.f != owmshell->wm.size_hints.f)

	if (set_prop
	    && (NEQ(flags) || NEQ(min_width) || NEQ(min_height)
		|| NEQ(max_width) || NEQ(max_height)
		|| NEQ(width_inc) || NEQ(height_inc)
		|| NEQ(min_aspect.x) || NEQ(min_aspect.y)
		|| NEQ(max_aspect.x) || NEQ(max_aspect.y)
#undef NEQ
#define NEQ(f) (nwmshell->wm.f != owmshell->wm.f)

		|| NEQ(base_width) || NEQ(base_height) || NEQ(win_gravity))) {
	    _SetWMSizeHints(nwmshell);
	}
#undef NEQ

	if (nwmshell->wm.title != owmshell->wm.title) {
	    XtFree(owmshell->wm.title);
	    if (! nwmshell->wm.title) nwmshell->wm.title = "";
	    nwmshell->wm.title = XtNewString(nwmshell->wm.title);
	    title_changed = True;
	} else
	    title_changed = False;

	if (set_prop
	    && (title_changed ||
		nwmshell->wm.title_encoding != owmshell->wm.title_encoding)) {

	    XTextProperty title;
	    Boolean copied = False;

            if (nwmshell->wm.title_encoding == None &&
		XmbTextListToTextProperty(XtDisplay(new),
					  (char**)&nwmshell->wm.title,
					  1, XStdICCTextStyle,
					  &title) >= Success) {
		copied = True;
	    } else {
		title.value = (unsigned char*)nwmshell->wm.title;
		title.encoding = nwmshell->wm.title_encoding ?
		    nwmshell->wm.title_encoding : XA_STRING;
		title.format = 8;
		title.nitems = strlen(nwmshell->wm.title);
	    }
	    XSetWMName(XtDisplay(new), XtWindow(new), &title);
	    if (copied)
		XFree((XPointer)title.value);
	}

	EvaluateWMHints(nwmshell);

#define NEQ(f)	(nwmshell->wm.wm_hints.f != owmshell->wm.wm_hints.f)

	if (set_prop
	    && (NEQ(flags) || NEQ(input) || NEQ(initial_state)
		|| NEQ(icon_x) || NEQ(icon_y)
		|| NEQ(icon_pixmap) || NEQ(icon_mask) || NEQ(icon_window)
		|| NEQ(window_group))) {

	    XSetWMHints(XtDisplay(new), XtWindow(new), &nwmshell->wm.wm_hints);
	}
#undef NEQ

 	if (XtIsRealized(new) &&
	    nwmshell->wm.transient != owmshell->wm.transient) {
 	    if (nwmshell->wm.transient) {
		if (!XtIsTransientShell(new) &&
		    !nwmshell->shell.override_redirect &&
		    nwmshell->wm.wm_hints.window_group !=
		       XtUnspecifiedWindowGroup)
		    XSetTransientForHint(XtDisplay(new), XtWindow(new),
					 nwmshell->wm.wm_hints.window_group);
	    }
 	    else XDeleteProperty(XtDisplay(new), XtWindow(new),
 				 XA_WM_TRANSIENT_FOR);
 	}

	if (nwmshell->wm.client_leader != owmshell->wm.client_leader
	    && XtWindow(new) && !nwmshell->shell.override_redirect) {
	    Widget leader = GetClientLeader(new);
	    if (XtWindow(leader))
		XChangeProperty(XtDisplay(new), XtWindow(new),
				XInternAtom(XtDisplay(new),
					    "WM_CLIENT_LEADER", False),
				XA_WINDOW, 32, PropModeReplace,
				(unsigned char *) &(leader->core.window), 1);
	}

	if (nwmshell->wm.window_role != owmshell->wm.window_role) {
	    XtFree(owmshell->wm.window_role);
	    if (set_prop && nwmshell->wm.window_role) {
		XChangeProperty(XtDisplay(new), XtWindow(new),
				XInternAtom(XtDisplay(new), "WM_WINDOW_ROLE",
					    False),
				XA_STRING, 8, PropModeReplace,
				(unsigned char *)nwmshell->wm.window_role,
				strlen(nwmshell->wm.window_role));
	    } else if (XtIsRealized(new) && ! nwmshell->wm.window_role) {
		XDeleteProperty(XtDisplay(new), XtWindow(new),
				XInternAtom(XtDisplay(new), "WM_WINDOW_ROLE",
					    False));
	    }
	}

	return FALSE;
}

/*ARGSUSED*/
static Boolean TransientSetValues(
     Widget oldW, Widget refW, Widget newW,
     ArgList args,		/* unused */
     Cardinal *num_args)	/* unused */
{
    TransientShellWidget old = (TransientShellWidget)oldW;
    TransientShellWidget new = (TransientShellWidget)newW;

    if (XtIsRealized(newW)
	&& ((new->wm.transient && !old->wm.transient)
	    || ((new->transient.transient_for != old->transient.transient_for)
		|| (new->transient.transient_for == NULL
		    && (new->wm.wm_hints.window_group
			!= old->wm.wm_hints.window_group))))) {

	_SetTransientForHint(new, True);
    }
    return False;
}


/* ARGSUSED */
static Boolean TopLevelSetValues(
     Widget oldW, Widget refW, Widget newW,
     ArgList args,		/* unused */
     Cardinal *num_args)	/* unused */
{
    TopLevelShellWidget old = (TopLevelShellWidget)oldW;
    TopLevelShellWidget new = (TopLevelShellWidget)newW;
    Boolean name_changed;

    if (old->topLevel.icon_name != new->topLevel.icon_name) {
	XtFree((XtPointer)old->topLevel.icon_name);
	if (! new->topLevel.icon_name) new->topLevel.icon_name = "";
	new->topLevel.icon_name = XtNewString(new->topLevel.icon_name);
	name_changed = True;
    } else
	name_changed = False;

    if (XtIsRealized(newW)) {
	if (new->topLevel.iconic != old->topLevel.iconic) {
	    if (new->topLevel.iconic)
		XIconifyWindow(XtDisplay(newW),
			       XtWindow(newW),
			       XScreenNumberOfScreen(XtScreen(newW))
			       );
	    else {
		Boolean map = new->shell.popped_up;
		XtPopup(newW, XtGrabNone);
		if (map) XMapWindow(XtDisplay(newW), XtWindow(newW));
	    }
	}

	if (!new->shell.override_redirect &&
	    (name_changed ||
	     (old->topLevel.icon_name_encoding
	      != new->topLevel.icon_name_encoding))) {

	    XTextProperty icon_name;
	    Boolean copied = False;

            if (new->topLevel.icon_name_encoding == None &&
		XmbTextListToTextProperty(XtDisplay(newW),
					  (char**) &new->topLevel.icon_name,
					  1, XStdICCTextStyle,
					  &icon_name) >= Success) {
		copied = True;
	    } else {
		icon_name.value = (unsigned char *)new->topLevel.icon_name;
		icon_name.encoding = new->topLevel.icon_name_encoding ?
		    new->topLevel.icon_name_encoding : XA_STRING;
		icon_name.format = 8;
		icon_name.nitems = strlen((char *)icon_name.value);
	    }
	    XSetWMIconName(XtDisplay(newW), XtWindow(newW), &icon_name);
	    if (copied)
		XFree((XPointer)icon_name.value);
	}
    }
    return False;
}

static String * NewArgv(
    int count,
    String *str)  /* do not assume it's terminated by a NULL element */
{
    Cardinal nbytes = 0;
    Cardinal num = 0;
    String *newarray, *new;
    String *strarray = str;
    String sptr;

    if (count <= 0 || !str) return NULL;

    for (num = count; num--; str++) {
	nbytes += strlen(*str);
	nbytes++;
    }
    num = (count+1) * sizeof(String);
    new = newarray = (String *) __XtMalloc(num + nbytes);
    sptr = ((char *) new) + num;

    for (str = strarray; count--; str++) {
	*new = sptr;
	strcpy(*new, *str);
	new++;
	sptr = strchr(sptr, '\0');
	sptr++;
    }
    *new = NULL;
    return newarray;
}


/*ARGSUSED*/
static Boolean ApplicationSetValues(
    Widget current, Widget request, Widget new,
    ArgList args,
    Cardinal *num_args)
{
    ApplicationShellWidget nw = (ApplicationShellWidget) new;
    ApplicationShellWidget cw = (ApplicationShellWidget) current;

    if (cw->application.argc != nw->application.argc ||
	cw->application.argv != nw->application.argv) {

	if (nw->application.argc > 0)
	    nw->application.argv = NewArgv(nw->application.argc,
					   nw->application.argv);
	if (cw->application.argc > 0)
	    FreeStringArray(cw->application.argv);

	if (XtIsRealized(new) && !nw->shell.override_redirect) {
	    if (nw->application.argc >= 0 && nw->application.argv)
		XSetCommand(XtDisplay(new), XtWindow(new),
			    nw->application.argv, nw->application.argc);
	    else
		XDeleteProperty(XtDisplay(new), XtWindow(new), XA_WM_COMMAND);
	}
    }
    return False;
}

/*ARGSUSED*/
static Boolean SessionSetValues(
    Widget current, Widget request, Widget new,
    ArgList args,
    Cardinal *num_args)
{
#ifndef XT_NO_SM
    SessionShellWidget nw = (SessionShellWidget) new;
    SessionShellWidget cw = (SessionShellWidget) current;
    unsigned long set_mask = 0UL;
    unsigned long unset_mask = 0UL;
    Boolean initialize = False;

    if (cw->session.session_id != nw->session.session_id) {
	nw->session.session_id = XtNewString(nw->session.session_id);
	XtFree(cw->session.session_id);
    }

    if (cw->session.clone_command != nw->session.clone_command) {
	if (nw->session.clone_command) {
	    nw->session.clone_command =
		NewStringArray(nw->session.clone_command);
	    set_mask |= XtCloneCommandMask;
	} else unset_mask |= XtCloneCommandMask;
	FreeStringArray(cw->session.clone_command);
    }

    if (cw->session.current_dir != nw->session.current_dir) {
	if (nw->session.current_dir) {
	    nw->session.current_dir =
		XtNewString(nw->session.current_dir);
	    set_mask |= XtCurrentDirectoryMask;
	} else unset_mask |= XtCurrentDirectoryMask;
	XtFree((char *) cw->session.current_dir);
    }

    if (cw->session.discard_command != nw->session.discard_command) {
	if (nw->session.discard_command) {
	    nw->session.discard_command =
		NewStringArray(nw->session.discard_command);
	    set_mask |=  XtDiscardCommandMask;
	} else unset_mask |= XtDiscardCommandMask;
	FreeStringArray(cw->session.discard_command);
    }

    if (cw->session.environment != nw->session.environment) {
	if (nw->session.environment) {
	    nw->session.environment =
		NewStringArray(nw->session.environment);
	    set_mask |= XtEnvironmentMask;
	} else unset_mask |= XtEnvironmentMask;
	FreeStringArray(cw->session.environment);
    }

    if (cw->session.program_path != nw->session.program_path) {
	if (nw->session.program_path) {
	    nw->session.program_path =
		XtNewString(nw->session.program_path);
	    set_mask |= XtProgramMask;
	} else unset_mask |= XtProgramMask;
	XtFree((char *) cw->session.program_path);
    }

    if (cw->session.resign_command != nw->session.resign_command) {
	if (nw->session.resign_command) {
	    nw->session.resign_command =
		NewStringArray(nw->session.resign_command);
	    set_mask |= XtResignCommandMask;
	} else set_mask |= XtResignCommandMask;
	FreeStringArray(cw->session.resign_command);
    }

    if (cw->session.restart_command != nw->session.restart_command) {
	if (nw->session.restart_command) {
	    nw->session.restart_command =
		NewStringArray(nw->session.restart_command);
	    set_mask |= XtRestartCommandMask;
	} else unset_mask |= XtRestartCommandMask;
	FreeStringArray(cw->session.restart_command);
    }

    if (cw->session.restart_style != nw->session.restart_style)
	set_mask |= XtRestartStyleHintMask;

    if (cw->session.shutdown_command != nw->session.shutdown_command) {
	if (nw->session.shutdown_command) {
	    nw->session.shutdown_command =
		NewStringArray(nw->session.shutdown_command);
	    set_mask |= XtShutdownCommandMask;
	} else unset_mask |= XtShutdownCommandMask;
	FreeStringArray(cw->session.shutdown_command);
    }

    if ((!cw->session.join_session && nw->session.join_session) ||
	(!cw->session.connection && nw->session.connection)) {
	JoinSession(nw);
	initialize = True;
    }

    if (nw->session.connection && (set_mask || unset_mask || initialize))
	SetSessionProperties((SessionShellWidget) new, initialize, set_mask, unset_mask);

    if ((cw->session.join_session && !nw->session.join_session) ||
	(cw->session.connection && !nw->session.connection))
	StopManagingSession(nw, nw->session.connection);
#endif /* !XT_NO_SM */

    if (cw->wm.client_leader != nw->wm.client_leader ||
	cw->session.session_id != nw->session.session_id) {
	Widget leader;
	if (cw->session.session_id) {
	    leader = GetClientLeader(current);
	    if (XtWindow(leader))
		XDeleteProperty(XtDisplay(leader), XtWindow(leader),
				XInternAtom(XtDisplay(leader), "SM_CLIENT_ID",
					    False));
	}
	if (nw->session.session_id) {
	    leader = GetClientLeader(new);
	    if (XtWindow(leader))
		XChangeProperty(XtDisplay(leader), XtWindow(leader),
				XInternAtom(XtDisplay(leader), "SM_CLIENT_ID",
					    False),
				XA_STRING, 8, PropModeReplace,
				(unsigned char *) nw->session.session_id,
				strlen(nw->session.session_id));
	}
    }
    return False;
}

void _XtShellGetCoordinates(
    Widget widget,
    Position* x,
    Position* y)
{
    ShellWidget w = (ShellWidget)widget;
    if (XtIsRealized(widget) &&
	!(w->shell.client_specified & _XtShellPositionValid)) {
	int tmpx, tmpy;
	Window tmpchild;
	(void) XTranslateCoordinates(XtDisplay(w), XtWindow(w),
				     RootWindowOfScreen(XtScreen(w)),
				     (int) -w->core.border_width,
				     (int) -w->core.border_width,
				     &tmpx, &tmpy, &tmpchild);
	w->core.x = tmpx;
	w->core.y = tmpy;
	w->shell.client_specified |= _XtShellPositionValid;
    }
    *x = w->core.x;
    *y = w->core.y;
}

static void GetValuesHook(
    Widget	widget,
    ArgList	args,
    Cardinal*	num_args)
{
    ShellWidget w = (ShellWidget) widget;

    /* x and y resource values may be invalid after a shell resize */
    if (XtIsRealized(widget) &&
	!(w->shell.client_specified & _XtShellPositionValid)) {
	Cardinal	n;
	Position	x, y;

	for (n = *num_args; n; n--, args++) {
	    if (strcmp(XtNx, args->name) == 0) {
		_XtShellGetCoordinates(widget, &x, &y);
		_XtCopyToArg((char *) &x, &args->value, sizeof(Position));
	    } else if (strcmp(XtNy, args->name) == 0) {
		_XtShellGetCoordinates(widget, &x, &y);
		_XtCopyToArg((char *) &y, &args->value, sizeof(Position));
	    }
	}
    }
}

static void ApplicationShellInsertChild(
    Widget widget)
{
    if (! XtIsWidget(widget) && XtIsRectObj(widget)) {
	XtAppWarningMsg(XtWidgetToApplicationContext(widget),
	       "invalidClass", "applicationShellInsertChild", XtCXtToolkitError,
	       "ApplicationShell does not accept RectObj children; ignored",
	       (String*)NULL, (Cardinal*)NULL);
    }
    else {
	XtWidgetProc insert_child;

	LOCK_PROCESS;
	insert_child =
	    ((CompositeWidgetClass)applicationShellClassRec.core_class.
	   superclass)->composite_class.insert_child;
	UNLOCK_PROCESS;
	(*insert_child) (widget);
    }
}

/**************************************************************************

  Session Protocol Participation

 *************************************************************************/

#define XtSessionCheckpoint	0
#define XtSessionInteract	1

static void CallSaveCallbacks(SessionShellWidget );
static String *EditCommand(String, String *, String *);
static Boolean ExamineToken(XtPointer);
static void GetIceEvent(XtPointer, int *, XtInputId *);
static XtCheckpointToken GetToken(Widget, int);
static void XtCallCancelCallbacks(SmcConn, SmPointer);
static void XtCallDieCallbacks(SmcConn, SmPointer);
static void XtCallSaveCallbacks(SmcConn, SmPointer, int, Bool, int, Bool);
static void XtCallSaveCompleteCallbacks(SmcConn, SmPointer);

#ifndef XT_NO_SM
static void StopManagingSession(
    SessionShellWidget w,
    SmcConn connection) /* connection to close, if any */
{
    if (connection)
	SmcCloseConnection(connection, 0, NULL);

    if (w->session.input_id) {
	XtRemoveInput(w->session.input_id);
	w->session.input_id = 0;
    }
    w->session.connection = NULL;
}

#define XT_MSG_LENGTH 256
static void JoinSession(
    SessionShellWidget w)
{
    IceConn ice_conn;
    SmcCallbacks smcb;
    char * sm_client_id;
    unsigned long mask;
    static char context;  /* used to guarantee the connection isn't shared */

    smcb.save_yourself.callback = XtCallSaveCallbacks;
    smcb.die.callback = XtCallDieCallbacks;
    smcb.save_complete.callback = XtCallSaveCompleteCallbacks;
    smcb.shutdown_cancelled.callback = XtCallCancelCallbacks;
    smcb.save_yourself.client_data = smcb.die.client_data =
	smcb.save_complete.client_data =
	    smcb.shutdown_cancelled.client_data = (SmPointer) w;
    mask = SmcSaveYourselfProcMask | SmcDieProcMask |
	SmcSaveCompleteProcMask | SmcShutdownCancelledProcMask;

    if (w->session.connection) {
	SmcModifyCallbacks(w->session.connection, mask, &smcb);
	sm_client_id = SmcClientID(w->session.connection);
    } else if (getenv("SESSION_MANAGER")) {
	char error_msg[XT_MSG_LENGTH];
	error_msg[0] = '\0';
	w->session.connection =
	    SmcOpenConnection(NULL, &context, SmProtoMajor, SmProtoMinor,
			      mask, &smcb, w->session.session_id,
			      &sm_client_id, XT_MSG_LENGTH, error_msg);
	if (error_msg[0]) {
	    String params[1];
	    Cardinal num_params = 1;
	    params[0] = error_msg;
	    XtAppWarningMsg(XtWidgetToApplicationContext((Widget) w),
			    "sessionManagement", "SmcOpenConnection",
			    XtCXtToolkitError,
			    "Tried to connect to session manager, %s",
			    params, &num_params);
	}
    }

    if (w->session.connection) {
	if (w->session.session_id == NULL
	    || (strcmp(w->session.session_id, sm_client_id) != 0)) {
	    XtFree(w->session.session_id);
	    w->session.session_id = XtNewString(sm_client_id);
	}
	free(sm_client_id);
	ice_conn = SmcGetIceConnection(w->session.connection);
	w->session.input_id =
	    XtAppAddInput(XtWidgetToApplicationContext((Widget)w),
			  IceConnectionNumber(ice_conn),
			  (XtPointer) XtInputReadMask,
			  GetIceEvent, (XtPointer) w);

	w->session.restart_command =
	    EditCommand(w->session.session_id, w->session.restart_command,
			w->application.argv);

	if (! w->session.clone_command) w->session.clone_command =
	    EditCommand(NULL, NULL, w->session.restart_command);

	if (! w->session.program_path)
	    w->session.program_path = w->session.restart_command
		? XtNewString(w->session.restart_command[0]) : NULL;
    }
}
#undef XT_MSG_LENGTH

#endif /* !XT_NO_SM */

static String * NewStringArray(String *str)
{
    Cardinal nbytes = 0;
    Cardinal num = 0;
    String *newarray, *new;
    String *strarray = str;
    String sptr;

    if (!str) return NULL;

    for (num = 0; *str; num++, str++) {
	nbytes += strlen(*str);
	nbytes++;
    }
    num = (num + 1) * sizeof(String);
    new = newarray = (String *) __XtMalloc(num + nbytes);
    sptr = ((char *) new) + num;

    for (str = strarray; *str; str++) {
	*new = sptr;
	strcpy(*new, *str);
	new++;
	sptr = strchr(sptr, '\0');
	sptr++;
    }
    *new = NULL;
    return newarray;
}

static void FreeStringArray(String *str)
{
    if (str)
	XtFree((char *) str);
}


#ifndef XT_NO_SM
static SmProp * CardPack(
    char *name,
    XtPointer closure)
{
    unsigned char *prop = (unsigned char *) closure;
    SmProp *p;

    p = (SmProp *) __XtMalloc(sizeof(SmProp) + sizeof(SmPropValue));
    p->vals = (SmPropValue *) (((char *) p) + sizeof(SmProp));
    p->num_vals = 1;
    p->type = SmCARD8;
    p->name = name;
    p->vals->length = 1;
    p->vals->value = (SmPointer) prop;
    return p;
}

static SmProp * ArrayPack(char *name, XtPointer closure)
{
    String prop = *(String *) closure;
    SmProp *p;

    p = (SmProp *) __XtMalloc(sizeof(SmProp) + sizeof(SmPropValue));
    p->vals = (SmPropValue *) (((char *) p) + sizeof(SmProp));
    p->num_vals = 1;
    p->type = SmARRAY8;
    p->name = name;
    p->vals->length = strlen(prop) + 1;
    p->vals->value = prop;
    return p;
}

static SmProp * ListPack(
    char *name,
    XtPointer closure)
{
    String *prop = *(String **) closure;
    SmProp *p;
    String *ptr;
    SmPropValue *vals;
    int n = 0;

    for (ptr = prop; *ptr; ptr++)
	n++;
    p = (SmProp*) __XtMalloc(sizeof(SmProp) + (Cardinal)(n*sizeof(SmPropValue)));
    p->vals = (SmPropValue *) (((char *) p) + sizeof(SmProp));
    p->num_vals = n;
    p->type = SmLISTofARRAY8;
    p->name = name;
    for (ptr = prop, vals = p->vals; *ptr; ptr++, vals++) {
	vals->length = strlen(*ptr) + 1;
	vals->value = *ptr;
    }
    return p;
}

static void FreePacks(
    SmProp **props,
    int num_props)
{
    while (--num_props >= 0)
	XtFree((char *) props[num_props]);
}

typedef SmProp* (*PackProc)(char *, XtPointer);

typedef struct PropertyRec {
    char *	name;
    int		offset;
    PackProc	proc;
} PropertyRec, *PropertyTable;

#define Offset(x) (XtOffsetOf(SessionShellRec, x))
static PropertyRec propertyTable[] = {
  {SmCloneCommand,     Offset(session.clone_command),    ListPack},
  {SmCurrentDirectory, Offset(session.current_dir),      ArrayPack},
  {SmDiscardCommand,   Offset(session.discard_command),  ListPack},
  {SmEnvironment,      Offset(session.environment),      ListPack},
  {SmProgram,          Offset(session.program_path),     ArrayPack},
  {SmResignCommand,    Offset(session.resign_command),   ListPack},
  {SmRestartCommand,   Offset(session.restart_command),  ListPack},
  {SmRestartStyleHint, Offset(session.restart_style),    CardPack},
  {SmShutdownCommand,  Offset(session.shutdown_command), ListPack}
};
#undef Offset

#define XT_NUM_SM_PROPS 11

static void SetSessionProperties(
    SessionShellWidget w,
    Boolean initialize,
    unsigned long set_mask,
    unsigned long unset_mask)
{
    PropertyTable p = propertyTable;
    int n;
    int num_props = 0;
    XtPointer *addr;
    unsigned long mask;
    SmProp *props[XT_NUM_SM_PROPS];
    char *pnames[XT_NUM_SM_PROPS];

    if (w->session.connection == NULL)
	return;

    if (initialize) {
	char nam_buf[32];
	char pid[12];
	String user_name;
	String pidp = pid;

	/* set all non-NULL session properties, the UserID and the ProcessID */
	for (n = XtNumber(propertyTable); n; n--, p++) {
	    addr = (XtPointer *) ((char *) w + p->offset);
	    if (p->proc == CardPack) {
		if (*(unsigned char *)addr)
		    props[num_props++] =(*(p->proc))(p->name, (XtPointer)addr);
	    }
	    else if (* addr)
		props[num_props++] = (*(p->proc))(p->name, (XtPointer)addr);

	}
	user_name = _XtGetUserName(nam_buf, sizeof nam_buf);
	if (user_name)
	    props[num_props++] = ArrayPack(SmUserID, &user_name);
	sprintf(pid, "%ld", (long)getpid());
	props[num_props++] = ArrayPack(SmProcessID, &pidp);

	if (num_props) {
	    SmcSetProperties(w->session.connection, num_props, props);
	    FreePacks(props, num_props);
	}
	return;
    }

    if (set_mask) {
	mask = 1L;
	for (n = XtNumber(propertyTable); n; n--, p++, mask <<= 1)
	    if (mask & set_mask) {
		addr = (XtPointer *) ((char *) w + p->offset);
		props[num_props++] = (*(p->proc))(p->name, (XtPointer)addr);
	    }
	SmcSetProperties(w->session.connection, num_props, props);
	FreePacks(props, num_props);
    }

    if (unset_mask) {
	mask = 1L;
	num_props = 0;
	for (n = XtNumber(propertyTable); n; n--, p++, mask <<= 1)
	    if (mask & unset_mask)
		pnames[num_props++] = p->name;
	SmcDeleteProperties(w->session.connection, num_props, pnames);
    }
}

/*ARGSUSED*/
static void GetIceEvent(
    XtPointer	client_data,
    int *	source,
    XtInputId *	id)
{
    SessionShellWidget w = (SessionShellWidget) client_data;
    IceProcessMessagesStatus status;

    status = IceProcessMessages(SmcGetIceConnection(w->session.connection),
				NULL, NULL);

    if (status == IceProcessMessagesIOError) {
	StopManagingSession(w, w->session.connection);
	XtCallCallbackList((Widget)w, w->session.error_callbacks,
			   (XtPointer) NULL);
    }
}

static void CleanUpSave(
    SessionShellWidget w)
{
    XtSaveYourself next = w->session.save->next;
    XtFree((char *)w->session.save);
    w->session.save = next;
    if (w->session.save)
	CallSaveCallbacks(w);
}

static void CallSaveCallbacks(
    SessionShellWidget w)
{
    XtCheckpointToken token;

    if (XtHasCallbacks((Widget) w, XtNsaveCallback) != XtCallbackHasSome) {
	/* if the application makes no attempt to save state, report failure */
	SmcSaveYourselfDone(w->session.connection, False);
	CleanUpSave(w);
    } else {
	w->session.checkpoint_state = XtSaveActive;
	token = GetToken((Widget) w, XtSessionCheckpoint);
	_XtCallConditionalCallbackList((Widget)w, w->session.save_callbacks,
				       (XtPointer)token, ExamineToken);
	XtSessionReturnToken(token);
    }
}

/*ARGSUSED*/
static void XtCallSaveCallbacks(
    SmcConn	connection,	/* unused */
    SmPointer	client_data,
    int		save_type,
    Bool	shutdown,
    int		interact,
    Bool	fast)
{
    SessionShellWidget w = (SessionShellWidget) client_data;
    XtSaveYourself save;
    XtSaveYourself prev;

    save = XtNew(XtSaveYourselfRec);
    save->next = NULL;
    save->save_type = save_type;
    save->interact_style = interact;
    save->shutdown = shutdown;
    save->fast = fast;
    save->cancel_shutdown = False;
    save->phase = 1;
    save->interact_dialog_type = SmDialogNormal;
    save->request_cancel = save->request_next_phase = False;
    save->save_success = True;
    save->save_tokens = save->interact_tokens = 0;

    prev = (XtSaveYourself) &w->session.save;
    while (prev->next)
	prev = prev->next;
    prev->next = save;

    if (w->session.checkpoint_state == XtSaveInactive)
	CallSaveCallbacks(w);
}

static void XtInteractPermission(
    SmcConn	connection,
    SmPointer	data)
{
    Widget w = (Widget) data;
    SessionShellWidget sw = (SessionShellWidget) data;
    XtCheckpointToken token;
    XtCallbackProc callback;
    XtPointer client_data;


    _XtPeekCallback(w, sw->session.interact_callbacks, &callback,
		    &client_data);
    if (callback) {
	sw->session.checkpoint_state = XtInteractActive;
	token = GetToken(w, XtSessionInteract);
    	XtRemoveCallback(w, XtNinteractCallback, callback, client_data);
	(*callback)(w, client_data, (XtPointer) token);
    } else if (! sw->session.save->cancel_shutdown) {
	SmcInteractDone(connection, False);
    }
}

/*ARGSUSED*/
static void XtCallSaveCompleteCallbacks(
    SmcConn	connection,
    SmPointer	client_data)
{
    SessionShellWidget w =  (SessionShellWidget) client_data;

    XtCallCallbackList((Widget)w, w->session.save_complete_callbacks,
		       (XtPointer) NULL);
}

/*ARGSUSED*/
static void XtCallNextPhaseCallbacks(
    SmcConn	connection,	/* unused */
    SmPointer	client_data)
{
    SessionShellWidget w =  (SessionShellWidget) client_data;
    w->session.save->phase = 2;
    CallSaveCallbacks(w);
}

/*ARGSUSED*/
static void XtCallDieCallbacks(
    SmcConn	connection,	/* unused */
    SmPointer	client_data)
{
    SessionShellWidget w =  (SessionShellWidget) client_data;

    StopManagingSession(w, w->session.connection);
    XtCallCallbackList((Widget)w, w->session.die_callbacks,
		       (XtPointer) NULL);
}

/*ARGSUSED*/
static void XtCallCancelCallbacks(
    SmcConn	connection,	/* unused */
    SmPointer	client_data)
{
    SessionShellWidget w = (SessionShellWidget) client_data;
    Boolean call_interacts = False;

    if (w->session.checkpoint_state != XtSaveInactive) {
	w->session.save->cancel_shutdown = True;
	call_interacts = (w->session.save->interact_style !=
			  SmInteractStyleNone);
    }

    XtCallCallbackList((Widget)w, w->session.cancel_callbacks,
		       (XtPointer) NULL);

    if (call_interacts) {
	w->session.save->interact_style = SmInteractStyleNone;
	XtInteractPermission(w->session.connection, (SmPointer) w);
    }

    if (w->session.checkpoint_state != XtSaveInactive) {
	if (w->session.save->save_tokens == 0 &&
	    w->session.checkpoint_state == XtSaveActive) {
	    w->session.checkpoint_state = XtSaveInactive;
	    SmcSaveYourselfDone(w->session.connection,
				w->session.save->save_success);
	    CleanUpSave(w);
	}
    }
}

static XtCheckpointToken GetToken(
    Widget	widget,
    int		type)
{
    SessionShellWidget w = (SessionShellWidget) widget;
    XtCheckpointToken token;
    XtSaveYourself save = w->session.save;

    if (type == XtSessionCheckpoint)
	w->session.save->save_tokens++;
    else if (type == XtSessionInteract)
	w->session.save->interact_tokens++;
    else
	return (XtCheckpointToken) NULL;

    token = (XtCheckpointToken) __XtMalloc(sizeof(XtCheckpointTokenRec));
    token->save_type = save->save_type;
    token->interact_style = save->interact_style;
    token->shutdown = save->shutdown;
    token->fast = save->fast;
    token->cancel_shutdown = save->cancel_shutdown;
    token->phase = save->phase;
    token->interact_dialog_type = save->interact_dialog_type;
    token->request_cancel = save->request_cancel;
    token->request_next_phase = save->request_next_phase;
    token->save_success = save->save_success;
    token->type = type;
    token->widget = widget;
    return token;
}

XtCheckpointToken XtSessionGetToken(Widget widget)
{
    SessionShellWidget w = (SessionShellWidget) widget;
    XtCheckpointToken token = NULL;
    WIDGET_TO_APPCON(widget);

    LOCK_APP(app);
    if (w->session.checkpoint_state)
	token = GetToken(widget, XtSessionCheckpoint);

    UNLOCK_APP(app);
    return token;
}

static Boolean ExamineToken(
    XtPointer	call_data)
{
    XtCheckpointToken token = (XtCheckpointToken) call_data;
    SessionShellWidget w = (SessionShellWidget) token->widget;

    if (token->interact_dialog_type == SmDialogError)
	w->session.save->interact_dialog_type = SmDialogError;
    if (token->request_next_phase)
	w->session.save->request_next_phase = True;
    if (! token->save_success)
	w->session.save->save_success = False;

    token->interact_dialog_type = w->session.save->interact_dialog_type;
    token->request_next_phase = w->session.save->request_next_phase;
    token->save_success = w->session.save->save_success;
    token->cancel_shutdown = w->session.save->cancel_shutdown;

    return True;
}

void XtSessionReturnToken(XtCheckpointToken token)
{
    SessionShellWidget w = (SessionShellWidget) token->widget;
    Boolean has_some;
    Boolean phase_done;
    XtCallbackProc callback;
    XtPointer client_data;
    WIDGET_TO_APPCON((Widget)w);

    LOCK_APP(app);

    has_some = (XtHasCallbacks(token->widget, XtNinteractCallback)
		== XtCallbackHasSome);

    (void) ExamineToken((XtPointer) token);

    if (token->type == XtSessionCheckpoint) {
	w->session.save->save_tokens--;
	if (has_some && w->session.checkpoint_state == XtSaveActive) {
	    w->session.checkpoint_state = XtInteractPending;
	    SmcInteractRequest(w->session.connection,
			       w->session.save->interact_dialog_type,
			       XtInteractPermission, (SmPointer) w);
	}
	XtFree((char*) token);
    } else {
	if (token->request_cancel)
	    w->session.save->request_cancel = True;
	token->request_cancel = w->session.save->request_cancel;
	if (has_some) {
	    _XtPeekCallback((Widget)w, w->session.interact_callbacks,
			    &callback, &client_data);
	    XtRemoveCallback((Widget)w, XtNinteractCallback,
			     callback, client_data);
	    (*callback)((Widget)w, client_data, (XtPointer)token);
	} else {
	    w->session.save->interact_tokens--;
	    if (w->session.save->interact_tokens == 0) {
		w->session.checkpoint_state = XtSaveActive;
		if (! w->session.save->cancel_shutdown)
		    SmcInteractDone(w->session.connection,
				    w->session.save->request_cancel);
	    }
	    XtFree((char *) token);
	}
    }

    phase_done = (w->session.save->save_tokens == 0 &&
		  w->session.checkpoint_state == XtSaveActive);

    if (phase_done) {
	if (w->session.save->request_next_phase &&
	    w->session.save->phase == 1) {
	    SmcRequestSaveYourselfPhase2(w->session.connection,
					 XtCallNextPhaseCallbacks,
					 (SmPointer)w);
	} else {
	    w->session.checkpoint_state = XtSaveInactive;
	    SmcSaveYourselfDone(w->session.connection,
				w->session.save->save_success);
	    CleanUpSave(w);
	}
    }

    UNLOCK_APP(app);
}

static Boolean IsInArray(
    String str,
    String *sarray)
{
    if (str == NULL || sarray == NULL)
	return False;
    for (; *sarray; sarray++) {
	if (strcmp(*sarray, str) == 0)
	    return True;
    }
    return False;
}

static String* EditCommand(
    String str,		/* if not NULL, the sm_client_id */
    String *src1,	/* first choice */
    String *src2)	/* alternate */
{
    Boolean have;
    Boolean want;
    int count;
    String *sarray;
    String *s;
    String *new;

    want = (str != NULL);
    sarray = (src1 ? src1 : src2);
    if (! sarray) return NULL;
    have = IsInArray("-xtsessionID", sarray);
    if ((want && have) || (!want && !have)) {
	if (sarray == src1)
	    return src1;
	else
	    return NewStringArray(sarray);
    }

    count = 0;
    for (s = sarray; *s; s++)
	count++;

    if (want) {
	s = new = (String *) __XtMalloc((Cardinal)(count+3) * sizeof(String*));
	*s = *sarray;		s++; sarray++;
	*s = "-xtsessionID";	s++;
	*s = str;		s++;
	for (; --count > 0; s++, sarray++)
	    *s = *sarray;
	*s = (String) NULL;
    } else {
	if (count < 3)
	    return NewStringArray(sarray);
	s = new = (String *) __XtMalloc((Cardinal)(count-1) * sizeof(String*));
	for (; --count >= 0; sarray++) {
	    if (strcmp(*sarray, "-xtsessionID") == 0) {
		sarray++;
		count--;
	    } else {
		*s = *sarray;
		s++;
	    }
	}
	*s = (String) NULL;
    }
    s = new;
    new = NewStringArray(new);
    XtFree((char *)s);
    return new;
}

#endif /* !XT_NO_SM */