File: NSWindow.m

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

   <abstract>The window class</abstract>

   Copyright (C) 1996-2015 Free Software Foundation, Inc.

   Author:  Scott Christley <scottc@net-community.com>
            Venkat Ajjanagadde <venkat@ocbi.com>
   Date: 1996
   Author: Felipe A. Rodriguez <far@ix.netcom.com>
   Date: June 1998
   Author: Richard Frith-Macdonald <richard@brainstorm.co.uk>
   Date: December 1998

   This file is part of the GNUstep GUI Library.

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

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

   You should have received a copy of the GNU Lesser General Public
   License along with this library; see the file COPYING.LIB.
   If not, see <http://www.gnu.org/licenses/> or write to the 
   Free Software Foundation, 51 Franklin Street, Fifth Floor, 
   Boston, MA 02110-1301, USA.
*/

#import "config.h"
#include <math.h>
#include <float.h>

#import <Foundation/NSArray.h>
#import <Foundation/NSDebug.h>
#import <Foundation/NSRunLoop.h>
#import <Foundation/NSScanner.h>
#import <Foundation/NSAutoreleasePool.h>
#import <Foundation/NSString.h>
#import <Foundation/NSCoder.h>
#import <Foundation/NSArray.h>
#import <Foundation/NSEnumerator.h>
#import <Foundation/NSGeometry.h>
#import <Foundation/NSNotification.h>
#import <Foundation/NSValue.h>
#import <Foundation/NSException.h>
#import <Foundation/NSSet.h>
#import <Foundation/NSLock.h>
#import <Foundation/NSUserDefaults.h>
#import <Foundation/NSUndoManager.h>

#import "AppKit/NSAnimation.h"
#import "AppKit/NSApplication.h"
#import "AppKit/NSButton.h"
#import "AppKit/NSButtonCell.h"
#import "AppKit/NSCachedImageRep.h"
#import "AppKit/NSColor.h"
#import "AppKit/NSColorList.h"
#import "AppKit/NSCursor.h"
#import "AppKit/NSDocumentController.h"
#import "AppKit/NSDocument.h"
#import "AppKit/NSDragging.h"
#import "AppKit/NSEvent.h"
#import "AppKit/NSFont.h"
#import "AppKit/NSGraphics.h"
#import "AppKit/NSHelpManager.h"
#import "AppKit/NSKeyValueBinding.h"
#import "AppKit/NSImage.h"
#import "AppKit/NSMenu.h"
#import "AppKit/NSPasteboard.h"
#import "AppKit/NSScreen.h"
#import "AppKit/NSTextField.h"
#import "AppKit/NSTextFieldCell.h"
#import "AppKit/NSView.h"
#import "AppKit/NSWindow.h"
#import "AppKit/NSWindowController.h"
#import "AppKit/PSOperators.h"

#import "GNUstepGUI/GSTheme.h"
#import "GNUstepGUI/GSTrackingRect.h"
#import "GNUstepGUI/GSDisplayServer.h"
#import "GNUstepGUI/GSWindowDecorationView.h"
#import "GSBindingHelpers.h"
#import "GSGuiPrivate.h"
#import "GSToolTips.h"
#import "GSIconManager.h"
#import "NSToolbarFrameworkPrivate.h"
#import "NSViewPrivate.h"

#define GSI_ARRAY_TYPES 0
#define GSI_ARRAY_TYPE NSWindow *
#define GSI_ARRAY_NO_RELEASE 1
#define GSI_ARRAY_NO_RETAIN 1

#ifdef GSIArray
#undef GSIArray
#endif
#include <GNUstepBase/GSIArray.h>

static GSToolTips *toolTipVisible = nil;
static id<GSWindowDecorator> windowDecorator = nil;


BOOL GSViewAcceptsDrag(NSView *v, id<NSDraggingInfo> dragInfo);

@interface NSObject (DragInfoBackend)
- (void) dragImage: (NSImage*)anImage
                at: (NSPoint)screenLocation
            offset: (NSSize)initialOffset
             event: (NSEvent*)event
        pasteboard: (NSPasteboard*)pboard
            source: (id)sourceObject
         slideBack: (BOOL)slideFlag;
- (void) postDragEvent: (NSEvent*)event;
@end

@interface NSView (MoveToWindow)
// Normally this method is only used internally.
- (void) _viewWillMoveToWindow: (NSWindow*)newWindow;
@end

@interface NSScreen (PrivateMethods)
- (id) _initWithScreenNumber: (int)screen;
@end

@interface NSApplication(Inactive)
- (BOOL) _isWindowInactive: (NSWindow *)window;
- (void) _setWindow: (NSWindow *)window inactive: (BOOL)inactive;
@end

@interface GSWindowAnimationDelegate : NSObject
{
}
@end

@implementation GSWindowAnimationDelegate
- (void) animationDidEnd: (NSAnimation *)animation
{
  AUTORELEASE(animation);
}

- (void) animationDidStop: (NSAnimation *)animation
{
  AUTORELEASE(animation);
}

@end

static GSWindowAnimationDelegate *animationDelegate;

/*
 * Category for internal methods (for use only within the NSWindow class itself
 * or with other AppKit classes.
 */
@interface NSWindow (GNUstepPrivate)

+ (void) _addAutodisplayedWindow: (NSWindow *)w;
+ (void) _removeAutodisplayedWindow: (NSWindow *)w;
+ (void) _setToolTipVisible: (GSToolTips*)t;
+ (GSToolTips*) _toolTipVisible;

- (void) _lossOfKeyOrMainWindow;
- (NSView *) _windowView; 
- (NSScreen *) _screenForFrame: (NSRect)frame;
@end

@implementation NSWindow (GNUstepPrivate)

+ (void) _setToolTipVisible: (GSToolTips*)t
{
  toolTipVisible = t;
}

+ (GSToolTips*) _toolTipVisible
{
  return toolTipVisible;
}

/* Window autodisplay machinery. */
- (void) _handleAutodisplay
{
  if (_f.is_autodisplay && _f.views_need_display)
    {
      [self disableFlushWindow];
      [self displayIfNeeded];
      [self enableFlushWindow];
      [self flushWindowIfNeeded];
    }
}

static NSArray *modes = nil;

/* Array of windows we might need to handle autodisplay for (in practice
a list of windows that are, wrt. -gui, on-screen). */
static GSIArray_t autodisplayedWindows;

/*
This method handles all normal displaying. It is set to be run on each
runloop iteration when the first window is created

The reason why this performer is always added, as opposed to adding it
when display is needed and not re-adding it here, is that
-setNeedsDisplay* might be called from a method invoked by
-performSelector:target:argument:order:modes:, and if it is, the display
needs to happen in the same runloop iteration, before blocking for
events. If the performer were added in a call to another performer, it
wouldn't be called until the next runloop iteration, ie. after the runloop
has blocked and waited for events.
*/
+(void) _handleAutodisplay: (id)bogus
{
  int i;
  for (i = 0; i < GSIArrayCount(&autodisplayedWindows); i++)
    [GSIArrayItemAtIndex(&autodisplayedWindows, i).ext _handleAutodisplay];

  [[NSRunLoop currentRunLoop]
         performSelector: @selector(_handleAutodisplay:)
                  target: self
                argument: nil
                   order: 600000
                   modes: modes];
}

+(void) _addAutodisplayedWindow: (NSWindow *)w
{
  int i;
  /* If it's the first time we're called, set up the performer and modes
  array. */
  if (!modes)
    {
      modes = [[NSArray alloc] initWithObjects: NSDefaultRunLoopMode,
                               NSModalPanelRunLoopMode,
                               NSEventTrackingRunLoopMode, nil];
      [[NSRunLoop currentRunLoop]
         performSelector: @selector(_handleAutodisplay:)
                  target: self
                argument: nil
                   order: 600000
                   modes: modes];
      GSIArrayInitWithZoneAndCapacity(&autodisplayedWindows,
        NSDefaultMallocZone(), 1);
    }

  /* O(n), but it's much more important that _handleAutodisplay: can iterate
  quickly over the array. (_handleAutodisplay: is called once for every
  event, this method is only called when windows are ordered in or out.) */
  for (i = 0; i < GSIArrayCount(&autodisplayedWindows); i++)
    if (GSIArrayItemAtIndex(&autodisplayedWindows, i).ext == w)
      return;
  GSIArrayAddItem(&autodisplayedWindows, (GSIArrayItem)w);
}

+(void) _removeAutodisplayedWindow: (NSWindow *)w
{
  int i;
  for (i = 0; i < GSIArrayCount(&autodisplayedWindows); i++)
    if (GSIArrayItemAtIndex(&autodisplayedWindows, i).ext == w)
      {
        GSIArrayRemoveItemAtIndex(&autodisplayedWindows, i);
        return;
      }
  /* This happens eg. if a window is ordered out twice. In such cases,
  the window has already been removed from the list, so we don't need
  to do anything here. */
}


/* We get here if we were ordered out or miniaturized. In this case if
   we were the key or main window, go through the list of all windows
   and try to find another window that can take our place as key
   and/or main. Automatically ignore windows that cannot become
   key/main and skip the main menu window (which is the only
   non-obvious window that can become key) unless we have no choice
   (i.e. all the candidate windows were ordered out.)
*/
- (void) _lossOfKeyOrMainWindow
{
  NSArray *windowList = GSOrderedWindows();
  NSUInteger pos = [windowList indexOfObjectIdenticalTo: self];
  NSUInteger c = [windowList count];
  NSUInteger i;

  // Don't bother when application is closing.
  if ([NSApp isRunning] == NO)
    return;

  if (!c)
    return;

  if (pos == NSNotFound)
    {
      pos = c;
    }

  if ([self isKeyWindow])
    {
      NSWindow *w = [NSApp mainWindow];

      [self resignKeyWindow];
      if (w != nil && w != self 
          && [w canBecomeKeyWindow])
        {
          [w makeKeyWindow];
        }
      else
        {
          NSWindow *menu_window = [[NSApp mainMenu] window];

          // try all windows front to back except self and menu
          for (i = 0; i < c; i++)
            {
              if (i != pos)
                {
                  w = [windowList objectAtIndex: i];
                  if ([w isVisible] && [w canBecomeKeyWindow] 
                      && w != menu_window)
                    {
                      [w makeKeyWindow];
                      break;
                    }
                }
            }

          /*
           * if we didn't find a possible key window - use the main menu window
           */
          if (i == c)
            {
              if (menu_window != nil)
                {
                  // FIXME: Why this call and not makeKeyWindow?
                  [GSServerForWindow(menu_window) setinputfocus: 
                                        [menu_window windowNumber]];
                }
            }
        }
    }

  if ([self isMainWindow])
    {
      NSWindow *w = [NSApp keyWindow];

      [self resignMainWindow];
      if (w != nil && [w canBecomeMainWindow])
        {
          [w makeMainWindow];
        }
      else
        {
         // try all windows front to back except self
          for (i = 0; i < c; i++)
            {
              if (i != pos)
                {
                  w = [windowList objectAtIndex: i];
                  if ([w isVisible] && [w canBecomeMainWindow])
                    {
                      [w makeMainWindow];
                      break;
                    }
                }
            }
        }
    }
}

- (NSView *) _windowView
{
  return _wv;
}

/*
 * This is just the Apple name for our _windowView method.
 */
- (NSView *) _borderView
{
  return _wv;
}

/* Support method to properly implement the 'screen' method for NSWindow.
   According to documentation the 'screen' method should return the screen
   that the window "show up the most or nil".  This method supports the 'screen'
   method and internal requests for the correct 'screen' based on the
   supplied frame request.
*/
- (NSScreen *) _screenForFrame: (NSRect)frame
{
  CGFloat    largest   = 0.0;
  NSArray   *screens   = [NSScreen screens];
  NSInteger  index     = 0;
  NSScreen  *theScreen = nil;

  for (index = 0; index < [screens count]; ++index)
    {
      NSScreen  *screen = [screens objectAtIndex: index];
      NSRect     sframe = [screen frame];
      NSRect     iframe = NSIntersectionRect(frame, sframe);
      CGFloat    isize  = NSWidth(iframe) * NSHeight(iframe);

      if (isize > largest)
        {
          largest   = isize;
          theScreen = screen;
        }
    }
  NSDebugLLog(@"NSWindow", @"%s: frame: %@ screen: %@ size: %ld\n", __PRETTY_FUNCTION__,
              NSStringFromRect(frame), theScreen, (long)largest);

  return theScreen;
}

@end


@interface NSMiniWindow : NSWindow
@end

@implementation NSMiniWindow

- (BOOL) canBecomeMainWindow
{
  return NO;
}

- (BOOL) canBecomeKeyWindow
{
  return NO;
}

- (void) _initDefaults
{
  [super _initDefaults];
  [self setExcludedFromWindowsMenu: YES];
  [self setReleasedWhenClosed: NO];
  /* App icons and mini windows are displayed at dock level by default. Yet,
     with the current window level mapping in -back, some window managers
     will order pop up and context menus behind app icons and mini windows.
     Therefore, it is possible to have app icons and mini windows displayed
     at normal window level under control of a user preference. */
  // See also NSIconWindow _initDefaults in NSApplication.m
  if ([[NSUserDefaults standardUserDefaults]
	boolForKey: @"GSAllowWindowsOverIcons"] == YES)
    _windowLevel = NSDockWindowLevel;
}

@end

@interface NSMiniWindowView : NSView
{
  NSCell *imageCell;
  NSTextFieldCell *titleCell;
}
- (void) setImage: (NSImage*)anImage;
- (void) setTitle: (NSString*)aString;
@end

static NSCell *tileCell = nil;

static NSSize scaledIconSizeForSize(NSSize imageSize)
{
  NSSize iconSize, retSize;

  iconSize = GSGetIconSize();
  retSize.width = imageSize.width * iconSize.width / 64;
  retSize.height = imageSize.height * iconSize.height / 64;
  return retSize;
}

@implementation NSMiniWindowView

+ (void) initialize
{
  NSImage *tileImage;
  NSSize iconSize;
  
  iconSize = GSGetIconSize();
  
  tileImage = [[GSCurrentServer() iconTileImage] copy];
  [tileImage setScalesWhenResized: YES];
  [tileImage setSize: iconSize];
  
  tileCell = [[NSCell alloc] initImageCell: tileImage];
  RELEASE(tileImage);
  [tileCell setBordered: NO];
}

- (BOOL) acceptsFirstMouse: (NSEvent*)theEvent
{
  return YES;
}

- (void) dealloc
{
  TEST_RELEASE(imageCell);
  TEST_RELEASE(titleCell);
  [super dealloc];
}

- (void) drawRect: (NSRect)rect
{   
  NSSize iconSize = GSGetIconSize();

  [tileCell drawWithFrame: NSMakeRect(0, 0, iconSize.width, iconSize.height)
                     inView: self];
  [imageCell
       drawWithFrame: NSMakeRect(iconSize.width / 8,
                                 (iconSize.height / 16),
                                 iconSize.width - ((iconSize.width / 8) * 2),
                                 iconSize.height - ((iconSize.height / 8) * 2))
              inView: self];
  [titleCell drawWithFrame: NSMakeRect(1, iconSize.height - 12,
                                       iconSize.width - 2, 11)
                    inView: self];
}

- (void) mouseDown: (NSEvent*)theEvent
{
  if ([theEvent clickCount] >= 2)
    {
      NSWindow *w = [_window counterpart];
      [w deminiaturize: self];
    }
  else
    {
      NSPoint lastLocation;
      NSPoint location;
      NSUInteger eventMask = NSLeftMouseDownMask | NSLeftMouseUpMask
        | NSPeriodicMask | NSOtherMouseUpMask | NSRightMouseUpMask;
      NSDate *theDistantFuture = [NSDate distantFuture];
      BOOL done = NO;

      lastLocation = [theEvent locationInWindow];
      [NSEvent startPeriodicEventsAfterDelay: 0.02 withPeriod: 0.02];

      while (!done)
        {
          theEvent = [NSApp nextEventMatchingMask: eventMask
                                        untilDate: theDistantFuture
                                           inMode: NSEventTrackingRunLoopMode
                                          dequeue: YES];
        
          switch ([theEvent type])
            {
              case NSRightMouseUp:
              case NSOtherMouseUp:
              case NSLeftMouseUp:
              /* right mouse up or left mouse up means we're done */
                done = YES;
                break;
              case NSPeriodic:
                location = [_window mouseLocationOutsideOfEventStream];
                if (NSEqualPoints(location, lastLocation) == NO)
                  {
                    NSPoint origin = [_window frame].origin;

                    origin.x += (location.x - lastLocation.x);
                    origin.y += (location.y - lastLocation.y);
                    [_window setFrameOrigin: origin];
                  }
                break;

              default:
                break;
            }
        }
      [NSEvent stopPeriodicEvents];
    }
}                                                        

- (void) setImage: (NSImage*)anImage
{
  NSImage *imgCopy = [anImage copy];

  [imgCopy setScalesWhenResized: YES];
  [imgCopy setSize: scaledIconSizeForSize([imgCopy size])];
 
  if (imageCell == nil)
    {
      imageCell = [[NSCell alloc] initImageCell: imgCopy];
      [imageCell setBordered: NO];
    }
  else
    {
      [imageCell setImage: imgCopy];
    }
  RELEASE(imgCopy);
  [self setNeedsDisplay: YES];  
}

- (void) setTitle: (NSString*)aString
{
  if (titleCell == nil)
    {
      titleCell = [[NSTextFieldCell alloc] initTextCell: aString];
      [titleCell setSelectable: NO];
      [titleCell setEditable: NO];
      [titleCell setBordered: NO];
      [titleCell setAlignment: NSCenterTextAlignment];
      [titleCell setDrawsBackground: YES];
      [titleCell setBackgroundColor: [NSColor blackColor]];
      [titleCell setTextColor: [NSColor whiteColor]];
      [titleCell setFont: [NSFont systemFontOfSize: 8]];
    }
  else
    {
      [titleCell setStringValue: aString];
    }
  [self setNeedsDisplay: YES];
}

@end



/*****************************************************************************
 *
 *        NSWindow
 *
 *****************************************************************************/

/**
  <unit>
  <heading>NSWindow</heading>
  
  <p> Instances of the NSWindow class handle on-screen windows, their
  associated NSViews, and events generate by the user.  An NSWindow's
  size is defined by its frame rectangle, which encompasses its entire
  structure, and its content rectangle, which includes only the
  content.  
  </p>

  <p> Every NSWindow has a content view, the NSView which forms the
  root of the window's view hierarchy.  This view can be set using the
  <code>setContentView:</code> method, and accessed through the
  <code>contentView</code> method.  <code>setContentView:</code>
  replaces the default content view created by NSWindow.  
  </p>

  <p> Other views may be added to the window by using the content
  view's <code>addSubview:</code> method.  These subviews can also
  have subviews added, forming a tree structure, the view hierarchy.
  When an NSWindow must display itself, it causes this hierarchy to
  draw itself.  Leaf nodes in the view hierarchy are drawn last,
  causing them to potentially obscure views further up in the
  hierarchy.  
  </p>

  <p> A delegate can be specified for an NSWindow, which will receive
  notifications of events pertaining to the window.  The delegate is
  set using <code>setDelegate:</code>, and can be retrieved using
  <code>delegate</code>.  The delegate can restrain resizing by
  implementing the <code>windowWillResize: toSize:</code> method, or
  control the closing of the window by implementing
  <code>windowShouldClose:</code>.  
  </p> 

  </unit>
*/
@implementation NSWindow

/*
 * Class variables
 */
static SEL        ccSel;
static SEL        ctSel;
static IMP        ccImp;
static IMP        ctImp;
static Class      responderClass;
static Class      viewClass;
static NSMutableSet *autosaveNames;
static NSMapTable *windowmaps = NULL;
static NSMapTable *windowUndoManagers = NULL;
static NSNotificationCenter *nc = nil;

/*
 * Class methods
 */
+ (void) initialize
{
  if (self == [NSWindow class])
    {
      [self setVersion: 3];
      ccSel = @selector(_checkCursorRectangles:forEvent:);
      ctSel = @selector(_checkTrackingRectangles:forEvent:);
      ccImp = [self instanceMethodForSelector: ccSel];
      ctImp = [self instanceMethodForSelector: ctSel];
      responderClass = [NSResponder class];
      viewClass = [NSView class];
      autosaveNames = [NSMutableSet new];
      windowmaps = NSCreateMapTable(NSIntMapKeyCallBacks,
                                    NSNonRetainedObjectMapValueCallBacks, 20);
      nc = [NSNotificationCenter defaultCenter];

      [self exposeBinding: NSTitleBinding];
    }
}

+ (void) removeFrameUsingName: (NSString*)name
{
  if (name != nil)
    {
      NSString *key;

      key = [NSString stringWithFormat: @"NSWindow Frame %@", name];
      [[NSUserDefaults standardUserDefaults] removeObjectForKey: key];
    }
}

+ (NSRect) contentRectForFrameRect: (NSRect)aRect
                         styleMask: (NSUInteger)aStyle
{
  if (!windowDecorator)
    windowDecorator = [GSWindowDecorationView windowDecorator];

  return [windowDecorator contentRectForFrameRect: aRect
                                        styleMask: aStyle];
}

+ (NSRect) frameRectForContentRect: (NSRect)aRect
                         styleMask: (NSUInteger)aStyle
{
  if (!windowDecorator)
    windowDecorator = [GSWindowDecorationView windowDecorator];

  return [windowDecorator frameRectForContentRect: aRect
                                        styleMask: aStyle];
}

+ (CGFloat) minFrameWidthWithTitle: (NSString *)aTitle
                       styleMask: (NSUInteger)aStyle
{
  if (!windowDecorator)
    windowDecorator = [GSWindowDecorationView windowDecorator];

  return [windowDecorator minFrameWidthWithTitle: aTitle
                                       styleMask: aStyle];
}

/* default Screen and window depth */
+ (NSWindowDepth) defaultDepthLimit
{
  return [[NSScreen deepestScreen] depth];
}

+ (void)menuChanged: (NSMenu*)aMenu
{
  // FIXME: This method is for MS Windows only, does nothing 
  // on other window systems 
}

/*
 * Instance methods
 */
- (id) init
{
  NSUInteger style;

  style = NSTitledWindowMask | NSClosableWindowMask
          | NSMiniaturizableWindowMask | NSResizableWindowMask;

  return [self initWithContentRect: NSZeroRect
                         styleMask: style
                           backing: NSBackingStoreBuffered
                             defer: NO];
}

/*
It is important to make sure that the window is in a meaningful state after
this has been called, and that the backend window can be recreated later,
since one-shot windows may have their backend windows created and terminated
many times.
*/
- (void) _terminateBackendWindow
{
  if (_windowNum)
    {
      [_wv setWindowNumber: 0];

      /* Check for context also as it might have disappeared before us */
      if (_context && _gstate)
        {
          GSUndefineGState(_context, _gstate);
          _gstate = 0;
        }
  
      if (_context)
        {
          /* 
             If there was a context, clear it and let it remove the
             window in that process. This indirection is needed so solve the 
             circular references between the window and the context.
             But first undo the release call in _startBackendWindow.
          */
          RETAIN(self);
          DESTROY(_context);
        }

      [GSServerForWindow(self) termwindow: _windowNum];
      NSMapRemove(windowmaps, (void*)(intptr_t)_windowNum);
      _windowNum = 0;
    }
}

- (void) dealloc
{
  // Remove all key value bindings for this object.
  [GSKeyValueBinding unbindAllForObject: self];

  DESTROY(_toolbar);
  [nc removeObserver: self];
  [[self class] _removeAutodisplayedWindow: self];
  [NSApp removeWindowsItem: self];
  [NSApp _windowWillDealloc: self];

  NSAssert([NSApp keyWindow] != self, @"window being deallocated is key");
  NSAssert([NSApp mainWindow] != self, @"window being deallocated is main");

  if (windowUndoManagers != NULL)
    NSMapRemove(windowUndoManagers, self);

  if (_autosaveName != nil)
    {
      [autosaveNames removeObject: _autosaveName];
      _autosaveName = nil;
    }

  if (_counterpart != 0 && (_styleMask & NSMiniWindowMask) == 0)
    {
      NSWindow *mini = [NSApp windowWithWindowNumber: _counterpart];

      _counterpart = 0;
      DESTROY(mini);
    }

  /* Terminate backend window early so that the receiver is no longer returned
     from GSOrderedWindows() or GSAllWindows(). This helps to prevent crashes
     due to a race with some lame window managers under X that do not update
     the _NET_CLIENT_LIST_STACKING property quickly enough. GSOrderedWindows()
     may be called (indirectly) when a tooltip is visible while a window is
     deallocated. */
  if (_windowNum)
    {
      [self _terminateBackendWindow];
    }

  /* Clean references to this window - important if some of the views
     are not deallocated now */
  [_wv _viewWillMoveToWindow: nil];
  /* NB: releasing the window view does not necessarily result in the
     deallocation of the window's views ! - some of them might be
     retained for some other reason by the programmer or by other
     parts of the code */
  DESTROY(_wv);
  DESTROY(_fieldEditor);
  DESTROY(_backgroundColor);
  DESTROY(_representedFilename);
  DESTROY(_miniaturizedTitle);
  DESTROY(_miniaturizedImage);
  DESTROY(_windowTitle);
  DESTROY(_rectsBeingDrawn);
  DESTROY(_initialFirstResponder);
  DESTROY(_defaultButtonCell);
  DESTROY(_cachedImage);
  DESTROY(_children);
  DESTROY(_lastLeftMouseDownView);
  DESTROY(_lastRightMouseDownView);
  DESTROY(_lastOtherMouseDownView);
  DESTROY(_lastDragView);
  DESTROY(_screen);

  /*
   * FIXME This should not be necessary - the views should have removed
   * their drag types, so we should already have been removed.
   */
  [GSServerForWindow(self) removeDragTypes: nil fromWindow: self];

  if (_delegate != nil)
    {
      [nc removeObserver: _delegate  name: nil  object: self];
      _delegate = nil;
    }

  [super dealloc];
}

- (NSString*) description
{
  return [[super description] stringByAppendingFormat: @"Number: %ld Title: %@",
    (long) [self windowNumber], [self title]];
}

- (void) _startBackendWindow
{
  NSDictionary *info;

  NSMapInsert(windowmaps, (void*)(intptr_t)_windowNum, self);

  // Make sure not to create an autoreleased object,
  // as this will lead to problems when the window is deallocated.
  info = [[NSDictionary alloc] 
             initWithObjects: &self 
             forKeys: &NSGraphicsContextDestinationAttributeName
             count: 1];
  _context = [[NSGraphicsContext alloc] initWithContextInfo: info];
  RELEASE(info);
  if (_context)
    {
      // Now the context retains the window, release it once to make up
      RELEASE(self);
    }

  // Set window in new _gstate
  _gstate = GSDefineGState(_context);

  {
    NSRect frame = _frame;
    frame.origin = NSZeroPoint;
    [_wv setFrame: frame];
    [_wv setWindowNumber: _windowNum];
    [_wv setDocumentEdited: _f.is_edited];
    [_wv setNeedsDisplay: YES];
  }
}

- (void) _initBackendWindow
{
  NSCountedSet *dragTypes;
  GSDisplayServer *srv = GSCurrentServer();

  /* If we were deferred or one shot, our drag types may not have
     been registered properly in the backend. Remove them then re-add
     them when we create the window */
  dragTypes = [srv dragTypesForWindow: self];
  if (dragTypes)
    {
      // As this is the original entry, it will change soon. 
      // We use a copy to reregister the same types later on.
      dragTypes = [dragTypes copy];

      /* Now we need to remove all the drag types for this window.  */
      [srv removeDragTypes: nil fromWindow: self];
    }

  _windowNum = [srv window: _frame
                    : _backingType
                    : _styleMask
                    : [_screen screenNumber]];
  if (_windowNum == 0)
    [NSException raise:@"No Window" format:@"Failed to obtain window from the back end"];
  [srv setwindowlevel: [self level] : _windowNum];
  if (_parent != nil)
    [srv setParentWindow: [_parent windowNumber] 
          forChildWindow: _windowNum];

  // Set up context
  [self _startBackendWindow];

  /* Ok, now add the drag types back */
  if (dragTypes)
    {
      id type;
      NSMutableArray *dragTypesArray = [NSMutableArray array];
      NSEnumerator *enumerator = [dragTypes objectEnumerator];

      NSDebugLLog(@"NSWindow", @"Resetting drag types for window");
      /* Now we need to restore the drag types.  */
      
      /* Put all the drag types to the dragTypesArray - counted
       * with their multiplicity.
       */
      while ((type = [enumerator nextObject]) != nil)
        {
          NSUInteger i, count = [dragTypes countForObject: type];
          
          for (i = 0; i < count; i++)
            {
              [dragTypesArray addObject: type];
            }
        }
      
      /* Now store the array.  */
      [srv addDragTypes: dragTypesArray toWindow: self];
      // Free our local copy.
      RELEASE(dragTypes);
    }

  /* Other stuff we need to do for deferred windows */
  if (!NSEqualSizes(_minimumSize, NSZeroSize))
    [self setMinSize: _minimumSize];
  if (!NSEqualSizes(_maximumSize, NSZeroSize))
    [self setMaxSize: _maximumSize];
  if (!NSEqualSizes(_increments, NSZeroSize))
    [self setResizeIncrements: _increments];

  NSDebugLLog(@"NSWindow", @"Created NSWindow window frame %@",
              NSStringFromRect(_frame));
}

/*
 * Initializing and getting a new NSWindow object
 */
/**
  <p> Initializes the receiver with a content rect of
  <var>contentRect</var>, a style mask of <var>styleMask</var>, and a
  backing store type of <var>backingType</var>.  This is the designated
  initializer.
  </p>

  <p> The style mask values are <code>NSTitledWindowMask</code>, for a
  window with a title, <code>NSClosableWindowMask</code>, for a window
  with a close widget, <code>NSMiniaturizableWindowMask</code>, for a
  window with a miniaturize widget, and
  <code>NSResizableWindowMask</code>, for a window with a resizing
  widget.  These mask values can be OR'd in any combination.  
  </p>
 
  <p> Backing store values are <code>NSBackingStoreBuffered</code>,
  <code>NSBackingStoreRetained</code> and
  <code>NSBackingStoreNonretained</code>.  
  </p> 
*/
- (id) initWithContentRect: (NSRect)contentRect
                 styleMask: (NSUInteger)aStyle
                   backing: (NSBackingStoreType)bufferingType
                     defer: (BOOL)flag
{
  NSRect  cframe;

  NSAssert(NSApp,
    @"The shared NSApplication instance must be created before windows "
    @"can be created.");

  NSDebugLLog(@"NSWindow", @"NSWindow start of init\n");

  // FIXME: This hack is here to work around a gorm decoding problem.
  if (_windowNum)
    {
      NSLog(@"Window already initialized %d", (int)_windowNum);
      return self;
    }

  /* Initialize attributes and flags */
  [super init];
  [self _initDefaults];
  
  _attachedSheet = nil;
  _backingType = bufferingType;
  _styleMask = aStyle;
  ASSIGN(_screen, [NSScreen mainScreen]);
  _depthLimit = [_screen depth];
  
  _frame = [NSWindow frameRectForContentRect: contentRect styleMask: aStyle];
  _minimumSize = NSMakeSize(_frame.size.width - contentRect.size.width + 1,
                            _frame.size.height - contentRect.size.height + 1);
  _maximumSize = NSMakeSize (10e4, 10e4);

  [self setNextResponder: NSApp];

  _f.cursor_rects_enabled = YES;
  _f.cursor_rects_valid = NO;

  /* Create the window view */
  cframe.origin = NSZeroPoint;
  cframe.size = _frame.size;
  if (!windowDecorator)
    windowDecorator = [GSWindowDecorationView windowDecorator];

  _wv = [windowDecorator newWindowDecorationViewWithFrame: cframe
                                                   window: self];
  [_wv _viewWillMoveToWindow: self];
  [_wv setNextResponder: self];

  /* Create the content view */
  cframe.origin = NSZeroPoint;
  cframe.size = contentRect.size;
  [self setContentView: AUTORELEASE([[NSView alloc] initWithFrame: cframe])];

  /* rectBeingDrawn is variable used to optimize flushing the backing store.
     It is set by NSGraphicsContext during a lockFocus to tell NSWindow what
     part a view is drawing in, so NSWindow only has to flush that portion */
  _rectsBeingDrawn = RETAIN([NSMutableArray arrayWithCapacity: 10]);

  /* Create window (if not deferred) */
  _windowNum = 0;
  _gstate = 0;
  if (flag == NO)
    {
      NSDebugLLog(@"NSWindow", @"Creating NSWindow\n");
      [self _initBackendWindow];
    }
  else
    NSDebugLLog(@"NSWindow", @"Deferring NSWindow creation\n");

  [nc addObserver: self
         selector: @selector(colorListChanged:)
             name: NSColorListDidChangeNotification
           object: nil];

  NSDebugLLog(@"NSWindow", @"NSWindow end of init\n");
  return self;
}

/**
  <p> Initializes the receiver with a content rect of
  <var>contentRect</var>, a style mask of <var>styleMask</var>, a
  backing store type of <var>backingType</var> and a boolean
  <var>flag</var>.  <var>flag</var> specifies whether the window
  should be created now (<code>NO</code>), or when it is displayed
  (<code>YES</code>).  
  </p>

  <p> The style mask values are <code>NSTitledWindowMask</code>, for a
  window with a title, <code>NSClosableWindowMask</code>, for a window
  with a close widget, <code>NSMiniaturizableWindowMask</code>, for a
  window with a miniaturize widget, and
  <code>NSResizableWindowMask</code>, for a window with a resizing
  widget.  These mask values can be OR'd in any combination.  
  </p>

  <p> Backing store values are <code>NSBackingStoreBuffered</code>,
  <code>NSBackingStoreRetained</code> and
  <code>NSBackingStoreNonretained</code>.  
  </p> 
*/
- (id) initWithContentRect: (NSRect)contentRect
                 styleMask: (NSUInteger)aStyle
                   backing: (NSBackingStoreType)bufferingType
                     defer: (BOOL)flag
                    screen: (NSScreen*)aScreen
{
  self = [self initWithContentRect: contentRect
                         styleMask: aStyle
                           backing: bufferingType
                             defer: flag];
  if (self && aScreen != nil)
    {
      ASSIGN(_screen, aScreen);
      _depthLimit = [_screen depth];
    }
  return self;
}

- (id) initWithWindowRef: (void *)windowRef
{
  NSRect contentRect;
  unsigned int aStyle;
  NSBackingStoreType bufferingType;
  NSScreen* aScreen;
  int screen;
  NSInteger winNum;
  GSDisplayServer *srv = GSCurrentServer();

  // Get the properties for the underlying window
  winNum = [srv nativeWindow: windowRef : &contentRect : &bufferingType
                                : &aStyle : &screen];

  // Get the screen for the right screen number.
  aScreen = [[NSScreen alloc] _initWithScreenNumber: screen];

  // Set up a NSWindow with the same properties
  self = [self initWithContentRect: contentRect
                         styleMask: aStyle
                           backing: bufferingType
                             defer: YES
                            screen: aScreen];
  RELEASE(aScreen);

  // Fake the initialisation of the backend
  _windowNum = winNum;

  // Set up context
  [self _startBackendWindow];

  return self;
}

-(void) colorListChanged:(NSNotification*)notif
{
  if ([[notif object] isEqual: [NSColorList colorListNamed:@"System"]])
    {
      [_wv setNeedsDisplay:YES];
    }
}

- (NSRect) contentRectForFrameRect: (NSRect)frameRect
{
  return [_wv contentRectForFrameRect: frameRect styleMask: _styleMask];
}

- (NSRect) frameRectForContentRect: (NSRect)contentRect
{
  return [_wv frameRectForContentRect: contentRect styleMask: _styleMask];
}

/*
 * Accessing the content view
 */
- (id) contentView
{
  return _contentView;
}

/**
  Sets the window's content view to <var>aView</var>, replacing any
  previous content view.  */
- (void) setContentView: (NSView*)aView
{
  if (aView == _contentView)
    return;

  if (_contentView != nil)
    {
      [_contentView removeFromSuperview];
    }
  _contentView = aView;

  if (_contentView != nil)
    {
      [_wv setContentView: _contentView];
    }
}

/*
 * Window graphics
 */
- (NSColor*) backgroundColor
{
  return _backgroundColor;
}

- (NSString*) representedFilename
{
  return _representedFilename;
}

- (void) setBackgroundColor: (NSColor*)color
{
  ASSIGN(_backgroundColor, color);
  [_wv setBackgroundColor: color];
}

- (void) setRepresentedFilename: (NSString*)aString
{
  ASSIGN(_representedFilename, aString);
}

/** Sets the window's title to the string <var>aString</var>. */
- (void) setTitle: (NSString*)aString
{
  if ([_windowTitle isEqual: aString] == NO)
    {
      ASSIGNCOPY(_windowTitle, aString);
      [self setMiniwindowTitle: _windowTitle];
      [_wv setTitle: _windowTitle];
      if (_f.menu_exclude == NO && _f.has_opened == YES)
        {
          [NSApp changeWindowsItem: self
                             title: _windowTitle
                          filename: NO];
        }
    }
}

static NSString *
titleWithRepresentedFilename(NSString *representedFilename)
{
  return [NSString stringWithFormat: @"%@  --  %@", 
		   [representedFilename lastPathComponent],
		   [[representedFilename stringByDeletingLastPathComponent]
		     stringByAbbreviatingWithTildeInPath]];
}

- (BOOL) _hasTitleWithRepresentedFilename
{
  NSString *aString = titleWithRepresentedFilename (_representedFilename);
  return [_windowTitle isEqualToString: aString];
}

- (void) setTitleWithRepresentedFilename: (NSString*)aString
{
  [self setRepresentedFilename: aString];
  aString = titleWithRepresentedFilename(aString);
  if ([_windowTitle isEqual: aString] == NO)
    {
      ASSIGNCOPY(_windowTitle, aString);
      [self setMiniwindowTitle: _windowTitle];
      [_wv setTitle: _windowTitle];
      if (_f.menu_exclude == NO && _f.has_opened == YES)
        {
          [NSApp changeWindowsItem: self
                             title: _windowTitle
                          filename: YES];
        }
    }
}

- (NSUInteger) styleMask
{
  return _styleMask;
}

/** Returns an NSString containing the text of the window's title. */
- (NSString*) title
{
  return _windowTitle;
}

- (void) setHasShadow: (BOOL)hasShadow
{
  _f.has_shadow = hasShadow;
  if (_windowNum)
    {
      [GSServerForWindow(self) setShadow: hasShadow : _windowNum];
    }
}

- (BOOL) hasShadow
{
  return _f.has_shadow;
}

- (void) invalidateShadow
{
// FIXME
}

- (void) setAlphaValue: (CGFloat)windowAlpha
{
  _alphaValue = windowAlpha;
  if (_windowNum)
    {
      [GSServerForWindow(self) setalpha: _alphaValue : _windowNum];
    }
}

- (CGFloat) alphaValue
{
  return _alphaValue;
}

- (void) setOpaque: (BOOL)isOpaque
{
  // FIXME
  _f.is_opaque = isOpaque;
}

- (BOOL) isOpaque
{
  return _f.is_opaque;
}

/*
 * Window device attributes
 */
- (NSBackingStoreType) backingType
{
  return _backingType;
}

- (NSDictionary*) deviceDescription
{
  return [[self screen] deviceDescription];
}

- (NSGraphicsContext*) graphicsContext
{
  return _context;
}

- (CGFloat) userSpaceScaleFactor
{
  if (_styleMask & NSUnscaledWindowMask)
    {
      return 1.0;
    }
  else if (_screen != nil)
     {
       return [_screen userSpaceScaleFactor];
     }
  else
    {
      return 1.0;
    }
}

- (NSInteger) gState
{
  if (_gstate <= 0)
    NSDebugLLog(@"NSWindow", @"gState called on deferred window");
  return _gstate;
}

- (BOOL) isOneShot
{
  return _f.is_one_shot;
}

- (void) setBackingType: (NSBackingStoreType)type
{
  _backingType = type;
}

- (void) setOneShot: (BOOL)flag
{
  _f.is_one_shot = flag;
}

- (NSInteger) windowNumber
{
  if (_windowNum <= 0)
    NSDebugLLog(@"NSWindow", @"windowNumber called on deferred window");
  return _windowNum;
}

/*
 * The miniwindow
 */
- (NSImage*) miniwindowImage
{
  return _miniaturizedImage;
}

- (NSString*) miniwindowTitle
{
  return _miniaturizedTitle;
}

- (void) setMiniwindowImage: (NSImage*)image
{
  ASSIGN(_miniaturizedImage, image);
  if (_counterpart != 0 && (_styleMask & NSMiniWindowMask) == 0)
    {
      NSMiniWindow        *mini;
      id                v;

      mini = (NSMiniWindow*)[NSApp windowWithWindowNumber: _counterpart];
      v = [mini contentView];
      if ([v respondsToSelector: @selector(setImage:)])
        {
          [v setImage: [self miniwindowImage]];
        }
    }
}

- (void) setMiniwindowTitle: (NSString*)title
{
  ASSIGN(_miniaturizedTitle, title);
  if (_counterpart != 0 && (_styleMask & NSMiniWindowMask) == 0)
    {
      NSMiniWindow        *mini;
      id                v;

      mini = (NSMiniWindow*)[NSApp windowWithWindowNumber: _counterpart];
      v = [mini contentView];
      if ([v respondsToSelector: @selector(setTitle:)])
        {
          [v setTitle: [self miniwindowTitle]];
        }
    }
}

- (NSWindow*) counterpart
{
  if (_counterpart == 0)
    return nil;
  return [NSApp windowWithWindowNumber: _counterpart];
}

/*
 * The field editor
 */
- (void) endEditingFor: (id)anObject
{
  NSText *t = [self fieldEditor: NO
                    forObject: anObject];

  if (t && (_firstResponder == t))
    {
      // Change first responder first to avoid recusion.
      _firstResponder = self;
      [_firstResponder becomeFirstResponder];
      [nc postNotificationName: NSTextDidEndEditingNotification
          object: t];
      [t setText: @""];
      [t setDelegate: nil];
      [t removeFromSuperview];
    }
}

- (NSText*) fieldEditor: (BOOL)createFlag forObject: (id)anObject
{
  /* ask delegate if it can provide a field editor */
  if ((_delegate != anObject) 
    && [_delegate respondsToSelector:
    @selector(windowWillReturnFieldEditor:toObject:)]) 
    {
      NSText *editor;
      
      editor = [_delegate windowWillReturnFieldEditor: self   
                                             toObject: anObject];
      
      if (editor != nil)
        {
          return editor;
        }
    }
  /*
   * Each window has a global text field editor, if it doesn't exist create it
   * if create flag is set
   */
  if (!_fieldEditor && createFlag)
    {
      _fieldEditor = [NSText new];
      [_fieldEditor setFieldEditor: YES];
    }

  return _fieldEditor;
}

/*
 * Window controller
 */
- (void) setWindowController: (NSWindowController*)windowController
{
  /* The window controller owns us, we only keep a weak reference to
     it */
  _windowController = windowController;
}

- (id) windowController
{
  return _windowController;
}

/*
 * Window status and ordering
 */
- (void) becomeKeyWindow
{
  if (_f.is_key == NO)
    {
      _f.is_key = YES;

      if ((!_firstResponder) || (_firstResponder == self))
        {
	  if (!_initialFirstResponder)
	    {
	      [self recalculateKeyViewLoop];
	    }
          if (_initialFirstResponder)
            {
              [self makeFirstResponder: _initialFirstResponder];
            }
        }

      [_firstResponder becomeFirstResponder];
      if ((_firstResponder != self)
        && [_firstResponder respondsToSelector: @selector(becomeKeyWindow)])
        {
          [_firstResponder becomeKeyWindow];
        }

      [_wv setInputState: GSTitleBarKey];
      [GSServerForWindow(self) setinputfocus: _windowNum];
      [self resetCursorRects];
      [nc postNotificationName: NSWindowDidBecomeKeyNotification object: self];
      NSDebugLLog(@"NSWindow", @"%@ is now key window", [self title]);
    }
}

- (void) becomeMainWindow
{
  if (_f.is_main == NO)
    {
      _f.is_main = YES;
      if (_f.is_key == NO)
        {
          [_wv setInputState: GSTitleBarMain];
        }
      [nc postNotificationName: NSWindowDidBecomeMainNotification object: self];
      NSDebugLLog(@"NSWindow", @"%@ is now main window", [self title]);
    }
}

/** Returns YES if the receiver can be made key. If this method returns
    NO, the window will not be made key. This implementation returns YES
    if the window is resizable or has a title bar. You can override this
    method to change it's behavior */
- (BOOL) canBecomeKeyWindow
{
  if ((NSResizableWindowMask | NSTitledWindowMask) & _styleMask)
    return YES;
  else
    return NO;
}

/** Returns YES if the receiver can be the main window. If this method
    returns NO, the window will not become the main window. This
    implementation returns YES if the window is resizable or has a
    title bar and is visible and is not an NSPanel. You can override
    this method to change it's behavior */
- (BOOL) canBecomeMainWindow
{
  if (!_f.visible)
    return NO;
  if ((NSResizableWindowMask | NSTitledWindowMask) & _styleMask)
    return YES;
  else
    return NO;
}

- (BOOL) hidesOnDeactivate
{
  return _f.hides_on_deactivate;
}

- (void) setCanHide: (BOOL)flag
{
  _f.can_hide = flag;
}

- (BOOL) canHide
{
  return _f.can_hide;
}

- (BOOL) isKeyWindow
{
  return _f.is_key;
}

- (BOOL) isMainWindow
{
  return _f.is_main;
}

- (BOOL) isMiniaturized
{
  return _f.is_miniaturized;
}

- (BOOL) isVisible
{
  return _f.visible;
}

- (NSInteger) level
{
  return _windowLevel;
}

- (void) makeKeyAndOrderFront: (id)sender
{
  [self deminiaturize: self];
  /*
   * If a window is ordered in, make sure that the application isn't hidden,
   * and is active.
   */
  if ([self canBecomeKeyWindow])
    [NSApp unhide: self];
  [self orderFrontRegardless];
  [self makeKeyWindow];
  /*
   * OPENSTEP makes a window the main window when it makes it the key window.
   * So we do the same (though the documentation doesn't mention it).
   */
  [self makeMainWindow];
}

- (void) makeKeyWindow
{
  if (!_f.visible || _f.is_miniaturized || _f.is_key == YES)
    {
      return;
    }
  if (![self canBecomeKeyWindow])
    return;
  [[NSApp keyWindow] resignKeyWindow];

  [self becomeKeyWindow];
}

- (void) makeMainWindow
{
  if (!_f.visible || _f.is_miniaturized || _f.is_main == YES)
    {
      return;
    }
  if (![self canBecomeMainWindow])
    return;
  [[NSApp mainWindow] resignMainWindow];
  [self becomeMainWindow];
}

/**
 * Orders the window to the back of its level. Equivalent to
 * -orderWindow:relativeTo: with arguments NSWindowBelow and 0.
 */
- (void) orderBack: (id)sender
{
  [self orderWindow: NSWindowBelow relativeTo: 0];
}

/**
 * If the application is active, orders the window to the front in its
 * level. If the application is not active, the window is ordered in as
 * far forward as possible in its level without being ordered in front
 * of the key or main window of the currently active app. The current key
 * and main window status is not changed. Equivalent to
 * -orderWindow:relativeTo: with arguments NSWindowAbove and 0.
 */
- (void) orderFront: (id)sender
{
  [self orderWindow: NSWindowAbove relativeTo: 0];
}

/**
  Orders the window to the front in its level (even in front of the
  key and main windows of the current app) regardless of whether the
  app is current or not. This method should only be used in rare cases
  where the app is cooperating with another app that is displaying
  data for it.  The current key and main window status is not changed.
*/
- (void) orderFrontRegardless
{
  [self orderWindow: NSWindowAbove relativeTo: -1];
}

/**
 * Orders the window out from the screen. Equivalent to
 * -orderWindow:relativeTo: with arguments NSWindowOut and 0.
 */
- (void) orderOut: (id)sender
{
  [self orderWindow: NSWindowOut relativeTo: 0];
}

/**
  <p> 
  If place is NSWindowOut, removes the window from the screen. If
  place is NSWindowAbove, places the window directly above otherWin,
  or directly above all windows in its level if otherWin is 0.  If
  place is NSWindowBelow, places the window directly below otherWin,
  or directly below all windows in its level if otherWin is 0.
  </p>
  <p>If otherWin is zero and the key window is at the same window level
  as the receiver, the receiver cannot be positioned above the key window.
  </p>
  <p>
  If place is NSWindowAbove or NSWindowBelow and the application is
  hidden, the application is unhidden.
  </p>
*/
/*
  As a special undocumented case (for -orderFrontRegardless), if otherWin
  is minus one, then the backend should not try to keep the window below the
  current key/main window
*/
- (void) orderWindow: (NSWindowOrderingMode)place relativeTo: (NSInteger)otherWin
{
  GSDisplayServer *srv = GSServerForWindow(self);
  BOOL display = NO;

  if (YES == [[NSUserDefaults standardUserDefaults]
    boolForKey: @"GSBackgroundApp"])
    {
      return;
    }

  if (place == NSWindowOut)
    {
      if (_windowNum == 0)
        {
          return;        /* This deferred window was never ordered in. */
        }
      _f.visible = NO;
      /*
       * Don't keep trying to update the window while it is ordered out
       */
      [[self class] _removeAutodisplayedWindow: self];
      [self _lossOfKeyOrMainWindow];
    }
  else
    {
      /* Windows need to be constrained when displayed or resized - but only
         titled windows are constrained. Also, and this is the tricky part,
         don't constrain if we are merely unhiding the window or if it's
         already visible and is just being reordered. */
      if ((_styleMask & NSTitledWindowMask)
          && [NSApp isHidden] == NO
          && _f.visible == NO)
        {
          NSRect nframe = [self constrainFrameRect: _frame
                                toScreen: [self screen]];
          [self setFrame: nframe display: NO];
        }
      // create deferred window
      if (_windowNum == 0)
        {
          [self _initBackendWindow];
          display = YES;
        }
    }

  /* If a hide on deactivate window is explicitly ordered in or out while
     the application is not active, remove it from the list of inactive
     windows. */
  if ([self hidesOnDeactivate] && ![NSApp isActive])
    {
      [NSApp _setWindow: self inactive: NO];
    }

  // Draw content before backend window ordering
  if (display)
    [_wv display];
  else if (place != NSWindowOut)
    [_wv displayIfNeeded];

  /* The backend will keep us below the current key window unless we
     force it not too */
  if ((otherWin == 0 
       || otherWin == [[NSApp keyWindow] windowNumber] 
       || otherWin == [[NSApp mainWindow] windowNumber])
      && [NSApp isActive])
    otherWin = -1;
    
  [srv orderwindow: place : otherWin : _windowNum];
  if (display)
    [self display];

  if (place != NSWindowOut)
    {
      /*
       * Once we are ordered back in, we will want to update the window
       * whenever there is anything to do.
       */
      [[self class] _addAutodisplayedWindow: self];

      if (_f.has_closed == YES)
        {
          _f.has_closed = NO;        /* A closed window has re-opened        */
        }
      if (_f.has_opened == NO)
        {
          _f.has_opened = YES;
          if (_f.menu_exclude == NO)
            {
              [NSApp addWindowsItem: self
                     title: _windowTitle
                     filename: [self _hasTitleWithRepresentedFilename]];
            }
        }
      if ([self isKeyWindow] == YES)
        {
          [_wv setInputState: GSTitleBarKey];
          [srv setinputfocus: _windowNum];
        }
      _f.visible = YES;
    }
  else if ([self isOneShot])
    {
      [self _terminateBackendWindow];
    }
}

- (void) resignKeyWindow
{
  if (_f.is_key == YES)
    {
      if ((_firstResponder != self)
          && [_firstResponder respondsToSelector: @selector(resignKeyWindow)])
        [_firstResponder resignKeyWindow];

      _f.is_key = NO;

      if (_f.is_main == YES)
        {
          [_wv setInputState: GSTitleBarMain];
        }
      else
        {
          [_wv setInputState: GSTitleBarNormal];
        }
      [self discardCursorRects];

      [nc postNotificationName: NSWindowDidResignKeyNotification object: self];
    }
}

- (void) resignMainWindow
{
  if (_f.is_main == YES)
    {
      _f.is_main = NO;
      if (_f.is_key == YES)
        {
          [_wv setInputState: GSTitleBarKey];
        }
      else
        {
          [_wv setInputState: GSTitleBarNormal];
        }
      [nc postNotificationName: NSWindowDidResignMainNotification object: self];
    }
}

- (void) setHidesOnDeactivate: (BOOL)flag
{
  if (flag != _f.hides_on_deactivate)
    {
      _f.hides_on_deactivate = flag;
      if (![NSApp isActive])
	{
	  if (flag)
	    {
	      if (_f.visible)
		{
		  /* Order is important here. We must first order out the window
		     and then add it to the inactive list, since -orderOut:
		     removes the receiver from the inactive list. */
		  [self orderOut: nil];
		  [NSApp _setWindow: self inactive: YES];
		}
	    }
	  else
	    {
	      if ([NSApp _isWindowInactive: self])
		{
		  [NSApp _setWindow: self inactive: NO];
		  [self orderFront: nil];
		}
	    }
	}
    }
}

- (void) setLevel: (NSInteger)newLevel
{
  if (_windowLevel != newLevel)
    {
      _windowLevel = newLevel;
      if (_windowNum > 0)
        {
          GSDisplayServer *srv = GSServerForWindow(self);
          [srv setwindowlevel: _windowLevel : _windowNum];
        }
    }
}

- (NSPoint) cascadeTopLeftFromPoint: (NSPoint)topLeftPoint
{
  NSRect cRect;

  if (NSEqualPoints(topLeftPoint, NSZeroPoint) == YES)
    {
      topLeftPoint.x = NSMinX(_frame);
      topLeftPoint.y = NSMaxY(_frame);
    }

  [self setFrameTopLeftPoint: topLeftPoint];
  cRect = [self contentRectForFrameRect: _frame];
  topLeftPoint.x = NSMinX(cRect);
  topLeftPoint.y = NSMaxY(cRect);

  /* make sure the new point is inside the screen */
  if ([self screen])
    {
      NSRect screenRect;

      screenRect = [[self screen] visibleFrame];
      if (topLeftPoint.x >= NSMaxX(screenRect))
        {
          topLeftPoint.x = NSMinX(screenRect);
        }
      if (topLeftPoint.y <= NSMinY(screenRect))
        {
          topLeftPoint.y = NSMaxY(screenRect);
        }
    }

  return topLeftPoint;
}

- (BOOL) showsResizeIndicator
{
  // TODO
  NSLog(@"Method %s is not implemented for class %s",
        "showsResizeIndicator", "NSWindow");
  return YES;
}

- (void) setShowsResizeIndicator: (BOOL)show
{
  // TODO
  NSLog(@"Method %s is not implemented for class %s",
        "setShowsResizeIndicator:", "NSWindow");
}

- (BOOL) preservesContentDuringLiveResize
{
  return _f.preserves_content_during_live_resize;
}

- (void) setPreservesContentDuringLiveResize: (BOOL)flag
{
  _f.preserves_content_during_live_resize = flag;
}

- (void) setFrame: (NSRect)frameRect
          display: (BOOL)displayFlag
          animate: (BOOL)animationFlag
{
  if (animationFlag && !NSEqualRects(_frame, frameRect))
    {
      // time that the resize is expected to take in seconds
      NSTimeInterval resizeTime;
      NSArray *animations;
      NSViewAnimation *viewAnimation;

      resizeTime = [self animationResizeTime: frameRect];
      animations = [NSArray arrayWithObject:
                              [NSDictionary dictionaryWithObjectsAndKeys:
                                              self, NSViewAnimationTargetKey,
                                                  [NSValue valueWithRect: frameRect], NSViewAnimationEndFrameKey, 
                                            nil]];
      viewAnimation = [[NSViewAnimation alloc] initWithViewAnimations: animations];
      [viewAnimation setAnimationBlockingMode: NSAnimationNonblocking];
      [viewAnimation setDuration: resizeTime];
      if (animationDelegate == nil)
        {
          animationDelegate = [[GSWindowAnimationDelegate alloc] init];
        }
      // The delegate handles the release of the viewAnimation
      [viewAnimation setDelegate: animationDelegate];
      [viewAnimation startAnimation];
      //AUTORELEASE(viewAnimation);
    }
  else
    {
      [self setFrame: frameRect display: displayFlag];
    }
}

- (NSTimeInterval) animationResizeTime: (NSRect)newFrame
{
  static float resizeTime = 0;
  float maxDiff;

  if (resizeTime == 0)
    {
      NSNumber *num;
      num = [[NSUserDefaults standardUserDefaults]
        objectForKey: @"NSWindowResizeTime"];
      if (num != nil)
        {
          resizeTime = [num floatValue];
        }
      else
        {
          resizeTime = 0.20;
        }
    }

  // Find the biggest difference
  maxDiff = fabs(newFrame.origin.x - _frame.origin.x);
  maxDiff = MAX(maxDiff, fabs(newFrame.origin.y - _frame.origin.y));
  maxDiff = MAX(maxDiff, fabs(newFrame.size.width - _frame.size.width));
  maxDiff = MAX(maxDiff, fabs(newFrame.size.height - _frame.size.height));

  return (maxDiff * resizeTime) / 150;
}

- (void) center
{
  NSScreen *screen = [self screen];
  NSSize screenSize;
  NSPoint origin = _frame.origin;

  if (screen == nil) {
    screen = [NSScreen mainScreen];
  }
  screenSize = [screen visibleFrame].size;
  origin.x = (screenSize.width - _frame.size.width) / 2;
  origin.y = (screenSize.height - _frame.size.height) / 2;

  [self setFrameOrigin: origin];
}

/**
 * Given a proposed frame rectangle, return a modified version
 * which will fit inside the screen.
 */
- (NSRect) constrainFrameRect: (NSRect)frameRect toScreen: (NSScreen*)screen
{
  NSRect screenRect;
  CGFloat difference;

  if (nil == screen)
    {
      return frameRect;
    }

  screenRect = [screen visibleFrame];

  if (NSHeight(frameRect) < NSHeight(screenRect))
    {
      /* Move top edge of the window inside the screen */
      difference = NSMaxY (frameRect) - NSMaxY (screenRect);
      if (difference > 0)
        {
          frameRect.origin.y -= difference;
        }
      else 
        {
          /* Move bottom edge of the window inside the screen */
          difference = screenRect.origin.y - frameRect.origin.y;
          if (difference > 0)
            {
              frameRect.origin.y += difference;
            }
        }
    }
  else
    {
      /* If the window is resizable, resize it so that 
         it fits on the screen. */
      if (_styleMask & NSResizableWindowMask)
        {
          /* Ensure that resizing doesn't make window smaller than minimum */
          if (_minimumSize.height < NSHeight(screenRect))
            {
              frameRect.origin.y = NSMinY(screenRect);
              frameRect.size.height = NSHeight(screenRect);
            }
          else
            {
              frameRect.origin.y = NSMaxY(screenRect) - _minimumSize.height;
              frameRect.size.height = _minimumSize.height;
            }
        }
      else
        {
          /* Move top edge of the window to the screen limit */
          frameRect.origin.y -= NSMaxY(frameRect) - NSMaxY(screenRect);
        }
    }

  if (NSWidth(frameRect) < NSWidth(screenRect))
    {
      /* Move right edge of the window inside the screen */
      difference = NSMaxX (frameRect) - NSMaxX (screenRect);
      if (difference > 0)
        {
          frameRect.origin.x -= difference;
        }
      else 
        {
          /* Move left edge of the window inside the screen */
          difference = screenRect.origin.x - frameRect.origin.x;
          if (difference > 0)
            {
              frameRect.origin.x += difference;
            }
        }
    }
  else
    {
      /* If the window is resizable, resize it so that 
         it fits on the screen. */
      if (_styleMask & NSResizableWindowMask)
        {
          /* Ensure that resizing doesn't make window smaller than minimum */
          if (_minimumSize.width < NSWidth(screenRect))
            {
              frameRect.origin.x = NSMinX(screenRect);
              frameRect.size.width = NSWidth(screenRect);
            }
          else
            {
              frameRect.origin.x = NSMaxX(screenRect) - _minimumSize.width;
              frameRect.size.width = _minimumSize.width;
            }
        }
      else
        {
          /* Move right edge of the window to the screen limit */
          frameRect.origin.x -= NSMaxX(frameRect) - NSMaxX(screenRect);
        }
    }

  return frameRect;
}

- (NSRect) frame
{
  return _frame;
}

- (NSSize) minSize
{
  return _minimumSize;
}

- (NSSize) maxSize
{
  return _maximumSize;
}

- (void) setContentSize: (NSSize)aSize
{
  NSRect r = _frame;

  r.size = aSize;
  r = [self frameRectForContentRect: r];
  r.origin = _frame.origin;
  [self setFrame: r display: YES];
}

- (void) setFrame: (NSRect)frameRect display: (BOOL)flag
{
  if (_maximumSize.width > 0 && frameRect.size.width > _maximumSize.width)
    {
      frameRect.size.width = _maximumSize.width;
    }
  if (_maximumSize.height > 0 && frameRect.size.height > _maximumSize.height)
    {
      frameRect.size.height = _maximumSize.height;
    }
  if (frameRect.size.width < _minimumSize.width)
    {
      frameRect.size.width = _minimumSize.width;
    }
  if (frameRect.size.height < _minimumSize.height)
    {
      frameRect.size.height = _minimumSize.height;
    }
      
  /* Windows need to be constrained when displayed or resized - but only
     titled windows are constrained */
  if (_styleMask & NSTitledWindowMask)
    {
      frameRect = [self constrainFrameRect: frameRect toScreen: [self screen]];
    }
        
  // If nothing changes, don't send it to the backend and don't redisplay 
  if (NSEqualRects(_frame, frameRect))
    return;

  if (NSEqualPoints(_frame.origin, frameRect.origin) == NO)
    [nc postNotificationName: NSWindowWillMoveNotification object: self];

  /*
   * Now we can tell the graphics context to do the actual resizing.
   * We will recieve an event to tell us when the resize is done.
   */
  if (_windowNum)
    [GSServerForWindow(self) placewindow: frameRect : _windowNum];
  else
    {
      _frame = frameRect;
      frameRect.origin = NSZeroPoint;
      [_wv setFrame: frameRect];
    }

  if (flag)
    [self display];
}

- (void) setFrameOrigin: (NSPoint)aPoint
{
  NSRect r = _frame;

  r.origin = aPoint;
  [self setFrame: r display: NO];
}

- (void) setFrameTopLeftPoint: (NSPoint)aPoint
{
  NSRect r = _frame;

  r.origin = aPoint;
  r.origin.y -= _frame.size.height;
  [self setFrame: r display: NO];
}

- (void) setMinSize: (NSSize)aSize
{
  if (aSize.width < 1)
    aSize.width = 1;
  if (aSize.height < 1)
    aSize.height = 1;
  _minimumSize = aSize;
  if (_windowNum > 0)
    [GSServerForWindow(self) setminsize: aSize : _windowNum];
}

- (void) setMaxSize: (NSSize)aSize
{
  /*
   * Documented maximum size for macOS-X - do we need this restriction?
   */
  if (aSize.width > 10000)
    aSize.width = 10000;
  if (aSize.height > 10000)
    aSize.height = 10000;
  _maximumSize = aSize;
  if (_windowNum > 0)
    [GSServerForWindow(self) setmaxsize: aSize : _windowNum];
}

- (NSSize) resizeIncrements
{
  return _increments;
}

- (void) setResizeIncrements: (NSSize)aSize
{
  _increments = aSize;
  if (_windowNum > 0)
    [GSServerForWindow(self) setresizeincrements: aSize : _windowNum];
}

- (NSSize) aspectRatio
{
  // FIXME: This method is missing
  return NSMakeSize(1, 1); 
}

- (void) setAspectRatio: (NSSize)ratio
{
  // FIXME: This method is missing
}

- (NSSize) contentMaxSize
{
// FIXME
  NSRect rect;

  rect.origin = NSMakePoint(0, 0);
  rect.size = [self maxSize];
  rect = [self contentRectForFrameRect: rect];
  return rect.size;
}

- (void) setContentMaxSize: (NSSize)size
{
// FIXME
  NSRect rect;

  rect.origin = NSMakePoint(0, 0);
  rect.size = size;
  rect = [self frameRectForContentRect: rect];
  [self setMaxSize: rect.size];
}

- (NSSize) contentMinSize
{
// FIXME
  NSRect rect;

  rect.origin = NSMakePoint(0, 0);
  rect.size = [self minSize];
  rect = [self contentRectForFrameRect: rect];
  return rect.size;
}

- (void) setContentMinSize: (NSSize)size
{
// FIXME
  NSRect rect;

  rect.origin = NSMakePoint(0, 0);
  rect.size = size;
  rect = [self frameRectForContentRect: rect];
  [self setMinSize: rect.size];
}

- (NSSize) contentAspectRatio
{
// FIXME
  return NSMakeSize(1, 1); 
}

- (void) setContentAspectRatio: (NSSize)ratio
{
// FIXME
}

- (NSSize) contentResizeIncrements
{
// FIXME
  return [self resizeIncrements];
}

- (void) setContentResizeIncrements: (NSSize)increments
{
// FIXME
  [self setResizeIncrements: increments];
}

/**
 * Convert from a point in the base coordinate system for the window
 * to a point in the screen coordinate system.
 */
- (NSPoint) convertBaseToScreen: (NSPoint)aPoint
{
  NSPoint screenPoint;

  screenPoint.x = _frame.origin.x + aPoint.x;
  screenPoint.y = _frame.origin.y + aPoint.y;
  return screenPoint;
}

/**
 * Convert from a point in the screen coordinate system to a point in the
 * screen coordinate system of the receiver.
 */
- (NSPoint) convertScreenToBase: (NSPoint)aPoint
{
  NSPoint basePoint;

  basePoint.x = aPoint.x - _frame.origin.x;
  basePoint.y = aPoint.y - _frame.origin.y;
  return basePoint;
}

/**
 * Converts aRect from the coordinate system of the screen
 * to the coordinate system of the window.
 */

- (NSRect) convertRectFromScreen: (NSRect)aRect
{
  NSRect result = aRect;
  NSPoint origin = result.origin;
  NSPoint newOrigin = [self convertScreenToBase: origin];
  result.origin = newOrigin;
  return result;  
}

/**
 * Converts aRect from the window coordinate system to a rect in
 * the screen coordinate system.
 */
- (NSRect) convertRectToScreen: (NSRect)aRect
{
  NSRect result = aRect;
  NSPoint origin = result.origin;
  NSPoint newOrigin = [self convertBaseToScreen: origin];
  result.origin = newOrigin;
  return result;
}

/*
 * Managing the display
 */
- (void) disableFlushWindow
{
  _disableFlushWindow++;
}

- (void) display
{
  if (_gstate == 0 || _f.visible == NO)
    return;

  [_wv display];
  [self discardCachedImage];
  _f.views_need_display = NO;
}

- (void) displayIfNeeded
{
  if (_gstate == 0 || _f.visible == NO)
    return;

  if (_f.views_need_display)
    {
      [_wv displayIfNeeded];
      [self discardCachedImage];
      _f.views_need_display = NO;
    }
}

- (void) update
{									
  [nc postNotificationName: NSWindowDidUpdateNotification object: self];
}

- (void) flushWindowIfNeeded
{
  if (_disableFlushWindow == 0 && _f.needs_flush == YES)
    {
      [self flushWindow];
    }
}

/**
 * Flush all drawing in the windows buffer to the screen unless the window
 * is not buffered or flushing is not enabled.
 */
- (void) flushWindow
{
  NSUInteger i;

  /*
   * If flushWindow is called while flush is disabled
   * mark self as needing a flush, then return
   */
  if (_disableFlushWindow)
    {
      _f.needs_flush = YES;
      return;
    }

  /*
   * Just flush graphics if backing is not buffered.
   * The documentation actually says that this is wrong ... the method
   * should do nothing when the backingType is NSBackingStoreNonretained
   */
  if (_backingType == NSBackingStoreNonretained)
    {
      [_context flushGraphics];
      return;
    }

  /* Check for special case of flushing while we are lock focused.
     For instance, when we are highlighting a button. */
  if (NSIsEmptyRect(_rectNeedingFlush))
    {
      if ([_rectsBeingDrawn count] == 0)
        {
          _f.needs_flush = NO;
          return;
        }
    }

  /*
   * Accumulate the rectangles from all nested focus locks.
   */
  i = [_rectsBeingDrawn count];
  while (i-- > 0)
    {
      _rectNeedingFlush = NSUnionRect(_rectNeedingFlush,
        [[_rectsBeingDrawn objectAtIndex: i] rectValue]);
    }

  if (_windowNum > 0)
    {
      [GSServerForWindow(self) flushwindowrect: _rectNeedingFlush
                                              : _windowNum];
    }
  _f.needs_flush = NO;
  _rectNeedingFlush = NSZeroRect;
}

- (void) enableFlushWindow
{
  if (_disableFlushWindow > 0)
    {
      _disableFlushWindow--;
    }
}

- (BOOL) isAutodisplay
{
  return _f.is_autodisplay;
}

- (BOOL) isFlushWindowDisabled
{
  return _disableFlushWindow == 0 ? NO : YES;
}

- (void) setAutodisplay: (BOOL)flag
{
  _f.is_autodisplay = flag;
}

- (void) setViewsNeedDisplay: (BOOL)flag
{
  if (_f.views_need_display != flag)
    {
      _f.views_need_display = flag;
      if (flag)
        {
          /* TODO: this call most likely shouldn't be here */
          [NSApp setWindowsNeedUpdate: YES];
        }
    }
}

- (BOOL) viewsNeedDisplay
{
  return _f.views_need_display;
}

- (void) cacheImageInRect: (NSRect)aRect
{
  NSView *cacheView;
  NSRect cacheRect;
  
  aRect = NSIntegralRect (NSIntersectionRect (aRect, [_wv frame]));
  _cachedImageOrigin = aRect.origin;
  DESTROY(_cachedImage);
  
  if (NSIsEmptyRect (aRect))
    {
      return;
    }
  
  cacheRect.origin = NSZeroPoint;
  cacheRect.size = aRect.size;
  _cachedImage = [[NSCachedImageRep alloc] initWithWindow: nil 
                                           rect: cacheRect];
  cacheView = [[_cachedImage window] contentView];
  [cacheView lockFocus];
  NSCopyBits (_gstate, aRect, NSZeroPoint);
  [cacheView unlockFocus];
}

- (void) discardCachedImage
{
  DESTROY(_cachedImage);
}

- (void) restoreCachedImage
{
  if (_cachedImage == nil)
    {
      return;
    }
  [_wv lockFocus];
  NSCopyBits ([[_cachedImage window] gState], 
              [_cachedImage rect],
              _cachedImageOrigin);
  [_wv unlockFocus];
}

- (void) useOptimizedDrawing: (BOOL)flag
{
  _f.optimize_drawing = flag;
}

- (BOOL) canStoreColor
{
  if (NSNumberOfColorComponents(NSColorSpaceFromDepth(_depthLimit)) > 1)
    {
      return YES;
    }
  else
    {
      return NO;
    }
}

/** Returns the screen the window is on. Unlike (apparently) OpenStep
    and MacOSX, GNUstep does not support windows being split across
    multiple screens */
- (NSScreen *) deepestScreen
{
  return [self screen];
}

- (NSWindowDepth) depthLimit
{
  return _depthLimit;
}

- (BOOL) hasDynamicDepthLimit
{
  return _f.dynamic_depth_limit;
}

/** Returns the screen the window is on. */
- (NSScreen *) screen
{
  // Only recompute the screen if the current screen
  // doesn't contain the whole window.
  // FIXME: Containing half the window would be enough
  if (_screen != nil)
    {
      NSRect sframe = [_screen frame];
      if (NSContainsRect(sframe, _frame))
        {
          return _screen;
        }
    }
  ASSIGN(_screen, [self _screenForFrame: _frame]);
  return _screen;
}

- (void) setDepthLimit: (NSWindowDepth)limit
{
  if (limit == 0)
    {
      limit = [[self class] defaultDepthLimit];
    }

  _depthLimit = limit;
}

- (void) setDynamicDepthLimit: (BOOL)flag
{
  _f.dynamic_depth_limit = flag;
}

- (NSWindowCollectionBehavior)collectionBehavior
{
  //TODO: we don't handle collections yet and perhaps never will fully
  return 0;
}

- (void)setCollectionBehavior:(NSWindowCollectionBehavior)props
{
  //TODO we don't handle collections yet. Perhaps certain features can be mapped on existing ones
  //other features are Expose specific or anyway probably not implementable
}

/*
 * Cursor management
 */
- (BOOL) areCursorRectsEnabled
{
  return _f.cursor_rects_enabled;
}

- (void) disableCursorRects
{
  _f.cursor_rects_enabled = NO;
}

static void
discardCursorRectsForView(NSView *theView)
{
  if (theView != nil)
    {
      if (theView->_rFlags.has_currects)
        {
          [theView discardCursorRects];
        }

      if (theView->_rFlags.has_subviews)
        {
          NSArray *s = theView->_sub_views;
          NSUInteger count = [s count];

          if (count)
            {
              NSView *subs[count];
              NSUInteger i;

              [s getObjects: subs];
              for (i = 0; i < count; i++)
                {
                  discardCursorRectsForView(subs[i]);
                }
            }
        }
    }
}

- (void) discardCursorRects
{
  discardCursorRectsForView(_wv);
}

- (void) enableCursorRects
{
  _f.cursor_rects_enabled = YES;
}

- (void) invalidateCursorRectsForView: (NSView*)aView
{
  if (aView->_rFlags.valid_rects)
    {
      [aView discardCursorRects];

      if (_f.cursor_rects_valid)
        {
          if (_f.is_key && _f.cursor_rects_enabled)
            {
              NSEvent *e = [NSEvent otherEventWithType: NSAppKitDefined
                                              location: NSMakePoint(-1, -1)
                                         modifierFlags: 0
                                             timestamp: 0
                                          windowNumber: _windowNum
                                               context: GSCurrentContext()
                                               subtype: -1
                                                 data1: 0
                                                 data2: 0];
              [self postEvent: e atStart: YES];
            }
          _f.cursor_rects_valid = NO;
        }
    }
}

static void
resetCursorRectsForView(NSView *theView)
{
  if (theView != nil)
    {
      [theView resetCursorRects];

      if (theView->_rFlags.has_subviews)
        {
          NSArray *s = theView->_sub_views;
          NSUInteger count = [s count];

          if (count)
            {
              NSView *subs[count];
              NSUInteger i;

              [s getObjects: subs];
              for (i = 0; i < count; i++)
                {
                  resetCursorRectsForView(subs[i]);
                }
            }
        }
    }
}

static void
checkCursorRectanglesEntered(NSView *theView,  NSEvent *theEvent, NSPoint lastPoint)
{

  /*
   * Check cursor rectangles for the subviews
   */
  if (theView->_rFlags.has_subviews)
    {
      NSArray *sb = theView->_sub_views;
      NSUInteger count = [sb count];

      if (count > 0)
        {
          NSView *subs[count];
          NSUInteger i;

          [sb getObjects: subs];
          for (i = 0; i < count; ++i)
            {
              if (![subs[i] isHidden])
                {
                  checkCursorRectanglesEntered(subs[i], theEvent, lastPoint);
                }
            }
        }
    }

  if (theView->_rFlags.valid_rects)
    {
      NSArray *tr = theView->_cursor_rects;
      NSUInteger count = [tr count];

      // Loop through cursor rectangles
      if (count > 0)
        {
          GSTrackingRect *rects[count];
          NSPoint loc = [theEvent locationInWindow];
          NSUInteger i;

          [tr getObjects: rects];

          for (i = 0; i < count; ++i)
            {
              GSTrackingRect *r = rects[i];
              BOOL last;
              BOOL now;

              if ([r isValid] == NO)
                continue;

              /*
               * Check for presence of point in rectangle.
               */
              last = NSMouseInRect(lastPoint, r->rectangle, NO);
              now = NSMouseInRect(loc, r->rectangle, NO);

              // Mouse entered
              if ((!last) && (now))
                {
                  NSEvent *e;

                  e = [NSEvent enterExitEventWithType: NSCursorUpdate
                    location: loc
                    modifierFlags: [theEvent modifierFlags]
                    timestamp: 0
                    windowNumber: [theEvent windowNumber]
                    context: [theEvent context]
                    eventNumber: 0
                    trackingNumber: (int)YES
                    userData: (void*)r];
                  [NSApp postEvent: e atStart: YES];
                  //NSLog(@"Add enter event %@ for view %@ rect %@", e, theView, NSStringFromRect(r->rectangle));
                }
            }
        }
    }
}

static void
checkCursorRectanglesExited(NSView *theView,  NSEvent *theEvent, NSPoint lastPoint)
{
  if (theView->_rFlags.valid_rects)
    {
      NSArray *tr = theView->_cursor_rects;
      NSUInteger count = [tr count];

      // Loop through cursor rectangles
      if (count > 0)
        {
          GSTrackingRect *rects[count];
          NSPoint loc = [theEvent locationInWindow];
          NSUInteger i;

          [tr getObjects: rects];

          for (i = 0; i < count; ++i)
            {
              GSTrackingRect *r = rects[i];
              BOOL last;
              BOOL now;

              if ([r isValid] == NO)
                continue;

              /*
               * Check for presence of point in rectangle.
               */
              last = NSMouseInRect(lastPoint, r->rectangle, NO);
              now = NSMouseInRect(loc, r->rectangle, NO);

              // Mouse exited
              if ((last) && (!now))
                {
                  NSEvent *e;

                  e = [NSEvent enterExitEventWithType: NSCursorUpdate
                    location: loc
                    modifierFlags: [theEvent modifierFlags]
                    timestamp: 0
                    windowNumber: [theEvent windowNumber]
                    context: [theEvent context]
                    eventNumber: 0
                    trackingNumber: (int)NO
                    userData: (void*)r];
                  [NSApp postEvent: e atStart: YES];
                  //[NSApp postEvent: e atStart: NO];
                  //NSLog(@"Add exit event %@ for view %@ rect %@", e, theView, NSStringFromRect(r->rectangle));
                }
            }
        }
    }

  /*
   * Check cursor rectangles for the subviews
   */
  if (theView->_rFlags.has_subviews)
    {
      NSArray *sb = theView->_sub_views;
      NSUInteger count = [sb count];

      if (count > 0)
        {
          NSView *subs[count];
          NSUInteger i;

          [sb getObjects: subs];
          for (i = 0; i < count; ++i)
            {
              if (![subs[i] isHidden])
                {
                  checkCursorRectanglesExited(subs[i], theEvent, lastPoint);
                }
            }
        }
    }
}

- (void) resetCursorRects
{
  [self discardCursorRects];
  resetCursorRectsForView(_wv);
  _f.cursor_rects_valid = YES;

  if (_f.is_key && _f.cursor_rects_enabled)
    {
      NSPoint loc = [self mouseLocationOutsideOfEventStream];
      if (NSMouseInRect(loc, [_wv bounds], NO))
        {
          NSEvent *e = [NSEvent mouseEventWithType: NSMouseMoved
                                          location: loc
                                     modifierFlags: 0
                                         timestamp: 0
                                      windowNumber: _windowNum
                                           context: GSCurrentContext()
                                       eventNumber: 0
                                        clickCount: 0
                                          pressure: 0];
          _lastPoint = NSMakePoint(-1,-1);
          checkCursorRectanglesEntered(_wv, e, _lastPoint);
          _lastPoint = loc;
        }
    }
}

/*
 * Handling user actions and events
 */
- (void) close
{
  if (_f.has_closed == NO)
    {
      CREATE_AUTORELEASE_POOL(pool);
      _f.has_closed = YES;

      /* The NSWindowCloseNotification might result in us being
         deallocated. To make sure self stays valid as long as is
         necessary, we retain ourselves here and balance it with a
         release later (unless we're supposed to release ourselves when
         we close).
      */
      if (!_f.is_released_when_closed)
        {
          RETAIN(self);
        }

      [nc postNotificationName: NSWindowWillCloseNotification object: self];
      _f.has_opened = NO;
      [NSApp removeWindowsItem: self];
      [self orderOut: self];

      if (_f.is_miniaturized == YES)
	{
	  NSWindow *mini = GSWindowWithNumber(_counterpart);
	  GSRemoveIcon(mini);
	}

      [pool drain];
      RELEASE(self);
    }
}

/* Private Method. Many X Window managers will just deminiaturize us without
   telling us to do it ourselves. Deal with it.
*/
- (void) _didDeminiaturize: sender
{
  if (_f.is_miniaturized == YES)
    {
      _f.is_miniaturized = NO;
      _f.visible = YES;
      if (self == [NSApp iconWindow])
	{
	  [self orderOut: self];
	  if ([NSApp isActive] == NO)
	    {
	      [NSApp activateIgnoringOtherApps: YES];
	    }
	  if ([NSApp isHidden] == YES)
	    {
	      [NSApp unhide: self];
	    }
	}
      [nc postNotificationName: NSWindowDidDeminiaturizeNotification
			object: self];
    }
}

/**
  Causes the window to deminiaturize. Normally you would not call this
  method directly. A window is automatically deminiaturized by the
  user via a mouse click event. Does nothing it the window isn't
  miniaturized.  */
- (void) deminiaturize: sender
{
  if (!_f.is_miniaturized)
    return;

  /* At least with X-Windows, the counterpart is tied to us, so it will
     automatically be ordered out when we are deminiaturized */
  if (_counterpart != 0)
    {
      NSWindow *mini = GSWindowWithNumber(_counterpart);

      GSRemoveIcon(mini);
      [mini orderOut: self];
    }

  _f.is_miniaturized = NO;
  [self makeKeyAndOrderFront: self];
  [self _didDeminiaturize: sender];
}

/**
   Returns YES, if the document has been changed. 
*/
- (BOOL) isDocumentEdited
{
  return _f.is_edited;
}


/**
   Returns YES, if the window is released when it is closed. 
*/
- (BOOL) isReleasedWhenClosed
{
  return _f.is_released_when_closed;
}

/**
  Causes the window to miniaturize, that is the window is removed from
  the screen and it's counterpart (mini)window is displayed. Does
  nothing if the window can't be miniaturized (eg. because it's already
  miniaturized).  */
- (void) miniaturize: (id)sender
{
  GSDisplayServer *srv = GSServerForWindow(self);
  NSSize iconSize = [GSCurrentServer() iconSize];

  if (_f.is_miniaturized || (_styleMask & NSMiniWindowMask))
    {
      /* Can't miniaturize a miniwindow or a miniaturized window.
       */
      return;
    }

  if (self == [NSApp iconWindow])
    {
      if (NO == [[NSUserDefaults standardUserDefaults]
	boolForKey: @"GSSuppressAppIcon"])
	{
	  return;
	}
    }
  else if ((!(_styleMask & (NSIconWindowMask | NSMiniaturizableWindowMask)))
    || (_styleMask & NSMiniWindowMask)
    || (![self isVisible]))
    {
      return;
    }

  [nc postNotificationName: NSWindowWillMiniaturizeNotification
                    object: self];
  
  _f.is_miniaturized = YES;
  /* Make sure we're not defered */
  if (_windowNum == 0)
    {
      [self _initBackendWindow];
    }
  /*
   * Ensure that we have a miniwindow counterpart.
   */
  if (_counterpart == 0 && [srv appOwnsMiniwindow])
    {
      NSWindow *mini;
      NSMiniWindowView *v;
      NSRect rect = NSMakeRect(0, 0, iconSize.height, iconSize.width); 
      
      mini = [[NSMiniWindow alloc] initWithContentRect: rect
                                             styleMask: NSMiniWindowMask
                                               backing: NSBackingStoreBuffered
                                                 defer: NO];
      mini->_counterpart = [self windowNumber];
      _counterpart = [mini windowNumber];
      v = [[NSMiniWindowView alloc] initWithFrame: rect]; 
      [v setImage: [self miniwindowImage]];
      [v setTitle: [self miniwindowTitle]];
      [mini setContentView: v];
      RELEASE(v);
    }
  [self _lossOfKeyOrMainWindow];
  [srv miniwindow: _windowNum];
  _f.visible = NO;
  
  /*
   * We must order the miniwindow in so that we will start sending
   * it messages to tell it to display itsself when neccessary.
   */
  if (_counterpart != 0)
    {
      NSRect iconRect;
      NSWindow *mini = GSWindowWithNumber(_counterpart);
      iconRect = GSGetIconFrame(mini);
      [mini setFrame: iconRect display: YES];
      [mini orderFront: self];
    }
  [nc postNotificationName: NSWindowDidMiniaturizeNotification
                    object: self];
}

/**
   Causes the window to close.  Calls the windowShouldClose: method
   on the delegate to determine if it should close and calls 
   shouldCloseWindowController on the controller for the receiver.
*/
- (void) performClose: (id)sender
{
  /* Don't close if a modal session is running and we are not the
     modal window */
  if ([NSApp modalWindow] && self != [NSApp modalWindow])
    {
      /* Panel that work in modal session can be closed nevertheless */
      if (![self worksWhenModal])
	return;
    }

  /* self must have a close button in order to be closed */
  if (!(_styleMask & NSClosableWindowMask))
    {
      NSBeep();
      return;
    }

  if (_windowController)
    {
      NSDocument *document = [_windowController document];

      if (document && ![document shouldCloseWindowController: _windowController])
        {
          NSBeep();
          return;
        }
    }
  if ([_delegate respondsToSelector: @selector(windowShouldClose:)])
    {
      /*
       * if delegate responds to windowShouldClose query it to see if
       * it's ok to close the window
       */
      if (![_delegate windowShouldClose: self])
        {
          NSBeep();
          return;
        }
    }
  else
    {
      /*
       * else if self responds to windowShouldClose query
       * self to see if it's ok to close self
       */
      if ([self respondsToSelector: @selector(windowShouldClose:)])
        {
          if (![self windowShouldClose: self])
            {
              NSBeep();
              return;
            }
        }
    }

  // FIXME: The button should be highlighted
  [self close];
}

/**
   Performs the key equivalent represented by theEvent.
 */
- (BOOL) performKeyEquivalent: (NSEvent*)theEvent
{
  if (_contentView)
    return [_contentView performKeyEquivalent: theEvent];
  return NO;
}

/**
 * Miniaturize the receiver ... as long as its style mask includes
 * NSMiniaturizableWindowMask (and as long as the receiver is not an
 * icon or mini window itsself). Calls -miniaturize: to do this.<br />
 * Beeps if the window can't be miniaturised.<br />
 * Should ideally provide visual feedback (highlighting the miniaturize
 * button as if it had been clicked) first ... but that's not yet implemented.
 */
- (void) performMiniaturize: (id)sender
{
  if ((!(_styleMask & NSMiniaturizableWindowMask))
    || (_styleMask & (NSIconWindowMask | NSMiniWindowMask)))
    {
      NSBeep();
      return;
    }

  // FIXME: The button should be highlighted
  [self miniaturize: sender];
}

+ (NSButton *) standardWindowButton: (NSWindowButton)button 
                       forStyleMask: (NSUInteger) mask
{
  return [[GSTheme theme] standardWindowButton: button 
				  forStyleMask: mask];
}

- (NSButton *) standardWindowButton: (NSWindowButton)button
{
  return [_wv viewWithTag: button];
}

- (BOOL) showsToolbarButton
{
  return _f.shows_toolbar_button;
}

- (void) setShowsToolbarButton: (BOOL)flag
{
  _f.shows_toolbar_button = flag;
}

- (NSInteger) resizeFlags
{
  // FIXME: The implementation is missing
  return 0;
}

/**
   Set document edit status.   If YES, then, if the receiver has a close
   button, the close button will show a broken X.  If NO, then, if the reciever
   has a close button, the close button will show a solid X.
 */
- (void) setDocumentEdited: (BOOL)flag
{
  if (_f.is_edited != flag)
    {
      _f.is_edited = flag;
      if (_f.menu_exclude == NO && _f.has_opened == YES)
        {
          [NSApp updateWindowsItem: self];
        }
      [_wv setDocumentEdited: flag];
    }
}

/**
   Get an undo manager from the delegate or create one.
 */
- (NSUndoManager*) undoManager
{
  NSUndoManager *undo = nil;

  if ([_delegate respondsToSelector: @selector(windowWillReturnUndoManager:)])
    {
      undo = [_delegate windowWillReturnUndoManager: self];
    }
  else if (_windowController)
    {
      NSDocument *document = [_windowController document];

      if (document)
        undo = [document undoManager];
    }

  if (undo == nil)
    {
      if (windowUndoManagers == NULL)
	windowUndoManagers =
	    NSCreateMapTable(NSNonRetainedObjectMapKeyCallBacks,
			     NSObjectMapValueCallBacks, 0);
      else
	undo = NSMapGet(windowUndoManagers, self);

      if (undo == nil)
        {
          undo = [[NSUndoManager alloc] init];
          NSMapInsertKnownAbsent(windowUndoManagers, self, undo);
          [undo release];
        }
    }
  return undo;
}

- (void) undo: (id)sender
{
  [[_firstResponder undoManager] undo];
}

- (void) redo: (id)sender
{
  [[_firstResponder undoManager] redo];
}

/**
   If YES, then the window is released when the close method is called.
 */
- (void) setReleasedWhenClosed: (BOOL)flag
{
  _f.is_released_when_closed = flag;
}

/*
 * Aiding event handling
 */
- (BOOL) acceptsMouseMovedEvents
{
  return _f.accepts_mouse_moved;
}

- (void) setAcceptsMouseMovedEvents: (BOOL)flag
{
  _f.accepts_mouse_moved = flag;
}

- (BOOL) ignoresMouseEvents
{
  return _f.ignores_mouse_events;
}

- (void) setIgnoresMouseEvents: (BOOL)flag
{
  _f.ignores_mouse_events = flag;
  [GSServerForWindow(self) setIgnoreMouse: flag : _windowNum];
}

- (NSEvent*) currentEvent
{
  return [NSApp currentEvent];
}

- (void) discardEventsMatchingMask: (NSUInteger)mask
                       beforeEvent: (NSEvent*)lastEvent
{
  [NSApp discardEventsMatchingMask: mask beforeEvent: lastEvent];
}

/**
   Returns the first responder of the window.
 */
- (NSResponder*) firstResponder
{
  return _firstResponder;
}

/**
   Returns YES, if the window can accept first responder.  The default
   implementation of this method returns YES.
 */
- (BOOL) acceptsFirstResponder
{
  return YES;
}

/**
   Makes aResponder the first responder within the receiver.
 */
- (BOOL) makeFirstResponder: (NSResponder*)aResponder
{
  if (_firstResponder == aResponder)
    return YES;

  if (aResponder != nil)
    {
      if (![aResponder isKindOfClass: responderClass])
        return NO;

      if (![aResponder acceptsFirstResponder])
        {
          return NO;
        }
    }

  /* So that the implementation of -resignFirstResponder in
     _firstResponder might ask for what will be the new first
     responder by calling our method _futureFirstResponder */
  _futureFirstResponder = aResponder;

  /*
   * If there is a first responder tell it to resign.
   * Change only if it replies YES.
   */
  if ((_firstResponder) && (![_firstResponder resignFirstResponder]))
    {
      return NO;
    }

  _firstResponder = aResponder;
  if ((aResponder == nil) || ![_firstResponder becomeFirstResponder])
    {
     _firstResponder = self;
      [_firstResponder becomeFirstResponder];
      return (aResponder == nil);
    }

  return YES;
}

/**
   Sets the initial first responder of the receiver.
 */
- (void) setInitialFirstResponder: (NSView*)aView
{
  if ([aView isKindOfClass: viewClass])
    {
      ASSIGN(_initialFirstResponder, aView);
    }
}

/**
   returns the initial first responder of the receiver.
 */
- (NSView*) initialFirstResponder
{
  return _initialFirstResponder;
}

/**
   Processes theEvent when a key is pressed while within
   the window.
 */
- (void) keyDown: (NSEvent*)theEvent
{
  NSString *characters = [theEvent characters];
  unichar character = 0;

  if ([characters length] > 0)
    {
      character = [characters characterAtIndex: 0];
    }

  if (character == NSHelpFunctionKey)
    {
      [NSHelpManager setContextHelpModeActive: YES];
      return;
    }

  // If this is a BACKTAB event, move to the previous key view
  if (character == NSBackTabCharacter)
    {
      [self selectPreviousKeyView: self];
      return;
    }

  // If this is a TAB or TAB+SHIFT event, move to the next key view
  if (character == NSTabCharacter)
    {
      if ([theEvent modifierFlags] & NSShiftKeyMask)
        [self selectPreviousKeyView: self];
      else
        [self selectNextKeyView: self];
      return;
    }

  // If this is an ESC event, abort modal loop
  if (character == 0x001b)
    {
      if ([NSApp modalWindow] == self)
        {
          // NB: The following *never* returns.
          [NSApp abortModal];
        }
      return;
    }

  if (character == NSEnterCharacter
    || character == NSFormFeedCharacter
    || character == NSCarriageReturnCharacter)
    {
      if (_defaultButtonCell && _f.default_button_cell_key_disabled == NO)
        {
          [_defaultButtonCell performClick: self];
          return;
        }
    }

  // Discard null character events such as a Shift event after a tab key
  if ([characters length] == 0)
    return;

  // FIXME: Why is this here, is the code still needed or a left over hack?
  // Try to process the event as a key equivalent
  // without Command having being pressed
  {
    NSEvent *new_event
      =  [NSEvent keyEventWithType: [theEvent type]
                  location: NSZeroPoint
                  modifierFlags: ([theEvent modifierFlags] | NSCommandKeyMask)
                  timestamp: [theEvent timestamp]
                  windowNumber: [theEvent windowNumber]
                  context: [theEvent context]
                  characters: characters
                  charactersIgnoringModifiers: [theEvent
                                                 charactersIgnoringModifiers]
                  isARepeat: [theEvent isARepeat]
                  keyCode: [theEvent keyCode]];
    if ([self performKeyEquivalent: new_event])
      return;
  }

  // Otherwise, pass the event up
  [super keyDown: theEvent];
}

- (void) keyUp: (NSEvent*)theEvent
{
  if ([NSHelpManager isContextHelpModeActive])
    {
      NSString *characters = [theEvent characters];
      unichar character = 0;

      if ([characters length] > 0)
        {
          character = [characters characterAtIndex: 0];
        }
      if (character == NSHelpFunctionKey)
        {
          [NSHelpManager setContextHelpModeActive: NO];
          return;
        }
    }

  [super keyUp: theEvent];
}

/* Return mouse location in reciever's base coord system, ignores event
 * loop status */
- (NSPoint) mouseLocationOutsideOfEventStream
{
  int screen;
  NSPoint p;

  screen = [_screen screenNumber];
  p = [GSServerForWindow(self) mouseLocationOnScreen: screen window: NULL];
  if (p.x != -1)
    p = [self convertScreenToBase: p];
  return p;
}

- (NSEvent*) nextEventMatchingMask: (NSUInteger)mask
{
  return [NSApp nextEventMatchingMask: mask
                            untilDate: [NSDate distantFuture]
                               inMode: NSEventTrackingRunLoopMode
                              dequeue: YES];
}

- (NSEvent*) nextEventMatchingMask: (NSUInteger)mask
                         untilDate: (NSDate*)expiration
                            inMode: (NSString*)mode
                           dequeue: (BOOL)deqFlag
{
  return [NSApp nextEventMatchingMask: mask
                            untilDate: expiration
                               inMode: mode
                              dequeue: deqFlag];
}

- (void) postEvent: (NSEvent*)event atStart: (BOOL)flag
{
  [NSApp postEvent: event atStart: flag];
}

- (void) _checkTrackingRectangles: (NSView*)theView
                         forEvent: (NSEvent*)theEvent
{
  if (theView == nil)
    return;
  if (theView->_rFlags.has_trkrects)
    {
      BOOL isFlipped = [theView isFlipped];
      NSArray *tr = theView->_tracking_rects;
      NSUInteger count = [tr count];

      /*
       * Loop through the tracking rectangles
       */
      if (count > 0)
        {
          GSTrackingRect *rects[count];
          NSPoint loc = [theEvent locationInWindow];
	  NSPoint lastPoint = _lastPoint;
	  NSRect vr = [theView visibleRect];
          NSUInteger i;

	  lastPoint = [theView convertPoint: lastPoint fromView: nil];
	  loc = [theView convertPoint: loc fromView: nil];
          [tr getObjects: rects];

          for (i = 0; i < count; ++i)
            {
              BOOL last;
              BOOL now;
              GSTrackingRect *r = rects[i];
	      NSRect tr = NSIntersectionRect(vr, r->rectangle);

              if ([r isValid] == NO)
                continue;
              /* Check mouse at last point */
              last = NSMouseInRect(lastPoint, tr, isFlipped);
              /* Check mouse at current point */
              now = NSMouseInRect(loc, tr, isFlipped);

              if ((!last) && (now))                // Mouse entered event
                {
                  if (r->flags.checked == NO)
                    {
                      if ([r->owner respondsToSelector:
                        @selector(mouseEntered:)])
                        r->flags.ownerRespondsToMouseEntered = YES;
                      if ([r->owner respondsToSelector:
                        @selector(mouseExited:)])
                        r->flags.ownerRespondsToMouseExited = YES;
                      r->flags.checked = YES;
                    }
                  if (r->flags.ownerRespondsToMouseEntered)
                    {
                      NSEvent        *e;

                      e = [NSEvent enterExitEventWithType: NSMouseEntered
                        location: loc
                        modifierFlags: [theEvent modifierFlags]
                        timestamp: 0
                        windowNumber: [theEvent windowNumber]
                        context: NULL
                        eventNumber: 0
                        trackingNumber: r->tag
                        userData: r->user_data];
                      [r->owner mouseEntered: e];
                    }
                }
                
              if ((last) && (!now))                // Mouse exited event
                {
                  if (r->flags.checked == NO)
                    {    
                      if ([r->owner respondsToSelector:
                        @selector(mouseEntered:)])
                        r->flags.ownerRespondsToMouseEntered = YES;
                      if ([r->owner respondsToSelector:
                        @selector(mouseExited:)])
                        r->flags.ownerRespondsToMouseExited = YES;
                      r->flags.checked = YES;
                    }
                  if (r->flags.ownerRespondsToMouseExited)
                    {
                      NSEvent        *e;

                      e = [NSEvent enterExitEventWithType: NSMouseExited
                        location: loc
                        modifierFlags: [theEvent modifierFlags]
                        timestamp: 0
                        windowNumber: [theEvent windowNumber]
                        context: NULL
                        eventNumber: 0
                        trackingNumber: r->tag
                        userData: r->user_data];
                      [r->owner mouseExited: e];
                    }
                }
            }
        }
    }

  /*
   * Check tracking rectangles for the subviews
   */
  if (theView->_rFlags.has_subviews)
    {
      NSArray *sb = theView->_sub_views;
      NSUInteger count = [sb count];

      if (count > 0)
        {
          NSView *subs[count];
          NSUInteger i;

          [sb getObjects: subs];
          for (i = 0; i < count; ++i)
            {
              if (![subs[i] isHidden])
                (*ctImp)(self, ctSel, subs[i], theEvent);
            }
        }
    }
}

- (void) _checkCursorRectangles: (NSView*)theView forEvent: (NSEvent*)theEvent
{
  // As we add the events to the front of the queue, we need to add the last
  // events first. That is, first the enter evnts from inner to outer and 
  // then the exit events
  checkCursorRectanglesEntered(theView, theEvent, _lastPoint);
  checkCursorRectanglesExited(theView, theEvent, _lastPoint);
  //[GSServerForWindow(self) _printEventQueue];
}

- (void) _processResizeEvent
{
  if (_windowNum && _gstate)
    {
      [GSServerForWindow(self) setWindowdevice: _windowNum 
                        forContext: _context];
      GSReplaceGState(_context, _gstate);
    }

  [self update];
}

- (void) mouseDown: (NSEvent*)theEvent
{
  // Quietly discard an unused mouse down.
}

- (BOOL) becomesKeyOnlyIfNeeded
{
  return NO;
}

/** Handles mouse and other events sent to the receiver by NSApplication.
    Do not invoke this method directly.
*/
- (void) sendEvent: (NSEvent*)theEvent
{
  NSView *v;
  NSEventType type;

  /*
  If the backend reacts slowly, events (eg. mouse down) might arrive for a
  window that has been ordered out (and thus is logically invisible). We
  need to ignore those events. Otherwise, eg. clicking twice on a button
  that ends a modal session and closes the window with the button might
  cause the button to be pressed twice, which causes Bad Things to happen
  when it tries to stop a modal session twice.

  We let NSAppKitDefined events through since they deal with window ordering.
  */
  if (!_f.visible && [theEvent type] != NSAppKitDefined)
    {
      NSDebugLLog(@"NSEvent", @"Discard (window not visible) %@", theEvent);
      return;
    }

  if (!_f.cursor_rects_valid)
    {
      [self resetCursorRects];
    }

  type = [theEvent type];
  if ([self ignoresMouseEvents] 
    && GSMouseEventMask == NSEventMaskFromType(type))
    {
      NSDebugLLog(@"NSEvent", @"Discard (window ignoring mouse) %@", theEvent);
      return;
    }

  switch (type)
    {
      case NSLeftMouseDown:
        {
          BOOL wasKey = _f.is_key;

          if (_f.has_closed == NO)
            {
              v = [_wv hitTest: [theEvent locationInWindow]];
              if (_f.is_key == NO && _windowLevel != NSDesktopWindowLevel)
                {
                  /* NSPanel modification: check becomesKeyOnlyIfNeeded. */
                  if (![self becomesKeyOnlyIfNeeded]
                      || [v needsPanelToBecomeKey])
                    {
                      v = nil;
                      [self makeKeyAndOrderFront: self];
                    }
                }
              /* Activate the app *after* making the receiver key, as app
                 activation tries to make the previous key window key.
		 However, don't activate the app after a single click into
		 the app icon or a miniwindow. This allows dragging app
		 icons and miniwindows without unnecessarily switching
		 applications (cf. Sect. 4 of the OpenStep UI Guidelines).
	      */
              if ((_styleMask & (NSIconWindowMask | NSMiniWindowMask)) == 0
	          && [NSApp isActive] == NO)
                {
                  v = nil;
                  [NSApp activateIgnoringOtherApps: YES];
                }
              // Activating the app may change the window layout.
              if (v == nil)
                {
                  v = [_wv hitTest: [theEvent locationInWindow]];
                }
              if (_lastLeftMouseDownView)
                {
                  DESTROY(_lastLeftMouseDownView);
                }
              // Don't make buttons first responder otherwise they cannot 
              // send actions to the current first responder.
              // TODO: First responder status update would more cleanly 
              // handled by -mouseDown in each control subclass (Mac OS X 
              // seems to do that).
              if (_firstResponder != v && ![v isKindOfClass: [NSButton class]])
                {
                  // Only try to set first responder, when the view wants it.
                  if ([v acceptsFirstResponder] && ![self makeFirstResponder: v])
                    {
                      return;
                    }
                }
              if (wasKey == YES || [v acceptsFirstMouse: theEvent] == YES)
                {
                  if ([NSHelpManager isContextHelpModeActive])
                    {
                      [v helpRequested: theEvent];
                    }
                  else
                    {
                      ASSIGN(_lastLeftMouseDownView, v);
                      if (toolTipVisible != nil)
                        {
                          /* Inform the tooltips system that we have had
                           * a mouse down so it should stop displaying.
                           */
                          [toolTipVisible mouseDown: theEvent];
                        }
                      [v mouseDown: theEvent];
                    }
                }
              else
                {
                    [self mouseDown: theEvent];
                }
            }
	  else
	    {
              NSDebugLLog(@"NSEvent", @"Discard (window closed) %@", theEvent);
	    }
          _lastPoint = [theEvent locationInWindow];
          break;
        }

      case NSLeftMouseUp:
        v = AUTORELEASE(RETAIN(_lastLeftMouseDownView));
        DESTROY(_lastLeftMouseDownView);
        if (v == nil)
          break;
        [v mouseUp: theEvent];
        _lastPoint = [theEvent locationInWindow];
        break;

      case NSOtherMouseDown:
          v = [_wv hitTest: [theEvent locationInWindow]];
	  ASSIGN(_lastOtherMouseDownView, v);
          [v otherMouseDown: theEvent];
          _lastPoint = [theEvent locationInWindow];
          break;

      case NSOtherMouseUp:
        v = AUTORELEASE(RETAIN(_lastOtherMouseDownView));
        DESTROY(_lastOtherMouseDownView);
        if (v == nil)
          break;
        [v otherMouseUp: theEvent];
        _lastPoint = [theEvent locationInWindow];
        break;

      case NSRightMouseDown:
        v = [_wv hitTest: [theEvent locationInWindow]];
	ASSIGN(_lastRightMouseDownView, v);
        [v rightMouseDown: theEvent];
        _lastPoint = [theEvent locationInWindow];
        break;

      case NSRightMouseUp:
        v = AUTORELEASE(RETAIN(_lastRightMouseDownView));
        DESTROY(_lastRightMouseDownView);
        if (v == nil)
          break; 
        [v rightMouseUp: theEvent];
        _lastPoint = [theEvent locationInWindow];
        break;

      case NSLeftMouseDragged:
      case NSOtherMouseDragged:
      case NSRightMouseDragged:
      case NSMouseMoved:
        switch (type)
          {
            case NSLeftMouseDragged:
              [_lastLeftMouseDownView mouseDragged: theEvent];
              break;
            case NSOtherMouseDragged:
              [_lastOtherMouseDownView otherMouseDragged: theEvent];
              break;
            case NSRightMouseDragged:
              [_lastRightMouseDownView rightMouseDragged: theEvent];
              break;
            default:
              if (_f.accepts_mouse_moved)
                {
                  /*
                   * If the window is set to accept mouse movements, we need to
                   * forward the mouse movement to the correct view.
                   */
                  v = [_wv hitTest: [theEvent locationInWindow]];

                  /* If the view is displaying a tooltip, we should
                   * send mouse movements to the tooltip system so
                   * that the window can track the mouse.
                   */
                  if (toolTipVisible != nil)
                    {
                      [toolTipVisible mouseMoved: theEvent];
                    }
                  else
                    {
                      [v mouseMoved: theEvent];
                    }
                }
              break;
          }

        /*
         * We need to go through all of the views, and if there is any with
         * a tracking rectangle then we need to determine if we should send
         * a NSMouseEntered or NSMouseExited event.
         */
        (*ctImp)(self, ctSel, _wv, theEvent);
        
        if (_f.is_key)
          {
            /*
             * We need to go through all of the views, and if there is any with
             * a cursor rectangle then we need to determine if we should send a
             * cursor update event.
             */
            if (_f.cursor_rects_enabled)
              {
                (*ccImp)(self, ccSel, _wv, theEvent);
              }
          }
        
        _lastPoint = [theEvent locationInWindow];
        break;
        
      case NSMouseEntered:
      case NSMouseExited:
        break;

      case NSKeyDown:
	/* Always shift keyboard focus to the next and previous key view,
	 * respectively, upon receiving Ctrl-Tab and Ctrl-Shift-Tab keyboard
	 * events. This means that the key view loop won't get stuck in views
	 * that interpret the Tab key differently, e.g., NSTextView. (cf. the
	 * Keyboard Interface Control section in Apple's Cocoa Event-Handling
	 * Guide).
	 */
	if (([theEvent modifierFlags] & NSControlKeyMask)
	    && [[theEvent charactersIgnoringModifiers] isEqualToString: @"\t"])
	  {
	    if ([theEvent modifierFlags] & NSShiftKeyMask)
	      [self selectPreviousKeyView: self];
	    else
	      [self selectNextKeyView: self];
	  }
	else
	  [_firstResponder keyDown: theEvent];
        break;
        
      case NSKeyUp:
        [_firstResponder keyUp: theEvent];
        break;

      case NSFlagsChanged:
        [_firstResponder flagsChanged: theEvent];
        break;

      case NSCursorUpdate:
        {
          GSTrackingRect *r =(GSTrackingRect*)[theEvent userData];
          NSCursor *c = (NSCursor*)[r owner];

	  // Don't update the cursor if the window isn't the key window.
	  if (!_f.is_key)
            {
              break;
            }
          
          if ([theEvent trackingNumber]) // It's a mouse entered
            {
	      /* Only send the event mouse entered if the
	       * cursor rectangle is valid. */
	      if ([r isValid])
		{
		  [c mouseEntered: theEvent];

		  /* This could seems redundant, but ensure the correct
		   * value to use in events mouse moved. And avoids strange
		   * issues with cursor. */
		  _lastPoint = [theEvent locationInWindow];
		}
            }
          else                           // it is a mouse exited
            {
              [c mouseExited: theEvent];
            }
        }
        break;

      case NSScrollWheel:
        v = [_wv hitTest: [theEvent locationInWindow]];
        [v scrollWheel: theEvent];
        break;

      case NSAppKitDefined:
        {
          id dragInfo;
          int action;
          NSEvent *e;
          GSAppKitSubtype sub = [theEvent subtype];

          switch (sub)
            {
            case GSAppKitWindowMoved:
              _frame.origin.x = (CGFloat)[theEvent data1];
              _frame.origin.y = (CGFloat)[theEvent data2];
              NSDebugLLog(@"Moving", @"Move event: %d %@",
                          (int)_windowNum, NSStringFromPoint(_frame.origin));
              if (_autosaveName != nil)
                {
                  [self saveFrameUsingName: _autosaveName];
                }
              [nc postNotificationName: NSWindowDidMoveNotification
                  object: self];
              break;
              
            case GSAppKitWindowResized:
              {
                NSRect newFrame;

                newFrame.size.width = [theEvent data1];
                newFrame.size.height = [theEvent data2];
                /* Resize events always move the frame origin. The new origin
                   is stored in the event location field. */
                newFrame.origin = [theEvent locationInWindow];

                /* FIXME: For a user resize we should call windowWillResize:toSize:
                   on the delegate.
                 */
                _frame = newFrame;
                newFrame.origin = NSZeroPoint;
                [_wv setFrame: newFrame];
                [_wv setNeedsDisplay: YES];

                if (_autosaveName != nil)
                  {
                    [self saveFrameUsingName: _autosaveName];
                  }

                [self _processResizeEvent];
                [nc postNotificationName: NSWindowDidResizeNotification
                                  object: self];
                break;
              }

            case GSAppKitRegionExposed:
              {
                NSRect region;

                region.size.width = [theEvent data1];
                region.size.height = [theEvent data2];
                region.origin = [theEvent locationInWindow];
                switch (_backingType)
                  {
                    case NSBackingStoreBuffered:
                    case NSBackingStoreRetained:
                      /*
                       * The backend may have the region buffered ...
                       * so we add it to the rectangle to be flushed
                       * and set the flag to say that a flush is required.
                       */
                      _rectNeedingFlush
                        = NSUnionRect(_rectNeedingFlush, region);
                      _f.needs_flush = YES;
                      /* Some or all of the window has not been drawn,
                       * so we must at least make sure that the exposed
                       * region gets drawn before its backing store is
                       * flushed ... otherwise we might actually flush
                       * bogus data from an out of date buffer.
                       * Maybe we should call
                       * [_wv displayIfNeededInRect: region]
                       * but why not do all drawing at this point so
                       * that if we get another expose event immediately
                       * (eg. something is dragged over the window and
                       * we get a series of expose events) we can just
                       * flush without having to draw again.
                       */
                      [self displayIfNeeded];
                      [self flushWindowIfNeeded];
                      break;

                    default:
                      /* non-retained ... so we need to redraw the exposed
                       * region here.
                       */
                      [_wv setNeedsDisplayInRect: region];
                      break;
                  }
                }
              break;

            case GSAppKitWindowClose:
              [self performClose: NSApp];
              break;
                
            case GSAppKitWindowDeminiaturize:
              [self _didDeminiaturize: NSApp];
              break;

            case GSAppKitWindowMiniaturize:
              [self performMiniaturize: NSApp];
              break;

            case GSAppKitWindowFocusIn:
              if (_f.is_miniaturized)
		{
		  /* Window Manager just deminiaturized us */
		  [self deminiaturize: self];
		}
              if ([NSApp modalWindow]
		&& self != [NSApp modalWindow]
		&& ![self worksWhenModal])
		{
		  /* Ignore this request. We're in a modal loop and the
		     user pressed on the title bar of another window. */
		  break;
		}
              if ([self canBecomeKeyWindow] == YES)
		{
		  NSDebugLLog(@"Focus", @"Making %d key", (int)_windowNum);
		  [self makeKeyWindow];
		  [self makeMainWindow];
		  [NSApp activateIgnoringOtherApps: YES];
		}
              if (self == [[NSApp mainMenu] window])
		{
		  /* We should really find another window that can become
		     key (if possible)
		  */
		  [self _lossOfKeyOrMainWindow];
		}
              break;

            case GSAppKitWindowFocusOut:
              break;

            case GSAppKitWindowLeave:
	      /* we ignore this event for a window that is already closed */
	      if (_f.has_closed == YES)
	        break;

              /*
               * We need to go through all of the views, and if there
               * is any with a tracking rectangle then we need to
               * determine if we should send a NSMouseExited event.  */
              (*ctImp)(self, ctSel, _wv, theEvent);

              if (_f.is_key)
                {
                  /*
                   * We need to go through all of the views, and if
                   * there is any with a cursor rectangle then we need
                   * to determine if we should send a cursor update
                   * event.  */
                  if (_f.cursor_rects_enabled)
                    {
                      checkCursorRectanglesExited(_wv, theEvent, _lastPoint);
                    }
                }
              
              _lastPoint = NSMakePoint(-1, -1);
              break;

            case GSAppKitWindowEnter:
              break;


#define     GSPerformDragSelector(view, sel, info, action) \
              if ([view window] == self) \
                { \
                  id target = view; \
                  \
                  if (target == _wv) \
                    { \
                      if (_delegate != nil \
                        && [_delegate respondsToSelector: sel] == YES) \
                        { \
                          target = _delegate; \
                        } \
                      else \
                        { \
                          target = self; \
                        } \
                    } \
                  \
                  if ([target respondsToSelector: sel]) \
                    { \
                      action = (intptr_t)[target performSelector: sel \
                                                      withObject: info]; \
                    } \
                }

#define     GSPerformVoidDragSelector(view, sel, info) \
              if ([view window] == self) \
                {  \
                  id target = view; \
                  \
                  if (target == _wv) \
                    { \
                      if (_delegate != nil \
                        && [_delegate respondsToSelector: sel] == YES) \
                        { \
                          target = _delegate; \
                        } \
                      else \
                        { \
                          target = self; \
                        } \
                    } \
                  \
                  if ([target respondsToSelector: sel]) \
                    { \
                      [target performSelector: sel withObject: info];   \
                    } \
                }

            case GSAppKitDraggingEnter:
            case GSAppKitDraggingUpdate:
            {
              BOOL        isEntry;

              dragInfo = [GSServerForWindow(self) dragInfo];
              v = [_wv hitTest: [theEvent locationInWindow]];
              
              while (v != nil)
                {
                  if (v->_rFlags.has_draginfo != 0
                      && GSViewAcceptsDrag(v, dragInfo))
                    break;
                  v = [v superview];
                }
              if (v == nil)
                {
                  v = _wv;
                }
              if (_lastDragView == v)
                {
                  isEntry = NO;
                }
              else
                {
                  isEntry = YES;
                  if (_lastDragView != nil && _f.accepts_drag)
                    {
                      NSDebugLLog(@"NSDragging", @"Dragging exit");
                      GSPerformVoidDragSelector(_lastDragView,
                        @selector(draggingExited:), dragInfo);
                    }
                  ASSIGN(_lastDragView, v);
                  _f.accepts_drag = GSViewAcceptsDrag(v, dragInfo);
                }
              if (_f.accepts_drag)
                {
                  if (isEntry == YES)
                    {
                      action = NSDragOperationNone;
                      NSDebugLLog(@"NSDragging", @"Dragging entered");
                      GSPerformDragSelector(v, @selector(draggingEntered:),
                        dragInfo, action);
                    }
                  else  
                    {
                      action = _lastDragOperationMask;
                      NSDebugLLog(@"NSDragging", @"Dragging updated");
                      GSPerformDragSelector(v, @selector(draggingUpdated:),
                                            dragInfo, action);
                    }
                }
              else
                {
                  action = NSDragOperationNone;
                }

              e = [NSEvent otherEventWithType: NSAppKitDefined
                           location: [theEvent locationInWindow]
                           modifierFlags: 0
                           timestamp: 0
                           windowNumber: _windowNum
                           context: GSCurrentContext()
                           subtype: GSAppKitDraggingStatus
                           data1: [theEvent data1]
                           data2: action];

              _lastDragOperationMask = action;
              [dragInfo postDragEvent: e];
              break;
            }

            case GSAppKitDraggingStatus:
              NSDebugLLog(@"NSDragging",
                @"Internal: dropped GSAppKitDraggingStatus event");
              break;

            case GSAppKitDraggingExit:
              NSDebugLLog(@"NSDragging", @"GSAppKitDraggingExit");
              dragInfo = [GSServerForWindow(self) dragInfo];
              if (_lastDragView && _f.accepts_drag)
                {
                  NSDebugLLog(@"NSDragging", @"Dragging exit");
                  GSPerformVoidDragSelector(_lastDragView,
                    @selector(draggingExited:), dragInfo);
                }
              _lastDragOperationMask = NSDragOperationNone;
              DESTROY(_lastDragView);
              break;

            case GSAppKitDraggingDrop:
              NSDebugLLog(@"NSDragging", @"GSAppKitDraggingDrop");
              dragInfo = [GSServerForWindow(self) dragInfo];
              if (_lastDragView && _f.accepts_drag
		  && _lastDragOperationMask != NSDragOperationNone)
                {
                  action = YES;
                  GSPerformDragSelector(_lastDragView,
                    @selector(prepareForDragOperation:), dragInfo, action);
                  if (action)
                    {
                      action = NO;
                      GSPerformDragSelector(_lastDragView,
                        @selector(performDragOperation:), dragInfo, action);
                    }
                  if (action)
                    {
                      GSPerformVoidDragSelector(_lastDragView,
                        @selector(concludeDragOperation:), dragInfo);
                    }
                }
              _lastDragOperationMask = NSDragOperationNone;
              DESTROY(_lastDragView);
              e = [NSEvent otherEventWithType: NSAppKitDefined
                           location: [theEvent locationInWindow]
                           modifierFlags: 0
                           timestamp: 0
                           windowNumber: _windowNum
                           context: GSCurrentContext()
                           subtype: GSAppKitDraggingFinished
                           data1: [theEvent data1]
                           data2: 0];
              [dragInfo postDragEvent: e];
              break;

            case GSAppKitDraggingFinished:
              _lastDragOperationMask = NSDragOperationNone;
              DESTROY(_lastDragView);
              NSDebugLLog(@"NSDragging",
                @"Internal: dropped GSAppKitDraggingFinished event");
              break;

            default:
              break;
            }
        }
        break;

      case NSPeriodic:
      case NSSystemDefined:
      case NSApplicationDefined:
        break;

      case NSTabletPoint:
      case NSTabletProximity:
        // FIXME: Tablet events
        break;
    }
}

- (BOOL) shouldBeTreatedAsInkEvent: (NSEvent *)theEvent
{
  NSView *v;

  v = [_wv hitTest: [theEvent locationInWindow]];
  if (![self isMainWindow])
    {
      return (v != _wv);
    }
  else
    {
      return [v shouldBeTreatedAsInkEvent: theEvent];
    }
}

- (BOOL) tryToPerform: (SEL)anAction with: (id)anObject
{
  if ([super tryToPerform: anAction with: anObject])
    return YES;
  else if (_delegate && [_delegate respondsToSelector: anAction])
    {
      [_delegate performSelector: anAction withObject: anObject];
      return YES;
    }
  else
    return NO;
}

- (BOOL) worksWhenModal
{
  return NO;
}

/** If aView responds to -nextValidKeyView with a new NSView, call 
  -makeFirstResponder: for the returned view.
*/
- (void) selectKeyViewFollowingView: (NSView*)aView
{
  NSView *theView = nil;

  if ([aView isKindOfClass: viewClass])
    theView = [aView nextValidKeyView];
  if (theView)
    {
      if (![self makeFirstResponder: theView])
        {
          return;
        }
      if ([theView respondsToSelector:@selector(selectText:)])
        {
          _f.selectionDirection =  NSSelectingNext;
          [(id)theView selectText: self];
          _f.selectionDirection =  NSDirectSelection;
        }
    }
}

/** If aView responds to -previousValidKeyView with a new NSView, call
  -makeFirstResponder: for this view.
*/
- (void) selectKeyViewPrecedingView: (NSView*)aView
{
  NSView *theView = nil;

  if ([aView isKindOfClass: viewClass])
    theView = [aView previousValidKeyView];
  if (theView)
    {
      if (![self makeFirstResponder: theView])
        {
          return;
        }
      if ([theView respondsToSelector:@selector(selectText:)])
        {
          _f.selectionDirection =  NSSelectingPrevious;
          [(id)theView selectText: self];
          _f.selectionDirection =  NSDirectSelection;
        }
    }
}

/** This method checks if:
  <list>
   <item>_firstResponder answers to -nextValidKeyView</item>
   <item>_initialFirstResponder answers to -acceptsFirstResponder</item>
   <item>_initialFirstResponder answers to -previousValidKeyView</item>
  </list>
  If any of these checks return a NSView, call -makeFirstResponder: on 
  this NSView.
*/
- (void) selectNextKeyView: (id)sender
{
  NSView *theView = nil;

  if ([_firstResponder isKindOfClass: viewClass])
    theView = [_firstResponder nextValidKeyView];

  if ((theView == nil) && (_initialFirstResponder))
    {
      if ([_initialFirstResponder acceptsFirstResponder])
        theView = _initialFirstResponder;
      else
        theView = [_initialFirstResponder nextValidKeyView];
    }

  if (theView)
    {
      if (![self makeFirstResponder: theView])
        {
          return;
        }
      if ([theView respondsToSelector:@selector(selectText:)])
        {
          _f.selectionDirection =  NSSelectingNext;
          [(id)theView selectText: self];
          _f.selectionDirection =  NSDirectSelection;
        }
    }
}

/** This method checks if:
  <list>
   <item>_firstResponder answers to -previousValidKeyView</item>
   <item>_initialFirstResponder answers to -acceptsFirstResponder</item>
   <item>_initialFirstResponder answers to -previousValidKeyView</item>
  </list>
  If any of these checks return a NSView, call -makeFirstResponder: on 
  this NSView.
*/
- (void) selectPreviousKeyView: (id)sender
{
  NSView *theView = nil;

  if ([_firstResponder isKindOfClass: viewClass])
    theView = [_firstResponder previousValidKeyView];

  if ((theView == nil) && (_initialFirstResponder))
    {
      if ([_initialFirstResponder acceptsFirstResponder])
        theView = _initialFirstResponder;
      else
        theView = [_initialFirstResponder previousValidKeyView];
    }

  if (theView)
    {
      if (![self makeFirstResponder: theView])
        {
          return;
        }
      if ([theView respondsToSelector:@selector(selectText:)])
        {
          _f.selectionDirection =  NSSelectingPrevious;
          [(id)theView selectText: self];
          _f.selectionDirection =  NSDirectSelection;
        }
    }
}

// This is invoked by selectText: of some views (eg matrixes),
// to know whether they have received it from the window, and
// if so, in which direction is the selection moving (so that they know
// if they should select the last or the first editable cell).
/** Returns the value of _selectionDirection, the direction of the
current key view.<br />
  See Also:
  <list>
   <item>-selectKeyViewFollowingView:</item>
   <item>-selectKeyViewPrecedingView:</item>
   <item>-selectNextKeyView:</item>
   <item>-selectPreviousKeyView:</item>
  </list>
*/
- (NSSelectionDirection) keyViewSelectionDirection
{
  return _f.selectionDirection;
}

- (BOOL) autorecalculatesKeyViewLoop
{
  return _f.autorecalculates_keyview_loop;
}

- (void) setAutorecalculatesKeyViewLoop: (BOOL)flag
{
  _f.autorecalculates_keyview_loop = flag;
}

- (void) recalculateKeyViewLoop
{
// Should be called from NSView viewWillMoveToWindow (but only if
// -autorecalculatesKeyViewLoop returns YES)
  [_contentView _setUpKeyViewLoopWithNextKeyView: _contentView];
  [self setInitialFirstResponder: [_contentView nextValidKeyView]];
}


/*
 * Dragging
 */
- (void) dragImage: (NSImage*)anImage
                at: (NSPoint)baseLocation
            offset: (NSSize)initialOffset
             event: (NSEvent*)event
        pasteboard: (NSPasteboard*)pboard
            source: (id)sourceObject
         slideBack: (BOOL)slideFlag
{
  id dragView = [GSServerForWindow(self) dragInfo];

  [NSApp preventWindowOrdering];
  [dragView dragImage: anImage
                   at: [self convertBaseToScreen: baseLocation]
               offset: initialOffset
                event: event
           pasteboard: pboard
               source: sourceObject
            slideBack: slideFlag];
}

- (void) registerForDraggedTypes: (NSArray*)newTypes
{
  [_wv registerForDraggedTypes: newTypes];
}

- (void) unregisterDraggedTypes
{
  [_wv unregisterDraggedTypes];
}

/*
 * Services and windows menu support
 */
- (BOOL) isExcludedFromWindowsMenu
{
  return _f.menu_exclude;
}

- (void) setExcludedFromWindowsMenu: (BOOL)flag
{
  if (_f.menu_exclude != flag)
    {
      _f.menu_exclude = flag;
      if (flag == YES)
        {
          [NSApp removeWindowsItem: self];
        }
      else if (_f.has_opened == YES && flag == NO)
        {
          [NSApp addWindowsItem: self
                          title: _windowTitle
                       filename: [self _hasTitleWithRepresentedFilename]];
        }
    }
}

- (id) validRequestorForSendType: (NSString*)sendType
                      returnType: (NSString*)returnType
{
  id result = nil;

  if (_delegate && [_delegate respondsToSelector: _cmd] 
      && ![_delegate isKindOfClass: [NSResponder class]])
    result = [_delegate validRequestorForSendType: sendType
                                      returnType: returnType];

  if (result == nil)
    result = [NSApp validRequestorForSendType: sendType
                                   returnType: returnType];
  return result;
}

/*
 * Saving and restoring the frame
 */
- (NSString*) frameAutosaveName
{
  return _autosaveName;
}

- (void) saveFrameUsingName: (NSString*)name
{
  NSUserDefaults *defs;
  NSString *key;
  id obj;

  defs = [NSUserDefaults standardUserDefaults];
  obj = [self stringWithSavedFrame];
  key = [NSString stringWithFormat: @"NSWindow Frame %@", name];
  [defs setObject: obj forKey: key];
}

- (BOOL) setFrameAutosaveName: (NSString*)name
{
  if ([name isEqual: _autosaveName])
    {
      return YES;                /* That's our name already.        */
    }

  if ([autosaveNames member: name] != nil)
    {
      return NO;                /* Name in use elsewhere.        */
    }
  if (_autosaveName != nil)
    {
      [[self class] removeFrameUsingName: _autosaveName];
      [autosaveNames removeObject: _autosaveName];
      _autosaveName = nil;
    }
  if (name != nil && [name isEqual: @""] == NO)
    {
      name = [name copy];
      [autosaveNames addObject: name];
      _autosaveName = name;
      RELEASE(name);
      if (![self setFrameUsingName: _autosaveName])
        {
          [self saveFrameUsingName: _autosaveName];
        }
    }
  return YES;
}

- (void) setFrameFromString: (NSString*)string
{
  NSScanner *scanner = [NSScanner scannerWithString: string];
  NSRect nRect;
  NSRect sRect;
  NSRect fRect;
  int value;
  NSScreen *screen;

  /*
   * Scan in the window frame (flipped coordinate system).
   */
  if ([scanner scanInt: &value] == NO)
    {
      NSLog(@"Bad window frame format - x-coord missing");
      return;
    }
  fRect.origin.x = value;

  if ([scanner scanInt: &value] == NO)
    {
      NSLog(@"Bad window frame format - y-coord missing");
      return;
    }
  fRect.origin.y = value;

  if ([scanner scanInt: &value] == NO)
    {
      NSLog(@"Bad window frame format - width missing");
      return;
    }
  fRect.size.width = value;

  if ([scanner scanInt: &value] == NO)
    {
      NSLog(@"Bad window frame format - height missing");
      return;
    }
  fRect.size.height = value;
  
  /*
   * Check that the window will come up on screen
   */
#if 0 // Not valid since screen frame x/y values can be negative...
  if (fRect.origin.x + fRect.size.width < 0)
  {
    NSLog(@"Bad screen frame  - window is off screen");  
    return;
  }
#endif

  // if toolbar is showing, adjust saved frame to add the toolbar back in
  if ([_toolbar isVisible])
    {
      CGFloat toolbarHeight = [[_toolbar _toolbarView] frame].size.height;
      fRect.size.height += toolbarHeight;
      fRect.origin.y -= toolbarHeight;
    }
  // if window has a menu, adjust saved frame to add the menu back in
  if ([_wv hasMenu])
    {
      CGFloat menuBarHeight = [[GSTheme theme] menuHeightForWindow: self];
      fRect.size.height += menuBarHeight;
      fRect.origin.y -= menuBarHeight;
    }

  /*
   * Scan in the frame for the area the window was placed in in screen.
   */
  if ([scanner scanInt: &value] == NO)
    {
      NSLog(@"Bad screen frame format - x-coord missing");
      return;
    }
  sRect.origin.x = value;

  if ([scanner scanInt: &value] == NO)
    {
      NSLog(@"Bad screen frame format - y-coord missing");
      return;
    }
  sRect.origin.y = value;

  if ([scanner scanInt: &value] == NO)
    {
      NSLog(@"Bad screen frame format - width missing");
      return;
    }
  sRect.size.width = value;

  if ([scanner scanInt: &value] == NO)
    {
      NSLog(@"Bad screen frame format - height missing");
      return;
    }
  sRect.size.height = value;

  /*
   * The screen rectangle gives the area of the screen in which
   * the window could be placed (ie a rectangle excluding the dock).
   */
  screen = [self _screenForFrame: fRect];

  // Check whether a portion is showing somewhere...
  if (screen == nil)
    {
      // If the window doesn't show up on any screen then we need
      // to move it so it can be seen and assign it to the main
      // screen...
      screen = [NSScreen mainScreen];
      NSDebugLLog(@"NSWindow", @"%s: re-assigning to main screen\n", __PRETTY_FUNCTION__);
    }
  nRect = [screen visibleFrame];

  /*
   * If the new screen drawable area has moved relative to the one in
   * which the window was saved, adjust the window position accordingly.
   */
  if (NSEqualPoints(nRect.origin, sRect.origin) == NO)
    {
      fRect.origin.x += nRect.origin.x - sRect.origin.x;
      fRect.origin.y += nRect.origin.y - sRect.origin.y;
    }

  /*
   * If the stored screen area is not the same as that currently
   * available, we adjust the window frame (position) to try to
   * make layout sensible.
   */
  if (nRect.size.width != sRect.size.width)
    {
      fRect.origin.x = nRect.origin.x + (fRect.origin.x - nRect.origin.x)
        * (nRect.size.width / sRect.size.width);
    }
  if (nRect.size.height != sRect.size.height)
    {
      fRect.origin.y = nRect.origin.y + (fRect.origin.y - nRect.origin.y)
        * (nRect.size.height / sRect.size.height);

      /*
       * If height of the window goes above the screen height, then adjust the window down.
       */
      if ((fRect.size.height + fRect.origin.y) > nRect.size.height)
      {
        fRect.origin.y = nRect.size.height - fRect.size.height; 
      }
    }

  // FIXME: Is this check needed?
  /* If we aren't resizable (ie. if we don't have a resize bar), make sure
     we don't change the size. */
  if (!(_styleMask & NSResizableWindowMask))
    fRect.size = _frame.size;

  if (NSEqualSizes(fRect.size, _frame.size) == NO)
    {
      if ([_delegate respondsToSelector: @selector(windowWillResize:toSize:)])
        {
          fRect.size = [_delegate windowWillResize: self
                                  toSize: fRect.size];
        }
    }

  // Make sure we are using the new screen we are applying to...
  ASSIGN(_screen, screen);

  /*
   * Set frame.
   */
  [self setFrame: fRect display: (_f.visible) ? YES : NO];
}

- (BOOL) setFrameUsingName: (NSString*)name
{
  NSUserDefaults *defs;
  id obj;
  NSString *key;

  defs = [NSUserDefaults standardUserDefaults];
  key = [NSString stringWithFormat: @"NSWindow Frame %@", name];
  obj = [defs objectForKey: key];
  if (obj == nil)
    return NO;

  [self setFrameFromString: obj];
  return YES;
}

- (BOOL) setFrameUsingName: (NSString *)name
                     force: (BOOL)force
{
  // FIXME
  if ((_styleMask & NSResizableWindowMask) || force)
    return [self setFrameUsingName: name];
  else
    return NO;
}

- (NSString *) stringWithSavedFrame
{
  NSRect fRect;
  NSRect sRect;
  NSString *autosaveString;

  fRect = _frame;

  // if toolbar is showing, adjust saved frame to not include the toolbar
  if ([_toolbar isVisible])
    {
      CGFloat toolbarHeight = [[_toolbar _toolbarView] frame].size.height;
      fRect.size.height -= toolbarHeight;
      fRect.origin.y += toolbarHeight;
    }
  // if window has a menu, adjust saved frame to not include the menu
  if ([_wv hasMenu])
    {
      CGFloat menuBarHeight = [[GSTheme theme] menuHeightForWindow: self];
      fRect.size.height -= menuBarHeight;
      fRect.origin.y += menuBarHeight;
    }

  /*
   * The screen rectangle should give the area of the screen in which
   * the window could be placed (ie a rectangle excluding the dock).
   */
  sRect = [[self screen] visibleFrame];
  autosaveString = [NSString stringWithFormat: @"%d %d %d %d %d %d % d %d ",
                               (int)fRect.origin.x, (int)fRect.origin.y,
                               (int)fRect.size.width, (int)fRect.size.height,
                               (int)sRect.origin.x, (int)sRect.origin.y,
                               (int)sRect.size.width, (int)sRect.size.height];
  NSDebugLLog(@"NSWindow", @"%s:autosaveName: %@ frame string: %@", __PRETTY_FUNCTION__,
              _autosaveName, autosaveString);

  return autosaveString;
}

/*
 * Printing and postscript
 */
- (NSData *) dataWithEPSInsideRect: (NSRect)rect
{
  return [_wv dataWithEPSInsideRect:
                           [_wv convertRect: rect fromView: nil]];
}

- (NSData *) dataWithPDFInsideRect:(NSRect)aRect
{
  return [_wv dataWithPDFInsideRect:
                           [_wv convertRect: aRect fromView: nil]];
}

/**
   Opens the fax panel to allow the user to fax the contents of
   the window view.
*/
- (void) fax: (id)sender
{
  [_wv fax: sender];
}

/**
   Opens the print panel to allow the user to print the contents of
   the window view.
*/
- (void) print: (id)sender
{
  [_wv print: sender];
}

/*
 * Zooming
 */

#define DIST 3

/**
   Returns yes, if the receiver is zoomed.
 */
- (BOOL) isZoomed
{
  NSRect maxRect = [[self screen] visibleFrame];

  if ([_delegate respondsToSelector: @selector(windowWillUseStandardFrame:defaultFrame:)])
    {
      maxRect = [_delegate windowWillUseStandardFrame: self defaultFrame: maxRect];
    }
  else if ([self respondsToSelector: @selector(windowWillUseStandardFrame:defaultFrame:)])
    {
      maxRect = [self windowWillUseStandardFrame: self defaultFrame: maxRect];
    }
  else if ([_delegate respondsToSelector: @selector(windowWillResize:toSize:)])
    {
      maxRect.size = [_delegate windowWillResize: self toSize: maxRect.size];
    }
  else if ([self respondsToSelector: @selector(windowWillResize:toSize:)])
    {
      maxRect.size = [self windowWillResize: self toSize: maxRect.size];
    }

  // Compare the new frame with the current one
  return NSEqualRects(maxRect, _frame);
}

/**
   Performs the zoom method on the receiver.
*/
- (void) performZoom: (id)sender
{
  // FIXME: We should check for the style and highlight the button
  [self zoom: sender];
}

/**
   Zooms the receiver.   This method calls the delegate method 
   windowShouldZoom:toFrame: to determine if the window should 
   be allowed to zoom to full screen.
*/
- (void) zoom: (id)sender
{
  NSRect maxRect = [[self screen] visibleFrame];

  if ([_delegate respondsToSelector: @selector(windowWillUseStandardFrame:defaultFrame:)])
    {
      maxRect = [_delegate windowWillUseStandardFrame: self defaultFrame: maxRect];
    }
  else if ([self respondsToSelector: @selector(windowWillUseStandardFrame:defaultFrame:)])
    {
      maxRect = [self windowWillUseStandardFrame: self defaultFrame: maxRect];
    }

  maxRect = [self constrainFrameRect: maxRect toScreen: [self screen]];

  // Compare the new frame with the current one
  if ((fabs(NSMaxX(maxRect) - NSMaxX(_frame)) < DIST)
    && (fabs(NSMaxY(maxRect) - NSMaxY(_frame)) < DIST)
    && (fabs(NSMinX(maxRect) - NSMinX(_frame)) < DIST)
    && (fabs(NSMinY(maxRect) - NSMinY(_frame)) < DIST))
    {
      // Already in zoomed mode, reset user frame, if stored
      if (_autosaveName != nil)
        {
          [self setFrameUsingName: _autosaveName];
        }
      return;
    }

  if ([_delegate respondsToSelector: @selector(windowShouldZoom:toFrame:)])
    {
      if (![_delegate windowShouldZoom: self toFrame: maxRect])
        return;
    }
  else if ([self respondsToSelector: @selector(windowShouldZoom:toFrame:)])
    {
      if (![self windowShouldZoom: self toFrame: maxRect])
        return;
    }

  if (_autosaveName != nil)
    {
      [self saveFrameUsingName: _autosaveName];
    }
  
  [self setFrame: maxRect display: YES];
}


/*
 * Default botton
 */

- (NSButtonCell *) defaultButtonCell
{
  return _defaultButtonCell;
}

- (void) setDefaultButtonCell: (NSButtonCell *)aCell
{
  ASSIGN(_defaultButtonCell, aCell);
  _f.default_button_cell_key_disabled = NO;

  [aCell setKeyEquivalent: @"\r"];
  [aCell setKeyEquivalentModifierMask: 0];
  [[GSTheme theme] didSetDefaultButtonCell: aCell];
}

- (void) disableKeyEquivalentForDefaultButtonCell
{
  _f.default_button_cell_key_disabled = YES;
}

- (void) enableKeyEquivalentForDefaultButtonCell
{
  _f.default_button_cell_key_disabled = NO;
}

- (NSArray *) childWindows
{
  return _children;
}

- (void) addChildWindow: (NSWindow *)child 
                ordered: (NSWindowOrderingMode)place
{
  if (_children == nil)
    {
      _children = [[NSMutableArray alloc] init];
    }
  [_children addObject: child];
  [child setParentWindow: self];
}

- (void) removeChildWindow: (NSWindow *)child
{
  [_children removeObject: child];
  [child setParentWindow: nil];
}

- (NSWindow *) parentWindow
{
  return _parent;
}

- (void) setParentWindow: (NSWindow *)window
{
  _parent = window;  

  if (_windowNum)
    {
      [GSServerForWindow(self) setParentWindow: [_parent windowNumber] 
				forChildWindow: _windowNum];
    }
}

- (BOOL) allowsToolTipsWhenApplicationIsInactive
{
  return _f.allows_tooltips_when_inactive;
}

- (void) setAllowsToolTipsWhenApplicationIsInactive: (BOOL)flag
{
  _f.allows_tooltips_when_inactive = flag;
}

- (BOOL) isMovableByWindowBackground
{
  return _f.is_movable_by_window_background;
}

- (void) setMovableByWindowBackground: (BOOL)flag
{
  _f.is_movable_by_window_background = flag;
}

- (BOOL) displaysWhenScreenProfileChanges
{
  return _f.displays_when_screen_profile_changes;
}

- (void) setDisplaysWhenScreenProfileChanges: (BOOL)flag
{
  _f.displays_when_screen_profile_changes = flag;
}

/*
 * Menu item validation
 */

- (BOOL) validateUserInterfaceItem: (id <NSValidatedUserInterfaceItem>)anItem
{
  BOOL result = YES;
  SEL  action = [anItem action];

  if (sel_isEqual(action, @selector(performClose:)))
    {
      result = ([self styleMask] & NSClosableWindowMask) ? YES : NO;
    }
  else if (sel_isEqual(action, @selector(performMiniaturize:)))
    {
      result = ([self styleMask] & NSMiniaturizableWindowMask) ? YES : NO;
    }
  else if (sel_isEqual(action, @selector(performZoom:)))
    {
      result = ([self styleMask] & NSResizableWindowMask) ? YES : NO;
    }
  else if (sel_isEqual(action, @selector(undo:)))
    {
      NSUndoManager *undo = [_firstResponder undoManager];
      if (undo == nil)
        {
          result = NO;
        }
      else
        {
          result = [undo canUndo];
          if ([(id)anItem respondsToSelector: @selector(setTitle:)])
            {
              if (result)
                [(id)anItem setTitle: [undo undoMenuItemTitle]];
              else
                [(id)anItem setTitle:
		       [undo undoMenuTitleForUndoActionName: @""]];
            }
        }
    }
  else if (sel_isEqual(action, @selector(redo:)))
    {
      NSUndoManager *undo = [_firstResponder undoManager];
      if (undo == nil)
        {
          result = NO;
        }
      else
        {
          result = [undo canRedo];
          if ([(id)anItem respondsToSelector: @selector(setTitle:)])
            {
              if (result)
                [(id)anItem setTitle: [undo redoMenuItemTitle]];
              else
                [(id)anItem setTitle:
		       [undo redoMenuTitleForUndoActionName: @""]];
            }
        }
    }
  else if (sel_isEqual(action, @selector(toggleToolbarShown:)))
    {
      NSToolbar *toolbar = [self toolbar];

      if (toolbar == nil)
        {
          result = NO;
        }
      else
        {
          result = YES;
          if ([(id)anItem respondsToSelector: @selector(setTitle:)])
            {
              if ([toolbar isVisible])
                [(id)anItem setTitle: _(@"Hide Toolbar")];
              else
                [(id)anItem setTitle: _(@"Show Toolbar")];
            }
        }
    }
  else if (sel_isEqual(action, @selector(runToolbarCustomizationPalette:)))
    {
      NSToolbar *toolbar = [self toolbar];

      if (toolbar == nil)
	{
	  result = NO;
	}
      else
	{
	  result = [toolbar allowsUserCustomization];
	}
    }
    
  return result;
}

- (BOOL) validateMenuItem: (NSMenuItem *)anItem
{
  return [self validateUserInterfaceItem: anItem];
}

/*
 * Assigning a delegate
 */

/**
   Returns the delegate.
 */
- (id) delegate
{
  return _delegate;
}

/**
   Sets the delegate to anObject.
*/
- (void) setDelegate: (id)anObject
{
  if (anObject == _delegate)
    {
      // don't remove previously registered notifications if delegate is unchanged!
      return;
    }	  	 

  if (_delegate)
    {
      [nc removeObserver: _delegate name: nil object: self];
    }
  _delegate = anObject;

#define SET_DELEGATE_NOTIFICATION(notif_name) \
  if ([_delegate respondsToSelector: @selector(window##notif_name:)]) \
    [nc addObserver: _delegate \
      selector: @selector(window##notif_name:) \
      name: NSWindow##notif_name##Notification object: self]

  SET_DELEGATE_NOTIFICATION(DidBecomeKey);
  SET_DELEGATE_NOTIFICATION(DidBecomeMain);
  SET_DELEGATE_NOTIFICATION(DidChangeScreen);
  SET_DELEGATE_NOTIFICATION(DidDeminiaturize);
  SET_DELEGATE_NOTIFICATION(DidExpose);
  SET_DELEGATE_NOTIFICATION(DidMiniaturize);
  SET_DELEGATE_NOTIFICATION(DidMove);
  SET_DELEGATE_NOTIFICATION(DidResignKey);
  SET_DELEGATE_NOTIFICATION(DidResignMain);
  SET_DELEGATE_NOTIFICATION(DidResize);
  SET_DELEGATE_NOTIFICATION(DidUpdate);
  SET_DELEGATE_NOTIFICATION(WillClose);
  SET_DELEGATE_NOTIFICATION(WillMiniaturize);
  SET_DELEGATE_NOTIFICATION(WillMove);
}

/*
 * NSCoding protocol
 */
- (void) encodeWithCoder: (NSCoder*)aCoder
{
  BOOL flag;

  // If were're being initialized from a keyed coder...
  if ([aCoder allowsKeyedCoding])
    {
      // The docs indicate that there should be an error when directly encoding with
      // a keyed coding archiver.  We should only encode NSWindow and subclasses
      // using NSWindowTemplate.
      [NSException raise: NSInvalidArgumentException
                   format: @"Keyed coding not implemented for %@.", 
                   NSStringFromClass([self class])];
    }

  [super encodeWithCoder: aCoder];

  [aCoder encodeRect: [[self contentView] frame]];
  [aCoder encodeValueOfObjCType: @encode(NSUInteger) at: &_styleMask];
  // This used to be int, we need to stay compatible
  [aCoder encodeValueOfObjCType: @encode(NSInteger) at: &_backingType];

  [aCoder encodePoint: NSMakePoint(NSMinX([self frame]), NSMaxY([self frame]))];
  [aCoder encodeObject: _contentView];
  [aCoder encodeObject: _backgroundColor];
  [aCoder encodeObject: _representedFilename];
  [aCoder encodeObject: _miniaturizedTitle];
  [aCoder encodeObject: _windowTitle];

  //  [aCoder encodeSize: _minimumSize];
  //  [aCoder encodeSize: _maximumSize];
  [aCoder encodeSize: [self contentMinSize]];
  [aCoder encodeSize: [self contentMaxSize]];

  [aCoder encodeValueOfObjCType: @encode(NSInteger) at: &_windowLevel];

  flag = _f.menu_exclude;
  [aCoder encodeValueOfObjCType: @encode(BOOL) at: &flag];
  flag = _f.is_one_shot;
  [aCoder encodeValueOfObjCType: @encode(BOOL) at: &flag];
  flag = _f.is_autodisplay;
  [aCoder encodeValueOfObjCType: @encode(BOOL) at: &flag];
  flag = _f.optimize_drawing;
  [aCoder encodeValueOfObjCType: @encode(BOOL) at: &flag];
  flag = _f.dynamic_depth_limit;
  [aCoder encodeValueOfObjCType: @encode(BOOL) at: &flag];
  flag = _f.cursor_rects_enabled;
  [aCoder encodeValueOfObjCType: @encode(BOOL) at: &flag];
  flag = _f.is_released_when_closed;
  [aCoder encodeValueOfObjCType: @encode(BOOL) at: &flag];
  flag = _f.hides_on_deactivate;
  [aCoder encodeValueOfObjCType: @encode(BOOL) at: &flag];
  flag = _f.accepts_mouse_moved;
  [aCoder encodeValueOfObjCType: @encode(BOOL) at: &flag];

  [aCoder encodeObject: _miniaturizedImage];
  [aCoder encodeConditionalObject: _initialFirstResponder];
}

- (id) initWithCoder: (NSCoder*)aDecoder
{
  id oldself = self;
  BOOL flag;

  // If were're being initialized from a keyed coder...
  if ([aDecoder allowsKeyedCoding])
    {
      // The docs indicate that there should be an error when directly encoding with
      // a keyed coding archiver.  We should only encode NSWindow and subclasses
      // using NSWindowTemplate.
      [NSException raise: NSInvalidArgumentException
                   format: @"Keyed coding not implemented for %@.", 
                   NSStringFromClass([self class])];
    }


  if ((self = [super initWithCoder: aDecoder]) == oldself)
    {
      NSSize aSize;
      NSRect aRect;
      NSPoint p;
      NSUInteger aStyle;
      NSBackingStoreType aBacking;
      NSInteger level;
      id obj;
      int version = [aDecoder versionForClassName: @"NSWindow"];

      aRect = [aDecoder decodeRect];
      [aDecoder decodeValueOfObjCType: @encode(NSUInteger)
                                   at: &aStyle];
      // This used to be int, we need to stay compatible
      [aDecoder decodeValueOfObjCType: @encode(NSInteger)
                                   at: &aBacking];

      // call the designated initializer....
      self = [self initWithContentRect: aRect
                             styleMask: aStyle
                               backing: aBacking
                                 defer: NO];

      p = [aDecoder decodePoint];
      obj = [aDecoder decodeObject];
      [self setContentView: obj];
      obj = [aDecoder decodeObject];
      [self setBackgroundColor: obj];
      obj = [aDecoder decodeObject];
      [self setRepresentedFilename: obj];
      obj = [aDecoder decodeObject];
      [self setMiniwindowTitle: obj];
      obj = [aDecoder decodeObject];
      [self setTitle: obj];

      if (version < 3)
        {
          aSize = [aDecoder decodeSize];
          [self setMinSize: aSize];
          aSize = [aDecoder decodeSize];
          [self setMaxSize: aSize];
        }
      else
        {
          aSize = [aDecoder decodeSize];
          [self setContentMinSize: aSize];
          aSize = [aDecoder decodeSize];
          [self setContentMaxSize: aSize];
        }

      [aDecoder decodeValueOfObjCType: @encode(NSInteger)
                                   at: &level];
      [self setLevel: level];

      [aDecoder decodeValueOfObjCType: @encode(BOOL) at: &flag];
      [self setExcludedFromWindowsMenu: flag];
      [aDecoder decodeValueOfObjCType: @encode(BOOL) at: &flag];
      [self setOneShot: flag];
      [aDecoder decodeValueOfObjCType: @encode(BOOL) at: &flag];
      [self setAutodisplay: flag];
      [aDecoder decodeValueOfObjCType: @encode(BOOL) at: &flag];
      [self useOptimizedDrawing: flag];
      [aDecoder decodeValueOfObjCType: @encode(BOOL) at: &flag];
      [self setDynamicDepthLimit: flag];
      [aDecoder decodeValueOfObjCType: @encode(BOOL) at: &flag];
      if (flag)
        [self enableCursorRects];
      else
        [self disableCursorRects];
      [aDecoder decodeValueOfObjCType: @encode(BOOL) at: &flag];
      [self setReleasedWhenClosed: flag];
      [aDecoder decodeValueOfObjCType: @encode(BOOL) at: &flag];
      [self setHidesOnDeactivate: flag];
      [aDecoder decodeValueOfObjCType: @encode(BOOL) at: &flag];
      [self setAcceptsMouseMovedEvents: flag];

      /* If the image has been specified, use it, if not use the default. */
      obj = [aDecoder decodeObject]; 
      if (obj != nil)
        {
          ASSIGN(_miniaturizedImage, obj);
        }

      [aDecoder decodeValueOfObjCType: @encode(id)
                                   at: &_initialFirstResponder];

      [self setFrameTopLeftPoint: p];
    }

  return self;
}

- (void) bind: (NSString *)binding
     toObject: (id)anObject
  withKeyPath: (NSString *)keyPath
      options: (NSDictionary *)options
{
  if ([binding isEqual: NSTitleBinding])
    {
      GSKeyValueBinding *kvb;

      [self unbind: binding];
      kvb = [[GSKeyValueBinding alloc] initWithBinding: @"title"
                                              withName: NSTitleBinding
                                              toObject: anObject
                                           withKeyPath: keyPath
                                               options: options
                                            fromObject: self];
      // The binding will be retained in the binding table
      RELEASE(kvb);
    }
  else
    {
      [super bind: binding toObject: anObject withKeyPath: keyPath 
        options: options];
    }
}

/**
   Returns all drawers associated with this window.
*/
- (NSArray *) drawers
{
  // TODO
  NSLog(@"Method %s is not implemented for class %s",
        "drawers", "NSWindow");
  return nil;
}

- (void *)windowRef
{
  GSDisplayServer *srv = GSServerForWindow(self);

  return [srv windowDevice: _windowNum];
}

- (void *) windowHandle
{
  // Should only be defined on MS Windows
  return (void *)(intptr_t)_windowNum;
}

- (NSWindow *) attachedSheet
{
  return _attachedSheet;
}

@end

@implementation NSWindow (Toolbar)

- (void) runToolbarCustomizationPalette: (id)sender
{
  [[self toolbar] runCustomizationPalette: sender];
}

- (void) toggleToolbarShown: (id)sender
{
  NSToolbar *toolbar = [self toolbar];
  BOOL isVisible = [toolbar isVisible];

  if (!toolbar)
    return;

  // We do this again on a lower level, but doing it here is faster.
  if (isVisible)
    {
      [_wv removeToolbarView: [toolbar _toolbarView]];
    }
  else
    {
      [_wv addToolbarView: [toolbar _toolbarView]];
    }

  [toolbar setVisible: !isVisible];

  [self display];
}

// Accessors

- (NSToolbar *) toolbar
{
  return _toolbar;
}

- (void) setToolbar: (NSToolbar*)toolbar
{
  if (toolbar == _toolbar)
    return;

  if (_toolbar != nil)
    {
      if ([_toolbar isVisible])
        {
          // Throw the last toolbar view out
          [_wv removeToolbarView: [_toolbar _toolbarView]];
        }
    }
  
  ASSIGN(_toolbar, toolbar);

  if (_toolbar != nil)
    {
      if ([_toolbar isVisible])
        {
          // Make the new toolbar view visible
          [_wv addToolbarView: [_toolbar _toolbarView]];
        }
    }

  // To show the changed toolbar
  [self displayIfNeeded];
}

@end

@implementation NSWindow (Menu)

- (void) setMenu: (NSMenu *)menu
{
  // Do theme specific logic...
  [[GSTheme theme] setMenu: menu forWindow: self];

  if([self menu] != menu)
    [super setMenu: menu];
}

@end

/*
 * GNUstep backend methods
 */
@implementation NSWindow (GNUstepBackend)

/*
 * Mouse capture/release
 */
- (void) _captureMouse: sender
{
  NSDebugLLog(@"CaptureMouse", @"Capturing the mouse");
  [GSCurrentServer() capturemouse: _windowNum];
}

- (void) _releaseMouse: sender
{
  NSDebugLLog(@"CaptureMouse", @"Releasing the mouse");
  [GSCurrentServer() releasemouse];
}

- (void) _setVisible: (BOOL)flag
{
  _f.visible = flag;
}

- (void) performDeminiaturize: sender
{
  [self deminiaturize: sender];
}

/*
 * Allow subclasses to init without the backend
 * class attempting to create an actual window
 */
- (void) _initDefaults
{
  _firstResponder = self;
//  _initialFirstResponder = nil;
//  _delegate = nil;
//  _windowNum = 0;
//  _gstate = 0;
  _backgroundColor = RETAIN([NSColor windowBackgroundColor]);
  _representedFilename = @"Window";
  _miniaturizedTitle = @"Window";
  _miniaturizedImage = RETAIN([NSApp applicationIconImage]);
  _windowTitle = @"Window";
  _lastPoint = NSZeroPoint;
  _windowLevel = NSNormalWindowLevel;

  _depthLimit = NSDefaultDepth;
  _disableFlushWindow = 0;
  _alphaValue = 1.0;

//  _f.accepts_drag = NO;
//  _f.is_one_shot = NO;
//  _f.needs_flush = NO;
  _f.is_autodisplay = YES;
//  _f.optimize_drawing = NO;
  _f.dynamic_depth_limit = YES;
//  _f.cursor_rects_enabled = NO;
//  _f.cursor_rects_valid = NO;
//  _f.visible = NO;
//  _f.is_key = NO;
//  _f.is_main = NO;
//  _f.is_edited = NO;
  _f.is_released_when_closed = YES;
//  _f.is_miniaturized = NO;
//  _f.menu_exclude = NO;
//  _f.hides_on_deactivate = NO;
//  _f.accepts_mouse_moved = NO;
//  _f.has_opened = NO;
//  _f.has_closed = NO;
//  _f.default_button_cell_key_disabled = NO;
  _f.can_hide = YES;
//  _f.has_shadow = NO;
  _f.is_opaque = YES;
  _f.views_need_display = YES;
  _f.selectionDirection = NSDirectSelection;
}

@end

@implementation NSWindow (GNUstepTextView)
- (id) _futureFirstResponder
{
  return _futureFirstResponder;
}
@end

@implementation NSApplication(Inactive)
- (BOOL) _isWindowInactive: (NSWindow *)window
{
  return [_inactive containsObject: window];
}

- (void) _setWindow: (NSWindow *)window inactive: (BOOL)inactive
{
  if (inactive)
    {
      [_inactive addObject: window];
    }
  else
    {
      [_inactive removeObject: window];
    }
}
@end

BOOL GSViewAcceptsDrag(NSView *v, id<NSDraggingInfo> dragInfo)
{
  NSPasteboard *pb = [dragInfo draggingPasteboard];
  if ([pb availableTypeFromArray: GSGetDragTypes(v)])
    return YES;
  return NO;
}

void NSCountWindows(NSInteger *count)
{
  *count = [[GSCurrentServer() windowlist] count];
}

void NSWindowList(NSInteger size, NSInteger list[])
{
  NSArray *windowList = [GSCurrentServer() windowlist];
  NSUInteger i, c;

  for (i = 0, c = [windowList count]; i < size && i < c; i++)
    {
      list[i] = [[windowList objectAtIndex: i] integerValue];
    }
}

NSArray *GSOrderedWindows(void)
{
  NSArray *window_list = [GSCurrentServer() windowlist];
  NSMutableArray *ret = [NSMutableArray array];
  NSUInteger i, c; 
  
  for (i = 0, c = [window_list count]; i < c; i++)
    {
      NSInteger windowNumber = [[window_list objectAtIndex: i] integerValue];
      NSWindow *win = GSWindowWithNumber(windowNumber);
      
      [ret addObject: win];
    }

  return ret;
}


NSArray* GSAllWindows(void)
{
  if (windowmaps)
    return NSAllMapTableValues(windowmaps);
  return nil;
}

NSWindow* GSWindowWithNumber(NSInteger num)
{
  if (windowmaps)
    return (NSWindow*)NSMapGet(windowmaps, (void*)(intptr_t)num);
  return nil;
}