File: NSView.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 (5141 lines) | stat: -rw-r--r-- 130,479 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
/** <title>NSView</title>

   <abstract>The view class which encapsulates all drawing functionality</abstract>

   Copyright (C) 1996 Free Software Foundation, Inc.

   Author: Scott Christley <scottc@net-community.com>
   Date: 1996
   Author: Ovidiu Predescu <ovidiu@net-community.com>
   Date: 1997   Author: Felipe A. Rodriguez <far@ix.netcom.com>
   Date: August 1998
   Author: Richard Frith-Macdonald <richard@brainstorm.co.uk>
   Date: January 1999

   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/NSString.h>
#import <Foundation/NSBundle.h>
#import <Foundation/NSCalendarDate.h>
#import <Foundation/NSCoder.h>
#import <Foundation/NSKeyedArchiver.h>
#import <Foundation/NSDictionary.h>
#import <Foundation/NSThread.h>
#import <Foundation/NSLock.h>
#import <Foundation/NSArray.h>
#import <Foundation/NSNotification.h>
#import <Foundation/NSValue.h>
#import <Foundation/NSData.h>
#import <Foundation/NSDebug.h>
#import <Foundation/NSPathUtilities.h>
#import <Foundation/NSSet.h>

#import "AppKit/NSAffineTransform.h"
#import "AppKit/NSApplication.h"
#import "AppKit/NSBezierPath.h"
#import "AppKit/NSBitmapImageRep.h"
#import "AppKit/NSCursor.h"
#import "AppKit/NSDocumentController.h"
#import "AppKit/NSDocument.h"
#import "AppKit/NSClipView.h"
#import "AppKit/NSFont.h"
#import "AppKit/NSGraphics.h"
#import "AppKit/NSKeyValueBinding.h"
#import "AppKit/NSMenu.h"
#import "AppKit/NSPasteboard.h"
#import "AppKit/NSPrintInfo.h"
#import "AppKit/NSPrintOperation.h"
#import "AppKit/NSScrollView.h"
#import "AppKit/NSView.h"
#import "AppKit/NSWindow.h"
#import "AppKit/NSWorkspace.h"
#import "AppKit/PSOperators.h"
#import "GNUstepGUI/GSDisplayServer.h"
#import "GNUstepGUI/GSTrackingRect.h"
#import "GNUstepGUI/GSNibLoading.h"
#import "GSToolTips.h"
#import "GSBindingHelpers.h"
#import "GSGuiPrivate.h"
#import "NSViewPrivate.h"

/*
 * We need a fast array that can store objects without retain/release ...
 */
#define GSI_ARRAY_TYPES		GSUNION_OBJ
#define GSI_ARRAY_NO_RELEASE	1
#define GSI_ARRAY_NO_RETAIN	1

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

#define	nKV(O)	((GSIArray)(O->_nextKeyView))
#define	pKV(O)	((GSIArray)(O->_previousKeyView))

/* Variable tells this view and subviews that we're printing. Not really
   a class variable because we want it visible to subviews also
*/
NSView *viewIsPrinting = nil;

/**
  <unit>
  <heading>NSView</heading>

  <p>NSView is an abstract class which provides facilities for drawing
  in a window and receiving events.  It is the superclass of many of
  the visual elements of the GUI.</p>

  <p>In order to display itself, a view must be placed in a window
  (represented by an NSWindow object).  Within the window is a
  hierarchy of NSViews, headed by the window's content view.  Every
  other view in a window is a descendant of this view.</p>

  <p>Subclasses can override -drawRect: in order to
  implement their appearance.  Other methods of NSView and NSResponder
  can also be overridden to handle user generated events.</p>

  </unit>
*/
  
@implementation NSView

/*
 * Class variables */
static Class	rectClass;
static Class	viewClass;

static NSAffineTransform	*flip = nil;

static NSNotificationCenter *nc = nil;

static SEL	preSel;
static SEL	invalidateSel;

static void	(*preImp)(NSAffineTransform*, SEL, NSAffineTransform*);
static void	(*invalidateImp)(NSView*, SEL);

/*
 *	Stuff to maintain a map table so we know what views are
 *	registered for drag and drop - we don't store the info in
 *	the view directly 'cot it would take up a pointer in each
 *	view and the vast majority of views wouldn't use it.
 *	Types are not registered/unregistered often enough for the
 *	performance of this mechanism to be an issue.
 */
static NSMapTable	*typesMap = 0;
static NSLock		*typesLock = nil;

/*
 * This is the only external interface to the drag types info.
 */
NSArray*
GSGetDragTypes(NSView *obj)
{
  NSArray	*t;

  [typesLock lock];
  t = (NSArray*)NSMapGet(typesMap, (void*)(gsaddr)obj);
  [typesLock unlock];
  return t;
}

static void
GSRemoveDragTypes(NSView* obj)
{
  [typesLock lock];
  NSMapRemove(typesMap, (void*)(gsaddr)obj);
  [typesLock unlock];
}

static NSArray*
GSSetDragTypes(NSView* obj, NSArray *types)
{
  NSUInteger	count = [types count];
  NSString	*strings[count];
  NSArray	*t;
  NSUInteger	i;

  /*
   * Make a new array with copies of the type strings so we don't get
   * them mutated by someone else.
   */
  [types getObjects: strings];
  for (i = 0; i < count; i++)
    {
      strings[i] = [strings[i] copy];
    }
  t = [NSArray arrayWithObjects: strings count: count];
  for (i = 0; i < count; i++)
    {
      RELEASE(strings[i]);
    }
  /*
   * Store it.
   */
  [typesLock lock];
  NSMapInsert(typesMap, (void*)(gsaddr)obj, (void*)(gsaddr)t);
  [typesLock unlock];
  return t;
}


/*
 *	Private methods.
 */


/*
 *	The [-_invalidateCoordinates] method marks the coordinate mapping
 *	matrices (matrixFromWindow and _matrixToWindow) and the cached visible
 *	rectangle as invalid.  It recursively invalidates the coordinates for
 *	all subviews as well.
 *	This method must be called whenever the size, shape or position of
 *	the view is changed in any way.
 */
- (void) _invalidateCoordinates
{
  if (_coordinates_valid == YES)
    {
      NSUInteger count;

      _coordinates_valid = NO;
      if (_rFlags.valid_rects != 0)
        {
          [_window invalidateCursorRectsForView: self];
        }
      if (_rFlags.has_subviews)
        {
          count = [_sub_views count];
          if (count > 0)
            {
              NSView*	array[count];
              NSUInteger i;
              
              [_sub_views getObjects: array];
              for (i = 0; i < count; i++)
                {
                  NSView	*sub = array[i];
                  
                  if (sub->_coordinates_valid == YES)
                    {
                      (*invalidateImp)(sub, invalidateSel);
                    }
                }
            }
        }
      [self renewGState];
    }
}

/*
 *	The [-_matrixFromWindow] method returns a matrix that can be used to
 *	map coordinates in the windows coordinate system to coordinates in the
 *	views coordinate system.  It rebuilds the mapping matrices and
 *	visible rectangle cache if necessary.
 *	All coordinate transformations use this matrix.
 */
- (NSAffineTransform*) _matrixFromWindow
{
  [self _rebuildCoordinates];
  return _matrixFromWindow;
}

/*
 *	The [-_matrixToWindow] method returns a matrix that can be used to
 *	map coordinates in the views coordinate system to coordinates in the
 *	windows coordinate system.  It rebuilds the mapping matrices and
 *	visible rectangle cache if necessary.
 *	All coordinate transformations use this matrix.
 */
- (NSAffineTransform*) _matrixToWindow
{
  [self _rebuildCoordinates];
  return _matrixToWindow;
}

/*
 *	The [-_rebuildCoordinates] method rebuilds the coordinate mapping
 *	matrices (matrixFromWindow and _matrixToWindow) and the cached visible
 *	rectangle if they have been invalidated.
 */
- (void) _rebuildCoordinates
{
  BOOL isFlipped = [self isFlipped];
  BOOL lastFlipped = _rFlags.flipped_view;

  if ((_coordinates_valid == NO) || (isFlipped != lastFlipped))
    {
      _coordinates_valid = YES;
      _rFlags.flipped_view = isFlipped;

      if (!_window)
        {
          _visibleRect = NSZeroRect;
          [_matrixToWindow makeIdentityMatrix];
          [_matrixFromWindow makeIdentityMatrix];
        }
      else
        {
          NSRect		superviewsVisibleRect;
          BOOL			superFlipped;
          NSAffineTransform	*pMatrix;
          NSAffineTransformStruct     ts;
 
	  if (_super_view != nil)
	    {
	      superFlipped = [_super_view isFlipped];
	      pMatrix = [_super_view _matrixToWindow];
	    }
	  else
	    {
	      superFlipped = NO;
	      pMatrix = [NSAffineTransform transform];
           }
	      
	  ts = [pMatrix transformStruct];

          /* prepend translation */
          ts.tX = NSMinX(_frame) * ts.m11 + NSMinY(_frame) * ts.m21 + ts.tX;
          ts.tY = NSMinX(_frame) * ts.m12 + NSMinY(_frame) * ts.m22 + ts.tY;
          [_matrixToWindow setTransformStruct: ts];
 
          /* prepend rotation */
          if (_frameMatrix != nil)
            {
              (*preImp)(_matrixToWindow, preSel, _frameMatrix);
            }
 
          if (isFlipped != superFlipped)
            {
              /*
               * The flipping process must result in a coordinate system that
               * exactly overlays the original.	 To do that, we must translate
               * the origin by the height of the view.
               */
              ts = [flip transformStruct];
              ts.tY = _frame.size.height;
              [flip setTransformStruct: ts];
              (*preImp)(_matrixToWindow, preSel, flip);
            }
          if (_boundsMatrix != nil)
            {
              (*preImp)(_matrixToWindow, preSel, _boundsMatrix);
            }
          ts = [_matrixToWindow transformStruct];
          [_matrixFromWindow setTransformStruct: ts];
          [_matrixFromWindow invert];

	  if (_super_view != nil)
	    {
	      superviewsVisibleRect = [self convertRect: [_super_view visibleRect]
					       fromView: _super_view];
	      
	      _visibleRect = NSIntersectionRect(superviewsVisibleRect, _bounds);
	    }
	  else
	    {
	      _visibleRect = _bounds;
	    }
        }
    }
}

- (void) _viewDidMoveToWindow
{
  [self viewDidMoveToWindow];
  if (_rFlags.has_subviews)
    {
      NSUInteger count = [_sub_views count];

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

          [_sub_views getObjects: array];
          for (i = 0; i < count; ++i)
            {
              [array[i] _viewDidMoveToWindow];
            }
        }
    }
}

- (void) _viewWillMoveToWindow: (NSWindow*)newWindow
{
  BOOL old_allocate_gstate;

  [self viewWillMoveToWindow: newWindow];
  if (_coordinates_valid)
    {
      (*invalidateImp)(self, invalidateSel);
    }
  if (_rFlags.has_currects != 0)
    {
      [self discardCursorRects];
    }

  if (newWindow == _window)
    {
      return;
    }

  // This call also reset _allocate_gstate, so we have 
  // to store this value and set it again.
  // This way we keep the logic in one place.
  old_allocate_gstate = _allocate_gstate;
  [self releaseGState];
  _allocate_gstate = old_allocate_gstate;

  if (_rFlags.has_draginfo)
    {
      NSArray *t = GSGetDragTypes(self);

      if (_window != nil)
        {
          [GSDisplayServer removeDragTypes: t fromWindow: _window];
	  if ([_window autorecalculatesKeyViewLoop])
	    {
	      [_window recalculateKeyViewLoop];
	    }
        }
      if (newWindow != nil)
        {
          [GSDisplayServer addDragTypes: t toWindow: newWindow];
	  if ([newWindow autorecalculatesKeyViewLoop])
	    {
	      [newWindow recalculateKeyViewLoop];
	    }
        }
    }
  
  _window = newWindow;

  if (_rFlags.has_subviews)
    {
      NSUInteger count = [_sub_views count];

      if (count > 0)
        {
          NSUInteger i;
          NSView *array[count];
          
          [_sub_views getObjects: array];
          for (i = 0; i < count; ++i)
            {
              [array[i] _viewWillMoveToWindow: newWindow];
            }
        }
    }
}

- (void) _viewWillMoveToSuperview: (NSView*)newSuper
{
  [self viewWillMoveToSuperview: newSuper];
  _super_view = newSuper;
}

/*
 * Extend in super view covered by the frame of a view.
 * When the frame is rotated, this is different from the frame.
 */
- (NSRect) _frameExtend
{
  NSRect frame = _frame;
              
  if (_frameMatrix != nil)
    {
      NSRect r;

      r.origin = NSZeroPoint;
      r.size = frame.size;
      [_frameMatrix boundingRectFor: r result: &r];
      frame = NSOffsetRect(r, NSMinX(frame),
                           NSMinY(frame));
    }

  return frame;
}


- (NSString*) _subtreeDescriptionWithPrefix: (NSString*)prefix
{
  NSMutableString *desc = [[NSMutableString alloc] init];
  NSEnumerator *e;
  NSView *v;

  [desc appendFormat: @"%@%@\n", prefix, [self description], nil];

  prefix = [prefix stringByAppendingString: @"  "];
  e = [_sub_views objectEnumerator];
  while ((v = (NSView*)[e nextObject]) != nil)
    {
      [desc appendString: [v _subtreeDescriptionWithPrefix: prefix]];
    }

  return AUTORELEASE(desc);
}

/*
 * Unofficial Cocoa method for debugging a view hierarchy.
 */
- (NSString*) _subtreeDescription
{
  return [self _subtreeDescriptionWithPrefix: @""]; 
}

- (NSString*) _flagDescription
{
  return @"";
}

- (NSString*) _resizeDescription
{
  return [NSString stringWithFormat: @"h=%c%c%c v=%c%c%c", 
                   (_autoresizingMask & NSViewMinXMargin) ? '&' : '-',
                   (_autoresizingMask & NSViewWidthSizable) ? '&' : '-',
                   (_autoresizingMask & NSViewMaxXMargin) ? '&' : '-',
                   (_autoresizingMask & NSViewMinYMargin) ? '&' : '-',
                   (_autoresizingMask & NSViewHeightSizable) ? '&' : '-',
                   (_autoresizingMask & NSViewMaxYMargin) ? '&' : '-',
                   nil];
}

- (NSString*) description
{
  return [NSString stringWithFormat: @"%@ %@ %@ f=%@ b=%@", 
                   [self _flagDescription], 
                   [self _resizeDescription], [super description], 
                   NSStringFromRect(_frame), NSStringFromRect(_bounds), nil];
}

/*
 * Class methods
 */
+ (void) initialize
{
  if (self == [NSView class])
    {
      Class	matrixClass = [NSAffineTransform class];
      NSAffineTransformStruct	ats = { 1, 0, 0, -1, 0, 1 };

      typesMap = NSCreateMapTable(NSNonOwnedPointerMapKeyCallBacks,
                NSObjectMapValueCallBacks, 0);
      typesLock = [NSLock new];

      preSel = @selector(prependTransform:);
      invalidateSel = @selector(_invalidateCoordinates);

      preImp = (void (*)(NSAffineTransform*, SEL, NSAffineTransform*))
          [matrixClass instanceMethodForSelector: preSel];

      invalidateImp = (void (*)(NSView*, SEL))
          [self instanceMethodForSelector: invalidateSel];

      flip = [matrixClass new];
      [flip setTransformStruct: ats];

      nc = [NSNotificationCenter defaultCenter];

      viewClass = [NSView class];
      rectClass = [GSTrackingRect class];
      NSDebugLLog(@"NSView", @"Initialize NSView class\n");
      [self setVersion: 1];

      // expose bindings
      [self exposeBinding: NSToolTipBinding];
      [self exposeBinding: NSHiddenBinding];
    }
}

/**
 Return the view at the top of graphics contexts stack
 or nil if none is focused.
 */
+ (NSView*) focusView
{
  return [GSCurrentContext() focusView];
}

/*
 * Instance methods
 */
- (id) init
{
  return [self initWithFrame: NSZeroRect];
}

- (id) initWithFrame: (NSRect)frameRect
{
  self = [super init];
  if (!self)
    return self;

  if (frameRect.size.width < 0)
    {
      NSWarnMLog(@"given negative width");
      frameRect.size.width = 0;
    }
  if (frameRect.size.height < 0)
    {
      NSWarnMLog(@"given negative height");
      frameRect.size.height = 0;
    }
  _frame = frameRect;			// Set frame rectangle
  _bounds.origin = NSZeroPoint;		// Set bounds rectangle
  _bounds.size = _frame.size;

  // _frameMatrix = [NSAffineTransform new];    // Map fromsuperview to frame
  // _boundsMatrix = [NSAffineTransform new];   // Map from superview to bounds
  _matrixToWindow = [NSAffineTransform new];   // Map to window coordinates
  _matrixFromWindow = [NSAffineTransform new]; // Map from window coordinates

  _sub_views = [NSMutableArray new];
  _tracking_rects = [NSMutableArray new];
  _cursor_rects = [NSMutableArray new];

  // Some values are already set by initialisation
  //_super_view = nil;
  //_window = nil;
  //_is_rotated_from_base = NO;
  //_is_rotated_or_scaled_from_base = NO;
  _rFlags.needs_display = YES;
  _post_bounds_changes = YES;
  _post_frame_changes = YES;
  _autoresizes_subviews = YES;
  _autoresizingMask = NSViewNotSizable;
  //_coordinates_valid = NO;
  //_nextKeyView = 0;
  //_previousKeyView = 0;

  _alphaValue = 1.0;
  
  return self;
}

- (void) dealloc
{
  NSView *tmp;
  NSUInteger count;

  // Remove all key value bindings for this view.
  [GSKeyValueBinding unbindAllForObject: self];

  /*
   * Remove self from view chain.  Try to mimic MacOS-X behavior ...
   * We send setNextKeyView: messages to all view for which we are the
   * next key view, setting their next key view to nil.
   *
   * First we do the obvious stuff using the standard methods.
   */
  [self setNextKeyView: nil];
  tmp = [self previousKeyView];
  if ([tmp nextKeyView] == self)
    [tmp setNextKeyView: nil];

  /*
   * Now, we locate any remaining cases where a view has us as its next
   * view, and ask the view to change that.
   */
  if (pKV(self) != 0)
    {
      count = GSIArrayCount(pKV(self));
      while (count-- > 0)
	{
	  tmp = GSIArrayItemAtIndex(pKV(self), count).obj;
	  if ([tmp nextKeyView] == self)
	    {
	      [tmp setNextKeyView: nil];
	    }
	}
    }

  /*
   * Now we clean up the previous view array, in case subclasses have
   * overridden the default -setNextKeyView: method and broken things.
   * We also relase the memory we used.
   */
  if (pKV(self) != 0)
    {
      count = GSIArrayCount(pKV(self));
      while (count-- > 0)
	{
	  tmp = GSIArrayItemAtIndex(pKV(self), count).obj;
	  if (tmp != nil && nKV(tmp) != 0)
	    {
	      NSUInteger otherCount = GSIArrayCount(nKV(tmp));
	
	      while (otherCount-- > 1)
		{
		  if (GSIArrayItemAtIndex(nKV(tmp), otherCount).obj == self)
		    {
		      GSIArrayRemoveItemAtIndex(nKV(tmp), otherCount);
		    }
		}
	      if (GSIArrayItemAtIndex(nKV(tmp), 0).obj == self)
		{
		  GSIArraySetItemAtIndex(nKV(tmp), (GSIArrayItem)nil, 0);
		}
	    }
	}
      GSIArrayClear(pKV(self));
      NSZoneFree(NSDefaultMallocZone(), pKV(self));
      _previousKeyView = 0;
    }

  /*
   * Now we clean up all views which have us as their previous view.
   * We also release the memory we used.
   */
  if (nKV(self) != 0)
    {
      count = GSIArrayCount(nKV(self));
      while (count-- > 0)
	{
	  tmp = GSIArrayItemAtIndex(nKV(self), count).obj;
	  if (tmp != nil && pKV(tmp) != 0)
	    {
	      NSUInteger otherCount = GSIArrayCount(pKV(tmp));
	
	      while (otherCount-- > 1)
		{
		  if (GSIArrayItemAtIndex(pKV(tmp), otherCount).obj == self)
		    {
		      GSIArrayRemoveItemAtIndex(pKV(tmp), otherCount);
		    }
		}
	      if (GSIArrayItemAtIndex(pKV(tmp), 0).obj == self)
		{
		  GSIArraySetItemAtIndex(pKV(tmp), (GSIArrayItem)nil, 0);
		}
	    }
	}
      GSIArrayClear(nKV(self));
      NSZoneFree(NSDefaultMallocZone(), nKV(self));
      _nextKeyView = 0;
    }

  /*
   * Now remove our subviews, AFTER cleaning up the view chain, in case
   * any of our subviews were in the chain.
   */
  while ([_sub_views count] > 0)
    {
      [[_sub_views lastObject] removeFromSuperviewWithoutNeedingDisplay];
    }

  RELEASE(_matrixToWindow);
  RELEASE(_matrixFromWindow);
  TEST_RELEASE(_frameMatrix);
  TEST_RELEASE(_boundsMatrix);
  TEST_RELEASE(_sub_views);
  if (_rFlags.has_tooltips != 0)
    {
      [GSToolTips removeTipsForView: self];
    }
  if (_rFlags.has_currects != 0)
    {
      [self discardCursorRects];	// Handle release of cursors
    }
  TEST_RELEASE(_cursor_rects);
  TEST_RELEASE(_tracking_rects);
  [self unregisterDraggedTypes];
  [self releaseGState];

  [super dealloc];
}

/**
 * Adds aView as a subview of the receiver.
 */
- (void) addSubview: (NSView*)aView
{
  [self addSubview: aView
        positioned: NSWindowAbove
        relativeTo: nil];
}

- (void) addSubview: (NSView*)aView
	 positioned: (NSWindowOrderingMode)place
	 relativeTo: (NSView*)otherView
{
  NSUInteger index;

  if (aView == nil)
    {
      return;
    }
  if ([self isDescendantOf: aView])
    {
      [NSException raise: NSInvalidArgumentException
		  format: @"addSubview:positioned:relativeTo: creates a "
	@"loop in the views tree!"];
    }

  if (aView == otherView)
    return;

  RETAIN(aView);
  [aView removeFromSuperview];

  // Do this after the removeFromSuperview, as aView may already 
  // be a subview and the index could change.
  if (otherView == nil)
    {
      index = NSNotFound;
    }
  else
    {
      index = [_sub_views indexOfObjectIdenticalTo: otherView];
    }
  if (index == NSNotFound)
    {
      if (place == NSWindowBelow)
        index = 0;
      else
        index = [_sub_views count];
    }
  else if (place != NSWindowBelow)
    {
      index += 1;
    }

  [aView _viewWillMoveToWindow: _window];
  [aView _viewWillMoveToSuperview: self];
  [aView setNextResponder: self];
  [_sub_views insertObject: aView atIndex: index];
  _rFlags.has_subviews = 1;
  [aView resetCursorRects];
  [aView setNeedsDisplay: YES];
  [aView _viewDidMoveToWindow];
  [aView viewDidMoveToSuperview];
  [self didAddSubview: aView];
  RELEASE(aView);
}

/**
 * Returns self if aView is the receiver or aView is a subview of the receiver,
 * the ancestor view shared by aView and the receiver if any, or
 * aView if it is an ancestor of the receiver, otherwise returns nil.
 */
- (NSView*) ancestorSharedWithView: (NSView*)aView
{
  if (self == aView)
    return self;

  if ([self isDescendantOf: aView])
    return aView;

  if ([aView isDescendantOf: self])
    return self;

  /*
   * If neither are descendants of each other and either does not have a
   * superview then they cannot have a common ancestor
   */
  if (!_super_view)
    return nil;

  if (![aView superview])
    return nil;

  /* Find the common ancestor of superviews */
  return [_super_view ancestorSharedWithView: [aView superview]];
}

/**
 * Returns YES if aView is an ancestor of the receiver.
 */
- (BOOL) isDescendantOf: (NSView*)aView
{
  if (aView == self)
    return YES;

  if (!_super_view)
    return NO;

  if (_super_view == aView)
    return YES;

  return [_super_view isDescendantOf: aView];
}

- (NSView*) opaqueAncestor
{
  NSView	*next = _super_view;
  NSView	*current = self;

  while (next != nil)
    {
      if ([current isOpaque] == YES)
	{
	  break;
	}
      current = next;
      next = current->_super_view;
    }
  return current;
}

/**
 * Removes the receiver from its superviews list of subviews.
 */
- (void) removeFromSuperviewWithoutNeedingDisplay
{
  if (_super_view != nil)
    {
      [_super_view removeSubview: self];
    }
}

/**
  <p> Removes the receiver from its superviews list of subviews
  and marks the rectangle that the reciever occupied in the 
  superview as needing redisplay.  </p>

  <p> This is dangerous to use during display, since it alters the
  rectangles needing display. In this case, you can use the
  -removeFromSuperviewWithoutNeedingDisplay method instead.</p> */
- (void) removeFromSuperview
{
  if (_super_view != nil)
    {
      [_super_view setNeedsDisplayInRect: _frame];
      [self removeFromSuperviewWithoutNeedingDisplay];
    }
}

/**
  <p> Removes aSubview from the receivers list of subviews and from
  the responder chain.  </p>

  <p> Also invokes -viewWillMoveToWindow: on aView with a nil argument,
  to handle
  removal of aView (and recursively, its children) from its window -
  performing tidyup by invalidating cursor rects etc.  </p> 
*/
- (void) removeSubview: (NSView*)aView
{
  id view;
  /*
   * This must be first because it invokes -resignFirstResponder:, 
   * which assumes the view is still in the view hierarchy
   */
  for (view = [_window firstResponder];
    view != nil && [view respondsToSelector: @selector(superview)];
    view = [view superview])
    {
      if (view == aView)
	{      
	  [_window makeFirstResponder: _window];
	  break;
	}
    }
  [self willRemoveSubview: aView];
  aView->_super_view = nil;
  [aView _viewWillMoveToWindow: nil];
  [aView _viewWillMoveToSuperview: nil];
  [aView setNextResponder: nil];
  RETAIN(aView);
  [_sub_views removeObjectIdenticalTo: aView];
  [aView setNeedsDisplay: NO];
  [aView _viewDidMoveToWindow];
  [aView viewDidMoveToSuperview];
  RELEASE(aView);
  if ([_sub_views count] == 0)
    {
      _rFlags.has_subviews = 0;
    }
}

/**
 * Removes oldView, which should be a subview of the receiver, from the
 * receiver and places newView in its place. If newView is nil, just
 * removes oldView. If oldView is nil, just adds newView.
 */
- (void) replaceSubview: (NSView*)oldView with: (NSView*)newView
{
  if (newView == oldView)
    {
      return;
    }
  /*
   * NB. we implement the replacement in full rather than calling addSubview:
   * since classes like NSBox override these methods but expect to be able to
   * call [super replaceSubview:with:] safely.
   */
  if (oldView == nil)
    {
      /*
       * Strictly speaking, the docs say that if 'oldView' is not a subview
       * of the receiver then we do nothing - but here we add newView anyway.
       * So a replacement with no oldView is an addition.
       */
      RETAIN(newView);
      [newView removeFromSuperview];
      [newView _viewWillMoveToWindow: _window];
      [newView _viewWillMoveToSuperview: self];
      [newView setNextResponder: self];
      [_sub_views addObject: newView];
      _rFlags.has_subviews = 1;
      [newView resetCursorRects];
      [newView setNeedsDisplay: YES];
      [newView _viewDidMoveToWindow];
      [newView viewDidMoveToSuperview];
      [self didAddSubview: newView];
      RELEASE(newView);
    }
  else if ([_sub_views indexOfObjectIdenticalTo: oldView] != NSNotFound)
    {
      if (newView == nil)
	{
	  /*
	   * If there is no new view to add - we just remove the old one.
	   * So a replacement with no newView is a removal.
	   */
	  [oldView removeFromSuperview];
	}
      else
	{
	  NSUInteger index;

	  /*
	   * Ok - the standard case - we remove the newView from wherever it
	   * was (which may have been in this view), locate the position of
	   * the oldView (which may have changed due to the removal of the
	   * newView), remove the oldView, and insert the newView in it's
	   * place.
	   */
	  RETAIN(newView);
	  [newView removeFromSuperview];
	  index = [_sub_views indexOfObjectIdenticalTo: oldView];
	  [oldView removeFromSuperview];
	  [newView _viewWillMoveToWindow: _window];
	  [newView _viewWillMoveToSuperview: self];
	  [newView setNextResponder: self];
          [_sub_views insertObject: newView
                           atIndex: index];
	  _rFlags.has_subviews = 1;
	  [newView resetCursorRects];
	  [newView setNeedsDisplay: YES];
	  [newView _viewDidMoveToWindow];
	  [newView viewDidMoveToSuperview];
	  [self didAddSubview: newView];
	  RELEASE(newView);
	}
    }
}

- (void) setSubviews: (NSArray *)newSubviews
{
  NSEnumerator *en;
  NSView *aView;
  NSMutableArray *uniqNew = [NSMutableArray array];
  
  if (nil == newSubviews)
    {
      [NSException raise: NSInvalidArgumentException
                  format: @"Setting nil as new subviews."];
    }

  // Use a copy as we remove from the subviews array
  en = [[NSArray arrayWithArray: _sub_views] objectEnumerator];
  while ((aView = [en nextObject]))
    {
      if (NO == [newSubviews containsObject: aView])
        {
          [aView removeFromSuperview];
        }
    }
  
  en = [newSubviews objectEnumerator];
  while ((aView = [en nextObject]))
    {
      id supersub = [aView superview];

      if (supersub != nil && supersub != self)
        {
          [NSException raise: NSInvalidArgumentException
                      format: @"Superviews of new subviews must be either nil or receiver."];
        }
      
      if ([uniqNew containsObject: aView])
        {
          [NSException raise: NSInvalidArgumentException
                      format: @"Duplicated new subviews."];
        }
      
      if (NO == [_sub_views containsObject: aView])
        {
          [self addSubview: aView];
        }
      
      [uniqNew addObject: aView];
    }
  
  ASSIGN(_sub_views, uniqNew);

  // The order of the subviews may have changed
  [self setNeedsDisplay: YES];
}

- (void) sortSubviewsUsingFunction: (NSComparisonResult (*)(id ,id ,void*))compare
			   context: (void*)context
{
  [_sub_views sortUsingFunction: compare context: context];
}

/**
 * Notifies the receiver that its superview is being changed to newSuper.
 */
- (void) viewWillMoveToSuperview: (NSView*)newSuper
{
}

/**
 * Notifies the receiver that it will now be a view of newWindow.
 * Note, this method is also used when removing a view from a window
 * (in which case, newWindow is nil) to let all the subviews know
 * that they have also been removed from the window.
 */
- (void) viewWillMoveToWindow: (NSWindow*)newWindow
{
}

- (void) didAddSubview: (NSView *)subview
{}

- (void) viewDidMoveToSuperview
{}

- (void) viewDidMoveToWindow
{}

- (void) willRemoveSubview: (NSView *)subview
{}

static NSSize _computeScale(NSSize fs, NSSize bs)
{
  NSSize scale;

  if (bs.width == 0)
    {
      if (fs.width == 0)
        scale.width = 1;
      else
        scale.width = FLT_MAX;
    }
  else
    {
      scale.width = fs.width / bs.width;
    }
  if (bs.height == 0)
    {
      if (fs.height == 0)
        scale.height = 1;
      else
        scale.height = FLT_MAX;
    }
  else
    {
      scale.height = fs.height / bs.height;
    }

  return scale;
}

- (void) _setFrameAndClearAutoresizingError: (NSRect)frameRect
{
  _frame = frameRect;
  _autoresizingFrameError = NSZeroRect;
}

- (void) setFrame: (NSRect)frameRect
{
  BOOL	changedOrigin = NO;
  BOOL	changedSize = NO;
  NSSize old_size = _frame.size;

  if (frameRect.size.width < 0)
    {
      NSWarnMLog(@"given negative width");
      frameRect.size.width = 0;
    }
  if (frameRect.size.height < 0)
    {
      NSWarnMLog(@"given negative height");
      frameRect.size.height = 0;
    }

  if (NSEqualPoints(_frame.origin, frameRect.origin) == NO)
    {
      changedOrigin = YES;
    }
  if (NSEqualSizes(_frame.size, frameRect.size) == NO)
    {
      changedSize = YES;
    }
  
  if (changedSize == YES || changedOrigin == YES)
    {
      [self _setFrameAndClearAutoresizingError: frameRect];

      if (changedSize == YES)
        {
          if (_is_rotated_or_scaled_from_base == YES)
            {
              NSAffineTransform *matrix;
              NSRect frame = _frame;

              frame.origin = NSMakePoint(0, 0);
              matrix = [_boundsMatrix copy];
              [matrix invert];
              [matrix boundingRectFor: frame result: &_bounds];
              RELEASE(matrix);               
            }
          else
            {
              _bounds.size = frameRect.size;
            }
        }

      if (_coordinates_valid)
        {
          (*invalidateImp)(self, invalidateSel);
        }
      [self resetCursorRects];
      [self resizeSubviewsWithOldSize: old_size];
      if (_post_frame_changes)
        {
          [nc postNotificationName: NSViewFrameDidChangeNotification
              object: self];
        }
    }
}

- (void) setFrameOrigin: (NSPoint)newOrigin
{
  if (NSEqualPoints(_frame.origin, newOrigin) == NO)
    {
      NSRect newFrame = _frame;
      newFrame.origin = newOrigin;

      if (_coordinates_valid)
        {
          (*invalidateImp)(self, invalidateSel);
        }
      [self _setFrameAndClearAutoresizingError: newFrame];
      [self resetCursorRects];
      if (_post_frame_changes)
        {
          [nc postNotificationName: NSViewFrameDidChangeNotification
              object: self];
        }
    }
}

- (void) setFrameSize: (NSSize)newSize
{
  NSRect newFrame = _frame;
  if (newSize.width < 0)
    {
      NSWarnMLog(@"given negative width");
      newSize.width = 0;
    }
  if (newSize.height < 0)
    {
      NSWarnMLog(@"given negative height");
      newSize.height = 0;
    }
  if (NSEqualSizes(_frame.size, newSize) == NO)
    {
      NSSize old_size = _frame.size;

      if (_is_rotated_or_scaled_from_base)
        {
          if (_boundsMatrix == nil)
            {
              CGFloat sx = _bounds.size.width  / _frame.size.width;
              CGFloat sy = _bounds.size.height / _frame.size.height;
              
              newFrame.size = newSize;
	      [self _setFrameAndClearAutoresizingError: newFrame];
              _bounds.size.width  = _frame.size.width  * sx;
              _bounds.size.height = _frame.size.height * sy;
            }
          else
            {
              NSAffineTransform *matrix;
              NSRect frame;
              
              newFrame.size = newSize;
	      [self _setFrameAndClearAutoresizingError: newFrame];

              frame = _frame;
              frame.origin = NSMakePoint(0, 0);
              matrix = [_boundsMatrix copy];
              [matrix invert];
              [matrix boundingRectFor: frame result: &_bounds];
              RELEASE(matrix);
            }
        }
      else
        {
          newFrame.size = _bounds.size = newSize;
	  [self _setFrameAndClearAutoresizingError: newFrame];
        }

      if (_coordinates_valid)
        {
          (*invalidateImp)(self, invalidateSel);
        }
      [self resetCursorRects];
      [self resizeSubviewsWithOldSize: old_size];
      if (_post_frame_changes)
        {
          [nc postNotificationName: NSViewFrameDidChangeNotification
              object: self];
        }
    }
}

- (void) setFrameRotation: (CGFloat)angle
{
  CGFloat oldAngle = [self frameRotation];

  if (oldAngle != angle)
    {
      /* no frame matrix, create one since it is needed for rotation */
      if (_frameMatrix == nil)
        {
          // Map from superview to frame
          _frameMatrix = [NSAffineTransform new];
        }

      [_frameMatrix rotateByDegrees: angle - oldAngle];
      _is_rotated_from_base = _is_rotated_or_scaled_from_base = YES;

      if (_coordinates_valid)
        {
          (*invalidateImp)(self, invalidateSel);
        }
      [self resetCursorRects];
      if (_post_frame_changes)
        {
          [nc postNotificationName: NSViewFrameDidChangeNotification
              object: self];
        }
    }
}

- (BOOL) isRotatedFromBase
{
  if (_is_rotated_from_base)
    {
      return YES;
    }
  else if (_super_view)
    {
      return [_super_view isRotatedFromBase];
    }
  else
    {
      return NO;
    }
}

- (BOOL) isRotatedOrScaledFromBase
{
  if (_is_rotated_or_scaled_from_base)
    {
      return YES;
    }
  else if (_super_view)
    {
      return [_super_view isRotatedOrScaledFromBase];
    }
  else
    {
      return NO;
    }
}

- (void) setBounds: (NSRect)aRect
{
  NSDebugLLog(@"NSView", @"setBounds %@", NSStringFromRect(aRect));
  if (aRect.size.width < 0)
    {
      NSWarnMLog(@"given negative width");
      aRect.size.width = 0;
    }
  if (aRect.size.height < 0)
    {
      NSWarnMLog(@"given negative height");
      aRect.size.height = 0;
    }

  if (_is_rotated_from_base || (NSEqualRects(_bounds, aRect) == NO))
    {
      NSAffineTransform *matrix;
      NSPoint oldOrigin;
      NSSize scale;
  
      if (_boundsMatrix == nil)
        {
          _boundsMatrix = [NSAffineTransform new]; 
        }

      // Adjust scale
      scale = _computeScale(_frame.size, aRect.size);
      if (scale.width != 1 || scale.height != 1)
        {
          _is_rotated_or_scaled_from_base = YES;
        }
      [_boundsMatrix scaleTo: scale.width : scale.height];
        {
          matrix = [_boundsMatrix copy];
          [matrix invert];
          oldOrigin = [matrix transformPoint: NSMakePoint(0, 0)];
          RELEASE(matrix);
        }
      [_boundsMatrix translateXBy: oldOrigin.x - aRect.origin.x 
                     yBy: oldOrigin.y - aRect.origin.y];      
      if (!_is_rotated_from_base)
        {
          // Adjust bounds
          _bounds = aRect;
        }
      else
        {
          // Adjust bounds
          NSRect frame = _frame;

          frame.origin = NSMakePoint(0, 0);
          matrix = [_boundsMatrix copy];
          [matrix invert];
          [matrix boundingRectFor: frame result: &_bounds];
          RELEASE(matrix);
       }

      if (_coordinates_valid)
        {
          (*invalidateImp)(self, invalidateSel);
        }
      [self resetCursorRects];
      if (_post_bounds_changes)
        {
          [nc postNotificationName: NSViewBoundsDidChangeNotification
              object: self];
        }
    }
}

- (void) setBoundsOrigin: (NSPoint)newOrigin
{
  NSPoint oldOrigin;
  
  if (_boundsMatrix == nil)
    {
      oldOrigin = NSMakePoint(NSMinX(_bounds), NSMinY(_bounds));
    }
  else
    {
      NSAffineTransform *matrix = [_boundsMatrix copy];
    
      [matrix invert];
      oldOrigin = [matrix transformPoint: NSMakePoint(0, 0)];
      RELEASE(matrix);
    }
  [self translateOriginToPoint: NSMakePoint(oldOrigin.x - newOrigin.x, 
                                            oldOrigin.y - newOrigin.y)];
}

- (void) setBoundsSize: (NSSize)newSize
{
  NSSize scale;

  NSDebugLLog(@"NSView", @"%@ setBoundsSize: %@", self, 
              NSStringFromSize(newSize));

  if (newSize.width < 0)
    {
      NSWarnMLog(@"given negative width");
      newSize.width = 0;
    }
  if (newSize.height < 0)
    {
      NSWarnMLog(@"given negative height");
      newSize.height = 0;
    }

  scale = _computeScale(_frame.size, newSize);
  if (scale.width != 1 || scale.height != 1)
    {
      _is_rotated_or_scaled_from_base = YES;
    }
  
  if (_boundsMatrix == nil)
    {
      _boundsMatrix = [NSAffineTransform new]; 
    }
  [_boundsMatrix scaleTo: scale.width : scale.height];
  if (!_is_rotated_from_base)
    {
      scale = _computeScale(_bounds.size, newSize);
      _bounds.origin.x = _bounds.origin.x / scale.width;
      _bounds.origin.y = _bounds.origin.y / scale.height;
      _bounds.size = newSize;
    }
  else
    {
      NSAffineTransform *matrix;
      NSRect frame = _frame;
      
      frame.origin = NSMakePoint(0, 0);
      matrix = [_boundsMatrix copy];
      [matrix invert];
      [matrix boundingRectFor: frame result: &_bounds];
      RELEASE(matrix);               
    }

  if (_coordinates_valid)
    {
      (*invalidateImp)(self, invalidateSel);
    }
  [self resetCursorRects];
  if (_post_bounds_changes)
    {
      [nc postNotificationName: NSViewBoundsDidChangeNotification
                        object: self];
    }
}

- (void) setBoundsRotation: (CGFloat)angle
{
  [self rotateByAngle: angle - [self boundsRotation]];
}

- (void) translateOriginToPoint: (NSPoint)point
{
  NSDebugLLog(@"NSView", @"%@ translateOriginToPoint: %@", self, 
              NSStringFromPoint(point));
  if (NSEqualPoints(NSZeroPoint, point) == NO)
    {
      if (_boundsMatrix == nil)
        {
          _boundsMatrix = [NSAffineTransform new];
        }
      [_boundsMatrix translateXBy: point.x
                     yBy: point.y];
      // Adjust bounds
      _bounds.origin.x -= point.x;
      _bounds.origin.y -= point.y;

      if (_coordinates_valid)
        {
          (*invalidateImp)(self, invalidateSel);
        }
      [self resetCursorRects];
      if (_post_bounds_changes)
        {
          [nc postNotificationName: NSViewBoundsDidChangeNotification
              object: self];
        }
    }
}

- (void) scaleUnitSquareToSize: (NSSize)newSize
{
  if (newSize.width != 1.0 || newSize.height != 1.0)
    {
      if (newSize.width < 0)
        {
          NSWarnMLog(@"given negative width");
          newSize.width = 0;
        }
      if (newSize.height < 0)
        {
          NSWarnMLog(@"given negative height");
          newSize.height = 0;
        }

      if (_boundsMatrix == nil)
        {
          _boundsMatrix = [NSAffineTransform new]; 
        }
      [_boundsMatrix scaleXBy: newSize.width yBy: newSize.height];
      // Adjust bounds
      _bounds.origin.x = _bounds.origin.x / newSize.width;
      _bounds.origin.y = _bounds.origin.y / newSize.height;
      _bounds.size.width  = _bounds.size.width  / newSize.width;
      _bounds.size.height = _bounds.size.height / newSize.height;

      _is_rotated_or_scaled_from_base = YES;

      if (_coordinates_valid)
        {
          (*invalidateImp)(self, invalidateSel);
        }
      [self resetCursorRects];
      if (_post_bounds_changes)
        {
          [nc postNotificationName: NSViewBoundsDidChangeNotification
              object: self];
        }
    }
}

- (void) rotateByAngle: (CGFloat)angle
{
  if (angle != 0.0)
    {
      NSAffineTransform *matrix;
      NSRect frame = _frame;
      
      frame.origin = NSMakePoint(0, 0);
      if (_boundsMatrix == nil)
        {
          _boundsMatrix = [NSAffineTransform new]; 
        }
      [_boundsMatrix rotateByDegrees: angle];
      // Adjust bounds
      matrix = [_boundsMatrix copy];
      [matrix invert];
      [matrix boundingRectFor: frame result: &_bounds];
      RELEASE(matrix);

      _is_rotated_from_base = _is_rotated_or_scaled_from_base = YES;

      if (_coordinates_valid)
        {
          (*invalidateImp)(self, invalidateSel);
        }
      [self resetCursorRects];
      if (_post_bounds_changes)
        {
          [nc postNotificationName: NSViewBoundsDidChangeNotification
              object: self];
        }
    }
}


- (CGFloat) alphaValue
{
  return _alphaValue;
}

- (void)setAlphaValue: (CGFloat)alpha
{
  _alphaValue = alpha;
}

- (CGFloat) frameCenterRotation
{
  // FIXME this is dummy, we don't have layers yet
  return 0.0;
}

- (void) setFrameCenterRotation:(CGFloat)rot;
{
  // FIXME this is dummy, we don't have layers yet
  // we probably need a Matrix akin frame rotation.
}


- (NSRect) centerScanRect: (NSRect)aRect
{
  NSAffineTransform	*matrix;
  CGFloat x_org;
  CGFloat y_org;

  /*
   *	Hmm - we assume that the windows coordinate system is centered on the
   *	pixels of the screen - this may not be correct of course.
   *	Plus - this is all pretty meaningless is we are not in a window!
   */
  matrix = [self _matrixToWindow];
  aRect.origin = [matrix transformPoint: aRect.origin];
  aRect.size = [matrix transformSize: aRect.size];
  if (aRect.size.height < 0.0)
    {
      aRect.size.height = -aRect.size.height;
    }

  x_org = aRect.origin.x;
  y_org = aRect.origin.y;
  aRect.origin.x = GSRoundTowardsInfinity(aRect.origin.x);
  aRect.origin.y = [self isFlipped] ? GSRoundTowardsNegativeInfinity(aRect.origin.y) : GSRoundTowardsInfinity(aRect.origin.y);
  aRect.size.width = GSRoundTowardsInfinity(aRect.size.width + (x_org - aRect.origin.x) / 2.0);
  aRect.size.height = GSRoundTowardsInfinity(aRect.size.height + (y_org - aRect.origin.y) / 2.0);

  matrix = [self _matrixFromWindow];
  aRect.origin = [matrix transformPoint: aRect.origin];
  aRect.size = [matrix transformSize: aRect.size];
  if (aRect.size.height < 0.0)
    {
      aRect.size.height = -aRect.size.height;
    }

  return aRect;
}

- (NSPoint) convertPoint: (NSPoint)aPoint fromView: (NSView*)aView
{
  NSPoint inBase;

  if (aView == self)
    {
      return aPoint;
    }

  if (aView != nil)
    {
      NSAssert(_window == [aView window], NSInvalidArgumentException);      
      inBase = [[aView _matrixToWindow] transformPoint: aPoint];    
    }
  else
    {
      inBase = aPoint;
    }

  return [[self _matrixFromWindow] transformPoint: inBase];
}

- (NSPoint) convertPoint: (NSPoint)aPoint toView: (NSView*)aView
{
  NSPoint inBase;

  if (aView == self)
    return aPoint;

  inBase = [[self _matrixToWindow] transformPoint: aPoint];

  if (aView != nil)
    {
      NSAssert(_window == [aView window], NSInvalidArgumentException);      
      return [[aView _matrixFromWindow] transformPoint: inBase];
    }
  else
    {
      return inBase;
    }
}


/* Helper for -convertRect:fromView: and -convertRect:toView:. */
static NSRect
convert_rect_using_matrices(NSRect aRect, NSAffineTransform *matrix1,
					  NSAffineTransform *matrix2)
{
  NSRect r;
  NSPoint p[4], min, max;
  int i;

  for (i = 0; i < 4; i++)
    p[i] = aRect.origin;
  p[1].x += aRect.size.width;
  p[2].y += aRect.size.height;
  p[3].x += aRect.size.width;
  p[3].y += aRect.size.height;

  for (i = 0; i < 4; i++)
    p[i] = [matrix1 transformPoint: p[i]];

  min = max = p[0] = [matrix2 transformPoint: p[0]];
  for (i = 1; i < 4; i++)
    {
      p[i] = [matrix2 transformPoint: p[i]];
      min.x = MIN(min.x, p[i].x);
      min.y = MIN(min.y, p[i].y);
      max.x = MAX(max.x, p[i].x);
      max.y = MAX(max.y, p[i].y);
    }

  r.origin = min;
  r.size.width = max.x - min.x;
  r.size.height = max.y - min.y;

  return r;
}

/**
 * Converts aRect from the coordinate system of aView to the coordinate
 * system of the receiver, ie. returns the bounding rectangle in the
 * receiver of aRect in aView.
 * <br />
 * aView and the receiver must be in the same window. If aView is nil,
 * converts from the receiver's window's coordinate system.
 */
- (NSRect) convertRect: (NSRect)aRect fromView: (NSView*)aView
{
  NSAffineTransform *matrix1, *matrix2;

  if (aView == self || _window == nil || (aView != nil && [aView window] == nil))
    {
      return aRect;
    }

  if (aView != nil)
    {
      NSAssert(_window == [aView window], NSInvalidArgumentException); 
      matrix1 = [aView _matrixToWindow];      
    }
  else
    {
      matrix1 = [NSAffineTransform transform];
    }

  matrix2 = [self _matrixFromWindow];

  return convert_rect_using_matrices(aRect, matrix1, matrix2);
}

/**
 * Converts aRect from the coordinate system of the receiver to the
 * coordinate system of aView, ie. returns the bounding rectangle in
 * aView of aRect in the receiver.
 * <br />
 * aView and the receiver must be in the same window. If aView is nil,
 * converts to the receiver's window's coordinate system.
 */
- (NSRect) convertRect: (NSRect)aRect toView: (NSView*)aView
{
  NSAffineTransform *matrix1, *matrix2;

  if (aView == self || _window == nil || (aView != nil && [aView window] == nil))
    {
      return aRect;
    }

  matrix1 = [self _matrixToWindow];

  if (aView != nil)
    {
      NSAssert(_window == [aView window], NSInvalidArgumentException);
      matrix2 = [aView _matrixFromWindow];
    }
  else
    {
      matrix2 = [NSAffineTransform transform];
    }

  return convert_rect_using_matrices(aRect, matrix1, matrix2);
}

- (NSSize) convertSize: (NSSize)aSize fromView: (NSView*)aView
{
  NSSize inBase;
  NSSize inSelf;

  if (aView)
    {
      NSAssert(_window == [aView window], NSInvalidArgumentException);      
      inBase = [[aView _matrixToWindow] transformSize: aSize];
      if (inBase.height < 0.0)
	{
	  inBase.height = -inBase.height;
	} 
    }
  else
    {
      inBase = aSize;
    }

  inSelf = [[self _matrixFromWindow] transformSize: inBase];
  if (inSelf.height < 0.0)
    {
      inSelf.height = -inSelf.height;
    }
  return inSelf;
}

- (NSSize) convertSize: (NSSize)aSize toView: (NSView*)aView
{
  NSSize inBase = [[self _matrixToWindow] transformSize: aSize];
  if (inBase.height < 0.0)
    {
      inBase.height = -inBase.height;
    } 

  if (aView)
    {
      NSSize inOther;
      NSAssert(_window == [aView window], NSInvalidArgumentException);      
      inOther = [[aView _matrixFromWindow] transformSize: inBase];
      if (inOther.height < 0.0)
	{
	  inOther.height = -inOther.height;
	}
      return inOther;
    }
  else
    {
      return inBase;
    }
}

- (NSPoint) convertPointFromBase: (NSPoint)aPoint
{
  return [self convertPoint: aPoint fromView: nil];
}

- (NSPoint) convertPointToBase: (NSPoint)aPoint
{
  return [self convertPoint: aPoint toView: nil];
}

- (NSRect) convertRectFromBase: (NSRect)aRect
{
  return [self convertRect: aRect fromView: nil];
}

- (NSRect) convertRectToBase: (NSRect)aRect
{
  return [self convertRect: aRect toView: nil];
}

- (NSSize) convertSizeFromBase: (NSSize)aSize
{
  return [self convertSize: aSize fromView: nil];
}

- (NSSize) convertSizeToBase: (NSSize)aSize
{
  return [self convertSize: aSize toView: nil];
}

/** 
 * Sets whether the receiver should post NSViewFrameDidChangeNotification 
 * when its frame changed. 
 */
- (void) setPostsFrameChangedNotifications: (BOOL)flag
{
  _post_frame_changes = flag;
}

/** 
 * Sets whether the receiver should post NSViewBoundsDidChangeNotification 
 * when its bound changed.
 */
- (void) setPostsBoundsChangedNotifications: (BOOL)flag
{
  _post_bounds_changes = flag;
}

/*
 * resize subviews only if we are supposed to and we have never been rotated
 */
- (void) resizeSubviewsWithOldSize: (NSSize)oldSize
{
  if (_rFlags.has_subviews)
    {
      id e, o;

      if (_autoresizes_subviews == NO || _is_rotated_from_base == YES)
          return;

      e = [_sub_views objectEnumerator];
      o = [e nextObject];
      while (o)
        {
          [o resizeWithOldSuperviewSize: oldSize];
          o = [e nextObject];
        }
    }
}

static void autoresize(CGFloat oldContainerSize,
		       CGFloat newContainerSize,
		       CGFloat *contentPositionInOut,
		       CGFloat *contentSizeInOut,
		       BOOL minMarginFlexible,
		       BOOL sizeFlexible,
		       BOOL maxMarginFlexible)
{
  const CGFloat change = newContainerSize - oldContainerSize;
  const CGFloat oldContentSize = *contentSizeInOut;
  const CGFloat oldContentPosition = *contentPositionInOut;
  CGFloat flexibleSpace = 0.0;

  // See how much flexible space we have to distrube the change over

  if (sizeFlexible)
    flexibleSpace += oldContentSize;

  if (minMarginFlexible)
    flexibleSpace += oldContentPosition;

  if (maxMarginFlexible)
    flexibleSpace += oldContainerSize - oldContentPosition - oldContentSize;


  if (flexibleSpace <= 0.0)
    {
      /**
       * In this code path there is no flexible space so we divide 
       * the available space equally among the flexible portions of the view
       */
      int subdivisions = (sizeFlexible ? 1 : 0) +
	(minMarginFlexible ? 1 : 0) +
	(maxMarginFlexible ? 1 : 0);

      if (subdivisions > 0)
	{
	  const CGFloat changePerOption = change / subdivisions;
	  
	  if (sizeFlexible)
	    { 
	      *contentSizeInOut += changePerOption;
	    }
	  if (minMarginFlexible)
	    {
	      *contentPositionInOut += changePerOption;
	    }
	}
    }
  else
    {
      /**
       * In this code path we distribute the change proportionately
       * over the flexible spaces
       */
      const CGFloat changePerPoint = change / flexibleSpace;

      if (sizeFlexible)
	{ 
          *contentSizeInOut += changePerPoint * oldContentSize;
	}
      if (minMarginFlexible)
	{
	  *contentPositionInOut += changePerPoint * oldContentPosition;
	}
    }
}

- (void) resizeWithOldSuperviewSize: (NSSize)oldSize
{
  NSSize superViewFrameSize;
  NSRect newFrame = _frame;
  NSRect newFrameRounded;

  if (_autoresizingMask == NSViewNotSizable)
    return;

  if (!NSEqualRects(NSZeroRect, _autoresizingFrameError))
    {
      newFrame.origin.x -= _autoresizingFrameError.origin.x;
      newFrame.origin.y -= _autoresizingFrameError.origin.y;
      newFrame.size.width -= _autoresizingFrameError.size.width;
      newFrame.size.height -= _autoresizingFrameError.size.height;
    }

  superViewFrameSize = NSMakeSize(0,0);
  if (_super_view)
    superViewFrameSize = [_super_view frame].size;

  autoresize(oldSize.width,
	     superViewFrameSize.width,
	     &newFrame.origin.x,
	     &newFrame.size.width,
	     (_autoresizingMask & NSViewMinXMargin),	     
	     (_autoresizingMask & NSViewWidthSizable),
	     (_autoresizingMask & NSViewMaxXMargin));

  {
    const BOOL flipped = (_super_view && [_super_view isFlipped]);

    autoresize(oldSize.height,
	       superViewFrameSize.height,
	       &newFrame.origin.y,
	       &newFrame.size.height,
	       flipped ? (_autoresizingMask & NSViewMaxYMargin) : (_autoresizingMask & NSViewMinYMargin),
	       (_autoresizingMask & NSViewHeightSizable),
	       flipped ? (_autoresizingMask & NSViewMinYMargin) : (_autoresizingMask & NSViewMaxYMargin));
  }

  newFrameRounded = newFrame;

  /**
   * Perform rounding to pixel-align the frame if we are not rotated
   */
  if (![self isRotatedFromBase] && [self superview] != nil)
    {
      newFrameRounded = [[self superview] centerScanRect: newFrameRounded];
    }

  [self setFrame: newFrameRounded];

  _autoresizingFrameError.origin.x = (newFrameRounded.origin.x - newFrame.origin.x);
  _autoresizingFrameError.origin.y = (newFrameRounded.origin.y - newFrame.origin.y);
  _autoresizingFrameError.size.width = (newFrameRounded.size.width - newFrame.size.width);
  _autoresizingFrameError.size.height = (newFrameRounded.size.height - newFrame.size.height);
}

- (void) _lockFocusInContext: (NSGraphicsContext *)ctxt inRect: (NSRect)rect
{
  NSRect wrect;
  NSInteger window_gstate = 0;

  if (viewIsPrinting == nil)
    {
      NSAssert(_window != nil, NSInternalInconsistencyException);
      /* Check for deferred window */
      if ((window_gstate = [_window gState]) == 0)
        {
          return;
        }
    }

  if (ctxt == nil)
    {
      if (viewIsPrinting != nil)
        {
          NSPrintOperation *printOp = [NSPrintOperation currentOperation];

          ctxt = [printOp context];
        }
      else
        {
          ctxt = [_window graphicsContext];
        }
    }

  // Set current context
  [NSGraphicsContext saveGraphicsState];
  [NSGraphicsContext setCurrentContext: ctxt];

  [ctxt lockFocusView: self inRect: rect];
  wrect = [self convertRect: rect toView: nil];
  NSDebugLLog(@"NSView", @"-lockFocusInRect: %@\n"
	      @"\t for view %@ in window %p (%@)\n"
	      @"\t frame %@, flip %d",
	      NSStringFromRect(wrect),
	      self, _window, NSStringFromRect([_window frame]),
	      NSStringFromRect(_frame), [self isFlipped]);
  if (viewIsPrinting == nil)
    {
      [_window->_rectsBeingDrawn addObject: [NSValue valueWithRect: wrect]];
    }

  /* Make sure we don't modify superview's gstate */
  DPSgsave(ctxt);

  if (viewIsPrinting != nil)
    {
      if (viewIsPrinting == self)
        {
          /* Make sure coordinates are valid, then fake that we don't have
             a superview so we get printed correctly */
          [self _matrixToWindow];
          [_matrixToWindow makeIdentityMatrix];
        }
      else
        {
          [[self _matrixToWindow] concat];
        }

      /* Allow subclases to make other modifications */
      [self setUpGState];
    }
  else
    {
      if (_gstate && !_renew_gstate)
        {
          DPSsetgstate(ctxt, _gstate);
          DPSgsave(ctxt);
        }
      else
        {
          // This only works, when the context comes from the window
          DPSsetgstate(ctxt, window_gstate);
          DPSgsave(ctxt);
          [[self _matrixToWindow] concat];
          
          /* Allow subclases to make other modifications */
          [self setUpGState];
          _renew_gstate = NO;
          if (_allocate_gstate)
            {
              if (_gstate)
                {
                  GSReplaceGState(ctxt, _gstate);
                }
              else
                {
                  _gstate = GSDefineGState(ctxt);
                }
              /* Balance the previous gsave and install our own gstate */
              DPSgrestore(ctxt);
              DPSsetgstate(ctxt, _gstate);
              DPSgsave(ctxt);
            }
        }
    }

  if ([self wantsDefaultClipping])
    {
      /* 
       * Clip to the visible rectangle - which will never be greater
       * than the bounds of the view. This prevents drawing outside
       * our bounds.
       */
      // Normally the second test is not needed, it can differ only
      // when the view is loaded from a NIB file.
      if (_is_rotated_from_base && (_boundsMatrix != nil))
        {
          // When the view is rotated, we clip to the frame.
          NSAffineTransform *matrix;
          NSRect frame = _frame;
          NSBezierPath *bp;

          frame.origin = NSMakePoint(0, 0);
          bp = [NSBezierPath bezierPathWithRect: frame];
          
          matrix = [_boundsMatrix copy];
          [matrix invert];
          [bp transformUsingAffineTransform: matrix];
          [bp addClip];
          RELEASE(matrix);
        }
      else
        { 
          // FIXME: Should we use _bounds or visibleRect here?
          DPSrectclip(ctxt, NSMinX(rect), NSMinY(rect),
                      NSWidth(rect), NSHeight(rect));
        }
    }

  /* Tell backends that images are drawn upside down. Obsolete?
     This is needed when a backend is able to handle full image transformation. */
  GSWSetViewIsFlipped(ctxt, [self isFlipped]);
}

- (void) _setIgnoresBacking: (BOOL) flag
{
  _rFlags.ignores_backing = flag;
}

- (BOOL) _ignoresBacking
{
  return _rFlags.ignores_backing;
}

- (void) unlockFocusNeedsFlush: (BOOL)flush
{
  NSGraphicsContext *ctxt = GSCurrentContext();

  NSDebugLLog(@"NSView_details", @"-unlockFocusNeedsFlush: %i for view %@\n",
	      flush, self);

  if (viewIsPrinting == nil)
    {
      NSAssert(_window != nil, NSInternalInconsistencyException);
      /* Check for deferred window */
      if ([_window gState] == 0)
        return;

      /* Restore our original gstate */
      DPSgrestore(ctxt);
    }

  /* Restore state of nesting lockFocus */
  DPSgrestore(ctxt);
  if (!_allocate_gstate)
    _gstate = 0;

  if (viewIsPrinting == nil)
    {
      NSRect        rect;
      if (flush && !_rFlags.ignores_backing)
        {
          rect = [[_window->_rectsBeingDrawn lastObject] rectValue];
          _window->_rectNeedingFlush =
              NSUnionRect(_window->_rectNeedingFlush, rect);
          _window->_f.needs_flush = YES;
        }
      [_window->_rectsBeingDrawn removeLastObject];
    }
  [ctxt unlockFocusView: self needsFlush: YES ];
  [NSGraphicsContext restoreGraphicsState];
}

/**
  <p> Tell the view to maintain a private gstate object which
  encapsulates all the information about drawing, such as coordinate
  transforms, line widths, etc. If you do not invoke this method, a
  gstate object is constructed each time the view is lockFocused.
  Allocating a private gstate may improve the performance of views
  that are focused a lot and have a lot of customized drawing
  parameters.  </p> 

  <p> View subclasses should override the
  setUpGstate method to set these custom parameters.
  </p> 
*/
- (void) allocateGState
{
  _allocate_gstate = YES;
  _renew_gstate = YES;
}

/**
  Frees the gstate object, if there is one. 
*/
- (void) releaseGState
{
  if (_allocate_gstate && _gstate &&
      _window && ([_window graphicsContext] != nil))
    {
      GSUndefineGState([_window graphicsContext], _gstate);
    }
  _gstate = 0;
  _allocate_gstate = NO;
}

/**
  Returns an identifier that represents the view's gstate object,
  which is used to encapsulate drawing information about the view.
  Most of the time a gstate object is created from scratch when the
  view is focused, so if the view is not currently focused or
  allocateGState has not been called, then this method will return 0.
  FIXME: The above is what the OpenStep and Cocoa specification say, but 
  gState is 0 unless allocateGState has been called. 
*/
- (NSInteger) gState
{
  if (_allocate_gstate && (!_gstate || _renew_gstate))
    {
      // Set the gstate by locking and unlocking focus.
      [self lockFocus];
      [self unlockFocusNeedsFlush: NO];
    }

  return _gstate;
}

/** 
  Invalidates the view's gstate object so it will be set up again
  using setUpGState the next time the view is focused.  */
- (void) renewGState
{
  _renew_gstate = YES;
  /* Note that the next time we lock focus, we'll realloc a gstate (if
     _allocate_gstate). This seems to make sense, and also allows us
     to call this method each time we invalidate the coordinates */
}

/* Overridden by subclasses to setup custom gstate */
- (void) setUpGState
{
}

- (void) lockFocusInRect: (NSRect)rect
{
  [self _lockFocusInContext: nil inRect: rect];
}

- (void) lockFocus
{
  [self lockFocusInRect: [self visibleRect]];
}

- (void) unlockFocus
{
  [self unlockFocusNeedsFlush: YES];
}

- (BOOL) lockFocusIfCanDraw
{
  return [self lockFocusIfCanDrawInContext: nil];
}

- (BOOL) lockFocusIfCanDrawInContext: (NSGraphicsContext *)context
{
  if ([self canDraw])
    {
      [self _lockFocusInContext: context inRect: [self visibleRect]];
      return YES;
    }
  else
    {
      return NO;
    }
}

- (BOOL) canDraw
{
  if (((viewIsPrinting != nil) && [self isDescendantOf: viewIsPrinting]) || 
      ((_window != nil) && ([_window windowNumber] != 0) && 
       ![self isHiddenOrHasHiddenAncestor]))
    {
      return YES;
    }
  else
    {
      return NO;
    }
}

/*
 * The following display* methods work based on these invariants:
 * - When a view is marked as needing display, all views above it 
 *   in the hierarchy are marked as well.
 * - When a view has an invalid rectangle, all views above it up 
 *   to the next opaque view also include this invalid rectangle.
 *
 * After drawing an area in a view give, subviews a chance to draw 
 * there too.
 * When drawing a non-opaque subview we need to make sure any area
 * we draw in has been drawn by the opaque superview as well.
 *
 * When drawing the invalid area of a view, we need to make sure 
 * that invalid areas in opaque subviews get drawn as well. These 
 * areas will not be included in the invalid area of the view.
 *
 * IfNeeded means we only draw if the view is marked as needing display
 * and will only draw in the _invalidRect of this view and that of all 
 * the opaque subviews. For non-opaque subviews we need to draw where 
 * ever a superview has already drawn.
 * 
 * InRect means we will only draw in this rectangle. If non is given the
 * visibleRect gets used.
 *
 * IgnoringOpacity means we start drawing at the current view. Otherwise 
 * we go up to the next opaque view.
 *
 */

- (void) display
{
  [self displayRect: [self visibleRect]];
}

- (void) displayIfNeeded
{
  if (_rFlags.needs_display == YES)
    {
      [self displayIfNeededInRect: [self visibleRect]];
    }
}

- (void) displayIfNeededIgnoringOpacity
{
  if (_rFlags.needs_display == YES)
    {
      [self displayIfNeededInRectIgnoringOpacity: [self visibleRect]];
    }
}

- (void) displayIfNeededInRect: (NSRect)aRect
{
  if (_rFlags.needs_display == YES)
    {
      if ([self isOpaque] == YES)
        {
          [self displayIfNeededInRectIgnoringOpacity: aRect];
        }
      else
        {
          NSView *firstOpaque = [self opaqueAncestor];

          aRect = [firstOpaque convertRect: aRect fromView: self];
          [firstOpaque displayIfNeededInRectIgnoringOpacity: aRect];
        }
    }
}

- (void) displayIfNeededInRectIgnoringOpacity: (NSRect)aRect
{
  if (_rFlags.needs_display == YES)
    {
      NSRect rect;
        
      /*
       * Restrict the drawing of self onto the invalid rectangle.
       */
      rect = NSIntersectionRect(aRect, _invalidRect);
      [self displayRectIgnoringOpacity: rect];

      /*
       * If we still need display after displaying the invalid rectangle,
       * this means that some subviews still need to display.
       * For opaque subviews their invalid rectangle may even overlap the
       * original aRect.
       * Display any subview that need display.
       */ 
      if (_rFlags.needs_display == YES)
        {
          NSEnumerator *enumerator = [_sub_views objectEnumerator];
          NSView *subview;
          BOOL subviewNeedsDisplay = NO;
         
          while ((subview = [enumerator nextObject]) != nil)
            {
              if (subview->_rFlags.needs_display)
                {
                  NSRect subviewFrame = [subview _frameExtend];
                  NSRect isect;
              
                  isect = NSIntersectionRect(aRect, subviewFrame);
                  if (NSIsEmptyRect(isect) == NO)
                    {
                      isect = [subview convertRect: isect fromView: self];
                      [subview displayIfNeededInRectIgnoringOpacity: isect];
                    }

                  if (subview->_rFlags.needs_display)
                    {
                      subviewNeedsDisplay = YES;
                    }
                }
            }
          /*
           * Make sure our needs_display flag matches that of the subviews.
           * Only set to NO when there is no _invalidRect.
           */
          if (NSIsEmptyRect(_invalidRect))
            {
              _rFlags.needs_display = subviewNeedsDisplay;
            }
        }
    }
}

/**
 * Causes the area of the view specified by aRect to be displayed.
 * This is done by moving up the view hierarchy until an opaque view
 * is found, then asking that view to update the appropriate area.
 */
- (void) displayRect: (NSRect)aRect
{
  if ([self isOpaque] == YES)
    {
      [self displayRectIgnoringOpacity: aRect];
    }
  else
    {
      NSView *firstOpaque = [self opaqueAncestor];

      aRect = [firstOpaque convertRect: aRect fromView: self];
      [firstOpaque displayRectIgnoringOpacity: aRect];
    }
}

- (void) displayRectIgnoringOpacity: (NSRect)aRect
{
  [self displayRectIgnoringOpacity: aRect inContext: nil];
}

- (void) displayRectIgnoringOpacity: (NSRect)aRect 
                          inContext: (NSGraphicsContext *)context
{
  NSGraphicsContext *wContext;
  BOOL flush = NO;
  BOOL subviewNeedsDisplay = NO;

  if (![self canDraw])
    {
      return;
    }

  wContext = [_window graphicsContext];
  if (context == nil)
    {
      context = wContext;
    }

  if (context == wContext)
    {
      NSRect neededRect;
      NSRect visibleRect = [self visibleRect];

      flush = YES;
      [_window disableFlushWindow];
      aRect = NSIntersectionRect(aRect, visibleRect);
      neededRect = NSIntersectionRect(_invalidRect, visibleRect);
  
      /*
       * If the rect we are going to display contains the _invalidRect
       * then we can empty _invalidRect. Do this before the drawing,
       * as drawRect: may change this value.
       * FIXME: If the drawn rectangle cuts of a complete part of the
       * _invalidRect, we should try to reduce this.
       */
      if (NSEqualRects(aRect, NSUnionRect(neededRect, aRect)) == YES)
        {
          _invalidRect = NSZeroRect;
          _rFlags.needs_display = NO;
        }
    }
  
  if (NSIsEmptyRect(aRect) == NO)
    {
      /*
       * Now we draw this view.
       */
      [self _lockFocusInContext: context inRect: aRect];
      [self drawRect: aRect];
      [self unlockFocusNeedsFlush: flush];
    }

  /*
   * Even when aRect is empty we need to loop over the subviews to see, 
   * if there is anything left to draw.
   */
  if (_rFlags.has_subviews == YES)
    {
      NSUInteger count = [_sub_views count];

      if (count > 0)
        {
          NSView *array[count];
          NSUInteger i;
          
          [_sub_views getObjects: array];

          for (i = 0; i < count; ++i)
            {
              NSView *subview = array[i];
              NSRect subviewFrame = [subview _frameExtend];
              NSRect isect;
              
              /*
               * Having drawn ourself into the rect, we must make sure that
               * subviews overlapping the area are redrawn.
               */
              isect = NSIntersectionRect(aRect, subviewFrame);
              if (NSIsEmptyRect(isect) == NO)
                {
                  isect = [subview convertRect: isect fromView: self];
                  [subview displayRectIgnoringOpacity: isect
                                            inContext: context];
                }
              /*
               * Is there still something to draw in the subview?
               * This keeps the invariant that views further up are marked
               * for redraw when ever a view further down needs to redraw.
               */
              if (subview->_rFlags.needs_display == YES)
                {
                  subviewNeedsDisplay = YES;
                }
            }
        }
    }

  if (context == wContext)
    {
      if (subviewNeedsDisplay)
        {
          /*
           * If not all subviews have been fully displayed, we cannot turn off
           * the 'needs_display' flag. This is to keep the invariant that when 
           * a view is marked as needing to display, all its ancestors will be 
           * marked too.
           */
          _rFlags.needs_display = YES;
        }
      [_window enableFlushWindow];
      [_window flushWindowIfNeeded];
    }
}

/**
  This method is invoked to handle drawing inside the view.  The
  default NSView's implementation does nothing; subclasses might
  override it to draw something inside the view.  Since NSView's
  implementation is guaranteed to be empty, you should not call
  super's implementation when you override it in subclasses.
  drawRect: is invoked when the focus has already been locked on the
  view; you can use arbitrary postscript functions in drawRect: to
  draw inside your view; the coordinate system in which you draw is
  the view's own coordinate system (this means for example that you
  should refer to the rectangle covered by the view using its bounds,
  and not its frame).  The argument of drawRect: is the rectangle
  which needs to be redrawn.  In a lossy implementation, you can
  ignore the argument and redraw the whole view; if you are aiming at
  performance, you may want to redraw only what is inside the
  rectangle which needs to be redrawn; this usually improves drawing
  performance considerably.  */
- (void) drawRect: (NSRect)rect
{}

- (NSRect) visibleRect
{
  if ([self isHiddenOrHasHiddenAncestor])
    {
      return NSZeroRect;
    }

  if (_coordinates_valid == NO)
    {
      [self _rebuildCoordinates];
    }
  return _visibleRect;
}

- (BOOL) wantsDefaultClipping
{
  return YES;
}

- (BOOL) needsToDrawRect: (NSRect)aRect
{
  const NSRect *rects;
  NSInteger i, count;

  [self getRectsBeingDrawn: &rects count: &count];
  for (i = 0; i < count; i++)
    {
      if (NSIntersectsRect(aRect, rects[i]))
	return YES;
    }
  return NO;
}

- (void) getRectsBeingDrawn: (const NSRect **)rects count: (NSInteger *)count
{
  // FIXME
  static NSRect rect;

  rect = [[_window->_rectsBeingDrawn lastObject] rectValue];
  rect = [self convertRect: rect fromView: nil];

  if (rects != NULL)
    {
      *rects = &rect;
    }

  if (count != NULL)
    {
      *count = 1;
    }
}

- (NSBitmapImageRep *) bitmapImageRepForCachingDisplayInRect: (NSRect)rect
{
  NSBitmapImageRep *bitmap;

  [self lockFocus];
  bitmap = [[NSBitmapImageRep alloc] initWithFocusedViewRect: rect];
  [self unlockFocus];

  return AUTORELEASE(bitmap);
}

- (void) cacheDisplayInRect: (NSRect)rect 
           toBitmapImageRep: (NSBitmapImageRep *)bitmap
{
  NSDictionary *dict;
  NSData *imageData;

  [self lockFocus];
  dict = [GSCurrentContext() GSReadRect: rect];
  [self unlockFocus];
  imageData = [dict objectForKey: @"Data"];

  if (imageData != nil)
    {
      // Copy the image data to the bitmap
      memcpy([bitmap bitmapData], [imageData bytes], [imageData length]);
    }
}


extern NSThread *GSAppKitThread; /* TODO */

/*
For -setNeedsDisplay*, the real work is done in the ..._real methods, and
the actual public method simply calls it, but makes sure that the call is
in the main thread.
*/

- (void) _setNeedsDisplay_real: (NSNumber *)n
{
  BOOL flag = [n boolValue];

  if (flag)
    {
      [self setNeedsDisplayInRect: _bounds];
    }
  else
    {
      _rFlags.needs_display = NO;
      _invalidRect = NSZeroRect;
    }
}

/**
 * As an exception to the general rules for threads and gui, this
 * method is thread-safe and may be called from any thread. Display
 * will always be done in the main thread. (Note that other methods are
 * in general not thread-safe; if you want to access other properties of
 * views from multiple threads, you need to provide the synchronization.)
 */
- (void) setNeedsDisplay: (BOOL)flag
{
  NSNumber *n = [[NSNumber alloc] initWithBool: flag];
  if (GSCurrentThread() != GSAppKitThread)
    {
      NSDebugMLLog (@"MacOSXCompatibility", 
                    @"setNeedsDisplay: called on secondary thread");
      [self performSelectorOnMainThread: @selector(_setNeedsDisplay_real:)
            withObject: n
            waitUntilDone: NO];
    }
  else
    {
      [self _setNeedsDisplay_real: n];
    }
  DESTROY(n);
}


- (void) _setNeedsDisplayInRect_real: (NSValue *)v
{
  NSRect invalidRect = [v rectValue];
  NSView *currentView = _super_view;

  /*
   *	Limit to bounds, combine with old _invalidRect, and then check to see
   *	if the result is the same as the old _invalidRect - if it isn't then
   *	set the new _invalidRect.
   */
  invalidRect = NSIntersectionRect(invalidRect, _bounds);
  invalidRect = NSUnionRect(_invalidRect, invalidRect);
  if (NSEqualRects(invalidRect, _invalidRect) == NO)
    {
      NSView	*firstOpaque = [self opaqueAncestor];

      _rFlags.needs_display = YES;
      _invalidRect = invalidRect;
      if (firstOpaque == self)
        {
	  /**
	   * Enlarge (if necessary) _invalidRect so it lies on integral device pixels 
	   */
	  const NSRect inBase =  [self convertRectToBase: _invalidRect];
	  const NSRect inBaseRounded = NSIntegralRect(inBase);
	  _invalidRect = [self convertRectFromBase: inBaseRounded];

          [_window setViewsNeedDisplay: YES];
        }
      else
        {
          invalidRect = [firstOpaque convertRect: _invalidRect fromView: self];
          [firstOpaque setNeedsDisplayInRect: invalidRect];
        }
    }

 /*
   * Must make sure that superviews know that we need display.
   * NB. we may have been marked as needing display and then moved to another
   * parent, so we can't assume that our parent is marked simply because we are.
   */
  while (currentView)
    {
      currentView->_rFlags.needs_display = YES;
      currentView = currentView->_super_view;
    }
  // Also mark the window, as this may not happen above
  [_window setViewsNeedDisplay: YES];
}

/**
 * Inform the view system that the specified rectangle is invalid and
 * requires updating.  This automatically informs any superviews of
 * any updating they need to do.
 *
 * As an exception to the general rules for threads and gui, this
 * method is thread-safe and may be called from any thread. Display
 * will always be done in the main thread. (Note that other methods are
 * in general not thread-safe; if you want to access other properties of
 * views from multiple threads, you need to provide the synchronization.)
 */
- (void) setNeedsDisplayInRect: (NSRect)invalidRect
{
  NSValue *v;

  if (NSIsEmptyRect(invalidRect))
    return; // avoid unnecessary work when rectangle is empty
	
  v = [[NSValue alloc]
		 initWithBytes: &invalidRect
		 objCType: @encode(NSRect)];

  if (GSCurrentThread() != GSAppKitThread)
    {
      NSDebugMLLog (@"MacOSXCompatibility", 
                    @"setNeedsDisplayInRect: called on secondary thread");
      [self performSelectorOnMainThread: @selector(_setNeedsDisplayInRect_real:)
            withObject: v
            waitUntilDone: NO];
    }
  else
    {
      [self _setNeedsDisplayInRect_real: v];
    }
  DESTROY(v);
}

+ (NSFocusRingType) defaultFocusRingType
{
  return NSFocusRingTypeDefault;
}

- (void) setKeyboardFocusRingNeedsDisplayInRect: (NSRect)rect
{
  // FIXME For external type special handling is needed
  [self setNeedsDisplayInRect: rect];
}

- (void) setFocusRingType: (NSFocusRingType)focusRingType
{
  _focusRingType = focusRingType;
}

- (NSFocusRingType) focusRingType
{
  return _focusRingType;
}

/*
 * Hidding Views
 */
- (void) setHidden: (BOOL)flag
{
  id view;

  if (_is_hidden == flag)
      return;

  _is_hidden = flag;

  if (_is_hidden)
    {
      for (view = [_window firstResponder];
           view != nil && [view respondsToSelector: @selector(superview)];
           view = [view superview])
        {
          if (view == self)
            {
              [_window makeFirstResponder: [self nextValidKeyView]];
              break;
            }
        }
      if (_rFlags.has_draginfo)
        {
          if (_window != nil)
            {
              NSArray *t = GSGetDragTypes(self);
              
              [GSDisplayServer removeDragTypes: t fromWindow: _window];
            }
        }
      [[self superview] setNeedsDisplay: YES];
    }
  else
    {
      if (_rFlags.has_draginfo)
        {
          if (_window != nil)
            {
              NSArray *t = GSGetDragTypes(self);
              
              [GSDisplayServer addDragTypes: t toWindow: _window];
            }
        }
      if (_rFlags.has_subviews)
        {
          // The _visibleRect of subviews will be NSZeroRect, because when they
          // were calculated in -[_rebuildCoordinates], they were intersected
          // with the result of calling -[visibleRect] on the hidden superview,
          // which returns NSZeroRect for hidden views.
          //
          // So, recalculate the subview coordinates now to make them correct.

          [_sub_views makeObjectsPerformSelector: 
            @selector(_invalidateCoordinates)];
        }
      [self setNeedsDisplay: YES];
    }
}

- (BOOL) isHidden
{
  return _is_hidden;
}

- (BOOL) isHiddenOrHasHiddenAncestor
{
  return ([self isHidden] || [_super_view isHiddenOrHasHiddenAncestor]);
}

/*
 * Live resize support
 */
- (BOOL) inLiveResize
{
  return _in_live_resize;
}

- (void) viewWillStartLiveResize
{
  // FIXME
  _in_live_resize = YES; 
}

- (void) viewDidEndLiveResize
{
  // FIXME
  _in_live_resize = NO; 
}

- (BOOL) preservesContentDuringLiveResize
{
  return NO;
}

- (void) getRectsExposedDuringLiveResize: (NSRect[4])exposedRects count: (NSInteger *)count
{
  // FIXME
  if (count != NULL)
    {
      *count = 1;
    }
  exposedRects[0] = _bounds;
}

- (NSRect) rectPreservedDuringLiveResize
{
  return NSZeroRect;
}

/*
 * Scrolling
 */
- (NSRect) adjustScroll: (NSRect)newVisible
{
  return newVisible;
}

/**
 * Finds the nearest enclosing NSClipView and, if the location of the event
 * is outside it, scrolls the NSClipView in the direction of the event. The
 * amount scrolled is proportional to how far outside the NSClipView the
 * event's location is.
 *
 * This method is suitable for calling periodically from a modal event
 * tracking loop when the mouse is dragged outside the tracking view. The
 * suggested period of the calls is 0.1 seconds.
 */
- (BOOL) autoscroll: (NSEvent*)theEvent
{
  if (_super_view)
    return [_super_view autoscroll: theEvent];

  return NO;
}

- (void) reflectScrolledClipView: (NSClipView*)aClipView
{
}

- (void) scrollClipView: (NSClipView*)aClipView toPoint: (NSPoint)aPoint
{
  [aClipView scrollToPoint: aPoint];
}

- (NSClipView*) _enclosingClipView
{
  static Class clipViewClass;
  id aView = [self superview];

  if (!clipViewClass)
    {
      clipViewClass = [NSClipView class];
    }

  while (aView != nil)
    {
      if ([aView isKindOfClass: clipViewClass])
	{
	  break;
	}
      aView = [aView superview];
    }

  return aView;
}

- (void) scrollPoint: (NSPoint)aPoint
{
  NSClipView *s = [self _enclosingClipView];

  if (s == nil)
    return;

  aPoint = [self convertPoint: aPoint toView: s];
  if (NSEqualPoints(aPoint, [s bounds].origin) == NO)
    {
      [s scrollToPoint: aPoint];
    }
}

/**
   Copy on scroll method, should be called from [NSClipView setBoundsOrigin].
 */
- (void) scrollRect: (NSRect)aRect by: (NSSize)delta
{
  NSPoint destPoint;

  aRect = NSIntersectionRect(aRect, _bounds);   // Don't copy stuff outside.
  destPoint = aRect.origin;
  destPoint.x += delta.width;
  destPoint.y += delta.height;
  if ([self isFlipped])
    {
      destPoint.y += aRect.size.height;
    }

  //NSLog(@"destPoint %@ in %@", NSStringFromPoint(destPoint), NSStringFromRect(_bounds));

  [self lockFocus];
  //NSCopyBits(0, aRect, destPoint);
  NSCopyBits([[self window] gState], [self convertRect: aRect toView: nil], destPoint);
  [self unlockFocus];
}

/**
Scrolls the nearest enclosing clip view the minimum required distance
necessary to make aRect (or as much of it possible) in the receiver visible.
Returns YES iff any scrolling was done.
*/
- (BOOL) scrollRectToVisible: (NSRect)aRect
{
  NSClipView *s = [self _enclosingClipView];

  if (s != nil)
    {
      NSRect	vRect = [s documentVisibleRect];
      NSPoint	aPoint = vRect.origin;
      // Ok we assume that the rectangle is origined at the bottom left
      // and goes to the top and right as it grows in size for the naming
      // of these variables
      CGFloat ldiff, rdiff, tdiff, bdiff;

      if (vRect.size.width == 0 && vRect.size.height == 0)
	return NO;

      aRect = [self convertRect: aRect toView: [s documentView]];

      // Find the differences on each side.
      ldiff = NSMinX(vRect) - NSMinX(aRect);
      rdiff = NSMaxX(aRect) - NSMaxX(vRect);
      bdiff = NSMinY(vRect) - NSMinY(aRect);
      tdiff = NSMaxY(aRect) - NSMaxY(vRect);

      // If the diff's have the same sign then nothing needs to be scrolled
      if ((ldiff * rdiff) >= 0.0) ldiff = rdiff = 0.0;
      if ((bdiff * tdiff) >= 0.0) bdiff = tdiff = 0.0;

      // Move the smallest difference
      aPoint.x += (fabs(ldiff) < fabs(rdiff)) ? (-ldiff) : rdiff;
      aPoint.y += (fabs(bdiff) < fabs(tdiff)) ? (-bdiff) : tdiff;

      if (aPoint.x != vRect.origin.x || aPoint.y != vRect.origin.y)
	{
	  aPoint = [[s documentView] convertPoint: aPoint toView: s];
	  [s scrollToPoint: aPoint];
	  return YES;
	}
    }
  return NO;
}

- (NSScrollView*) enclosingScrollView
{
  static Class scrollViewClass;
  id	aView = [self superview];

  if (!scrollViewClass)
    {
      scrollViewClass = [NSScrollView class];
    }

  while (aView != nil)
    {
      if ([aView isKindOfClass: scrollViewClass])
	{
	  break;
	}
      aView = [aView superview];
    }

  return aView;
}

/*
 * Managing the Cursor
 *
 * We use the tracking rectangle class to maintain the cursor rects
 */
- (void) addCursorRect: (NSRect)aRect cursor: (NSCursor*)anObject
{
  if (_window != nil)
    {
      GSTrackingRect	*m;

      aRect = [self convertRect: aRect toView: nil];
      m = [rectClass allocWithZone: NSDefaultMallocZone()];
      m = [m initWithRect: aRect
		      tag: 0
		    owner: RETAIN(anObject)
		 userData: NULL
		   inside: YES];
      [_cursor_rects addObject: m];
      RELEASE(m);
      _rFlags.has_currects = 1;
      _rFlags.valid_rects = 1;
    }
}

- (void) discardCursorRects
{
  if (_rFlags.has_currects != 0)
    {
      NSUInteger count = [_cursor_rects count];

      if (count > 0)
        {
	  GSTrackingRect *rects[count];

	  [_cursor_rects getObjects: rects];
	  if (_rFlags.valid_rects != 0)
	    {
	      NSPoint loc = _window->_lastPoint;
	      NSUInteger i;

	      for (i = 0; i < count; ++i)
		{
		  GSTrackingRect *r = rects[i];
		  if (NSMouseInRect(loc, r->rectangle, NO))
		    {
		      [r->owner mouseExited: nil];
		    }
		  [r invalidate];
		}
	      _rFlags.valid_rects = 0;
	    }
	  while (count-- > 0)
	    {
	      RELEASE([rects[count] owner]);
	    }
	  [_cursor_rects removeAllObjects];
	}
      _rFlags.has_currects = 0;
    }
}

- (void) removeCursorRect: (NSRect)aRect cursor: (NSCursor*)anObject
{
  id e = [_cursor_rects objectEnumerator];
  GSTrackingRect	*o;
  NSCursor		*c;
  NSPoint loc = [_window mouseLocationOutsideOfEventStream];

  /* Base remove test upon cursor object */
  o = [e nextObject];
  while (o)
    {
      c = [o owner];
      if (c == anObject)
	{
	  if (NSMouseInRect(loc, o->rectangle, NO))
	    {
	      [c mouseExited: nil];
	    }
	  [o invalidate];
	  [_cursor_rects removeObject: o];
	  if ([_cursor_rects count] == 0)
	    {
	      _rFlags.has_currects = 0;
	      _rFlags.valid_rects = 0;
	    }
	  RELEASE(c);
	  break;
	}
      else
	{
	  o = [e nextObject];
	}
    }
}

- (void) resetCursorRects
{
}

static NSView* findByTag(NSView *view, NSInteger aTag, NSUInteger *level)
{
  NSUInteger i, count;
  NSArray *sub = [view subviews];

  count = [sub count];
  if (count > 0)
    {
      NSView	*array[count];

      [sub getObjects: array];

      for (i = 0; i < count; i++)
	{
	  if ([array[i] tag] == aTag)
	    return array[i];
	}
      *level += 1;
      for (i = 0; i < count; i++)
	{
	  NSView	*v;

	  v = findByTag(array[i], aTag, level);
	  if (v != nil)
	    return v;
	}
      *level -= 1;
    }
  return nil;
}

- (id) viewWithTag: (NSInteger)aTag
{
  NSView	*view = nil;

  /*
   * If we have the specified tag - return self.
   */
  if ([self tag] == aTag)
    {
      view = self;
    }
  else if (_rFlags.has_subviews)
    {
      NSUInteger count = [_sub_views count];

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

	  [_sub_views getObjects: array];

	  /*
	   * Quick check to see if any of our direct descendents has the tag.
	   */
	  for (i = 0; i < count; i++)
	    {
	      NSView *subView = array[i];

	      if ([subView tag] == aTag)
	        {
		  view = subView;
		  break;
		}
	    }

	  if (view == nil)
	    {
	      NSUInteger level = 0xffffffff;

	      /*
	       * Ok - do it the long way - search the whole tree for each of
	       * our descendents and see which has the closest view matching
	       * the tag.
	       */
	      for (i = 0; i < count; i++)
		{
		  NSUInteger l = 0;
		  NSView *v;

		  v = findByTag(array[i], aTag, &l);

		  if (v != nil && l < level)
		    {
		      view = v;
		      level = l;
		    }
		}
	    }
	}
    }
  return view;
}

/*
 * Aiding Event Handling
 */

/**
 * Returns YES if the view object will accept the first
 * click received when in an inactive window, and NO
 * otherwise.
 */
- (BOOL) acceptsFirstMouse: (NSEvent*)theEvent
{
  return NO;
}

/**
 * Returns the subview, lowest in the receiver's hierarchy, which
 * contains aPoint, or nil if there is no such view.
 */
- (NSView*) hitTest: (NSPoint)aPoint
{
  NSPoint p;
  NSView *v = nil, *w;

  /* If not within our frame then it can't be a hit.

  As a special case, always assume that it's a hit if our _super_view is nil,
  ie. if we're the top-level view in a window.
  */

  if ([self isHidden])
    {
      return nil;
    }

  if (_is_rotated_or_scaled_from_base)
    {
      p = [self convertPoint: aPoint fromView: _super_view];
      if (!NSPointInRect (p, _bounds))
        {
          return nil;
        }
    }
  else if (_super_view && ![_super_view mouse: aPoint inRect: _frame])
    {
      return nil;
    }
  else
    {
      p = [self convertPoint: aPoint fromView: _super_view];
    }

  if (_rFlags.has_subviews)
    {
      NSUInteger count;

      count = [_sub_views count];
      if (count > 0)
        {
          NSView *array[count];

          [_sub_views getObjects: array];
          
          while (count > 0)
            {
              w = array[--count];
              v = [w hitTest: p];
              if (v)
                break;
            }
        }
    }
  /*
   * mouse is either in the subview or within self
   */
  if (v)
    return v;
  else
    return self;
}

/**
 * Returns whether or not aPoint lies within aRect.
 */
- (BOOL) mouse: (NSPoint)aPoint  inRect: (NSRect)aRect
{
  return NSMouseInRect (aPoint, aRect, [self isFlipped]);
}

- (BOOL) performKeyEquivalent: (NSEvent*)theEvent
{
  NSUInteger i;

  for (i = 0; i < [_sub_views count]; i++)
    if ([[_sub_views objectAtIndex: i] performKeyEquivalent: theEvent] == YES)
      return YES;
  return NO;
}

- (BOOL) performMnemonic: (NSString *)aString
{
  NSUInteger i;

  for (i = 0; i < [_sub_views count]; i++)
    if ([[_sub_views objectAtIndex: i] performMnemonic: aString] == YES)
      return YES;
  return NO;
}

- (BOOL) mouseDownCanMoveWindow
{
  return ![self isOpaque];
}

- (void) removeTrackingRect: (NSTrackingRectTag)tag
{
  NSUInteger i, j;
  GSTrackingRect	*m;

  j = [_tracking_rects count];
  for (i = 0;i < j; ++i)
    {
      m = (GSTrackingRect*)[_tracking_rects objectAtIndex: i];
      if ([m tag] == tag)
	{
	  [m invalidate];
	  [_tracking_rects removeObjectAtIndex: i];
	  if ([_tracking_rects count] == 0)
	    {
	      _rFlags.has_trkrects = 0;
	    }
	  return;
	}
    }
}

- (BOOL) shouldDelayWindowOrderingForEvent: (NSEvent*)anEvent
{
  return NO;
}

- (NSTrackingRectTag) addTrackingRect: (NSRect)aRect
				owner: (id)anObject
			     userData: (void*)data
			 assumeInside: (BOOL)flag
{
  NSTrackingRectTag	t;
  NSUInteger		i, j;
  GSTrackingRect	*m;

  t = 0;
  j = [_tracking_rects count];
  for (i = 0; i < j; ++i)
    {
      m = (GSTrackingRect*)[_tracking_rects objectAtIndex: i];
      if ([m tag] > t)
	t = [m tag];
    }
  ++t;

  m = [[rectClass alloc] initWithRect: aRect
				  tag: t
				owner: anObject
			     userData: data
			       inside: flag];
  [_tracking_rects addObject: m];
  RELEASE(m);
  _rFlags.has_trkrects = 1;
  return t;
}

-(BOOL) needsPanelToBecomeKey
{
  return NO;
}


/**
 * <p>The effect of the -setNextKeyView: method is to set aView to be the
 * value returned by subsequent calls to the receivers -nextKeyView method.
 * This also has the effect of setting the previous key view of aView,
 * so that subsequent calls to its -previousKeyView method will return
 * the receiver.
 * </p>
 * <p>As a special case, if you pass nil as aView then the -previousKeyView
 * of the receivers current -nextKeyView is set to nil as well as the
 * receivers -nextKeyView being set to nil.<br />
 * This behavior provides MacOS-X compatibility.
 * </p>
 * <p>If you pass a non-view object other than nil, an
 * NSInternaInconsistencyException is raised.
 * </p>
 * <p><strong>NB</strong> This method does <em>NOT</em> cause aView to be
 * retained, and if aView is deallocated, the [NSView-dealloc] method will
 * automatically remove it from the key view chain it is in.
 * </p>
 * <p>For keyboard navigation, views are linked together in a chain, so that
 * the current first responder view can be changed by stepping backward
 * and forward in that chain.  This is the method for building and modifying
 * that chain.
 * </p>
 * <p>The MacOS-X documentation refers to this chain as a <em>loop</em>, but
 * the actual implementation is not a loop at all (except as a special case
 * when you make the chain into a loop).  In fact, while each view may have
 * only zero or one <em>next</em> view, and zero or one <em>previous</em>
 * view, several views may have their <em>next</em> view set to a single
 * view and/or their <em>previous</em> views set to a single view.  So the
 * actual setup is a directed graph rather than a loop.
 * </p>
 * <p>While a directed graph is a very powerful and flexible way of managing
 * the way views get keyboard focus in response to  tabs etc, it can be
 * confusing if misused.  It is probably best therefore, to set your views
 * up as a single loop within each window.
 * </p>
 * <example>
 *   [a setNextKeyView: b];
 *   [b setNextKeyView: c];
 *   [c setNextKeyView: d];
 *   [d setNextKeyView: a];
 * </example>
 */
- (void) setNextKeyView: (NSView *)aView
{
  NSView	*tmp;
  NSUInteger	count;

  if (aView != nil && [aView isKindOfClass: viewClass] == NO)
    {
      [NSException raise: NSInternalInconsistencyException
	format: @"[NSView -setNextKeyView:] passed non-view object %@", aView];
    }

  if (aView == nil)
    {
      if (nKV(self) != 0)
	{
	  tmp = GSIArrayItemAtIndex(nKV(self), 0).obj;
	  if (tmp != nil)
	    {
	      /*
	       * Remove all reference to self from our next key view.
	       */
	      if (pKV(tmp) != 0)
		{
		  count = GSIArrayCount(pKV(tmp));
		  while (count-- > 1)
		    {
		      if (GSIArrayItemAtIndex(pKV(tmp), count).obj == self)
			{
			  GSIArrayRemoveItemAtIndex(pKV(tmp), count);
			}
		    }
		  if (GSIArrayItemAtIndex(pKV(tmp), 0).obj == self)
		    {
		      GSIArraySetItemAtIndex(pKV(tmp), (GSIArrayItem)nil, 0);
		    }
		}
	      /*
	       * Clear link to the next key view.
	       */
	      GSIArraySetItemAtIndex(nKV(self), (GSIArrayItem)nil, 0);
	    }
	}
      return;
    }

  if (nKV(self) == 0)
    {
      /*
       * Create array and ensure that it has a nil item at index 0 ...
       * so we always have room for the pointer to the next view.
       */
      _nextKeyView = NSZoneMalloc(NSDefaultMallocZone(), sizeof(GSIArray_t));
      GSIArrayInitWithZoneAndCapacity(nKV(self), NSDefaultMallocZone(), 1);
      GSIArrayAddItem(nKV(self), (GSIArrayItem)nil);
    }
  else
    {
      /* A safety measure against recursion.  */
      tmp = GSIArrayItemAtIndex(nKV(self), 0).obj;
      if (tmp == aView)
	{
	  return;
	}
    }

  if (pKV(aView) == 0)
    {
      /*
       * Create array and ensure that it has a nil item at index 0 ...
       * so we always have room for the pointer to the previous view.
       */
      aView->_previousKeyView = NSZoneMalloc(NSDefaultMallocZone(), sizeof(GSIArray_t));
      GSIArrayInitWithZoneAndCapacity(pKV(aView), NSDefaultMallocZone(), 1);
      GSIArrayAddItem(pKV(aView), (GSIArrayItem)nil);
    }

  /*
   * Tell the old previous view of aView that aView no longer points to it.
   */
  tmp = GSIArrayItemAtIndex(pKV(aView), 0).obj;
  if (tmp != nil)
    {
      count = GSIArrayCount(nKV(tmp));
      while (count-- > 1)
	{
	  if (GSIArrayItemAtIndex(nKV(tmp), count).obj == aView)
	    {
	      GSIArrayRemoveItemAtIndex(nKV(tmp), count);
	    }
	}
      /*
       * If the view still points to aView, make a note of it in the
       * 'previous' array of aView while making space for the new link.
       */
      if (GSIArrayItemAtIndex(nKV(tmp), 0).obj == aView)
	{
	  GSIArrayInsertItem(pKV(aView), (GSIArrayItem)nil, 0);
	}
    }

  /*
   * Set up 'previous' link in aView to point to us.
   */
  GSIArraySetItemAtIndex(pKV(aView), (GSIArrayItem)((id)self), 0);

  /*
   * Tell our current 'next' view that we are no longer pointing to it.
   */
  tmp = GSIArrayItemAtIndex(nKV(self), 0).obj;
  if (tmp != nil)
    {
      count = GSIArrayCount(pKV(tmp));
      while (count-- > 1)
	{
	  if (GSIArrayItemAtIndex(pKV(tmp), count).obj == self)
	    {
	      GSIArrayRemoveItemAtIndex(pKV(tmp), count);
	    }
	}
      if (GSIArrayItemAtIndex(pKV(tmp), 0).obj == self)
	{
	  GSIArraySetItemAtIndex(pKV(tmp), (GSIArrayItem)nil, 0);
	}
    }

  /*
   * Set up 'next' link to point to aView.
   */
  GSIArraySetItemAtIndex(nKV(self), (GSIArrayItem)((id)aView), 0);
}

/**
 * Returns the next view after the receiver in the key view chain.<br />
 * Returns nil if there is no view after the receiver.<br />
 * The next view is set up using the -setNextKeyView: method.<br />
 * The key view chain is used to determine the order in which views become
 * first responder when using keyboard navigation.
 */
- (NSView *) nextKeyView
{
  if (nKV(self) == 0)
    {
      return nil;
    }
  return GSIArrayItemAtIndex(nKV(self), 0).obj;
}

/**
 * Returns the first available view after the receiver which is
 * actually able to become first responder. See -nextKeyView and
 * [NSResponder-acceptsFirstResponder]
 */
- (NSView *) nextValidKeyView
{
  NSView *theView;

  theView = [self nextKeyView];
  while (1)
    {
      if ((theView == nil) || (theView == self) || 
	  [theView canBecomeKeyView])
	{
	  return theView;
	}
      theView = [theView nextKeyView];
    }
}

/**
 * GNUstep addition ... a conveninece method to insert a view in the
 * key view chain before the receiver, using the -previousKeyView and
 * -setNextKeyView: methods.
 */
- (void) setPreviousKeyView: (NSView *)aView
{
  NSView	*p = [self previousKeyView];

  if (aView == p || aView == self)
    {
      return;
    }
  [p setNextKeyView: aView];
  [aView setNextKeyView: self];
}

/**
 * Returns the view before the receiver in the key view chain.<br />
 * Returns nil if there is no view before the receiver in the chain.<br />
 * The previous view of the receiver was set up by passing it as the
 * argument to a call of -setNextKeyView: on that view.<br />
 * The key view chain is used to determine the order in which views become
 * first responder when using keyboard navigation.
 */
- (NSView *) previousKeyView
{
  if (pKV(self) == 0)
    {
      return nil;
    }
  return GSIArrayItemAtIndex(pKV(self), 0).obj;
}

/**
 * Returns the first available view before the receiver which is
 * actually able to become first responder. See -nextKeyView and
 * [NSResponder-acceptsFirstResponder]
 */
- (NSView *) previousValidKeyView
{
  NSView *theView;

  theView = [self previousKeyView];
  while (1)
    {
      if ((theView == nil) || (theView == self) || 
	  [theView canBecomeKeyView])
	{
	  return theView;
	}
      theView = [theView previousKeyView];
    }
}

- (BOOL) canBecomeKeyView
{
  // FIXME
  return [self acceptsFirstResponder] && ![self isHiddenOrHasHiddenAncestor];
}

/*
 * Dragging
 */
- (BOOL) dragFile: (NSString*)filename
	 fromRect: (NSRect)rect
	slideBack: (BOOL)slideFlag
	    event: (NSEvent*)event
{
  NSImage *anImage = [[NSWorkspace sharedWorkspace] iconForFile: filename];
  NSPasteboard *pboard = [NSPasteboard pasteboardWithName: NSDragPboard];

  if (anImage == nil)
    return NO;

  [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType] 
	  owner: self];
  if (![pboard setPropertyList: [NSArray arrayWithObject: filename]
	       forType: NSFilenamesPboardType])
    return NO;

  [self dragImage: anImage
	at: rect.origin
	offset: NSMakeSize(0, 0)
	event: event
	pasteboard: pboard
	source: self
	slideBack: slideFlag];
  return YES;
}

- (void) dragImage: (NSImage*)anImage
		at: (NSPoint)viewLocation
	    offset: (NSSize)initialOffset
	     event: (NSEvent*)event
	pasteboard: (NSPasteboard*)pboard
	    source: (id)sourceObject
	 slideBack: (BOOL)slideFlag
{
  [_window dragImage: anImage
	   at: [self convertPoint: viewLocation toView: nil]
	   offset: initialOffset
	   event: event
	   pasteboard: pboard
	   source: sourceObject
	   slideBack: slideFlag];
}

/**
 * Registers the fact that the receiver should accept dragged data
 * of any of the specified types.  You need to do this if you want
 * your view to support drag and drop.
 */
- (void) registerForDraggedTypes: (NSArray*)newTypes
{
  NSArray	*o;
  NSArray	*t;

  if (newTypes == nil || [newTypes count] == 0)
    [NSException raise: NSInvalidArgumentException
		format: @"Types information missing"];

  /*
   * Get the old drag types for this view if we need to tell the context
   * to change the registered types for the window.
   */
  if (_rFlags.has_draginfo == 1 && _window != nil)
    {
      o = TEST_RETAIN(GSGetDragTypes(self));
    }
  else
    {
      o = nil;
    }

  t = GSSetDragTypes(self, newTypes);
  _rFlags.has_draginfo = 1;
  if (_window != nil)
    {
      // Remove the old types first, that way overlapping types stay assigned.
      if (o != nil)
	{
	  [GSDisplayServer removeDragTypes: o fromWindow: _window];
	}
      [GSDisplayServer addDragTypes: t toWindow: _window];
    }
  TEST_RELEASE(o);
}

- (void) unregisterDraggedTypes
{
  if (_rFlags.has_draginfo)
    {
      if (_window != nil)
	{
	  NSArray		*t = GSGetDragTypes(self);

	  [GSDisplayServer removeDragTypes: t fromWindow: _window];
	}
      GSRemoveDragTypes(self);
      _rFlags.has_draginfo = 0;
    }
}

- (NSArray *) registeredDraggedTypes
{
  return GSGetDragTypes(self);
}

- (BOOL) dragPromisedFilesOfTypes: (NSArray *)typeArray
                         fromRect: (NSRect)aRect
                           source: (id)sourceObject 
                        slideBack: (BOOL)slideBack
                            event: (NSEvent *)theEvent
{
  // FIXME: Where to get the image from?
  NSImage *anImage = nil;
  NSPasteboard *pboard = [NSPasteboard pasteboardWithName: NSDragPboard];

  if (anImage == nil)
    return NO;

  [pboard declareTypes: [NSArray arrayWithObject: NSFilesPromisePboardType] 
	  owner: sourceObject];
  // FIXME: Not sure if this is correct.
  if (![pboard setPropertyList: typeArray
	       forType: NSFilesPromisePboardType])
    return NO;

  [self dragImage: anImage
	at: aRect.origin
	offset: NSMakeSize(0, 0)
	event: theEvent
	pasteboard: pboard
	source: sourceObject
	slideBack: slideBack];
  return YES;
}

/*
 * Printing
 */
- (void) fax: (id)sender
{
  NSPrintInfo *aPrintInfo = [NSPrintInfo sharedPrintInfo];

  [aPrintInfo setJobDisposition: NSPrintFaxJob];
  [[NSPrintOperation printOperationWithView: self
		     printInfo: aPrintInfo] runOperation];
}

- (void) print: (id)sender
{
  [[NSPrintOperation printOperationWithView: self] runOperation];
}

- (NSData*) dataWithEPSInsideRect: (NSRect)aRect
{
  NSMutableData *data = [NSMutableData data];

  if ([[NSPrintOperation EPSOperationWithView: self
			 insideRect: aRect
			 toData: data] runOperation])
    {
      return data;
    }
  else
    {
      return nil;
    }
}

- (void) writeEPSInsideRect: (NSRect)rect
	       toPasteboard: (NSPasteboard*)pasteboard
{
  NSData *data = [self dataWithEPSInsideRect: rect];

  if (data != nil)
    [pasteboard setData: data
		forType: NSPostScriptPboardType];
}

- (NSData *) dataWithPDFInsideRect: (NSRect)aRect
{
  NSMutableData *data = [NSMutableData data];
  
  if ([[NSPrintOperation PDFOperationWithView: self
			 insideRect: aRect
			 toData: data] runOperation])
    {
      return data;
    }
  else
    {
      return nil;
    }
}

- (void) writePDFInsideRect: (NSRect)aRect 
	       toPasteboard: (NSPasteboard *)pboard
{
  NSData *data = [self dataWithPDFInsideRect: aRect];

  if (data != nil)
    [pboard setData: data
	    forType: NSPDFPboardType];
}

- (NSString *) printJobTitle
{
  id doc;
  NSString *title;
  doc = [[NSDocumentController sharedDocumentController] documentForWindow:
							   [self window]];
  if (doc)
    title = [doc displayName];
  else
    title = [[self window] title];
  return title;
}

/*
 * Pagination
 */
- (void) adjustPageHeightNew: (CGFloat*)newBottom
			 top: (CGFloat)oldTop
		      bottom: (CGFloat)oldBottom
		       limit: (CGFloat)bottomLimit
{
  CGFloat bottom = oldBottom;

  if (_rFlags.has_subviews)
    {
      id e, o;

      e = [_sub_views objectEnumerator];
      while ((o = [e nextObject]) != nil)
	{
          // FIXME: We have to convert this values for the subclass

	  CGFloat oTop, oBottom, oLimit;
	  /* Don't ask me why, but gcc-2.91.66 crashes if we use
	     NSMakePoint in the following expressions.  We avoid this
	     compiler internal bug by using an auxiliary aPoint
	     variable, and setting it manually to the NSPoints we
	     need.  */
	  {
	    NSPoint aPoint = {0, oldTop};
	    oTop = ([self convertPoint: aPoint  toView: o]).y;
	  }
	  
	  {
	    NSPoint aPoint = {0, bottom};
	    oBottom = ([self convertPoint: aPoint  toView: o]).y;
	  }

	  {
	    NSPoint aPoint = {0, bottomLimit};
	    oLimit = ([self convertPoint: aPoint  toView: o]).y;
	  }

	  [o adjustPageHeightNew: &oBottom
	     top: oTop
	     bottom: oBottom
	     limit: oLimit];

	  {
	    NSPoint aPoint = {0, oBottom};
	    bottom = ([self convertPoint: aPoint  fromView: o]).y; 
	  }	    
	}
    }

  *newBottom = bottom;
}

- (void) adjustPageWidthNew: (CGFloat*)newRight
		       left: (CGFloat)oldLeft
		      right: (CGFloat)oldRight
		      limit: (CGFloat)rightLimit
{
  CGFloat right = oldRight;

  if (_rFlags.has_subviews)
    {
      id e, o;

      e = [_sub_views objectEnumerator];
      while ((o = [e nextObject]) != nil)
	{
          // FIXME: We have to convert this values for the subclass

	  /* See comments in adjustPageHeightNew:top:bottom:limit:
	     about why code is structured in this funny way.  */
	  CGFloat oLeft, oRight, oLimit;
	  /* Don't ask me why, but gcc-2.91.66 crashes if we use
	     NSMakePoint in the following expressions.  We avoid this
	     compiler internal bug by using an auxiliary aPoint
	     variable, and setting it manually to the NSPoints we
	     need.  */
	  {
	    NSPoint aPoint = {oldLeft, 0};
	    oLeft = ([self convertPoint: aPoint  toView: o]).x;
	  }
	  
	  {
	    NSPoint aPoint = {right, 0};
	    oRight = ([self convertPoint: aPoint  toView: o]).x;
	  }

	  {
	    NSPoint aPoint = {rightLimit, 0};
	    oLimit = ([self convertPoint: aPoint  toView: o]).x;
	  }

	  [o adjustPageHeightNew: &oRight
	     top: oLeft
	     bottom: oRight
	     limit: oLimit];

	  {
	    NSPoint aPoint = {oRight, 0};
	    right = ([self convertPoint: aPoint  fromView: o]).x; 
	  }	    
	}
    }

  *newRight = right;
}

- (CGFloat) heightAdjustLimit
{
  return 0.0;
}

- (BOOL) knowsPagesFirst: (int*)firstPageNum last: (int*)lastPageNum
{
  return NO;
}

- (BOOL) knowsPageRange: (NSRange*)range
{
  return NO;
}

- (NSPoint) locationOfPrintRect: (NSRect)aRect
{
  int pages;
  NSPoint location;
  NSRect bounds;
  NSMutableDictionary *dict;
  NSPrintOperation *printOp = [NSPrintOperation currentOperation];
  NSPrintInfo *printInfo = [printOp printInfo];
  dict = [printInfo dictionary];

  pages = [[dict objectForKey: @"NSPrintTotalPages"] intValue];
  if ([dict objectForKey: @"NSPrintPaperBounds"])
    bounds = [[dict objectForKey: @"NSPrintPaperBounds"] rectValue];
  else
    bounds = aRect;
  location = NSMakePoint(0, NSHeight(bounds)-NSHeight(aRect));
  /* FIXME:  I can't figure out how the location for a multi-page document
     is computed. Just ignore centering? */
  if (pages == 1)
    {
      if ([printInfo isHorizontallyCentered])
        location.x = (NSWidth(bounds) - NSWidth(aRect))/2;
      if ([printInfo isVerticallyCentered])
        location.y = (NSHeight(bounds) - NSHeight(aRect))/2;
    }

  return location;
}

- (NSRect) rectForPage: (NSInteger)page
{
  return NSZeroRect;
}

- (CGFloat) widthAdjustLimit
{
  return 0.0;
}

/*
 * Writing Conforming PostScript
 */
- (void) beginPage: (int)ordinalNum
             label: (NSString*)aString
              bBox: (NSRect)pageRect
             fonts: (NSString*)fontNames
{
  NSPrintOperation *printOp = [NSPrintOperation currentOperation];
  NSGraphicsContext *ctxt = [printOp context];

  [ctxt  beginPage: ordinalNum
         label: aString
         bBox: pageRect
         fonts: fontNames];
}

- (void) beginPageSetupRect: (NSRect)aRect placement: (NSPoint)location
{
  [self beginPageInRect: aRect atPlacement: location];
}

- (void) beginPrologueBBox: (NSRect)boundingBox
              creationDate: (NSString*)dateCreated
                 createdBy: (NSString*)anApplication
                     fonts: (NSString*)fontNames
                   forWhom: (NSString*)user
                     pages: (int)numPages
                     title: (NSString*)aTitle
{
  NSPrintOperation *printOp = [NSPrintOperation currentOperation];
  NSGraphicsContext *ctxt = [printOp context];

  [ctxt beginPrologueBBox: boundingBox
	      creationDate: dateCreated
        createdBy: anApplication
        fonts: fontNames
        forWhom: user
        pages: numPages
        title: aTitle];
}

- (void) addToPageSetup
{
}

- (void) beginSetup
{
  NSPrintOperation *printOp = [NSPrintOperation currentOperation];
  NSGraphicsContext *ctxt = [printOp context];

  [ctxt beginSetup];
}

- (void) beginTrailer
{
  NSPrintOperation *printOp = [NSPrintOperation currentOperation];
  NSGraphicsContext *ctxt = [printOp context];

  [ctxt beginTrailer];
}

- (void) drawPageBorderWithSize: (NSSize)borderSize
{
}

- (void) drawSheetBorderWithSize: (NSSize)borderSize
{
}

- (void) endHeaderComments
{
  NSPrintOperation *printOp = [NSPrintOperation currentOperation];
  NSGraphicsContext *ctxt = [printOp context];

  [ctxt endHeaderComments];
}

- (void) endPrologue
{
  NSPrintOperation *printOp = [NSPrintOperation currentOperation];
  NSGraphicsContext *ctxt = [printOp context];

  [ctxt endPrologue];
}

- (void) endSetup
{
  NSPrintOperation *printOp = [NSPrintOperation currentOperation];
  NSGraphicsContext *ctxt = [printOp context];

  [ctxt endSetup];
}

- (void) endPageSetup
{
  NSPrintOperation *printOp = [NSPrintOperation currentOperation];
  NSGraphicsContext *ctxt = [printOp context];

  [ctxt endPageSetup];
}

- (void) endPage
{
  int nup;
  NSPrintOperation *printOp = [NSPrintOperation currentOperation];
  NSGraphicsContext *ctxt = [printOp context];
  NSDictionary *dict = [[printOp printInfo] dictionary];

  // Balance gsave in beginPageInRect:
  DPSgrestore(ctxt);

  nup = [[dict objectForKey: NSPrintPagesPerSheet] intValue];
  if (nup > 1)
    {
      DPSPrintf(ctxt, "__GSpagesaveobject restore\n\n");
    }

  // [self unlockFocus];
}

- (void) endTrailer
{
  NSPrintOperation *printOp = [NSPrintOperation currentOperation];
  NSGraphicsContext *ctxt = [printOp context];

  [ctxt endTrailer];
}

- (NSAttributedString *) pageFooter
{
  return [[[NSAttributedString alloc] initWithString:
		  [NSString stringWithFormat:@"Page %d", 
			    [[NSPrintOperation currentOperation] currentPage]]] 
	     autorelease];
}

- (NSAttributedString *) pageHeader
{
  return [[[NSAttributedString alloc] initWithString: 
		  [NSString stringWithFormat:@"%@ %@", [self printJobTitle], 
			    [[NSCalendarDate calendarDate] description]]] autorelease];
}


/** 
    Writes header and job information for the PostScript document. This
    includes at a minimum, PostScript header information. It may also 
    include job setup information if the output is intended for a printer
    (i.e. not an EPS file). Most of the information for writing the
    header comes from the NSPrintOperation and NSPrintInfo objects 
    associated with the current print operation.

    There isn't normally anything that the program needs to override
    at the beginning of a document, although if there is additional
    setup that needs to be done, you can override the NSView's methods
    endHeaderComments, endPrologue, beginSetup, and/or endSetup.

    This method calls the above methods in the listed order before
    or after writing the required information. For an EPS operation, the
    beginSetup and endSetup methods aren't used.  */
- (void)beginDocument
{
  int first, last, pages, nup;
  NSRect bbox;
  NSPrintOperation *printOp = [NSPrintOperation currentOperation];
  NSGraphicsContext *ctxt = [printOp context];
  NSDictionary *dict = [[printOp printInfo] dictionary];

  if (printOp == nil)
    {
      [NSException raise: NSInternalInconsistencyException
		  format: @"beginDocument called without a current print op"];
    }
  /* Inform ourselves and subviews that we're printing so we adjust
     the PostScript accordingly. Perhaps this could be in the thread
     dictionary, but that's probably overkill and slow */
  viewIsPrinting = self;

  /* Get pagination information */
  nup = [[dict objectForKey: NSPrintPagesPerSheet] intValue];
  bbox = NSZeroRect;
  if ([dict objectForKey: @"NSPrintSheetBounds"])
    bbox = [[dict objectForKey: @"NSPrintSheetBounds"] rectValue];
  first = [[dict objectForKey: NSPrintFirstPage] intValue];
  last  = [[dict objectForKey: NSPrintLastPage] intValue];
  pages = last - first + 1;
  if (nup > 1)
    pages = ceil((float)pages / nup);

  /* Begin document structure */
  [self beginPrologueBBox: bbox
	     creationDate: [[NSCalendarDate calendarDate] description]
	        createdBy: [[NSProcessInfo processInfo] processName]
		    fonts: nil
	          forWhom: NSUserName()
		    pages: pages
	            title: [self printJobTitle]];
  [self endHeaderComments];

  [ctxt printerProlog];
  [self endPrologue];
  if ([printOp isEPSOperation] == NO)
    {
      [self beginSetup];
      // Setup goes here !
      [self endSetup];
    }

  [ctxt resetUsedFonts];
  /* Make sure we set the visible rect so everything is printed. */
  [self _invalidateCoordinates];
  _visibleRect = _bounds;
}

- (void) beginPageInRect: (NSRect)aRect 
             atPlacement: (NSPoint)location
{
  int nup;
  NSRect bounds;
  NSPrintOperation *printOp = [NSPrintOperation currentOperation];
  NSGraphicsContext *ctxt = [printOp context];
  NSDictionary *dict = [[printOp printInfo] dictionary];

  if (NSIsEmptyRect(aRect))
    {
      if ([dict objectForKey: @"NSPrintPaperBounds"])
        {
          bounds = [[dict objectForKey: @"NSPrintPaperBounds"] rectValue];
        }
      else
        {
          // FIXME: What should we use here?
          bounds = aRect;
        }
    }
  else
    {
      bounds = aRect;
    }

  nup = [[dict objectForKey: NSPrintPagesPerSheet] intValue];
  if (nup > 1)
    {
      int page;
      float xoff, yoff;
      float scale;

      DPSPrintf(ctxt, "/__GSpagesaveobject save def\n");

      scale = [[dict objectForKey: @"NSNupScale"] floatValue];
      page = [printOp currentPage] 
          - [[dict objectForKey: NSPrintFirstPage] intValue];
      page = page % nup;
      if (nup == 2)
        xoff = page;
      else
        xoff = (page % (nup/2));
      xoff *= NSWidth(bounds) * scale;
      if (nup == 2)
        yoff = 0;
      else
        yoff = (int)((nup-page-1) / (nup/2));
      yoff *= NSHeight(bounds) * scale;
      DPStranslate(ctxt, xoff, yoff);
      DPSgsave(ctxt);
      DPSscale(ctxt, scale, scale);
    }
  else
    {
      DPSgsave(ctxt);
    }

  /* Translate to placement */
  if ((location.x != 0 || location.y != 0) && NSIsEmptyRect(aRect) == YES)
    DPStranslate(ctxt, location.x, location.y);

  // FIXME: Need to place this correctly. Maybe it isn't needed at all, 
  // as all drawing happens in displayRectIgnoringOpacity:
  // [self lockFocusIfCanDrawInContext: ctxt];
}

- (void) _endSheet
{
  NSPrintOperation *printOp = [NSPrintOperation currentOperation];
  NSGraphicsContext *ctxt = [printOp context];

  [ctxt endSheet];
}

- (void) endDocument
{
  int first, last, current, pages;
  NSPrintOperation *printOp = [NSPrintOperation currentOperation];
  NSGraphicsContext *ctxt = [printOp context];
  NSDictionary *dict = [[printOp printInfo] dictionary];

  first = [[dict objectForKey: NSPrintFirstPage] intValue];
  last  = [[dict objectForKey: NSPrintLastPage] intValue];
  pages = last - first + 1;
  [self beginTrailer];

  if (pages == 0)
    {
      int nup = [[dict objectForKey: NSPrintPagesPerSheet] intValue];
      current = [printOp currentPage];
      pages = current - first; // Current is 1 more than the last page
      if (nup > 1)
        pages = ceil((float)pages / nup);
    }
  else
    {
      // Already reported at start of document
      pages = 0;
    }
  [ctxt endDocumentPages: pages documentFonts: [ctxt usedFonts]];

  [self endTrailer];
  [self _invalidateCoordinates];
  viewIsPrinting = nil;
}

/* An exception occurred while printing. Clean up */
- (void) _cleanupPrinting
{
  [self _invalidateCoordinates];
  viewIsPrinting = nil;
}  

/*
 * NSCoding protocol
 */
- (void) encodeWithCoder: (NSCoder*)aCoder
{
  if ([aCoder allowsKeyedCoding])
    {
      NSUInteger vFlags = 0;

      // encoding
      [aCoder encodeConditionalObject: [self nextKeyView] 
	      forKey: @"NSNextKeyView"];
      [aCoder encodeConditionalObject: [self previousKeyView] 
	      forKey: @"NSPreviousKeyView"];
      [aCoder encodeObject: _sub_views 
	      forKey: @"NSSubviews"];
      [aCoder encodeRect: _frame 
	      forKey: @"NSFrame"];

      // autosizing masks.
      vFlags = _autoresizingMask;

      // add the autoresize flag.
      if (_autoresizes_subviews)
        {
          vFlags |= 0x100;
        }

      // add the hidden flag
      if (_is_hidden)
        {
          vFlags |= 0x80000000;
        }
      
      [aCoder encodeInt: vFlags 
	      forKey: @"NSvFlags"];

      //
      // Don't attempt to archive the superview of a view which is the
      // content view for a window.
      //
      if (([[self window] contentView] != self) && _super_view != nil)
        {
          [aCoder encodeConditionalObject: _super_view forKey: @"NSSuperview"];
        }
    }
  else
    {
      NSDebugLLog(@"NSView", @"NSView: start encoding\n");
      [super encodeWithCoder: aCoder];

      [aCoder encodeRect: _frame];
      [aCoder encodeRect: _bounds];
      [aCoder encodeValueOfObjCType: @encode(BOOL) at: &_is_rotated_from_base];
      [aCoder encodeValueOfObjCType: @encode(BOOL)
	      at: &_is_rotated_or_scaled_from_base];
      [aCoder encodeValueOfObjCType: @encode(BOOL) at: &_post_frame_changes];
      [aCoder encodeValueOfObjCType: @encode(BOOL) at: &_autoresizes_subviews];
      [aCoder encodeValueOfObjCType: @encode(NSUInteger) at: &_autoresizingMask];
      [aCoder encodeConditionalObject: [self nextKeyView]];
      [aCoder encodeConditionalObject: [self previousKeyView]];
      [aCoder encodeObject: _sub_views];
      NSDebugLLog(@"NSView", @"NSView: finish encoding\n");
    }
}

- (id) initWithCoder: (NSCoder*)aDecoder
{
  NSEnumerator *e;
  NSView	*sub;
  NSArray	*subs;

  // decode the superclass...
  self = [super initWithCoder: aDecoder];
  if (!self)
    return nil;

  // initialize these here, since they're needed in either case.
  // _frameMatrix = [NSAffineTransform new];    // Map fromsuperview to frame
  // _boundsMatrix = [NSAffineTransform new];   // Map from superview to bounds
  _matrixToWindow = [NSAffineTransform new];  // Map to window coordinates
  _matrixFromWindow = [NSAffineTransform new];// Map from window coordinates
 
  if ([aDecoder allowsKeyedCoding])
    {
      NSView *prevKeyView = nil;
      NSView *nextKeyView = nil;

      if ([aDecoder containsValueForKey: @"NSFrame"])
        {
          _frame = [aDecoder decodeRectForKey: @"NSFrame"];
        }
      else
        {
          _frame = NSZeroRect;
          if ([aDecoder containsValueForKey: @"NSFrameSize"])
            {
              _frame.size = [aDecoder decodeSizeForKey: @"NSFrameSize"];
            }
        }

      // Set bounds rectangle
      _bounds.origin = NSZeroPoint;
      _bounds.size = _frame.size;
      if ([aDecoder containsValueForKey: @"NSBounds"])
        {
          [self setBounds: [aDecoder decodeRectForKey: @"NSBounds"]];
        }
      
      _sub_views = [NSMutableArray new];
      _tracking_rects = [NSMutableArray new];
      _cursor_rects = [NSMutableArray new];
      
      _is_rotated_from_base = NO;
      _is_rotated_or_scaled_from_base = NO;
      _rFlags.needs_display = YES;
      _post_bounds_changes = YES;
      _post_frame_changes = YES;
      _autoresizes_subviews = YES;
      _autoresizingMask = NSViewNotSizable;
      _coordinates_valid = NO;
      /*
       * Note: don't zero _nextKeyView and _previousKeyView, as the key view
       * chain may already have been established by super's initWithCoder:
       *
       * _nextKeyView = 0;
       * _previousKeyView = 0;
       */
      
      // previous and next key views...
      prevKeyView = [aDecoder decodeObjectForKey: @"NSPreviousKeyView"];
      nextKeyView = [aDecoder decodeObjectForKey: @"NSNextKeyView"];
      if (nextKeyView != nil)
        {
          [self setNextKeyView: nextKeyView];
        }
      if (prevKeyView != nil)
        {
          [self setPreviousKeyView: prevKeyView];
        }
      if ([aDecoder containsValueForKey: @"NSvFlags"])
        {
          NSUInteger vFlags = [aDecoder decodeIntForKey: @"NSvFlags"];
	  
          // We are lucky here, Apple use the same constants
          // in the lower bits of the flags
          [self setAutoresizingMask: vFlags & 0x3F];
          [self setAutoresizesSubviews: ((vFlags & 0x100) == 0x100)];
          [self setHidden: ((vFlags & 0x80000000) == 0x80000000)];
        }

      // iterate over subviews and put them into the view...
      subs = [aDecoder decodeObjectForKey: @"NSSubviews"];
      e = [subs objectEnumerator];
      while ((sub = [e nextObject]) != nil)
	{
	  NSAssert([sub class] != [NSCustomView class],
		   NSInternalInconsistencyException);
	  NSAssert([sub window] == nil,
		   NSInternalInconsistencyException);
          NSAssert([sub superview] == nil,
                   NSInternalInconsistencyException);
	  [sub _viewWillMoveToWindow: _window];
	  [sub _viewWillMoveToSuperview: self];
	  [sub setNextResponder: self];
	  [_sub_views addObject: sub];
	  _rFlags.has_subviews = 1;
	  [sub resetCursorRects];
	  [sub setNeedsDisplay: YES];
	  [sub _viewDidMoveToWindow];
	  [sub viewDidMoveToSuperview];
	  [self didAddSubview: sub];
	}

      // the superview...
      //[aDecoder decodeObjectForKey: @"NSSuperview"];
    }
  else
    {
      NSRect	rect;
      
      NSDebugLLog(@"NSView", @"NSView: start decoding\n");

      _frame = [aDecoder decodeRect];
      
      _bounds.origin = NSZeroPoint;
      _bounds.size = _frame.size;
      
      rect = [aDecoder decodeRect];
      [self setBounds: rect];
      
      _sub_views = [NSMutableArray new];
      _tracking_rects = [NSMutableArray new];
      _cursor_rects = [NSMutableArray new];
      
      _super_view = nil;
      _window = nil;
      _rFlags.needs_display = YES;
      [aDecoder decodeValueOfObjCType: @encode(BOOL)
				   at: &_is_rotated_from_base];
      [aDecoder decodeValueOfObjCType: @encode(BOOL)
				   at: &_is_rotated_or_scaled_from_base];
      _post_bounds_changes = YES;
      [aDecoder decodeValueOfObjCType: @encode(BOOL) at: &_post_frame_changes];
      [aDecoder decodeValueOfObjCType: @encode(BOOL)
				   at: &_autoresizes_subviews];
      [aDecoder decodeValueOfObjCType: @encode(NSUInteger)
				   at: &_autoresizingMask];
      _coordinates_valid = NO;
      [self setNextKeyView: [aDecoder decodeObject]];
      [[aDecoder decodeObject] setNextKeyView: self];

      [aDecoder decodeValueOfObjCType: @encode(id) at: &subs];
      NSDebugLLog(@"NSView", @"NSView: finish decoding\n");

      // iterate over subviews and put them into the view...
      e = [subs objectEnumerator];
      while ((sub = [e nextObject]) != nil)
	{
	  NSAssert([sub window] == nil,
	    NSInternalInconsistencyException);
	  NSAssert([sub superview] == nil,
	    NSInternalInconsistencyException);
	  [sub _viewWillMoveToWindow: _window];
	  [sub _viewWillMoveToSuperview: self];
	  [sub setNextResponder: self];
	  [_sub_views addObject: sub];
	  _rFlags.has_subviews = 1;
	  [sub resetCursorRects];
	  [sub setNeedsDisplay: YES];
	  [sub _viewDidMoveToWindow];
	  [sub viewDidMoveToSuperview];
	  [self didAddSubview: sub];
	}
      RELEASE(subs);
    }

  return self;
}

/*
 * Accessor methods
 */
- (void) setAutoresizesSubviews: (BOOL)flag
{
  _autoresizes_subviews = flag;
}

- (void) setAutoresizingMask: (NSUInteger)mask
{
  _autoresizingMask = mask;
}

/** Returns the window in which the receiver resides. */
- (NSWindow*) window
{
  return _window;
}

- (BOOL) autoresizesSubviews
{
  return _autoresizes_subviews;
}

- (NSUInteger) autoresizingMask
{
  return _autoresizingMask;
}

- (NSArray*) subviews
{
  /*
   * Return a mutable copy 'cos we know that a mutable copy of an array or
   * a mutable array does a shallow copy - which is what we want to give
   * away - we don't want people to mess with our actual subviews array.
   */
  return AUTORELEASE([_sub_views mutableCopyWithZone: NSDefaultMallocZone()]);
}

- (NSView*) superview
{
  return _super_view;
}

- (BOOL) shouldDrawColor
{
  return YES;
}

- (BOOL) isOpaque
{
  return NO;
}

- (BOOL) needsDisplay
{
  return _rFlags.needs_display;
}

- (NSInteger) tag
{
  return -1;
}

- (BOOL) isFlipped
{
  return NO;
}

- (NSRect) bounds
{
  return _bounds;
}

- (NSRect) frame
{
  return _frame;
}

- (CGFloat) boundsRotation
{
  if (_boundsMatrix != nil)
    {
      return [_boundsMatrix rotationAngle];
    }

  return 0.0;
}

- (CGFloat) frameRotation
{
  if (_frameMatrix != nil)
    {
      return [_frameMatrix rotationAngle];
    }

  return 0.0;
}

/** 
 * Returns whether the receiver posts NSViewFrameDidChangeNotification when 
 * its frame changed.
 *
 * Returns YES by default (as documented in Cocoa View Programming Guide). 
 */
- (BOOL) postsFrameChangedNotifications
{
  return _post_frame_changes;
}

/** 
 * Returns whether the receiver posts NSViewBoundsDidChangeNotification when 
 * its bound changed. 
 *
 * Returns YES by default (as documented in Cocoa View Programming Guide). 
 */
- (BOOL) postsBoundsChangedNotifications
{
  return _post_bounds_changes;
}


/**
 * <p>Returns the default menu to be used for instances of the 
 *    current class; if no menu has been set through setMenu:
 *    this default menu will be used.
 * </p>
 * <p>NSView's implementation returns nil. You should override
 *    this method if you want all instances of your custom view
 *    to use the same menu.
 * </p>
 */
+ (NSMenu *)defaultMenu
{
  return nil;
}

/**
 * <p>NSResponder's method, overriden by NSView.</p>
 * <p>If no menu has been set through the use of setMenu:, or 
 *    if a nil value has been set through setMenu:, then the 
 *    value returned by defaultMenu is used. Otherwise this
 *    method returns the menu set through NSResponder.
 * <p>
 * <p> see [NSResponder -menu], [NSResponder -setMenu:],
 *     [NSView +defaultMenu] and [NSView -menuForEvent:].
 * </p>
 */
- (NSMenu *)menu
{
  NSMenu *m = [super menu];
  if (m)
    {
      return m;
    }
  else
    {
      return [[self class] defaultMenu];
    }
}

/**
 * <p>Returns the menu that it appropriates for the given 
 *    event. NSView's implementation returns the default menu of
 *    the view.</p>
 * <p>This methods is intended to be overriden so that it can
 *    return a context-sensitive for appropriate mouse's events. (
 *    (although it seems it can be used for any kind of event)</p>
 * <p>This method is used by NSView's rightMouseDown: method, 
 *    and the returned NSMenu is displayed as a context menu</p> 
 * <p>Use of this method is discouraged in GNUstep as it breaks many
 *    user interface guidelines. At the very least, menu items that appear
 *    in a context sensitive menu should also always appear in a normal
 *    menu. Otherwise, users are faced with an inconsistant interface where
 *    the menu items they want are only available in certain (possibly
 *    unknown) cases, making it difficult for the user to understand how
 *    the application operates</p>
 * <p> see [NSResponder -menu], [NSResponder -setMenu:],
 *     [NSView +defaultMenu] and [NSView -menu].
 * </p>
 */
- (NSMenu *)menuForEvent: (NSEvent *)theEvent
{
  return [self menu];
}

/*
 * Tool Tips
 */

- (NSToolTipTag) addToolTipRect: (NSRect)aRect 
			  owner: (id)anObject 
		       userData: (void *)data
{
  GSToolTips	*tt = [GSToolTips tipsForView: self];

  _rFlags.has_tooltips = 1;
  return [tt addToolTipRect: aRect owner: anObject userData: data];
}

- (void) removeAllToolTips
{
  if (_rFlags.has_tooltips == 1)
    {
      GSToolTips	*tt = [GSToolTips tipsForView: self];

      [tt removeAllToolTips];
    }
}

- (void) removeToolTip: (NSToolTipTag)tag
{
  if (_rFlags.has_tooltips == 1)
    {
      GSToolTips	*tt = [GSToolTips tipsForView: self];

      [tt removeToolTip: tag];
    }
}

- (void) setToolTip: (NSString *)string
{
  if (_rFlags.has_tooltips == 1 || [string length] > 0)
    {
      GSToolTips	*tt = [GSToolTips tipsForView: self];

      _rFlags.has_tooltips = 1;
      [tt setToolTip: string];
    }
}

- (NSString *) toolTip
{
  if (_rFlags.has_tooltips == 1)
    {
      GSToolTips	*tt = [GSToolTips tipsForView: self];

      return [tt toolTip];
    }
  return nil;
}

- (void) rightMouseDown: (NSEvent *) theEvent
{
  NSMenu *m;
  m = [self menuForEvent: theEvent];
  if (m)
    {
      [NSMenu popUpContextMenu: m
	      withEvent: theEvent
	      forView: self];
    }
  else
    {
      [super rightMouseDown: theEvent];
    }
}

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

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

      [self unbind: binding];
      kvb = [[GSKeyValueOrBinding alloc] initWithBinding: NSHiddenBinding 
                                   withName: binding 
                                   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];
    }
}

@end

@implementation NSView(KeyViewLoop)

static NSComparisonResult
cmpFrame(id view1, id view2, void *context)
{
  BOOL flippedSuperView = [(NSView *)context isFlipped];
  NSRect frame1 = [view1 frame];
  NSRect frame2 = [view2 frame];

  if (NSMinY(frame1) < NSMinY(frame2))
    return flippedSuperView ? NSOrderedAscending : NSOrderedDescending;
  if (NSMaxY(frame1) > NSMaxY(frame2))
    return flippedSuperView ? NSOrderedDescending : NSOrderedAscending;

  // FIXME Should use NSMaxX in a Hebrew or Arabic locale
  if (NSMinX(frame1) < NSMinX(frame2))
    return NSOrderedAscending;
  if (NSMinX(frame1) > NSMinX(frame2))
    return NSOrderedDescending;
  return NSOrderedSame;
}

- (void) _setUpKeyViewLoopWithNextKeyView: (NSView *)nextKeyView
{
  if (_rFlags.has_subviews)
    {
      [self _recursiveSetUpKeyViewLoopWithNextKeyView: nextKeyView];
    }
  else
    {
      [self setNextKeyView: nextKeyView];
    }
}

- (void) _recursiveSetUpKeyViewLoopWithNextKeyView: (NSView *)nextKeyView
{
  NSArray *sortedViews;
  NSView *aView;
  NSEnumerator *e;

  sortedViews = [_sub_views sortedArrayUsingFunction: cmpFrame context: self];
  e = [sortedViews reverseObjectEnumerator];
  while ((aView = [e nextObject]) != nil)
    {
      [aView _setUpKeyViewLoopWithNextKeyView: nextKeyView];
      nextKeyView = aView;
    }
  [self setNextKeyView: nextKeyView];
}

@end